package io.github.joaomarccos.pos.airsoft.repositories;

import io.github.joaomarccos.pos.airsoft.dao.DAO;
import io.github.joaomarccos.pos.airsoft.dao.DaoJPAFactory;
import io.github.joaomarccos.pos.airsoft.entitys.GameInvitation;
import io.github.joaomarccos.pos.airsoft.repositories.interfaces.GameInvitationRepository;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author João Marcos <joaomarccos.github.io>
 */
public class GameInvitationRepositoryImpl implements GameInvitationRepository {

    private final DAO<GameInvitation> dao;

    public GameInvitationRepositoryImpl() {
        this.dao = DaoJPAFactory.createDefaultDao();
    }

    @Override
    public void save(GameInvitation entity) {
        dao.save(entity);
    }

    @Override
    public void delete(GameInvitation entity) {
        dao.delete(entity);
    }

    @Override
    public void update(GameInvitation entity) {
        dao.update(entity);
    }

    @Override
    public GameInvitation findByToken(String token) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        return dao.simpleQuery("invitation.findbytoken", params);
    }

}


package com.practice.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.practice.demo.exception.EntityNotFoundException;

@ControllerAdvice
public class CommonExceptionHandlerController {

    private static final Logger logger = LoggerFactory.getLogger(CommonExceptionHandlerController.class);

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(EntityNotFoundException.class)
    public void handleEntityNotFoundException(EntityNotFoundException ex) {
        logger.error(ex.getMessage(), ex);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.class)
    public void handleAllExceptions(Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}


package cz.bbmri.entities.enumeration;

/**
 * General system role of user.
 * USER - anyone who is authorized to access system (who fullfill authorization requirements to acces)
 * implicit role
 * ADMINISTRATOR - administrator of system. He has access to global settings of BBMRI, can browse everything
 * DEVELOPER - programmer responsible for maintenance of system
 * BIOBANK_OPERATOR - user managing at least one biobank
 * PROJECT_TEAM_WORKER - user working on at leat one project which is upload to system
 * PROJECT_TEAM_MEMBER_CONFIRMED - user working on at least one confirmed project
 *
 * @author Ondrej Vojtisek (ondra.vojtisek@gmail.com)
 * @version 1.0
 */

public enum SystemRole {
      USER("user"),
      ADMINISTRATOR("administrator"),
      BIOBANK_OPERATOR("biobank_operator"),
      PROJECT_TEAM_MEMBER("project_team_member"),
      PROJECT_TEAM_MEMBER_CONFIRMED("project_team_member_confirmed"),
      DEVELOPER("developer");

      private final String state;

      private SystemRole(String state) {
          this.state = state;
      }

      @Override
      public String toString() {
          return this.state;
      }
}


package com.saml.util;

import java.util.ArrayList;

import com.saml.util.StateTransitionRule;

public class StateTransitionInfo {
	private ArrayList<StateTransitionRule> stRuleSet;
	private ArrayList<String> states;
	private ArrayList<String> edges;

	public StateTransitionInfo(){
		stRuleSet = new ArrayList<StateTransitionRule>();
		states = new ArrayList<String>();
		edges = new ArrayList<String>();
	}

	public void clearST(){
		if (stRuleSet.size() > 0) {
			stRuleSet.clear();
			states.clear();
			edges.clear();
		}
	}

	public ArrayList<StateTransitionRule> getStRuleSet() {
		return stRuleSet;
	}

	public void setStRuleSet(ArrayList<StateTransitionRule> stRuleSet) {
		this.stRuleSet = stRuleSet;
	}

	public ArrayList<String> getStates() {
		return states;
	}

	public void setStates(ArrayList<String> states) {
		this.states = states;
	}

	public ArrayList<String> getEdges() {
		return edges;
	}

	public void setEdges(ArrayList<String> edges) {
		this.edges = edges;
	}

}


package com.ManagmentSystem.FleetApp.services;

import com.ManagmentSystem.FleetApp.models.Supplier;
import com.ManagmentSystem.FleetApp.repositories.ClientRepository;
import com.ManagmentSystem.FleetApp.repositories.SupplierRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SupplierService {

    @Autowired
    private SupplierRepository supplierRepository;

    // Return list of Clients
    public List<Supplier> getSuppliers() {
        return supplierRepository.findAll();
    }

    //Save new Clients
    public void save(Supplier supplier) {
        supplierRepository.save(supplier);
    }

    //Find Supplier by Id
    public Optional<Supplier> findById(Integer id) {
        return supplierRepository.findById(id);
    }

    //Delete by Supplier id
    public void delete(Integer id) {
        supplierRepository.deleteById(id);
    }

}


package br.com.jpb.superlogica.model;

import br.com.jpb.JsonUtil;
import lombok.Getter;
import lombok.Setter;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

import java.io.Serializable;
import java.math.BigDecimal;

@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
public final class RespostaCheckout implements Serializable {
	@JsonProperty("id_plano_pla")
	private int idPlano;
	@JsonProperty("st_nome_sac")
	private String nomeOuRazaoSocial;
	@JsonProperty("st_nomeref_sac")
	private String nomeFantasia;
	@JsonProperty("st_cgc_sac")
	private String cpfCnpj;
	@JsonProperty("st_email_sac")
	private String email;
	@JsonProperty("st_telefone_sac")
	private String telefone;
	@JsonProperty("valor_primeira_cobranca")
	private BigDecimal valorPrimeiraCobranca;
	@JsonProperty("link_boleto")
	private String linkBoleto;
	@JsonProperty("valor_boleto")
	private BigDecimal valorBoleto;
	@JsonProperty("urlcallback")
	private String urlCallback;
	@JsonProperty("msg")
	private String msg;

	protected RespostaCheckout() {
	}

	@Override
	public String toString() {
		return JsonUtil.serialize(this);
	}

}


package com.lili.net.mina;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lili.net.CommonMessage;

public class CommonMessageEncoder extends ProtocolEncoderAdapter
{
    private static Logger LOGGER = LoggerFactory
            .getLogger(CommonMessageEncoder.class);

    public CommonMessageEncoder()
    {
    }

    /**
     * 对数据包进行二进制流编码
     */
    public void encode(IoSession session, Object message,
            ProtocolEncoderOutput out) throws Exception
    {
        CommonMessage rsp = (CommonMessage) message;
        IoBuffer buffer = IoBuffer.wrap(rsp.toByteBuffer());

        if (buffer == null)
        {
            // 丢弃这个数据包
            LOGGER.error("Drop this packet: {}.", rsp.headerToStr());
            return;
        }

        out.write(buffer);
    }
}


package com.szy.lamda.concurrent.threads_runnable;

/**
 * 〈一句话功能简述〉<br>
 * 〈测试java 死锁〉
 *
 * @author sunzhengyu
 * @create 2019/8/20
 * @since 1.0.0
 */
public class DeadLockSample extends Thread {

    private String first;
    private String second;

    public DeadLockSample(String name, String first, String second) {
        super(name);
        this.first = first;
        this.second = second;
    }

    @Override
    public void run() {
        synchronized (first) {
            System.out.println(this.getName() + " obtained: " + first);
            try {
                Thread.sleep(1_000);
                synchronized (second) {
                    System.out.println(this.getName() + " obtained:" + second);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        String lockA = "lockA";
        String lockB = "lockB";

        DeadLockSample t1 = new DeadLockSample("ThreadA", lockA, lockB);
        DeadLockSample t2 = new DeadLockSample("ThreadB", lockB, lockA);

        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }
}


package com.vijay.SpringKafkaMessaging.persistence.model;
import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name="access_token")
public class AccessToken implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long token_id;

    @Column(name="token")
    private String token;

    @Column(name="user_id")
    private Long userId;

    @Column(name="created_at")
    private Date createdAt;

    public AccessToken(String token,Long userId,Date createdAt) {
		this.token = token;
		this.userId = userId;
		this.createdAt = createdAt;
	}
}


package cn.xanderye.controller;

import cn.xanderye.base.ResultBean;
import cn.xanderye.entity.AccessLog;
import cn.xanderye.service.AccessLogService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author XanderYe
 * @description:
 * @date 2021/7/29 18:49
 */
@RestController
@RequestMapping("system")
public class SystemController {
    @Autowired
    private AccessLogService accessLogService;

    /**
     * 分页获取日志
     * @param pageNum
     * @param pageSize
     * @return cn.xanderye.base.ResultBean<com.github.pagehelper.PageInfo>
     * @author XanderYe
     * @date 2021/7/29
     */
    @GetMapping("getAccessLogList")
    public ResultBean<Page<AccessLog>> getAccessLogList(Integer pageNum, Integer pageSize) {
        pageNum = pageNum == null || pageNum < 0 ? 0 : pageNum;
        pageSize = pageSize == null || pageSize < 0 ? 12 : pageSize;
        return new ResultBean<>(accessLogService.getAccessLogPageInfo(pageNum, pageSize));
    }
}


package com.example.chinesecalendar;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.List;

import us.codecraft.xsoup.Xsoup;

public class Foo implements Runnable {
    private String intentName;
    private volatile String value;

    public Foo(String intentName) {
        this.intentName = intentName;
    }

    @Override
    public void run() {
        String scrap = "";
        Document document = null;
        try {
            document = Jsoup.connect("https://www.viaje-a-china.com/zodiacos-chinos/" + intentName + ".asp").get();

            List<String> list = Xsoup.compile("//meta[@name=\"description\"]/@content").evaluate(document).list();
            for (String element : list) {
                scrap += element;
            }
            value = scrap;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getValue() {
        return value;
    }
}


http://blockchain-voting-system.surge.sh/

![](images/blockchain-mockup.png)

# Blockchain voting app.

	•	In this project I’m exploring blockchain basics and how it can be made tamper-proof through use of blockchain technology.

	•	The 3 main files of this small project are:
	•	> blockchanManager.js - describe the functions
	•	> blockchain.js aka index.js - describe the functions
	•	> index.html - describe the functions

	•	The technologies are:
	•	> webpack.config.js
	•	> Handlebars.js
	•	> Crypto-JS library provides the SHA256.js module
	•	> Jasmine Testing library

	•	Testing:
	•	to run the test: [ jasmine spec/spec-test.js ]
	•	the test file is: spec/spec-test.js

	•	The Readme.md file contains:
	•	screenshot of a block form
	•	future features
	•	instructions for installation and operation
	•	technologies used
	•	link to Pivotal Tracker

	•	Things to demonstrate:
	•	run the test and play with it a bit
	•	show the raw block data in console & in code
	•	show the blocks being mined - via hash & nonce

	•	The Design Phase:
	•	describe basic interactivity - simple voting
	•	OAuth 2.0 login
	•	more ideas

	•	Deployment:
	•	use Surge.sh to deploy the application


package com.example.y_xl.neihanduanzi.view.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/4/14 0014.
 */

public abstract  class MBaseAdapter<T> extends android.widget.BaseAdapter {
    private List<T> entities;
    private LayoutInflater inflater;

    public MBaseAdapter(Context context) {
        this.entities = new ArrayList<>();
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return entities.size();
    }

    @Override
    public T getItem(int i) {
        return entities.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }
    public void addAll(List<T> dd){
        entities.addAll(dd);
        notifyDataSetChanged();
    }

    public LayoutInflater getInflater() {
        return inflater;
    }
}


package tw.brad.gtest2;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Brad62 {
	public static void main(String[] args) {
		String urlString = "http://www.gamer.com.tw";
		try {
			URL url = new URL("https://pdfmyurl.com/index.php?url=" + urlString);
			HttpURLConnection conn =
					(HttpURLConnection) url.openConnection();
			conn.connect();

			String filename = urlString.replace("/", "_");

			FileOutputStream fout = new FileOutputStream("mytest/" + filename + ".pdf");
			BufferedInputStream bin = new BufferedInputStream(conn.getInputStream());

			byte[] buf = new byte[1024*4096];
			int len;
			while ( (len = bin.read(buf)) != -1) {
				fout.write(buf, 0, len);
			}

			bin.close();
			fout.flush();
			fout.close();

			System.out.println("finish");
		}catch(Exception e) {
			System.out.println(e.toString());
		}

	}
}


package com.eixox;

import java.lang.System.Logger;

/**
 * Generic exceptions should never be thrown (squid:S00112). Using such generic
 * exceptions as Error, RuntimeException, Throwable, and Exception prevents
 * calling methods from handling true, system-generated exceptions differently
 * than application-generated errors.
 *
 * @author rportela
 *
 */
public class JetfuelException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = 4286269740011946021L;

	public JetfuelException(String msg) {
		super(msg);
	}

	public JetfuelException(Throwable cause) {
		super(cause);
	}

	public JetfuelException(String msg, Throwable cause) {
		super(msg, cause);
	}

	public static void log(Object source, System.Logger.Level level, Throwable t) {
		Logger logger = System.getLogger(source == null
				? "GLOBAL"
				: source.getClass().getName());

		logger.log(level, t);
	}

	public static void log(Object source, System.Logger.Level level, String message, Throwable t) {
		Logger logger = System.getLogger(source == null
				? "GLOBAL"
				: source.getClass().getName());

		logger.log(level, message, t);
	}

}


public class AdminDep extends CollegeAcc{
	private String studentAddress;
	private String studentEthnicity;
	private String studentGender;

	public AdminDep()
	{
		this(0,"","","","");
	}

	public AdminDep(int accNo, String name,String Address,String Ethnicity, String Gender)
	{
		super(accNo, name);
		this.studentAddress = Address;
		this.studentEthnicity = Ethnicity;
		this.studentGender = Gender;

	}

	public String getStudentAddress() {
		return studentAddress;
	}
	public void setStudentAddress(String studentAddress) {
		this.studentAddress = studentAddress;
	}
	public String getStudentEthnicity() {
		return studentEthnicity;
	}
	public void setStudentEthnicity(String studentEthnicity) {
		this.studentEthnicity = studentEthnicity;
	}
	public String getStudentGender() {
		return studentGender;
	}
	public void setGender(String studentGender) {
		this.studentGender = studentGender;
	}

	@Override
	public String toString() {
		return "Administration Department [studentAddress=" + studentAddress + ", studentEthnicity=" + studentEthnicity
				+ ", studentGender=" + studentGender + "]";
	}

}


package com.musafi.memorygame.game;

public class Card {

    private int id;
    private int image;
    private boolean enable;
    private boolean discovered;

    public Card() {
    }

    public Card(int id, int image, boolean enable, boolean discovered) {
        this.id = id;
        this.image = image;
        this.enable= enable;
        this.discovered = discovered;

    }

    public int getId() {
        return id;
    }

    public Card setId(int id) {
        this.id = id;
        return this;
    }

    public int getImage() {
        return image;
    }

    public Card setImage(int image) {
        this.image = image;
        return this;
    }

    public boolean isEnable() {
        return enable;
    }

    public Card setEnable(boolean enable) {
        this.enable = enable;
        return this;
    }

    public boolean isDiscovered() {
        return discovered;
    }

    public Card setDiscovered(boolean discovered) {
        this.discovered = discovered;
        return this;
    }
}


package advanced.todo.com.todoadvanced.base;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

import advanced.todo.com.todoadvanced.R;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author Tiany
 * @desc
 * @date 2017/3/9
 */
public abstract class BaseActivity extends AppCompatActivity {

	@BindView(R.id.toolBar)
	Toolbar mToolbar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(getLayoutId());

		ButterKnife.bind(this);

		initData();

		initView();

		setListener();

		initToolBar();
	}

	private  void initToolBar() {
		mToolbar.setTitle(initTitle());
		mToolbar.setNavigationIcon(R.mipmap.ic_back);
		setSupportActionBar(mToolbar);
		mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				BaseActivity.this.finish();
			}
		});
	}

	public abstract int getLayoutId();

	public abstract void initData();

	public abstract void initView();

	public abstract void setListener();

	public abstract String initTitle();

}


package com.cdkhd.npc.entity;

import com.cdkhd.npc.enums.StatusEnum;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.persistence.*;

/**
 * @Description
 * @Author rfx
 * @Date 2019-12-03
 */

@Setter
@Getter
@Entity
@Table(name = "government_user")
public class GovernmentUser extends BaseDomain {
    /**
     * 1、正常
     * 2、锁定
     */
    @Column(name = "status")
    private Byte status = StatusEnum.ENABLED.getValue();

    /**
     * 等级，县/区后台管理员 or 镇后台管理员
     * 见com.cdkhd.npc.enums.LevelEnum
     */
    @Column(name = "level")
    private Byte level;

    //关联区
    @ManyToOne(targetEntity = Area.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "area", referencedColumnName = "id")
    private Area area;

    //关联镇
    @ManyToOne(targetEntity = Town.class, fetch = FetchType.LAZY)
    @JoinColumn(name = "town", referencedColumnName = "id")
    private Town town;

    /**
     * 账号表id
     */
    @OneToOne(targetEntity = Account.class, fetch = FetchType.LAZY)
    private Account account;

    @OneToOne(targetEntity = Government.class, fetch = FetchType.LAZY)
    private Government government;

}


package com.transport.service;

import com.transport.form.RegistrationForm;
import com.transport.model.Employee;
import com.transport.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * Created by 1 on 6/13/2016.
 */
@Service
public class RegistrationServiceImpl implements RegistrationService {

    @Autowired
    EmployeeRepository employeeRepository;

    @Override
    @Transactional
    public void addEmployee(RegistrationForm registrationForm) {

        Employee employee = new Employee();

        employee.setFirstName(registrationForm.getFirstName());
        employee.setLastName(registrationForm.getLastName());
        employee.setPosition(registrationForm.getPosition());
        employee.setMail(registrationForm.getMail());
        employee.setPhone(registrationForm.getPhone());
        employee.setRate(registrationForm.getRate());

        employee = employeeRepository.save(employee);
    }
}


package MxCompiler.AST;

import MxCompiler.Utilities.CompilationError;
import MxCompiler.Utilities.Location;

import java.util.ArrayList;

public class ProgramNode extends ASTNode {
    private ArrayList<ProgramUnitNode> programUnits;

    public ProgramNode(Location location, ArrayList<ProgramUnitNode> programUnits) {
        super(location);
        this.programUnits = programUnits;
    }

    public ArrayList<ProgramUnitNode> getProgramUnits() {
        return programUnits;
    }

    public void addProgramUnit(ProgramUnitNode programUnit) {
        programUnits.add(programUnit);
    }

    @Override
    public String toString() {
        StringBuilder string = new StringBuilder("<ProgramNode>\n");
        string.append("programUnits:\n");
        for (ProgramUnitNode unit : programUnits)
            string.append(unit.toString());
        return string.toString();
    }

    @Override
    public void accept(ASTVisitor visitor) throws CompilationError {
        visitor.visit(this);
    }
}


package com.hunliji.marrybiz.model.realm;

import android.util.Log;

import com.hunliji.hljcommonlibrary.models.realm.CommonRealmMigrationUtil;
import com.hunliji.hljcommonlibrary.models.realm.WSChat;

import io.realm.DynamicRealm;
import io.realm.RealmMigration;
import io.realm.RealmSchema;

/**
 * Created by wangtao on 2017/8/15.
 */

public class MerchantRealmMigration implements RealmMigration {

    public static final int REALM_VERSION = CommonRealmMigrationUtil.COMMON_VERSION;

    @Override
    public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
        Log.e("RealmMigration:", "oldVersion: " + oldVersion + " newVersion: " + newVersion);
        RealmSchema schema = realm.getSchema();
        while (oldVersion < newVersion) {
            if (oldVersion == 5) {
                realm.where(WSChat.class.getSimpleName())
                        .equalTo("isError", false)
                        .findAll()
                        .deleteAllFromRealm();
            }else {
                CommonRealmMigrationUtil.migrate(schema, oldVersion, newVersion);
            }
            oldVersion++;
        }
    }
}


package net.amigocraft.GoldBank.util;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class NameFetcher {

	private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/";
	private static final JSONParser jsonParser = new JSONParser();

	public static String getUsername(UUID uuid) throws Exception {
		HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL+uuid.toString().replace("-", "")).openConnection();
		JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
		String name = (String) response.get("name");
		String cause = (String) response.get("cause");
		String errorMessage = (String) response.get("errorMessage");
		if (cause != null && cause.length() > 0) {
			throw new IllegalStateException(errorMessage);
		}
		return name;
	}
}


package com.maxbilbow.common.ui;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Service
public class FrontendUtil
{

  private Charset charset = Charset.defaultCharset();
  private Reference<String> view = null;

  private List<String> resources = new ArrayList<>();

  @PostConstruct
  public void init()
  {
    System.out.println("HERE");
  }
  public String getJs() throws IOException
  {
    String view = this.view != null ? this.view.get() : null;
    if (view == null)
    {
      final StringBuilder sb = new StringBuilder();
      for (String resource : resources)
      {
        try (final InputStream startsWithStream = this.getClass().getResourceAsStream("/bpmnViewer/startsWith.js"))
        {
          sb.append(IOUtils.toString(startsWithStream, charset));
        }
      }
      this.view = new SoftReference<>(view = sb.toString());
    }
    return view;
  }
}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.Random;

/**
 *
 * @author Admin
 */
@Named(value = "navigationController")
@SessionScoped
public class NavigationController implements Serializable {

    private boolean navigate;
    /**
     * Creates a new instance of NavigationController
     */
    public NavigationController() {
    }

    public String page2()
    {return "page2";}

    public void randomize()
    {Random rand=new Random();
       navigate=rand.nextBoolean();

    }

    public boolean isNavigate() {
        return navigate;
    }

    public void setNavigate(boolean navigate) {
        this.navigate = navigate;
    }

}


package economics;

import org.mortbay.component.AbstractLifeCycle;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.jetty.webapp.WebAppContext;
import org.springframework.web.servlet.DispatcherServlet;

public class StartWebServer {
    private static int PORT = 8080;

    public static void main(String[] args) {
        if (args.length == 1) PORT = Integer.parseInt(args[0]);
        Server server = new Server(PORT);
        WebAppContext context = new WebAppContext(server, ".", "/");
        context.addServlet(springConfig(), "/*");
        start(server);
    }

    private static ServletHolder springConfig() {
        DispatcherServlet servletDispatcher = new DispatcherServlet();
        servletDispatcher.setContextConfigLocation("classpath:dispatcher-servlet.xml");
        ServletHolder holder = new ServletHolder();
        holder.setServlet(servletDispatcher);
        return holder;
    }

    private static void start(AbstractLifeCycle server) {
        try {
            server.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


package com.cg.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cg.model.MessageModel;
import com.cg.service.IMessageService;

@RestController
@RequestMapping("/home")
public class MessageController {
	@Autowired
	private IMessageService messageService;

	@RequestMapping(value = "/{name}", method = RequestMethod.GET, headers = "application/json")
	public MessageModel displayMessage(@PathVariable("name") String name) {

		MessageModel messageModel= new MessageModel();
		messageModel.setName(name);
		return messageService.displayMessage(messageModel);

	}
	public void setMessageService(IMessageService messageService) {
		this.messageService = messageService;
	}

}


# Refactoring

As your project grows, you will begin to notice opportunities to refactor and
reuse the components you have created. To encourage this behavior, Tangle
provides intelligent tools to automate several common refactoring patterns.

## Extract module

Extract a module from your project into a new repository, preserving its
history, and install it instead as an external dependency.

    $ tangle module extract
    # ... interactive configuration

## Convert module to primitive

Convert a module implementation into a new primitive, and reimplement the module
extending from that primitive.

    $ tangle module primitive
    # ... interactive configuration

## Extract primitive

Extract a primitive from your project into a new repository, preserving its
history, and install it instead as an external dependency.

    $ tangle primitive extract
    # ... interactive configuration

## Reparent module

Create a new module and reparent several modules into it to group related
features together, or move a submodule up to an ancestor or into a different
group altogether.

    $ tangle module reparent
    # ... interactive configuration


package comp1206.sushi.server;

import javax.swing.*;
import java.awt.*;

public abstract class SuppIngredTemplate extends JPanel {

    protected JPanel buttons;
    protected JPanel table;
    protected JTable jTable;
    protected GridBagConstraints gbc;

    abstract JTable createTable();
    abstract JPanel createButtons();

    public SuppIngredTemplate() {

    }

    public void createTemplate() {
        BorderLayout borderLayout = new BorderLayout();
        this.setLayout(borderLayout);

        buttons = new JPanel(new GridBagLayout());
        buttons.setBorder(BorderFactory.createEmptyBorder(0, 15, 0, 15));
        gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        this.buttons = createButtons();

        table = new JPanel();
        this.add(table, borderLayout.CENTER);
        this.add(buttons, borderLayout.WEST);
        table.setLayout(new BorderLayout());
        this.jTable = createTable();
        table.add(jTable, BorderLayout.CENTER);
        table.add(jTable.getTableHeader(), BorderLayout.NORTH);
    }

}


package com.cloud.river.common.minio;

import com.cloud.river.common.minio.service.MinioTemplate;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * @program: RiverCloud
 * @description:
 * @author: River
 * @create: 2019-04-01 10:23
 **/
@AllArgsConstructor
@EnableConfigurationProperties(MinioProperties.class)
public class MinioAutoConfiguration {
    private final MinioProperties minioProperties;

    @Bean
    @ConditionalOnMissingBean(MinioProperties.class)
    @ConditionalOnProperty(name = "minio.url")
    MinioTemplate template(){
        return new MinioTemplate(
                minioProperties.getUrl(),
                minioProperties.getAccessKey(),
                minioProperties.getSecretKey());
    }
}


package com.intland.eurocup.io.jms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import com.intland.eurocup.common.jms.model.MessageFromFrontend;

/**
 * JMS Sender handles outgoing messages.
 */
@Component
@Profile("default")
public class JmsSender {
  Logger logger = LoggerFactory.getLogger(JmsSender.class);

  @Value("${jms.queue.from.ui.name}")
  private String queueName;

  @Autowired
  private JmsTemplate jmsTemplate;

  /**
   * Sends message to destination.
   *
   * @param message {@link MessageFromFrontend}
   */
  public void send(final MessageFromFrontend message) {
    logger.info("Frontend sends - " + message);
    jmsTemplate.convertAndSend(queueName, message);
  }
}


package pl.venixpll.app.render;

import lombok.Data;
import org.newdawn.slick.*;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import pl.venixpll.app.DodgeAPP;

import java.awt.*;
import java.util.Random;

@Data
public class RenderAsteroid implements IRender {

    private int posX;
    private int posY;
    private Image asteroid;

    private Rectangle boundbox;

    public RenderAsteroid(int posX,int posY,DodgeAPP app){
        this.posX = posX;
        this.posY = posY;
        asteroid = app.getLoader().getAsteroid();
        boundbox = new Rectangle(posX,posY,50,50);
    }

    @Override
    public void render(Graphics graphics, GameContainer container, DodgeAPP app) {
        asteroid.draw(posX,posY,50,50);
    }

    @Override
    public void tick(GameContainer container, DodgeAPP app) {
        posY += app.getGameSpeed() * 2;
        this.boundbox.setBounds(posX + 13,posY + 15,25,25);
    }
}


package be.ipl.blitz.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.ipl.blitz.usecases.GameUcc;

@WebServlet("/join-lobby.html")
public class JoinLobbyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private GameUcc gameUcc;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		final ServletContext context = getServletContext();
		synchronized (context) {
			String gameName = (String) context.getAttribute("game-name");
			if (gameName != null) {
				if (gameUcc.joinGame(gameName, (String) request.getSession().getAttribute("username"))) {
					response.sendRedirect(request.getContextPath() + "/lobby.html");
				}
			}
		}

	}

}


package com.chuangxin.monitor.config;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.ArrayList;
import java.util.List;

public class WaterSystem<T> {

    @JsonProperty("chiller")
    private List<NameValues<T>> chiller = new ArrayList();

    @JsonProperty("chwCircuit")
    private  ChwCircuit<T>  chwCircuit;

    @JsonProperty("cowCircuit")
    private List<NameValues<T>> cowCircuit = new ArrayList();

    public WaterSystem() {
    }

    public List<NameValues<T>> getChiller() {
        return chiller;
    }

    public void setChiller(List<NameValues<T>> chiller) {
        this.chiller = chiller;
    }

    public ChwCircuit<T> getChwCircuit() {
        return chwCircuit;
    }

    public void setChwCircuit(ChwCircuit<T> chwCircuit) {
        this.chwCircuit = chwCircuit;
    }

    public List<NameValues<T>> getCowCircuit() {
        return cowCircuit;
    }

    public void setCowCircuit(List<NameValues<T>> cowCircuit) {
        this.cowCircuit = cowCircuit;
    }
}


package com.salesupload.login.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

public class MyLogoutSuccessHandler  implements LogoutSuccessHandler{

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	Environment environment;

	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {

		logger.info("Logout Sucessfull with Principal: " + authentication.getName());
		response.setStatus(HttpServletResponse.SC_OK);
		response.sendRedirect(environment.getProperty("server.servlet.context-path") + "/");
	 }
}


package email.reader.grab;

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

public class EmailGrab {
	private Folder f = null;
	private Session sesh = null;
	private Store store = null;

	public EmailGrab(String email, String pass) throws MessagingException {
		Properties props = new Properties();
		props.setProperty("mail.store.protocol", "imaps");
		sesh = Session.getInstance(props);
		store = sesh.getStore();
		store.connect("imap.gmail.com", email, pass);
		f = store.getFolder("INBOX");
		f.open(Folder.READ_ONLY);
		}

	public Folder getInbox() throws MessagingException {
		if (!f.isOpen()) {
			f.open(Folder.READ_ONLY);
		}
		return f;
	}

	public Session getSesh() {
		return sesh;
	}

	public void setSesh(Session sesh) {
		this.sesh = sesh;
	}

	public Store getStore() {
		return store;
	}

	public void setStore(Store store) {
		this.store = store;
	}

}


package model.notify;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * author：康乐
 * time：2014/11/23
 * function：用于存放和管理客户端请求（消息推送）对象
 */
public class WaitingNotifyManager {

	// map最大值
	public static final int MAXNOTIFYWAITERNUMBER = 1000;

	// 初始化大小
	public static final int WAITENOTIFYINITNUMBER = 100;

	// 在线等待容器
	private static ConcurrentHashMap<Integer, NotifyTask> waiteMessageIdMap =
			new ConcurrentHashMap<Integer, NotifyTask>(WAITENOTIFYINITNUMBER);

	/**
	 * 获取等待者对象
	 * @param ID 需要获取的等待者的ID
	 * @return 等待者对象
	 */
	public static NotifyTask getWaiter(int ID) {
		return waiteMessageIdMap.get(ID);
	}

	/**
	 * 将等待者放入map
	 * @param ID 等待者ID
	 * @param waiter 等待者执行对象
	 * @return 放入成功，返回true；否则返回false
	 */
	public static boolean putWaiter(int ID, NotifyTask waiter) {
		return waiteMessageIdMap.put(ID, waiter) != null;
	}

	/**
	 * 将等待者移除
	 * @param ID 需要被移除的等待者
	 * @return 是否移除成功
	 */
	public static boolean removeWaiter(int ID) {
		return waiteMessageIdMap.remove(ID) != null;
	}

	/**
	 * 获取等待者的个数
	 * @return 等待者的个数
	 */
	public static int getWaiterNumber() {
		return waiteMessageIdMap.size();
	}

}


## To build the tile:

### Prerequisites

1. [Kiln](https://github.com/pivotal-cf/kiln)
2. First copy the `aerospike-service-adapter-release*.tgz` `aerospike-service-release*.tgz` and `on-demand-service-broker-0.21.2.tgz` into the release directory. The service adapter release may be found at: https://network.pivotal.io/products/on-demand-services-sdk/ . It is necessary to log in to download the file. Alternatively it may be found at the github repository for the project as a release
3. Download the routing release from the [GitHub Repo](https://github.com/cloudfoundry/routing-release) as a release

### Build Instructions
1. Ensure that the kiln-build/version file is equal to the current version of the tile, (1 less than the version to be released).
2.  Run `bake_metadata` and write it to .yml file to see the generated tile metadata.
3. If it looks alright, run `./bake` to write out the tile to a file `named aerospike-on-demand-$VERSION.pivotal` . This is the tile which can be uploaded into opsmanager.


package com.example.textcolor;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView view;
    Button   size;
    Button   color;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        view=(TextView)findViewById(R.id.view);
        size=(Button)findViewById(R.id.size);
        color=(Button)findViewById(R.id.color);

        size.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view.setTextSize(TypedValue.COMPLEX_UNIT_SP,view.getTextSize()+1);
            }
        });
        color.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                view.setTextColor(Color.RED);

            }
        });
    }
}


package com.businness.controller;

import com.businness.entity.CommissionEx;
import com.businness.result.Result;
import com.businness.service.CommissionExService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/miss")
public class ComController {

    @Resource
    private CommissionExService commissionExService;

    @RequestMapping(value = "/querycomm",method = RequestMethod.POST)
    public Result queryAllComm(@RequestParam Map map){
        PageHelper.startPage(Integer.parseInt(map.get("pageNum").toString()),Integer.parseInt(map.get("pageSize").toString()));
        List<CommissionEx> lists=commissionExService.queryAllComm(map);
        PageInfo<CommissionEx> pageInfo = new PageInfo(lists);

        return Result.success(1,pageInfo);
    }
}


package com.blogger.entity.admin;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;

/**
 * 权限实体类（继承角色字段）
 *
 * @author Liu wei
 * @date 2020-03-31 16:00
 **/
@Data
@TableName(value = "permission")
public class Permission extends Role {

    @TableField(value = "permissionId", el = "权限ID")
    private int permissionId;

    @TableField(value = "permissionName", el = "权限名称")
    private String permissionName;

    @TableField(value = "permissionPath", el = "权限路径")
    private String permissionPath;

    @TableField(value = "parentId", el = "父类ID")
    private int parentId;

    @TableField(value = "parentName", el = "父类名称")
    private String parentName;

    @TableField(value = "levelNo", el = "权限等级")
    private int levelNo;

    @TableField(value = "createPerson", el = "创建者（用户ID）")
    private String createPerson;

    @TableField(value = "createDate", el = "创建时间")
    private String createDate;

    @TableField(value = "updatePerson", el = "更新者（用户ID）")
    private String updatePerson;

    @TableField(value = "updateDate", el = "更新时间")
    private String updateDate;

}


package skcc.fresh.honeypot;

import skcc.fresh.backup.Backup1Activity;
import skccc.fresh.honeypot.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

	View.OnClickListener bHandler = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_backup:
				Intent intent = new Intent(getBaseContext(),
						Backup1Activity.class);
				startActivity(intent);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		startActivity(new Intent(this, IntroActivity.class));

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Button btn_backup = (Button) findViewById(R.id.btn_backup);
		btn_backup.setOnClickListener(bHandler);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}


package <missing>;

public class GlobalMembers
{
	public static int Main()
	{
		int num = char;
		int le = char;
		int n;
		int i;
		int len;
		String str = new String(new char[100]);
		String tempVar = ConsoleInput.scanfRead();
		if (tempVar != null)
		{
			n = Integer.parseInt(tempVar);
		}
		System.in.read();
		while (n-- != 0)
		{
		  str = new Scanner(System.in).nextLine();
		  len = str.length();
		  if (le(str.charAt(0)) == 0)
		  {
			  System.out.print("0\n");
			  continue;
		  }
			for (i = 0;i < len;i++)
			{
				if ((le(str.charAt(i)) == 0) && (num(str.charAt(i)) == 0))
				{
				  break;
				}
			}
			if (i == len)
			{
				System.out.print("1\n");
			}
			else
			{
				System.out.print("0\n");
			}
		}
	}
	public static int le(char c)
	{
		if ('a' <= c && c <= 'z')
		{
			return 1;
		}
		else if ('A' <= c && c <= 'Z')
		{
			return 1;
		}
		else if (c == '_')
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
	public static int num(char c)
	{
		if ('0' <= c && c <= '9')
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
}


package edu.uade.appl_interact;

import edu.uade.appl_interact.model.entities.User;
import edu.uade.controller.Controller;
import edu.uade.controller.LoginController;
import edu.uade.controller.MainController;

import javax.swing.*;

public class Main  {

    private Controller controller;
    private JFrame frame;
    private User loggedUser;

    public Main () {
        frame  = new JFrame("Regalitos");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(1024, 768);
        frame.setLocationRelativeTo(null);
        controller = new LoginController(frame);
        controller.setMain(this);
    }

    public void run() {
        controller.updateView();
    }

    public void OnUserLogout() {
        loggedUser = null;
        controller = new LoginController(frame);
        controller.setMain(this);
        run();
    }

    public void OnUserLogin(User user) {
        loggedUser = user;
        controller = new MainController(frame, user);
        controller.setMain(this);
        run();
    }
}


package us.ihmc.rdx.ui.yo;

import imgui.type.ImBoolean;
import us.ihmc.behaviors.tools.yo.YoBooleanClientHelper;
import us.ihmc.tools.Timer;

public class ImGuiModifiableYoBoolean
{
   private final YoBooleanClientHelper yoBooleanHelper;
   private final ImBoolean imBoolean = new ImBoolean();
   private final Timer setValueTimer = new Timer();
   private boolean lastSetValue = false;

   public ImGuiModifiableYoBoolean(YoBooleanClientHelper yoBooleanHelper)
   {
      this.yoBooleanHelper = yoBooleanHelper;
   }

   public void update()
   {
      if (!setValueTimer.isRunning(2.0))
      {
         imBoolean.set(yoBooleanHelper.get());
      }
   }

   public void set()
   {
      lastSetValue = imBoolean.get();
      yoBooleanHelper.set(lastSetValue);
      setValueTimer.reset();
   }

   public YoBooleanClientHelper getYoBooleanHelper()
   {
      return yoBooleanHelper;
   }

   public ImBoolean getImBoolean()
   {
      return imBoolean;
   }
}


package com.example.explicitintent;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {

    private TextView dataShow;
    private Button back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        setTitle("second Activity");

        dataShow = findViewById(R.id.inputShow);
        back = findViewById(R.id.back);

        Intent intent = getIntent();

        String data = intent.getStringExtra("input");

        dataShow.setText(data);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

    }
}


---
layout: page
title:  Ruby
author: jevon
date:   2015-06-09 21:11:21 +12:00
tags:
  - Ruby
---

[Ruby](Ruby.md) is a programming language which is used as the basis of [Ruby on Rails](Ruby_on_Rails.md).

1. [Rake](Rake.md)
1. [Rspec](rspec.md)

## ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError) too many connection resets

I was getting this error when trying to install the gem https://au-m.rubygems.org/quick/Marshal.4.8/turbolinks-2.3.0.gemspec.rz. It looks like it was a temporary issue with the server, and running `gem install turbolinks -v '2.3.0' --source "http://production.s3.rubygems.org"` didn't make any difference.

One workaround is to download the gem file manually (e.g. http://au-m.rubygems.org/gems/turbolinks-2.3.0.gem --> http://production.s3.rubygems.org/gems/turbolinks-2.3.0.gem) and then `gem install turbolinks-2.3.0.gem`.


package com.godoro.client;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class SampleClient {

	public static void main(String[] args) throws Exception {

		String address="http://localhost:8080/Java09/sapmle";
		URL url=new URL(address);
		URLConnection connection=url.openConnection();
		InputStream in=connection.getInputStream();

		String response=read(in);
		System.out.println("Yanıt:\n"+response);

	}

	private static String read(InputStream in) throws Exception
	{
		BufferedReader reader=new BufferedReader(
				new InputStreamReader(in,"utf-8"));

		StringBuilder builder=new StringBuilder();
		String line=null;
		while((line=reader.readLine())!=null)
		{
			builder.append(line).append("\r\n");

		}
		return builder.toString();
	}

}


package com.mycompany.siemproject.services;

import com.mycompany.siemproject.model.Alert;
import com.mycompany.siemproject.repositories.AlertRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AlertService {

    @Autowired
    private AlertRepository alertRepository;

    public Alert getAlert(Integer id) throws Exception {
        return alertRepository.findById(id).orElseThrow(() -> new Exception("Alert does not exist."));
    }

    public List<Alert> getAllAlerts() {
        return alertRepository.findAllByOrderByDateDesc();
    }

    @Transactional
    public Alert createOrUpdateAlert(Alert alert) {
        return alertRepository.save(alert);
    }

    @Transactional
    public void deleteAlert(Integer id) throws Exception {
        alertRepository.deleteById(id);
    }

}


package chronos.chronos.View.Principal;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import chronos.chronos.View.Principal.Cadastros.FragActPrincipalCadastros;
import chronos.chronos.View.Principal.OrdemServico.FragActPrincipalos;

public class PagerAdapter extends FragmentPagerAdapter {

    private int numeroDeTabs;

    public PagerAdapter(FragmentManager fm, int numeroDeTabs) {
        super(fm);

        this.numeroDeTabs = numeroDeTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:{
                return new FragActPrincipalos();
            }

            case 1:{
                return new FragActPrincipalCadastros();
            }

            default: {
                return null;
            }
        }
    }

    @Override
    public int getCount() {
        return numeroDeTabs;
    }
}


package com.universe.jdkapi.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK动态代理为面向接口的代理，被代理的类必须实现接口
 */
public class DynamicProxyInvocationHandler implements InvocationHandler {

  private Object targetObject;

  public DynamicProxyInvocationHandler(Object targetObject) {
    this.targetObject = targetObject;
  }

  public Object createProxyInstance() {
    return Proxy.newProxyInstance(DynamicProxyInvocationHandler.class.getClassLoader(),
        targetObject.getClass().getInterfaces(), this);
  }

  /**
   * 第一个参数为代理对象，第二个参数为被代理的方法，第三个参数为方法参数
   */
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.err.println("=================目标对象方法执行之前进行拦截======================");
    Object value = method.invoke(targetObject, args);
    System.err.println("=================目标对象方法执行之后进行拦截======================");
    return value;
  }
}


package com.harrys.hyppo.executor.proto.init;

import com.harrys.hyppo.executor.proto.ExecutorError;
import com.harrys.hyppo.executor.proto.ExecutorInitMessage;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;

/**
 * Created by jpetty on 7/21/15.
 */
public final class InitializationFailed extends ExecutorInitMessage {
    private static final long serialVersionUID = 1L;

    @JsonProperty("error")
    private final ExecutorError error;

    @JsonCreator
    public InitializationFailed(
            @JsonProperty("error") final ExecutorError error
    ) {
        this.error = error;
    }

    @JsonProperty("error")
    public final ExecutorError getError(){
        return error;
    }

    public static final InitializationFailed createFromThrowable(final Throwable t) {
        final ExecutorError error = ExecutorError.createFromThrowable(t);
        return new InitializationFailed(error);
    }
}


package org.stefata.mediadownloader.piratebay;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import reactor.test.StepVerifier;

import static org.assertj.core.api.Assertions.assertThat;

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = ProxySearch.class)
class ProxySearchTest {

    @Autowired
    private ProxySearch subject;

    @Test
    public void getsSingleProxy() {
        StepVerifier.create(subject.getProxy())
                .assertNext(proxy -> {
                    assertThat(proxy.getCountry()).isEqualTo("GB");
                    assertThat(proxy.getSecure()).isTrue();
                    assertThat(proxy.getDomain()).isNotNull();
                })
                .verifyComplete();
    }

}


package view;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author Zach Ouellette | arzalam@uw.edu
 */
public class EditReviewPromptPanel extends JPanel {

	private static final long serialVersionUID = 1L;

	private final JTextArea content;
	JScrollPane scrollPane;

	public EditReviewPromptPanel(String oldReview) {

		JLabel t = new JLabel("Edit Your Review");

		content = new JTextArea(oldReview);
		scrollPane = new JScrollPane(content);
		setPreferredSize(new Dimension(500, 300));

    	JPanel cw = new JPanel();
    	cw.add(t);
    	setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

    	add(cw);
    	add(scrollPane, BorderLayout.CENTER);
	}

	public String getContent() {
		return new String(content.getText().toString());
	}

}


package com.yg.base;

import java.io.Serializable;

/**
 * Created by Administrator on 2015/9/14.
 */
public class BaseResult<T> implements Serializable {
    private String msg;
    private int code;
    private T data;

    public BaseResult() {
    }

    public BaseResult(ReturnCode returnCode) {
        this.code = returnCode.getCode();
        this.msg = returnCode.getMsg();
    }

    public BaseResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public BaseResult(int code, T data) {
        this.code = code;
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}


package com.fuzz.android.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewParent;
import android.widget.LinearLayout;

/**
 * View presenting an article.
 */
public class ArticleView extends LinearLayout {
    private static final float TOUCH_DOWN_ALPHA = 0.7f;

    /**
     * Whether is picked up by the user.
     */
    private boolean isPickedUp;

    /**
     * Milliseconds since last tap, for removing purposes.
     */
    public long millisSinceTap;

    public ArticleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public boolean isPickedUp() {
        return isPickedUp;
    }

    public void setPickedUp(boolean pickedUp) {
        isPickedUp = pickedUp;
    }

    public void setHoverEffectEnabled(boolean enabled){
        setAlpha(enabled ? TOUCH_DOWN_ALPHA : 1);
    }
}


package com.fulong.portlet.site.vertical;

import javax.portlet.PortletPreferences;

/**
 *
 *

 * Title: 龙驭门户引擎
 *

 *
 *

 * Description: 龙驭网站内容管理系统核心引擎
 *

 *
 *

 * Copyright: 北京中科辅龙计算机技术股份有限公司
 *

 *
 *

 * Company: 北京中科辅龙计算机技术股份有限公司
 *

 *
 * @author Lixf
 * @version 1.0
 */
public class NavigatorConfig {
	private PortletPreferences preferences;
	private String[] channels;

	public NavigatorConfig(PortletPreferences preferences) {
		this.preferences = preferences;
		this.channels = this.preferences.getValues("channels", new String[0]);
	}

	public int getChannelCount() {
		return this.channels.length;
	}

	public String getChannelId(int index) {
		if (index < this.channels.length) {
			if ((channels[index] == null) || (channels[index].length() == 0)) {
				return null;
			}
			return channels[index];
		}
		return null;
	}

	public String getSeperator() {
		return this.preferences.getValue("seperator", "");
	}
}


package org.sid.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@SuppressWarnings("serial")
@Embeddable
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class StockeId implements Serializable {

	private int idstock ;
	private int idcategories ;

	public StockeId() {

	}

	public StockeId(int idstock, int idcategories) {

		this.idstock = idstock;
		this.idcategories = idcategories;
	}
	@Column(name = "id_stock", nullable = false)
	public int getIdstock() {
		return idstock;
	}

	public void setIdstock(int idstock) {
		this.idstock = idstock;
	}

	@Column(name = "idcategories", nullable = false)
	public int getIdcategories() {
		return idcategories;
	}

	public void setIdcategories(int idcategories) {
		this.idcategories = idcategories;
	}

}


package grape.learn.netty.protocol.http.xml.order;

import java.util.List;

import grape.learn.netty.protocol.http.xml.pojo.Order;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpResponse;

/**
 * 从FullHttpResponse对象中解码构造HttpXmlResponse对象
 *
 * @author grape
 * @date 2019-06-12
 */
public class HttpXmlResponseDecoder extends AbstractHttpXmlDecoder<FullHttpResponse> {

  protected HttpXmlResponseDecoder(Class clazz, boolean isPrint) {
    super(clazz, isPrint);
  }

  protected HttpXmlResponseDecoder(Class clazz) {
    super(clazz);
  }

  @Override
  protected void decode(ChannelHandlerContext ctx, FullHttpResponse msg, List<Object> out)
      throws Exception {
    if (!msg.getDecoderResult().isSuccess()) {
      System.out.println("receive server response decode failure.");
      return;
    }

    HttpXmlResponse<Order> response = new HttpXmlResponse(msg, decoder0(ctx, msg.content()));
    out.add(response);
  }
}


package com.nextcontrols.domain;

public class ContactTypeDetails implements java.io.Serializable  {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
    private int contactType;
    private String contactString;
	private String iconName;

	public ContactTypeDetails() {
	}
	public ContactTypeDetails(int contactType, String contactString,
			String iconName) {
		super();
		this.contactType = contactType;
		this.contactString = contactString;
		this.iconName = iconName;
	}
	public int getContactType() {
		return contactType;
	}
	public void setContactType(int contactType) {
		this.contactType = contactType;
	}
	public String getContactString() {
		return contactString;
	}
	public void setContactString(String contactString) {
		this.contactString = contactString;
	}
	public String getIconName() {
		return iconName;
	}
	public void setIconName(String iconName) {
		this.iconName = iconName;
	}

}


package com.xdarkdog.web.controller.interceptor;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;

/**
 * <pre>
 * 负责对请求的参数进行拦截，作如下的工作：
 * 1. 将param中的参数重新设置到attribute中，可以做到参数穿透
 * 2. 参数合法性做通用的验证
 * </pre>
 *
 * @author hzr
 */
public class ParamInterceptor implements Interceptor {

	/* 需要穿透的参数名称集合 */
	private static final Set<String> THROUGH_PARAMS = new HashSet<String>();

	static {
		THROUGH_PARAMS.add("fromUrl");
	}

	@Override
	public void intercept(ActionInvocation ai) {

		// 1. 参数穿透
		Controller controller = ai.getController();
		for (String thoughParam : THROUGH_PARAMS) {
			String param = controller.getPara(thoughParam);
			if (StringUtils.isNotEmpty(param)) {
				controller.setAttr(thoughParam, param.trim());
			}
		}

		ai.invoke();
	}
}


package com.northmeter.meshbluecontrol.bluetooth.bluetooth.tools;

/**
 * Created by benjamin on 16/4/27.
 */
public class Tool {
    public static String printBytes(byte[] bytes){
        String s = "";
        for(int i=0;i<bytes.length;i++){
            if(i!=bytes.length-1){
                s += Integer.toHexString(bytes[i] & 0x00ff)+"-";
            }else{
                s += Integer.toHexString(bytes[i] & 0x00ff);
            }
        }
        return s;
    }

    public static byte[] decodeStringTo16(String source){
        byte[] result = new byte[0];
        try {
            String[] temp = source.split("-");

            result = new byte[0];
            result = new byte[temp.length];
            for(int i=0;i<temp.length;i++){
                result [i] = (byte)Integer.parseInt(temp[i],16);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return result;
    }
}


package com.riftlabs.communicationlib.concurrency;

import com.riftlabs.communicationlib.api.datatypes.KickDatagramPacket;
import com.riftlabs.communicationlib.utils.Log;

/**
 * The Class CommunicationPacket is to wrap the KickDatagramPacket
 */
public class CommunicationPacket implements KickConcurrentPacket {

	private static final String TAG = CommunicationPacket.class.getName();
	private KickDatagramPacket mDatagramPacket;
	private boolean locked = false;

	@Override
	public synchronized void setPacket(KickDatagramPacket datagramPacket) {
		if (datagramPacket != null) {
			while (locked == true) {
				try {
					wait();
				} catch (InterruptedException e) {
					Log.v(TAG, "Interrupted exception", e);
				}
			}
		}
		mDatagramPacket = datagramPacket;
		locked = true;
	}

	@Override
	public synchronized KickDatagramPacket getPacket() {
		return mDatagramPacket;
	}

	public synchronized void releaseLock() {
		locked = false;
		notifyAll();
	}
}


package su.msk.jet.phonebook.configs;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import su.msk.jet.phonebook.config.AppDataBaseConfig;

import java.nio.charset.StandardCharsets;

@Configuration
@Import({WebConfig.class, AppDataBaseConfig.class})
@ComponentScan({"su.msk.jet.phonebook.service", "su.msk.jet.phonebook.dao", "su.msk.jet.phonebook.mapper"})
@PropertySource(value = "classpath:application.properties")
public class AppConfig {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setUseCodeAsDefaultMessage(true);
        messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
        return messageSource;
    }

}


package cap.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private File file;
	private String fileFileName;

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String execute() throws Exception {
		InputStream is = new FileInputStream(file);
		OutputStream os = new FileOutputStream("F:\\" + fileFileName);
		byte[] buffer = new byte[1024];
		int length = 0;
		while ((length = is.read(buffer)) != -1) {
			os.write(buffer, 0, length);
		}
		os.close();
		is.close();
		return SUCCESS;
	}

}


package com.example.drools.RuleEngine.Service;

import com.example.drools.RuleEngine.Config.DroolsStartUp;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;

@Service
public class DroolsSharder {

    @Autowired
    private Environment environment;

    @Autowired
    private DroolsStartUp droolsConfig;

    public final static Long TOTAL_SHARDS = 1L;

    KnowledgeBuilder getShard(Long ruleId) {
        return droolsConfig.getKnowledgeBuilders().get((int) (ruleId % TOTAL_SHARDS));
    }

    ArrayList<KieSession> getKieSessions() {
        try {
            return droolsConfig.getKieSessions();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


package com.ads.dagger.modules;

import com.ads.countries.interactor.CountryListInteractor;
import com.ads.countries.presenter.CountryListPresenter;
import com.ads.countries.presenter.CountryListPresenterImpl;
import com.ads.countries.view.CountryListView;

import dagger.Module;
import dagger.Provides;

/**
 * Created by bah on 9/21/15.
 */
@Module
public class CountryListModule {

    private CountryListView countryListView;

    public CountryListModule(CountryListView countryListView) {
        this.countryListView = countryListView;
    }

    @Provides
    public CountryListView provideCountryListView() {
        return countryListView;
    }

    @Provides
    public CountryListPresenter provideCountryListPresenter(CountryListView countryListView,
                                                            CountryListInteractor countryListInteractor) {
        return new CountryListPresenterImpl(countryListView, countryListInteractor);
    }
}


package id.co.rumahcoding.myquran.utils;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.support.v4.app.NotificationCompat;

import id.co.rumahcoding.myquran.R;

/**
 * Created by blastocode on 4/7/16.
 */
public class NotificationUtil {
    public static void showNotification(Context context, PendingIntent pendingIntent, String message) {
        NotificationCompat.Builder builder  = new NotificationCompat.Builder(context)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(message)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, builder.build());
    }
}


package lab3.service;

import lab3.Launcher;
import lab3.ui.MainFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Controller implements ActionListener {
    private MainFrame view;
    private AddressBook addressBook;

    public static void main(String[] args) {
        Launcher launcher = new Launcher();
        launcher.launch();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        BuddyInfo buddyInfo;
        try {
            buddyInfo = new BuddyInfo(view.getFullName(), view.getAddress(), view.getPhone());
            addressBook.addBuddy(buddyInfo);
            view.clearForm();
            view.display(addressBook);
        } catch (Exception ex) {
            System.out.println("Error");
        }
    }

    public void setView(MainFrame view) {
        this.view = view;
    }

    public void setAddressBook(AddressBook addressBook) {
        this.addressBook = addressBook;
    }
}


package com.karimun.fordperformanceact;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.support.v7.widget.Toolbar;

public class EventPhotosActivity extends AppCompatActivity{

    @Override
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_photos);

        Toolbar toolbar = findViewById(R.id.event_photos_toolbar);
        setSupportActionBar(toolbar);

        if(getSupportActionBar()!= null){
            getSupportActionBar().setTitle("");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            toolbar.setNavigationOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View view){
                    finish();
                }
            });
        }
    }
}


package com.pandatv.user.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.pandatv.base.BaseActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Yuan on 2017/9/20.
 */

public class RegisterAdapter extends FragmentPagerAdapter {
    private List<Fragment> list;
    private final ArrayList<String> titleList;

    public RegisterAdapter(FragmentManager fm, List<Fragment> list) {
        super(fm);
        this.list = list;
        titleList = new ArrayList<>();
        titleList.add("手机注册");
        titleList.add("邮箱注册");
    }

    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titleList.get(position);
    }
}


# js_env_demo
#### Following along Pluralsight: Building a JavaScript Development Enviornment Course
Components
* .editorconfig: settings for ide editor
* Package Manager: npm
* sharing work in progress: localtunnel, ngrock, now, surge
	* lets you expose app running from local machine globally
* Javascript automation: grunt, gulp, npm scripts
* Transpiling: babel
* Bundling: ES6 modules + webpack
* Sourcemaps. Maps transpiled code back to the original source
	* generated as part of our build
* Linting. ESLint
	* enforce consistency
	* avoid mistakes
	* has eslint plugins + presets
* Testing + Continuous Integration:
	* Mocha
	* Assertion library: chai
	* Helper library: jsdom, cheerio
	* Test Runners: PhantomJS, JSDOM
* Continuous Integration: TravisCI, Appveyor
* Mock HTTP Calls
	* JSON Schema Faker
	* faker.js, chance.js, randexp.js
* Http Calls:
	* Browser: fetch
	* Node: http, request
	* Node and Browser: Axios
* Error Logging. TrackJS


package com.summer.digest;

import com.summer.digest.dao.AuthorDao;
import com.summer.digest.dao.BookDao;
import com.summer.digest.entity.Author;
import com.summer.digest.entity.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DigestApplicationTests {

    @Resource
    AuthorDao authorDao;

    @Resource
    BookDao bookDao;

    @Test
    public void contextLoads() {

    Author author = authorDao.findById(1);
    Book book = new Book();
    book.setAuthor(author);
    book.setLookCount(0);
    book.setBookName("云边有个小卖部");
    book.setContent("现在的问题是，在页面保存一个product时，传进来的dic是id值，" +
            "是不能直接转换成dic的所以只能在product里增加一个冗余字段dicid，" +
            "但是这样的话spring data jpa会自动在数据表里新增一个字段，但是");
    bookDao.save(book);
    }

}


## React Router v4 Example

[![Greenkeeper badge](https://badges.greenkeeper.io/jaredwilli/react-router4-example.svg)](https://greenkeeper.io/)
[![dependencies Status](https://david-dm.org/jaredwilli/react-router4-example/status.svg)](https://david-dm.org/jaredwilli/react-router4-example)

## Overview
_____

This is a bare bones React Router 4 example app that shows how to use the new version of the router and how routes are defined for child routes.

It's pretty basic and straight-forward. I intend to keep the dependencies up-to-date for this repository, at least for a little while. That way anyone looking for a _WORKING_ example of react-router4, they will be able to see an actual working example that uses the most recent updates for dependencies.

You can see a demo of this at: [http://react-router4.surge.sh](http://react-router4.surge.sh/)

## License
-----

[MIT License](https://github.com/jaredwilli/react-router4-example/blob/master/LICENSE)


package com.oauth.accesstoken.redis.service;

import java.util.Optional;

import com.oauth.accesstoken.redis.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.oauth.accesstoken.redis.repository.UserRepository;

@Service
@Transactional
public class UserService {
	@Autowired
	private UserRepository repository;

	public void save(UserEntity entity) {
		repository.save(entity);
	}

	@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
	public UserEntity findOne(String username) {
		Optional<UserEntity> userEntityOption = repository.findById(username);
		if (userEntityOption.isPresent() == false) {
			return null;
		}
		UserEntity userEntity = userEntityOption.get();
		userEntity.getRoles().size();
		return userEntity;
	}

}


package Monsters;

public class Zombie extends Monster {
	private String name;
	private int zombieEnergy;
	private int zombieDamage;

	public Zombie(String name, int energy, int damage) {
		this.name = name;
		this.zombieEnergy = energy;
		this.zombieDamage = damage;
	}

	public String getName() {
		return name;
	}

	public int getZombieEnergy() {
		return zombieEnergy;
	}

	public int getZombieDamage() {
		return zombieDamage;
	}

	@Override
	public int attack() {
		System.out.println(getName() + " attacks you. Damage: " + getZombieDamage());
		return zombieDamage;
	}

	@Override
	public boolean isDead() {
		if (zombieEnergy <= 0)
			return true;
		else
			return false;
	}

	@Override
	public void isAttacked(int damage) {
		zombieEnergy -= damage;
		System.out.println();
		System.out.println("Nice work!");
		if (isDead())
			System.out.println("You killed a " + getName() + "! Well done :)");

	}

}


package com.road.pilot.security;

import com.road.pilot.domain.User;
import com.road.pilot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Created by road on 16. 12. 12.
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(username);
        if(user == null) {
            return null;
        }

        CustomUserDetails userDetails = new CustomUserDetails(user);

        return userDetails;
    }
}


package org.jagodzinskikacper.renataslibrary.book;

import org.jagodzinskikacper.renataslibrary.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
@Transactional
public class BookService {

    private final BookRepository bookRepository;

    @Autowired
    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    void saveBook(Book book) {
        bookRepository.save(book);
    }

    List<Book> findBooksByUser(User user) {
        return bookRepository.findBooksByUser(user);
    }

    Book findBookById(Long id) {
        return bookRepository.findBookById(id);
    }

    void update(Book book) {
        bookRepository.save(book);
    }

    List<Book> findBooksByUserIsNot(User user) {
        return bookRepository.findBooksByUserIsNot(user);
    }

}


package com.inn.controller.impl;

import com.inn.controller.IEmployeeRest;
import com.inn.model.Employee;
import com.inn.service.IEmployeeService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("employee")
@Slf4j
public class EmployeeRestImpl implements IEmployeeRest {

    @Autowired
    private IEmployeeService employeeService;

    @SneakyThrows
    @Override
    public Employee create(Employee empDetails) {
        return employeeService.create(empDetails);
    }

    @SneakyThrows
    @Override
    public Employee update(Employee empDetails) {
        return employeeService.update(empDetails);
    }

    @SneakyThrows
    @Override
    public void delete(Integer id) {
         employeeService.delete(id);
    }
}


package com.chongdao.client.entitys;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;

/**
 * @Author onlineS
 * @Description 订单奖励
 * @Date 9:06 2019/4/19
 */
@Setter
@Getter
@NoArgsConstructor
public class RewardSystem implements Serializable {
   private static final long serialVersionUID = 1L;

   //商家的id
    private Integer shopid;
   //起始单(从第几单开始算奖励)
    private Integer actually;
    //终止单(第几单结束奖励)
    private Integer termination;
    //奖励金额
    private Integer AmountOfMoney;
    //活动开始时间
    private String startTime;
    //活动结束时间
    private String EndTime;

 @Override
 public String toString() {
  return "RewardSystem{" +
          "shopid=" + shopid +
          ", actually=" + actually +
          ", termination=" + termination +
          ", AmountOfMoney=" + AmountOfMoney +
          ", startTime='" + startTime + '\'' +
          ", EndTime='" + EndTime + '\'' +
          '}';
 }
}


import javafx.application.Application;
import javafx.stage.Stage;

public class MyATM extends Application
{

	public static void main(String[] args) {
		launch(args);
		}

     @Override
	public void start(Stage primaryStage) throws Exception {
    	 ProgramLogic amount1=new ProgramLogic();
    	 primaryStage.setTitle("ATM");
    	 UserInfo user=new UserInfo(primaryStage);
    	 MainMenu menu=new MainMenu(primaryStage,amount1);
    	 WithDraw withdraw=new WithDraw(primaryStage,amount1);
    	 Deposit deposit=new Deposit(primaryStage,amount1);

    	 user.prepareScene();
    	 menu.prepareScene();
    	 withdraw.preparescene();
    	 deposit.preparescene();

    	 user.setMenu(menu);
    	 menu.setWithdraw(withdraw);
    	 menu.setDeposit(deposit);
    	 withdraw.setMenu(menu);
    	 deposit.setMenu(menu);

    	 primaryStage.setScene(user.getScene());
		 primaryStage.show();

	}

}


package org.smartlearning.domain.content.goTop;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.smartlearning.configuration.RootConfig;
import org.smartlearning.domain.user.extenders.SystemUserStatistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.*;

/**
 * @Author
 * Karol Meksuła
 * 24-03-2018
 * */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RootConfig.class)
public class GoToTopImplTest {
    private final long USER_ID = 1;

    @Autowired
    private GoToTop goToTop;

    @Test
    public void notNullTest() {
        assertNotNull(goToTop);
    }

    @Test
    public void shouldCorrectlyFetchDataFromDB() {
        goToTop.getStats(USER_ID);
    }

    @Test
    public void shouldCorrectlyReturnData() {

    }

}


package com.study.utils.volley;

import java.util.HashMap;

/**
 * 说明：存放参数（请求头，请求参数）对象
 * <p>
 * date: 2020/5/2 16:19
 *
 * @author syd
 * @version 1.0
 */
@SuppressWarnings("WeakerAccess")
public class Parameter extends HashMap<String, String> {

    /**
     * 添加参数
     *
     * @param key   key
     * @param value value
     * @return this
     */
    public Parameter add(String key, String value) {
        put(key, value);
        return this;
    }

    /**
     * 参数拼接 user=syd&age=18
     *
     * @return string
     */
    public String toParameterString() {
        StringBuilder result = new StringBuilder();
        for (Entry<String, String> entry : entrySet()) {
            result.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if (result.toString().endsWith("&")) {
            result = new StringBuilder(result.substring(0, result.length() - 1));
        }
        return result.toString();
    }
}


package com.crui.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.crui.entity.Result;
import com.crui.pojo.user.User;
import com.crui.service.user.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    @GetMapping("sendSms")
    public Result sendSms(String phone){
        userService.sendSms(phone);
        return new Result();
    }

    @PostMapping("/save")
    public Result save(@RequestBody User user, String smsCode){
        //密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String newPass = encoder.encode(user.getPassword());
        System.out.println("passwprd:"+newPass);
        user.setPassword(newPass);

        userService.add(user,smsCode);
        return new Result();
    }
}


package me.pauloferreira.catcli.service;

import java.awt.*;
import java.io.IOException;
import java.net.URISyntaxException;

import me.pauloferreira.catcli.exception.CatException;

public class BrowserService {

  private Desktop desktop;

  /**
   * @throws CatException if desktop or browse action not supported
   */
  public BrowserService() {
    if (!java.awt.Desktop.isDesktopSupported()) {
      throw new CatException("Desktop not supported");
    }

    desktop = Desktop.getDesktop();

    if (!desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
      throw new CatException("Desktop doesn't support the \"browse\" action");
    }
  }

  /**
   * @throws CatException if invalid url is passed or the browser fails to be launched
   */
  public void openUrl(String url) {
    try {
      desktop.browse(new java.net.URI(url));
    } catch (IOException | URISyntaxException e) {
      throw new CatException("Could not open browser", e);
    }
  }
}


package com.company;

public class SkiTrip extends Trip {

    //Fields
    private int slopes;
    private int lifts;

    public SkiTrip(String destination, int duration, String hotel, int price, int slopes, int lifts) {
        super(destination, duration, hotel, price);
        this.slopes = slopes;
        this.lifts = lifts;
    }

    public void setSlopes(int slopes) {
        this.slopes = slopes;
    }

    public void setLifts(int lifts) {
        this.lifts = lifts;
    }

    public int getSlopes() {
        return slopes;
    }

    public int getLifts() {
        return lifts;
    }

    @Override
    public String toString() {
        return "SkiTrip{" +
                "destination='" + destination + '\'' +
                ", duration=" + duration +
                ", hotel='" + hotel + '\'' +
                ", price=" + price +
                ", slopes=" + slopes +
                ", lifts=" + lifts +
                '}';
    }
}


package com.examples.demos.topic;

import javax.persistence.Entity;
import javax.persistence.Id;

import com.fasterxml.jackson.annotation.JsonProperty;

@Entity
public class Topic {

    @Id
    private String id;
    private String name;
    private String description;

    public Topic() {

    }

    public Topic(@JsonProperty("id") String id, @JsonProperty("name") String name,
            @JsonProperty("description") String description) {
        this.id = id;
        this.name = name;
        this.description = description;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}


public class Solution {
    static DoublyLinkedListNode sortedInsert(DoublyLinkedListNode head, int data) {
        DoublyLinkedListNode node = new DoublyLinkedListNode(data);
        DoublyLinkedListNode temp = head;
        boolean isInserted = false;

        if(head.data > data){
            node.next = head;
            node.prev = null;
            head.prev = node;
            head = node;
            isInserted = true;
        }

        while(!isInserted & temp.next != null){
            temp = temp.next;
            if(temp.data > data){
                DoublyLinkedListNode prev = temp.prev;
                prev.next = node;
                node.next = temp;

                temp.prev = node;
                node.prev = prev;

                isInserted = true;

            }

        }

        if(!isInserted){
            node.prev = temp;
            temp.next = node;
            node.next = null;
        }
        return head;

    }
}


# Developing

To setup your development environment run:

```
git clone git@github.com:angular/angular
cd devtools
yarn
```

To run the extension in development mode run:

```
ng serve
```

This would start a development server that you can access on <http://localhost:4200>. In development, Angular DevTools uses a "development shell." This is different from "chrome shell" in a way, that it runs the user's app in an iframe. DevTools then communicate with the user's app via message passing.

## Building the extension

To build the Angular DevTools Chrome extension run:

```
npm run release
```

This would output the production assets of the app in `dist/shell-browser`. If you want to build the extension with development settings (i.e., not minified sources), just run:

```
ng build shell-browser
```

Later on, you can install the extension from `dist/shell-browser` following the guide from [here](https://developer.chrome.com/apps/external_extensions).


package com.springapp.socialnet.controller;

import com.springapp.socialnet.model.Position;
import com.springapp.socialnet.service.PositionService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/position")
public class PositionController {

    private final PositionService service;

    public PositionController(PositionService service) {
        this.service = service;
    }

    @GetMapping
    public String positionForm(@RequestParam("compId") int compId, Model model) {
        model.addAttribute("compId", compId);
        model.addAttribute("position", new Position());
        return "positionForm";
    }

    @PostMapping
    public String addPositionNode(@RequestParam("compId") int compId, @ModelAttribute Position position, Model model) {
        service.addPosition(compId, position);
        return "redirect:/company/all";
    }
}


package com.example.firstbutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // This pulls up the xml document where we defined the button.  Without this, we will not be able to find our button.
        Button button = findViewById(R.id.toast); // Here we find the button we defined earlier in our xml and assign it to a variable of type Button
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Yay, our button works!", Toast.LENGTH_SHORT).show(); //Toast message
            }
        });

    }
}


package com.zkw.concurrent.java_Multithread_programmingbook.c3_1.c3_1_8;

import com.zkw.concurrent.java_Multithread_programmingbook.c3_1.c3_1_3.third.ThreadA;

/**
 * 注：说是超过wait(timeout)的timeout时间后自动唤醒，可是不是这样的。
 *
 * @author James
 * @create 2017-09-11 下午 8:36
 **/

public class MyRunnable {
    static private Object lock=new Object();
    static private Runnable runnable1=new Runnable() {
        public void run() {
            try {

                synchronized (lock){
                    System.out.println("wait begin timer="+System.currentTimeMillis());
                    lock.wait(0);
                    System.out.println("wait end timer="+System.currentTimeMillis());
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    public static void main(String[] args) {
        Thread t=new ThreadA(runnable1);
        t.start();
    }
}


package org.NooLab.somfluid.core.engines.det;

import java.util.SortedMap;
import java.util.TreeMap;

import org.NooLab.somfluid.lattice.VirtualLattice;
import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.bidimap.DualHashBidiMap;

/**
 *
 * this class maintains dispatching lists
 * - which node of a SOM is processed on which processor core
 * - which metrices are checked in evo-devo on which machine
 *
 * for each processor there is a dedicated class
 *
 *
 */
public class MultiprocDispatcher {

	DSom dSom;
	private VirtualLattice somLattice;

	SortedMap<Integer,Integer>  NodeCoreMap = new TreeMap<Integer,Integer>();

	// ========================================================================
	public MultiprocDispatcher(DSom dsom) {

		dSom = dsom;

		somLattice = dSom.getSomLattice() ;

	}
	// ========================================================================

}


package com.hanky.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateUtils {
    public static String getTransDate(){
        final LocalDate date = LocalDate.now();
        return date.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

    }

    /**
     * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }

    public static void main(String[] args) {
        String transDate = DateUtils.getTransDate();
        System.out.println(transDate);
    }

}


package org.vidi.spark.demo.sql;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.SQLContext;

/**
 * @author vidi
 * @date 2019-03-28
 */
public class JSONDataSource {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf()
                .setAppName("JavaJsonDataSource")
                .setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(conf);
        SQLContext sqlContext = new SQLContext(sc);

        DataFrame employeeDF = sqlContext.read().format("json").load("/Users/tanglei/workplace/about_hadoop/spark1-demo/data/employee.json");
        employeeDF.registerTempTable("employee");

        DataFrame df = sqlContext.sql("select * from employee where salary > 18000");
        df.show();
        df.write().json("/Users/tanglei/workplace/about_hadoop/spark1-demo/data/result");
        sc.close();
    }
}


# Javascript Notes App

<img src="https://user-images.githubusercontent.com/71288920/111700580-7f924700-8831-11eb-9b5c-fa39d1e5ad51.gif" width="400" border="1">

## Requirements
```
As a programmer
I can see a list of my notes, where each note is abbreviated to the first 20 characters
So I can find the one I want

As a programmer
I can create a new note
So I can record something I need to remember

As a programmer
I can see the full text of an individual note on its own page
So I can see all the information in the note

As a programmer
I can use shortcodes like `:fire:` that get converted into emojis like 🔥
So I can record notes with fun little pictures

As a programmer
I can refresh the page and still see my notes
So I can remember what I took down
```
## Concepts applied
* Frontend, single page web apps.
* Events and event handlers.
* Manipulating the Document Object Model (DOM).
* Asynchronous requests.
* Frontend templating.
* Frontend routing.


package p2pcrwal.rpc;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.StandardProtocolFamily;
import java.net.StandardSocketOptions;
import java.nio.channels.DatagramChannel;

/**
 * Created by BFD_702 on 2017/6/7.
 */
public class SocketHandler {
    DatagramChannel datagramChannel ;
    private  InetAddress addr ;
    private int port ;
    void start(){
        try {
            datagramChannel = DatagramChannel.open(StandardProtocolFamily.INET) ;
            datagramChannel.configureBlocking(false) ;
            datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, 2*1024*1024);   //设置缓冲区大小
            datagramChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);       //一个端口释放后会等待两分钟之后才能再被使用，SO_REUSEADDR是让端口释放后立即就可以被再次使用
            datagramChannel.bind(new InetSocketAddress(addr, port)) ;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


/*
*Wendy Mei
*CISC 3150
*HW 9
* DID NOT Work
*
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class HomeworkNine {
	public static void main(String [] args){
		String [] arr1={"A", "E", "I", "M", "Q", "U", "Y"};
		String [] arr2={"B", "F", "J", "N", "R", "V", "Z"};
		String [] arr3={"C", "G", "K", "O", "S", "W"};
		String [] arr4={"D", "H", "L", "P", "T", "X"};
		try{
		Thread t1=new Thread(new datas(arr1));
		Thread t2=new Thread(new datas(arr2));
		Thread t3=new Thread(new datas(arr3));
		Thread t4=new Thread(new datas(arr4));
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t1.join(1000);
		t2.join(1000);
		t3.join(1000);
		t4.join(1000);
		}
		catch(InterruptedException e){

		}
	}
}
class datas implements Runnable{
	String []arrays;
	public datas(String [] a){
		this.arrays=a;
	}
	public void run(){
		for(int i=0;i<arrays.length;i++){
			System.out.println(arrays[i]);
		}
	}
}


package io.paratek.tut.modules.n_nodes;

import io.paratek.api.util.Chatbox;
import io.paratek.fw.ParaScript;
import io.paratek.fw.handler.node.Node;
import org.osbot.rs07.api.ui.RS2Widget;

import java.util.ArrayList;

/**
 * @author Parametric on 5/5/2018
 * @project OSBot-Framework
 */
public class HandleDialogNode implements Node {

    private Chatbox chatbox;

    private final ArrayList<String> options = new ArrayList<>();
    private final String[] strings;

    public HandleDialogNode() {
        options.add("I've played in the past, but not recently.");
        this.strings = this.options.toArray(new String[this.options.size()]);
    }

    @Override
    public boolean activate(ParaScript ctx) {
        this.chatbox = new Chatbox(ctx);
        return this.chatbox.isOpen();
    }

    @Override
    public boolean execute(ParaScript ctx) throws InterruptedException {
        this.chatbox.complete(this.strings);
        return true;
    }

}