text
stringlengths 10
2.72M
|
|---|
package com.fudanscetool.springboot.service;
import com.fudanscetool.springboot.dao.HistoryProjectDAO;
import com.fudanscetool.springboot.dao.HistoryStage1DAO;
import com.fudanscetool.springboot.dao.HistoryStage2DAO;
import com.fudanscetool.springboot.dao.HistoryStage3DAO;
import com.fudanscetool.springboot.pojo.*;
import org.elasticsearch.common.util.ESSloppyMath;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class AnalogyModel implements EstimateModel {
static boolean isTrain = false;
EstimateSystemService es = new EstimateSystemService();
ProjectService ps = new ProjectService();
@Autowired
private HistoryProjectDAO hdao;
@Autowired
private HistoryStage1DAO h1dao;
@Autowired
private HistoryStage2DAO h2dao;
@Autowired
private HistoryStage3DAO h3dao;
@Override
public void train() {
return ;
}
@Override
public double estimateStage1(double weight, Stage1 stage) {
List<HistoryProject> allHistoryProject = hdao.searchAllHistoryProject();
double[] distance = new double[allHistoryProject.size()];
double maxsize = 0;
double minsize = 100000000;
double maxweight = 0;
double minweight = 100000000;
EstimateSystemService es = new EstimateSystemService();
for (int i = 0; i < allHistoryProject.size(); i++) {
HistoryProject hp = allHistoryProject.get(i);
HistoryStage1 hs = h1dao.searchHistoryStage1(hp.getProjectID());
if (hs.getSize() > maxsize)
maxsize = hs.getSize();
if (hs.getSize() < minsize)
minsize = hs.getSize();
if (es.getHistoryProjectWeight(hp) > maxweight)
maxweight = es.getHistoryProjectWeight(hp);
if (es.getHistoryProjectWeight(hp) < minweight)
minweight = es.getHistoryProjectWeight(hp);
}
for (int i = 0; i < allHistoryProject.size(); i++) {
HistoryProject hp = allHistoryProject.get(i);
HistoryStage1 hs = h1dao.searchHistoryStage1(hp.getProjectID());
double sizedis = Math.pow(Math.abs(stage.getSize() - hs.getSize()) / (maxsize - minsize), 2);
double weightsize = Math.pow(Math.abs((weight - es.getHistoryProjectWeight(hp)) / maxweight - minweight), 2);
distance[i] = Math.sqrt((sizedis + weightsize) / 2);
}
double mindis = 1000000000;
double load = 0;
for (int i = 0; i < allHistoryProject.size(); i++) {
if (distance[i] < mindis) {
mindis = distance[i];
load = allHistoryProject.get(i).getRealLoad();
}
}
return load;
}
@Override
public double estimateStage2(double weight, Stage2 stage) {
List<HistoryProject> allHistoryProject = hdao.searchAllHistoryProject();
double[] distance = new double[allHistoryProject.size()];
double maxsize = 0;
double minsize = 100000000;
double maxweight = 0;
double minweight = 100000000;
EstimateSystemService es = new EstimateSystemService();
for (int i = 0; i < allHistoryProject.size(); i++) {
HistoryProject hp = allHistoryProject.get(i);
HistoryStage2 hs = h2dao.searchHistoryStage2(hp.getProjectID());
if (hs.getSize() > maxsize)
maxsize = hs.getSize();
if (hs.getSize() < minsize)
minsize = hs.getSize();
if (es.getHistoryProjectWeight(hp) > maxweight)
maxweight = es.getHistoryProjectWeight(hp);
if (es.getHistoryProjectWeight(hp) < minweight)
minweight = es.getHistoryProjectWeight(hp);
}
for (int i = 0; i < allHistoryProject.size(); i++) {
HistoryProject hp = allHistoryProject.get(i);
HistoryStage2 hs = h2dao.searchHistoryStage2(hp.getProjectID());
double sizedis = Math.pow(Math.abs(stage.getSize() - hs.getSize()) / (maxsize - minsize), 2);
double weightsize = Math.pow(Math.abs((weight - es.getHistoryProjectWeight(hp)) / maxweight - minweight), 2);
double[] em2 = new double[7];
em2[0] = Math.pow(Math.abs(ps.changeEMToRate("PCPX", stage.getPCPX()) - ps.changeEMToRate("PCPX", hs.getPCPX())) / (1.45 - 0.87), 2);
em2[1] = Math.pow(Math.abs(ps.changeEMToRate("RUSE", stage.getRUSE()) - ps.changeEMToRate("RUSE", hs.getRUSE())) / (1.10 - 0.87), 2);
em2[2] = Math.pow(Math.abs(ps.changeEMToRate("PDIF", stage.getPDIF()) - ps.changeEMToRate("PDIF", hs.getPDIF())) / (1.35 - 0.90), 2);
em2[3] = Math.pow(Math.abs(ps.changeEMToRate("PERS", stage.getPERS()) - ps.changeEMToRate("PERS", hs.getPERS())) / (1.23 - 0.90), 2);
em2[4] = Math.pow(Math.abs(ps.changeEMToRate("PREX", stage.getPREX()) - ps.changeEMToRate("PREX", hs.getPREX())) / (1.23 - 0.65), 2);
em2[5] = Math.pow(Math.abs(ps.changeEMToRate("FCIL", stage.getFCIL()) - ps.changeEMToRate("FCIL", hs.getFCIL())) / (1.23 - 0.89), 2);
em2[6] = Math.pow(Math.abs(ps.changeEMToRate("SCED", stage.getSCED()) - ps.changeEMToRate("SCED", hs.getSCED())) / (1.23 - 1.00), 2);
distance[i] = Math.sqrt((sizedis + weightsize + em2[0] + em2[1] + em2[2] + em2[3] + em2[4] + em2[5] + em2[6]) / 9);
}
double mindis = 1000000000;
double load = 0;
for (int i = 0; i < allHistoryProject.size(); i++) {
if (distance[i] < mindis) {
mindis = distance[i];
load = allHistoryProject.get(i).getRealLoad();
}
}
return load;
}
@Override
public double estimateStage3(double weight, Stage3 stage) {
List<HistoryProject> allHistoryProject = hdao.searchAllHistoryProject();
double[] distance = new double[allHistoryProject.size()];
double maxsize = 0;
double minsize = 100000000;
double maxweight = 0;
double minweight = 100000000;
EstimateSystemService es = new EstimateSystemService();
for (int i = 0; i < allHistoryProject.size(); i++) {
HistoryProject hp = allHistoryProject.get(i);
HistoryStage3 hs = h3dao.searchHistoryStage3(hp.getProjectID());
if (hs.getSize() > maxsize)
maxsize = hs.getSize();
if (hs.getSize() < minsize)
minsize = hs.getSize();
if (es.getHistoryProjectWeight(hp) > maxweight)
maxweight = es.getHistoryProjectWeight(hp);
if (es.getHistoryProjectWeight(hp) < minweight)
minweight = es.getHistoryProjectWeight(hp);
}
for (int i = 0; i < allHistoryProject.size(); i++) {
HistoryProject hp = allHistoryProject.get(i);
HistoryStage3 hs = h3dao.searchHistoryStage3(hp.getProjectID());
double sizedis = Math.pow(Math.abs(stage.getSize() - hs.getSize()) / (maxsize - minsize), 2);
double weightsize = Math.pow(Math.abs((weight - es.getHistoryProjectWeight(hp)) / maxweight - minweight), 2);
double[] em3 = new double[17];
em3[0] = Math.pow(Math.abs(ps.changeEMToRate("RELY", stage.getRELY()) - ps.changeEMToRate("RELY", hs.getRELY())) / (1.40 - 0.75), 2);
em3[1] = Math.pow(Math.abs(ps.changeEMToRate("DATA", stage.getDATA()) - ps.changeEMToRate("DATA", hs.getDATA())) / (1.16 - 0.93), 2);
em3[2] = Math.pow(Math.abs(ps.changeEMToRate("DOCU", stage.getDOCU()) - ps.changeEMToRate("DOCU", hs.getDOCU())) / (1.21 - 0.89), 2);
em3[3] = Math.pow(Math.abs(ps.changeEMToRate("CPLX", stage.getCPLX()) - ps.changeEMToRate("CPLX", hs.getCPLX())) / (1.30 - 0.70), 2);
em3[4] = Math.pow(Math.abs(ps.changeEMToRate("RUSE", stage.getRUSE()) - ps.changeEMToRate("RUSE", hs.getRUSE())) / (1.10 - 0.87), 2);
em3[5] = Math.pow(Math.abs(ps.changeEMToRate("TIME", stage.getTIME()) - ps.changeEMToRate("TIME", hs.getTIME())) / (1.30 - 0.98), 2);
em3[6] = Math.pow(Math.abs(ps.changeEMToRate("STOR", stage.getSTOR()) - ps.changeEMToRate("STOR", hs.getSTOR())) / (1.21 - 0.98), 2);
em3[7] = Math.pow(Math.abs(ps.changeEMToRate("PVOL", stage.getPVOL()) - ps.changeEMToRate("PVOL", hs.getPVOL())) / (1.30 - 0.86), 2);
em3[8] = Math.pow(Math.abs(ps.changeEMToRate("ACAP", stage.getACAP()) - ps.changeEMToRate("ACAP", hs.getACAP())) / (1.46 - 0.71), 2);
em3[9] = Math.pow(Math.abs(ps.changeEMToRate("AEXP", stage.getAEXP()) - ps.changeEMToRate("AEXP", hs.getAEXP())) / (1.29 - 0.82), 2);
em3[10] = Math.pow(Math.abs(ps.changeEMToRate("PCAP", stage.getPCAP()) - ps.changeEMToRate("PCAP", hs.getPCAP())) / (1.42 - 0.70), 2);
em3[11] = Math.pow(Math.abs(ps.changeEMToRate("PEXP", stage.getPEXP()) - ps.changeEMToRate("PEXP", hs.getPEXP())) / (1.86 - 1.00), 2);
em3[12] = Math.pow(Math.abs(ps.changeEMToRate("LTEX", stage.getLTEX()) - ps.changeEMToRate("LTEX", hs.getLTEX())) / (1.14 - 0.94), 2);
em3[13] = Math.pow(Math.abs(ps.changeEMToRate("PCON", stage.getPCON()) - ps.changeEMToRate("PCON", hs.getPCON())) / (1.24 - 0.82), 2);
em3[14] = Math.pow(Math.abs(ps.changeEMToRate("TOOL", stage.getTOOL()) - ps.changeEMToRate("TOOL", hs.getTOOL())) / (1.23 - 1.00), 2);
em3[15] = Math.pow(Math.abs(ps.changeEMToRate("SCED", stage.getSCED()) - ps.changeEMToRate("SCED", hs.getSCED())) / (1.23 - 1.00), 2);
em3[16] = Math.pow(Math.abs(ps.changeEMToRate("SITE", stage.getSITE()) - ps.changeEMToRate("SITE", hs.getSITE())) / (1.10 - 0.90), 2);
distance[i] = Math.sqrt((sizedis + weightsize + em3[0] + em3[1] + em3[2] + em3[3] + em3[4] + em3[5] + em3[6] + em3[7] + em3[8] + em3[9] + em3[10] + em3[11] + em3[12] + em3[13] + em3[14] + em3[15] + em3[16]) / 9);
}
double mindis = 1000000000;
double load = 0;
for (int i = 0; i < allHistoryProject.size(); i++) {
if (distance[i] < mindis) {
mindis = distance[i];
load = allHistoryProject.get(i).getRealLoad();
}
}
return load;
}
}
|
package com.ants.theantsgo.base.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* ====================================
* 作者:DUKE_HwangZj
* 日期:2018/5/17
* 时间:20:00
* 描述:所有ListView和GridView的适配器的父类
* 修改:
* 说明:
* ====================================
*/
public abstract class BaseAdapterForLvOrGv<T> extends BaseAdapter {
private List<T> list = new ArrayList<>();
protected Context context;
protected LayoutInflater inflater;
public BaseAdapterForLvOrGv(Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return list.size();
}
@Override
public T getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
public void updata(List<T> data) {
list.addAll(data);
notifyDataSetChanged();
}
public void clear() {
list.clear();
notifyDataSetChanged();
}
public void removeItem(int i) {
if (i < 0 || i >= list.size())
return;
list.remove(i);
notifyDataSetChanged();
}
public List<T> getList() {
return list;
}
}
|
package com.emiza.service;
import com.emiza.exception.DivideByZero;
import com.emiza.exception.IntegerOutOfLimit;
import com.emiza.exception.InvalidOperator;
import com.emiza.mathOperation.Divide;
import com.emiza.mathOperation.MathsOp;
import com.emiza.mathOperation.Modulus;
import com.emiza.mathOperation.Multiply;
import com.emiza.mathOperation.Subtract;
public class OperationFactory {
private MathsOp mOp;
public MathsOp getmOp() {
return mOp;
}
public OperationFactory(int pOperand1, int pOperand2, char pOperator) throws IntegerOutOfLimit, InvalidOperator {
pOperator = Character.toUpperCase(pOperator);
switch (pOperator) {
case 'P':
this.mOp = new MathsOp(pOperand1, pOperand2);
break;
case 'S':
this.mOp = new Subtract(pOperand1, pOperand2);
break;
case 'M':
this.mOp = new Multiply(pOperand1, pOperand2);
break;
case 'D':
if (pOperand2 == 0) {
throw new DivideByZero();
}
this.mOp = new Divide(pOperand1, pOperand2);
break;
case 'N':
if (pOperand2 == 0) {
throw new DivideByZero();
}
this.mOp = new Modulus(pOperand1, pOperand2);
break;
default:
throw new InvalidOperator();
}
}
public float calculate() throws InvalidOperator, IntegerOutOfLimit {
return mOp.operate();
}
public String getmSign() {
System.out.println(this.mOp.getmSign());
return this.mOp.getmSign();
}
}
|
package edu.epam.training.task3.entity;
public class Matrix {
private static int[][] matrix;
private static final Matrix INSTANCE = new Matrix();
public static Matrix getInstance(){
return MatrixHolder.INSTANCE;
}
private Matrix() {}
public void setElement(int element, int i, int j){
matrix[i][j] = element;
}
public int[][] getMatrix() {
return matrix;
}
public void setMatrix(int[][] matrix) {
this.matrix = matrix;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("\n");
for (int[] row : matrix) {
for (int elem : row) {
sb.append(elem);
sb.append(" ");
}
sb.append("\n");
}
return sb.toString();
}
private static class MatrixHolder{
private static final Matrix INSTANCE = new Matrix();
}
}
|
package TST_teamproject.team.model;
public class TeamBoardVo {
private int no;
private int tst_team_notice_board_no;
private String tst_user_nickname;
private String tst_team_notice_board_title;
private String tst_team_notice_board_content;
private int tst_team_no;
private int tst_team_notice_board_view;
private int tst_team_notice_board_max;
private String tst_team_notice_board_del;
private String tst_team_notice_insert_date;
private String tst_team_notice_modify_date;
private int teammembers;
private int team_members_view;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public int getTst_team_notice_board_no() {
return tst_team_notice_board_no;
}
public void setTst_team_notice_board_no(int tst_team_notice_board_no) {
this.tst_team_notice_board_no = tst_team_notice_board_no;
}
public String getTst_user_nickname() {
return tst_user_nickname;
}
public void setTst_user_nickname(String tst_user_nickname) {
this.tst_user_nickname = tst_user_nickname;
}
public String getTst_team_notice_board_title() {
return tst_team_notice_board_title;
}
public void setTst_team_notice_board_title(String tst_team_notice_board_title) {
this.tst_team_notice_board_title = tst_team_notice_board_title;
}
public String getTst_team_notice_board_content() {
return tst_team_notice_board_content;
}
public void setTst_team_notice_board_content(String tst_team_notice_board_content) {
this.tst_team_notice_board_content = tst_team_notice_board_content;
}
public int getTst_team_no() {
return tst_team_no;
}
public void setTst_team_no(int tst_team_no) {
this.tst_team_no = tst_team_no;
}
public int getTst_team_notice_board_view() {
return tst_team_notice_board_view;
}
public void setTst_team_notice_board_view(int tst_team_notice_board_view) {
this.tst_team_notice_board_view = tst_team_notice_board_view;
}
public int getTst_team_notice_board_max() {
return tst_team_notice_board_max;
}
public void setTst_team_notice_board_max(int tst_team_notice_board_max) {
this.tst_team_notice_board_max = tst_team_notice_board_max;
}
public String getTst_team_notice_board_del() {
return tst_team_notice_board_del;
}
public void setTst_team_notice_board_del(String tst_team_notice_board_del) {
this.tst_team_notice_board_del = tst_team_notice_board_del;
}
public String getTst_team_notice_insert_date() {
return tst_team_notice_insert_date;
}
public void setTst_team_notice_insert_date(String tst_team_notice_insert_date) {
this.tst_team_notice_insert_date = tst_team_notice_insert_date;
}
public String getTst_team_notice_modify_date() {
return tst_team_notice_modify_date;
}
public void setTst_team_notice_modify_date(String tst_team_notice_modify_date) {
this.tst_team_notice_modify_date = tst_team_notice_modify_date;
}
public int getTeammembers() {
return teammembers;
}
public void setTeammembers(int teammembers) {
this.teammembers = teammembers;
}
public int getTeam_members_view() {
return team_members_view;
}
public void setTeam_members_view(int team_members_view) {
this.team_members_view = team_members_view;
}
@Override
public String toString() {
return "TeamBoardVo [no=" + no + ", tst_team_notice_board_no=" + tst_team_notice_board_no
+ ", tst_user_nickname=" + tst_user_nickname + ", tst_team_notice_board_title="
+ tst_team_notice_board_title + ", tst_team_notice_board_content=" + tst_team_notice_board_content
+ ", tst_team_no=" + tst_team_no + ", tst_team_notice_board_view=" + tst_team_notice_board_view
+ ", tst_team_notice_board_max=" + tst_team_notice_board_max + ", tst_team_notice_board_del="
+ tst_team_notice_board_del + ", tst_team_notice_insert_date=" + tst_team_notice_insert_date
+ ", tst_team_notice_modify_date=" + tst_team_notice_modify_date + ", teammembers=" + teammembers
+ ", team_members_view=" + team_members_view + "]\n";
}
}
|
package net.nowtryz.mcutils.command;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabExecutor;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.function.Predicate;
public abstract class CommandHandler<P extends JavaPlugin,D> extends AbstractCommand<P,D> implements TabExecutor {
protected final P plugin;
private final boolean canComplete;
public CommandHandler(@NotNull P plugin, @NotNull String label, @NotNull String usage,
@NotNull String permission, boolean canComplete) {
super(label, usage, permission);
this.canComplete = canComplete;
this.plugin = plugin;
PluginCommand command = plugin.getCommand(label);
if (command != null) {
if (canComplete) command.setTabCompleter(this);
command.setExecutor(this);
} else {
plugin.getLogger().severe("Unable to register command " + label);
}
}
public CommandHandler(@NotNull P plugin, @NotNull String label, @NotNull String usage,
@NotNull String permission, @Nullable Predicate<String[]> validator, boolean canComplete) {
super(label, usage, permission, validator);
this.canComplete = canComplete;
this.plugin = plugin;
PluginCommand command = plugin.getCommand(label);
if (command != null) {
if (canComplete) command.setTabCompleter(this);
command.setExecutor(this);
} else {
plugin.getLogger().severe("Unable to register command " + label);
}
}
@Override
public final boolean onCommand(@NotNull CommandSender sender, @Nullable Command command, @NotNull String label, String[] args) {
return super.process(this.plugin, sender, args);
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @Nullable Command command, @NotNull String alias, String[] args) {
return this.tabComplete(this.plugin, sender, args);
}
public boolean canComplete() { return this.canComplete; }
}
|
package app.com.example.android.spotifystreamer;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity implements MainActivityFragment.OnArtistSelectedListener {
private static final String ARTISTTOPTEN_TAG = "TTTAG";
private boolean mTwoPane;
String countryPrefLocal = "US";
String countryPrefMaster = "US";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
countryPrefMaster = sharedPrefs.getString(getString(R.string.pref_country_key), getString(R.string.pref_country_US));
if (findViewById(R.id.artist_top_ten_container) != null) {
// The detail container view will be present only in the large-screen layouts
// (res/layout-sw600dp). If this view is present, then the activity should be
// in two-pane mode.
mTwoPane = true;
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.artist_top_ten_container, new ArtistTopTenActivityFragment(), ARTISTTOPTEN_TAG)
.commit();
}
} else {
mTwoPane = false;
}
}
public void onArtistSelected(String[] idAndName) {
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle args = new Bundle();
args.putStringArray("IdAndNameArray", idAndName);
args.putBoolean("mTwoPane",mTwoPane);
ArtistTopTenActivityFragment fragment = new ArtistTopTenActivityFragment();
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.artist_top_ten_container, fragment)
.commit();
} else {
Intent intent = new Intent(this, ArtistTopTenActivity.class);
intent.putExtra("IdAndNameArray", idAndName);
intent.putExtra("mTwoPane",mTwoPane);
startActivity(intent);
}
}
/* @Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
countryPrefLocal = sharedPrefs.getString(getString(R.string.pref_country_key), getString(R.string.pref_country_US));
if (countryPrefLocal != null && !countryPrefLocal.equals(countryPrefMaster) )
{
MainActivityFragment ff = (MainActivityFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_main);
//Toast.makeText(getActivity(), "On Resume Country " + countryPrefMaster +" "+countryPrefLocal, Toast.LENGTH_SHORT).show();
countryPrefMaster = countryPrefLocal;
}
}*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.example.cruiseTrip.authentication;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.cruiseTrip.R;
import com.example.cruiseTrip.database.entity.User;
import com.example.cruiseTrip.database.UsersRepository;
public class RegisterActivity extends AppCompatActivity {
private User newUser;
private EditText usernameEditText;
private EditText passwordEditText;
private EditText passwordConformEditText;
private EditText emailEditText;
private EditText phoneNumberEditText;
private TextView errorsTxtView;
private String username;
private String password;
private String passwordConform;
private String email;
private String phoneNumber;
private Button signUpBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
usernameEditText = findViewById(R.id.username_register);
passwordEditText = findViewById(R.id.password_register);
passwordConformEditText = findViewById(R.id.password_confirm_register);
emailEditText = findViewById(R.id.email_register);
phoneNumberEditText = findViewById(R.id.phone_register);
signUpBtn = findViewById(R.id.signUpBtn_register);
signUpBtn.setOnClickListener(v -> {
username = usernameEditText.getText().toString().trim();
password = passwordEditText.getText().toString().trim();
passwordConform = passwordConformEditText.getText().toString().trim();
email = emailEditText.getText().toString().trim();
phoneNumber = phoneNumberEditText.getText().toString().trim();
errorsTxtView = findViewById(R.id.errors_register);
errorsTxtView.setText("");
//Validate
Validation validation = new Validation(username, password, passwordConform, email, phoneNumber);
if(validation.validateForm().equals("")) {
try {
UsersRepository usersRepository = new UsersRepository(this.getApplication());
newUser = new User(username, password, email, phoneNumber);
usersRepository.insertUser(newUser);
Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
i.putExtra("registerStatus", true);
startActivity(i);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
String s = validation.validateForm();
errorsTxtView.setText(s);
passwordEditText.setText("");
passwordConformEditText.setText("");
}
});
}
}
|
package com.example.ontheleash;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
public class GenericTextWatcher implements TextWatcher {
private final EditText nextView;
public GenericTextWatcher(EditText nextView){
this.nextView = nextView;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String text = s.toString();
if(nextView != null && text.length() == 1) {
nextView.requestFocus();
}
else if(nextView == null){
//ToDo hide the keyboard
}
}
}
|
package cn.lyh.spa.ptrnew;
import android.app.Activity;
import android.text.TextUtils;
import com.alibaba.fastjson.TypeReference;
import okhttp3.MediaType;
import spa.lyh.cn.ft_httpcenter.httpbase.BaseRequestCenter;
import spa.lyh.cn.lib_https.listener.DisposeDataListener;
import spa.lyh.cn.lib_https.request.RequestParams;
/**
* Created by zhaolb on 2017/11/3.
*/
public class RequestCenter extends BaseRequestCenter {
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("jpg");
/**
* 尝试得到所有的list数据
*/
public static void getCommonListNoLoading(Activity activity, ListParams params, DisposeDataListener listener){
RequestParams bodyParams = new RequestParams();
bodyParams.put("user_id",String.valueOf(params.user_id));
bodyParams.put("pageNo",String.valueOf(params.pageNo));
bodyParams.put("pageSize",String.valueOf(params.pageSize));
if (!params.title.equals("")){
bodyParams.put("title",params.title);
}
if (!params.tag.equals("")){
bodyParams.put("tag",params.tag);
}
if (!params.author.equals("")){
bodyParams.put("author",params.author);
}
if (!(params.lxId == -1)){
bodyParams.put("lxId",params.lxId+"");
}
if (!(params.districtId == -1)){
bodyParams.put("districtId",params.districtId+"");
}
if (!params.beginTime.equals("")){
bodyParams.put("beginTime",params.beginTime);
}
if (!params.endTime.equals("")){
bodyParams.put("endTime",params.endTime);
}
if (!(params.isReceived == -1)){
bodyParams.put("isReceived",params.isReceived+"");
}
//Log.e("CommonListUrl",HttpConstants.ROOT_URL +Global.MAIN_URL);
TypeReference typeReference = new TypeReference<ListData>(){};
RequestCenter.getRequest(activity, HttpConstants.ROOT_URL +"/app/all_checked_list.jspx", bodyParams, null, typeReference,null, listener);
}
}
|
package count;
import java.util.HashMap;
import java.util.Map;
public class Mapssss {
public static void main(String[] args) {
MapFile m = new MapFile();
int ar[][] = m.load();
/* for(int[] as:ar){
for (int i:as){
System.out.print(i);
}
System.out.println();
}*/
/*int[] a1 = {1,1,1,1,1,1,1,1,1,0};
int[] a2 = {0,1,1,0,0,0,2,1,1,1};
int[] a3 = {0,1,0,0,1,0,1,1,1,1};
int[] a4 = {1,1,0,1,1,1,1,0,1,0};
int[] a5 = {1,1,0,0,0,0,0,1,1,0};
int[] a6 = {1,1,1,1,1,0,1,1,1,0};
int[] a7 = {1,1,1,1,1,0,1,1,1,0};
int[] a8 = {1,1,1,1,1,0,0,1,1,0};
int[] a9 = {1,1,1,1,1,1,3,1,1,0};
int[] a0 = {1,1,1,1,1,1,1,1,1,0};
int[][] arr = {a1,a2,a3,a4,a5,a6,a7,a8,a9,a0};*/
Map<String,Integer> map = find(ar);
/*int x_2 = map.get("2_x");
int y_2 = map.get("2_y");
System.out.println(x_2+" " + y_2);*/
//int i = arr[0][5];
//System.out.println(i);
//System.out.println(map.get("2_x"));
//System.out.println(map.get("2_y"));
//System.out.println(map.get("3_x"));
//System.out.println(map.get("3_y"));
//int a = arr[map.get("2_y")][map.get("2_x")];
// System.out.println("11111111");
int x=map.get("2_x");
int y=map.get("2_y");
/*for(int[] as:arr){
for (int i:as){
System.out.print(i);
}
System.out.println();
}*/
int[][] a = getout(ar,x,y);
a[map.get("2_y")][map.get("2_x")] = 2;
for(int[] as:a){
for (int i:as){
System.out.print(i);
}
System.out.println();
}
}
public static Map<String,Integer> find(int[][] arr){
Map<String,Integer> map = new HashMap<String, Integer>();
int y = 0;
int x;
for(int[] a:arr){
y++;
x=0;
for(int i:a){
x++;
if(i == 2){
map.put("2_x",new Integer(x-1));
map.put("2_y",new Integer(y-1));
}
if(i == 3){
map.put("3_x",new Integer(x-1));
map.put("3_y",new Integer(y-1));
}
}
}
return map;
}
public static int[][] getout(int arr[][],int x,int y){
while(arr[y][x] != 3){
if (arr[y][x+1] == 3){
arr[y][x]=-1;
x++;
}else if(arr[y+1][x] == 3){
arr[y][x]=-1;
y++;
}else if(arr[y][x-1]==3){
arr[y][x]=-1;
x--;
}else if (arr[y-1][x]==3) {
arr[y][x] = -1;
y--;
}
if (arr[y][x+1] == 0){
arr[y][x]=5;
x++;
}else if(arr[y+1][x] == 0){
arr[y][x]=5;
y++;
}else if(arr[y][x-1]==0){
arr[y][x]=5;
x--;
}else if (arr[y-1][x]==0){
arr[y][x]=5;
y--;
}else{
if (arr[y][x+1] == 5){
arr[y][x]=-2;
x++;
}else if(arr[y+1][x] == 5){
arr[y][x]=-2;
y++;
}else if(arr[y][x-1]==5){
arr[y][x]=-2;
x--;
}else if (arr[y-1][x]==5) {
arr[y][x] = -2;
y--;
}
}
if (((arr[y][x+1] == -2)||(arr[y][x+1] == 1))&&((arr[y][x-1] == -2)||(arr[y][x-1] == 1))&&
((arr[y+1][x] == -2)||(arr[y+1][x] == 1))&&((arr[y-1][x] == -2)||(arr[y-1][x] == 1))){
System.out.println("没有出路");
for (int i = 0 ;i < arr.length ;i++){
for (int j = 0;j<arr[i].length;j++){
if (arr[i][j] == -2){
arr[i][j]=0;
}
}
}
return arr;
}
/*for (int i = 0 ;i < arr.length ;i++){
for (int j = 0;j<arr[i].length;j++){
if (!(arr[i][j] == 0)){
System.out.println("没有出口");
return arr;
}
}
}*/
}
for (int i = 0 ;i < arr.length ;i++){
for (int j = 0;j<arr[i].length;j++){
if (arr[i][j] == -2){
arr[i][j]=0;
}
if(arr[i][j]==-1){
arr[i][j]=5;
}
}
}
return arr;
}
}
|
package lk.ac.mrt.cse.mscresearch.persistance.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="jar_index")
public class JarIndex implements EntityId {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="primaryKey")
private int primaryKey;
@Column(name="jar_name")
private String name;
@Column(name="jar_hash")
private String jarHash;
@Column(name="artifact")
private String artifact;
@ManyToMany(cascade = { CascadeType.MERGE })
@JoinTable(
name = "jar_class_mapping",
joinColumns = { @JoinColumn(name = "jar_key") },
inverseJoinColumns = { @JoinColumn(name = "class_key") }
)
private Set<ClassIndex> classes = new HashSet<>();
public int getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(int primaryKey) {
this.primaryKey = primaryKey;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJarHash() {
return jarHash;
}
public void setJarHash(String jarHash) {
this.jarHash = jarHash;
}
public String getArtifact() {
return artifact;
}
public void setArtifact(String artifact) {
this.artifact = artifact;
}
public Set<ClassIndex> getClasses() {
return classes;
}
public void setClasses(Set<ClassIndex> classes) {
this.classes = classes;
}
@Override
public String toString() {
return "JarIndex [primaryKey=" + primaryKey + ", name=" + name + ", jarHash=" + jarHash + ", artifact="
+ artifact + "]";
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.examples.resources.shared;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.EntityProxyId;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
import com.sencha.gxt.examples.resources.server.data.Music;
@ProxyFor(Music.class)
public interface MusicProxy extends EntityProxy, NamedProxy {
String getName();
void setName(String name);
String getAuthor();
void setAuthor(String author);
String getGenre();
void setGenre(String genre);
@Override
public EntityProxyId<MusicProxy> stableId();
}
|
package com.jd.jarvisdemonim.http;
import com.jd.jarvisdemonim.entity.RetrofitTestBean;
import retrofit2.Call;
import retrofit2.http.POST;
import retrofit2.http.Query;
/**
* Auther: Jarvis Dong
* Time: on 2017/2/20 0020
* Name:
* OverView: retrofit联网服务请求;
* Usage:
*/
public interface RApiService {
@POST("api.axd")//这里是跟在baseurl后面的,拼接起来完整的
Call<RetrofitTestBean> getDatasByRetrofit(@Query("api") String api,
@Query("action") String action,
@Query("page") String page,
@Query("pageSize") String pageSize,
@Query("order") String order,
@Query("sqlText") String sqlText,
@Query("content") String content);
}
|
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
private static Scanner scanner;
private static final String DAT_PATTERN = "\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-\\d{2}$";
public static void main(String[] args) {
Patient.load();
VisitTime.load();
run();
}
private static void run() {
int input;
scanner = new Scanner(System.in);
while(true) {
System.out.println("What do you want to do?\n" +
"1. Create an account\n" +
"2. Determine a time\n" +
"3. See a doctor\n" +
"4. Visits' records\n" +
"5. Exit");
try {
input = validateInput(scanner.nextLine().trim());
switch (input) {
case 1:
createAccount();
break;
case 2:
determineTime();
break;
case 3:
reserve();
break;
case 4:
viewRecords();
break;
case 5:
scanner.close();
Patient.save();
VisitTime.save();
System.exit(1);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
private static void viewRecords() {
ArrayList<VisitTime> visitTimes = VisitTime.getVisitTimes();
for(VisitTime visitTime : visitTimes) {
System.out.println(visitTime);
}
}
private static void reserve() {
while(true) {
System.out.println("Enter your national code, then enter beginning and end date:" +
"\nNational Code-yyyy-MM-dd-HH-mm-HH-mm\nExample:0925617318-2020-11-23-12-00-14-00");
try {
String information = getDateAndNationalCode(scanner.nextLine().trim());
int nationalCode = Integer.parseInt(information.split(",")[0]);
hasPatientRegistered(nationalCode);
String datesInString = information.split(",")[1];
String beginningDate = datesInString.substring(0, 16);
String endDate = datesInString.substring(0, 10) + datesInString.substring(16);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
Date date1 = format.parse(beginningDate);
Date date2 = format.parse(endDate);
System.out.println("You can see the doctor between these two dates:\n"
+ VisitTime.reserveTimeForPatient(date1, date2, nationalCode));
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
private static void hasPatientRegistered(int nationalCode) throws Exception {
if(Patient.getPatientByNationalCode(nationalCode) == null)
throw new Exception("You must first register!");
}
private static String getDateAndNationalCode(String input) throws Exception {
Pattern pattern = Pattern.compile("^\\d+-" + DAT_PATTERN);
Matcher matcher = pattern.matcher(input);
if(!matcher.matches())
throw new Exception("Enter information in the correct format!");
input = input.replaceFirst("-", ",");
return input;
}
private static void determineTime() {
while (true) {
System.out.println("Enter beginning and end date:\nyyyy-MM-dd-HH-mm-HH-mm\nExample:2020-11-23-12-00-14-00");
try {
String dateInput = getDateInput(scanner.nextLine().trim());
String beginningDate = dateInput.split(",")[0];
String endDate = dateInput.split(",")[1];
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
Date date1 = format.parse(beginningDate);
Date date2 = format.parse(endDate);
System.out.println("Starts at: " + date1.toString());
System.out.println("Ends at: " + date2.toString());
new VisitTime(date1, date2);
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
private static String getDateInput(String nextLine) throws Exception {
Pattern pattern = Pattern.compile("^" + DAT_PATTERN);
Matcher matcher = pattern.matcher(nextLine);
if(!matcher.matches())
throw new Exception("Enter valid input!");
String beginningDate = nextLine.substring(0, 16);
String endDate = nextLine.substring(0, 10) + nextLine.substring(16);
return beginningDate + "," + endDate;
}
private static void createAccount() {
String[] information = null;
while (information == null) {
System.out.println("Enter:\nName-National Code-Age");
try {
information = getPatientsInformation(scanner.nextLine().trim());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
new Patient(information[0], Integer.parseInt(information[1]), Integer.parseInt(information[2]));
}
private static String[] getPatientsInformation(String nextLine) throws Exception {
Pattern pattern = Pattern.compile("^[a-zA-Z]+-\\d+-\\d+$");
Matcher matcher = pattern.matcher(nextLine);
if(!matcher.matches())
throw new Exception("Enter valid input!");
return nextLine.split("-");
}
private static int validateInput(String nextLine) throws Exception {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(nextLine);
if(!matcher.matches()) {
throw new Exception("Enter a Number!");
}
Integer input = Integer.parseInt(nextLine);
if(input < 1 || input > 5) {
throw new Exception("Enter one of the above options!");
}
return input;
}
}
|
package main.reports;
import java.util.Arrays;
public class ContractGenerator implements ReportGenerator {
private String contractContent;
public ContractGenerator(String contractContent) {
this.contractContent = contractContent;
}
@Override
public String generatePDF() {
return Arrays.toString(this.contractContent.getBytes());
}
@Override
public String generateTextDocument() {
return "Contract for the Employment : " + this.contractContent;
}
@Override
public String generateJsonFile() {
return "{'EmployeeContract':'" + this.contractContent + "'}";
}
}
|
package infix;
import java.util.Stack;
public class Infix {
public static void main(String[] args) {
// (a+b)*c+d = ab+c*d+
// (a+b)*(c+d) = ab+cd+*
// a+b*c+d = abc*+d+
System.out.println(toPostfix("(a+b)*c+d"));
System.out.println(toPostfix("(a+b)*(c+d)"));
System.out.println(toPostfix("a+b*c+d"));
// (a+b)*c+d = +*+abcd
// (a+b)*(c+d) = *+ab+cd
// a+b*c+d = +a+*bcd
System.out.println(toPrefix("(a+b)*c+d"));
System.out.println(toPrefix("(a+b)*(c+d)"));
System.out.println(toPrefix("a+b*c+d"));
}
public static String toPostfix(String infix) {
StringBuilder output = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (char c : infix.toCharArray()) {
if (c == '(')
stack.push(c);
else if (c == ')') {
while (stack.peek() != '(')
output.append(stack.pop());
stack.pop();
} else if ("+-*/".indexOf(c) != -1) {
while (!stack.isEmpty() && priority(stack.peek()) >= priority(c))
output.append(stack.pop());
stack.push(c);
} else
output.append(c);
}
while (!stack.isEmpty())
output.append(stack.pop());
return output.toString();
}
public static String toPrefix(String infix) {
StringBuilder output = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (char c : new StringBuilder(infix).reverse().toString().toCharArray()) {
if (c == ')')
stack.push(c);
else if (c == '(') {
while (stack.peek() != ')')
output.append(stack.pop());
stack.pop();
} else if ("+-*/".indexOf(c) != -1) {
while (!stack.isEmpty() && priority(stack.peek()) >= priority(c))
output.append(stack.pop());
stack.push(c);
} else
output.append(c);
}
while (!stack.isEmpty())
output.append(stack.pop());
return output.reverse().toString();
}
private static int priority(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
}
|
package seven;
/**
* <p>Modifikatori vidljivosti:
* <li>1. public </li>
* <li>2. bez kljucne rijeci(paketno privatna vidljivost)</li>
* <li>3. protected</li>
* <li>4. private </li>
* </p>
*/
public class Person {
public String name;//public
String surname;//paketno-privatni
private int age;
protected double weight;
public Person(){
super();
System.out.println("Poziva se konstruktor BEZ PARAM klase Person");
}
protected Person(String param1){
this.name = param1;
System.out.println("Poziva se konstruktor SA NAME PARAM klase Person");
}
public void setAge(int age){
if(age>0 && age <18){
this.age = age;
}
}
public int getAge(){
return age;
}
public void setName(String name){
this.name = name;
}
}
|
package com.ef.Parser.model;
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;
@Entity
@Table(name = "log_info")
public class LogInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "log_date", nullable = false)
private Date logDate;
@Column(name = "ip_address", length = 255, nullable = true)
private String iPAddress;
@Column(name = "http_request", length = 255, nullable = true)
private String httpRequest;
@Column(name = "http_status", length = 255, nullable = true)
private String httpStatus;
@Column(name = "user_agent", length = 255, nullable = true)
private String userAgent;
public Long getId() {
return id;
}
public Date getDate() {
return logDate;
}
public void setDate(Date logDate) {
this.logDate = logDate;
}
public String getIPAddress() {
return iPAddress;
}
public void setIPAddress(String iPAddress) {
this.iPAddress = iPAddress;
}
public String getHttpRequest() {
return httpRequest;
}
public void setHttpRequest(String httpRequest) {
this.httpRequest = httpRequest;
}
public String getHttpStatus() {
return httpStatus;
}
public void setHttpStatus(String httpStatus) {
this.httpStatus = httpStatus;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public LogInfo() {
}
public LogInfo(Date logDate, String iPAddress, String httpRequest, String httpStatus, String userAgent) {
super();
this.logDate = logDate;
this.iPAddress = iPAddress;
this.httpRequest = httpRequest;
this.httpStatus = httpStatus;
this.userAgent = userAgent;
}
@Override
public String toString() {
return "LogInfo{" + "id=" + id + ", date='" + logDate.toString() + '\'' + ", ipAddress='" + iPAddress + '\''
+ ", request='" + httpRequest + '\'' + ", httpStatus='" + httpStatus + '\'' + ", userAgent='"
+ userAgent + '\'' + '}';
}
}
|
/*
* @lc app=leetcode.cn id=74 lang=java
*
* [74] 搜索二维矩阵
*/
// @lc code=start
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int mLen = matrix.length;
if (mLen == 0)
return false;
int nLen = matrix[0].length;
int[] array = new int[mLen * nLen];
for (int i = 0; i < mLen; i++)
for (int j = 0; j < nLen; j++)
array[i * nLen + j] = matrix[i][j];
return binarySearch(array, target);
}
public boolean binarySearch(int[] array, int target) {
int left, right, medium;
left = 0;
right = array.length - 1;
while (left <= right) {
medium = (left + right) / 2;
if (array[medium] == target)
return true;
else if (array[medium] < target)
left = medium + 1;
else if (array[medium] > target)
right = medium - 1;
}
return false;
}
}
// @lc code=end
|
package pl.herbata.project.database;
/**
* Interface that extends Operation interface, and specifies codes for specific
* operation types.
*
* @see Operation
* @author Malczuuu
*/
public interface PlayerOperation extends Operation {
public final int PLAYER_ADDED = 1001;
public final int PLAYER_UPDATED = 1002;
public final int PLAYER_REMOVED = 1003;
}
|
package com.hfjy.framework.net.http.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.hfjy.framework.net.http.entity.ControllerDataChecker;
import com.hfjy.framework.net.http.entity.RequestMethod;
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Path {
String value();
Class<? extends ControllerDataChecker>[] checker() default ControllerDataChecker.class;
RequestMethod type() default RequestMethod.ALL;
}
|
package com.t11e.discovery.datatool;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.xml.stream.XMLStreamException;
import org.apache.commons.lang.StringUtils;
public class DeleteActionRowCallbackHandler
implements CompletionAwareRowCallbackHandler
{
private final ChangesetWriter writer;
private final ItemIdBuilder itemIdBuilder;
private final String providerColumn;
private final String kindColumn;
private final ProgressLogger progress;
public DeleteActionRowCallbackHandler(
final ChangesetWriter writer,
final String idColumn,
final String providerColumn,
final String kindColumn,
final ProgressLogger progress)
{
this.writer = writer;
this.providerColumn = providerColumn;
this.kindColumn = kindColumn;
this.progress = progress;
itemIdBuilder = new ItemIdBuilder(idColumn);
}
@Override
public void processRow(final ResultSet rs)
throws SQLException
{
final String id = itemIdBuilder.getId(rs);
try
{
if (providerColumn != null || kindColumn != null)
{
final String provider = StringUtils.trimToEmpty(rs.getString(providerColumn));
final String kind = StringUtils.trimToEmpty(rs.getString(kindColumn));
writer.removeItem(id, provider, kind);
}
else
{
writer.removeItem(id);
}
progress.worked(1);
}
catch (final XMLStreamException e)
{
throw new RuntimeException(e);
}
}
@Override
public void flushItem()
{
// do nothing
}
}
|
package com.ggtf.xieyingwu.cloudphoto.instagram;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.ggtf.xieyingwu.cloudphoto.instagram.model.IgAccessToken;
import com.ggtf.xieyingwu.cloudphoto.instagram.model.IgData;
import com.ggtf.xieyingwu.cloudphoto.utils.FileUtil;
import com.ggtf.xieyingwu.cloudphoto.utils.GsonUtil;
import com.ggtf.xieyingwu.cloudphoto.utils.NetUtil;
import com.ggtf.xieyingwu.cloudphoto.utils.SpUtil;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by xieyingwu on 2017/5/17.
*/
public class IgRequest {
static final String TAG = IgRequest.class.getName();
static final String AUTH_URL = "https://api.instagram.com/oauth/authorize/";
static final String TOKEN_URL = "https://api.instagram.com/oauth/access_token";
static final String API_URL = "https://api.instagram.com/v1";
static final String AUTH_URL_SERVICE = AUTH_URL + "?client_id=" + IgConstant.CLIENT_ID +
"&redirect_uri=" + IgConstant.REDIRECT_URL +
"&response_type=code";
static final String AUTH_URL_CLIENT = AUTH_URL + "?client_id=" + IgConstant.CLIENT_ID +
"&redirect_uri=" + IgConstant.REDIRECT_URL +
"&response_type=token";
static final int WHAT_ACCESS_TOKE_SUC = 100;
static final int WHAT_ACCESS_TOKE_FAIL = 101;
ExecutorService executorService;
Context context;
private IgAccessToken igAccessToken;
Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int what = msg.what;
handleByWhat(what);
}
};
public IgRequest(Context context) {
this.context = context;
executorService = Executors.newFixedThreadPool(10);
}
private void handleByWhat(int what) {
switch (what) {
case WHAT_ACCESS_TOKE_SUC:
toGetUserPhotos();
toGetUserInfo();
break;
}
}
private void toGetUserInfo() {
final String userUrl = API_URL + "/users/self/?access_token=" + igAccessToken.access_token;
executorService.execute(new Runnable() {
@Override
public void run() {
String userJsonStr = NetUtil.connectByGet(userUrl);
Log.w(TAG, "userJsonStr = " + userJsonStr);
FileUtil.writeContent("userJsonStr", userJsonStr);
}
});
}
private void toGetUserPhotos() {
int max_id = 0;
int min_id = 0;
int count = Integer.MAX_VALUE >> 2;
final String photoUrl = API_URL + "/users/self/media/recent/?access_token=" + igAccessToken.access_token
+ "&max_id=" + max_id + "&min_id=" + min_id + "&count=" + count
+ "&scope=" + IgConstant.SCOPE_BASIC;
Log.w(TAG, "photoUrl = " + photoUrl);
executorService.execute(new Runnable() {
@Override
public void run() {
String mediaJsonStr = NetUtil.connectByGet(photoUrl);
Log.w(TAG, "mediaJsonStr = " + mediaJsonStr);
FileUtil.writeContent("mediaJsonStr", mediaJsonStr);
IgData igData = GsonUtil.json2Object(mediaJsonStr, IgData.class);
if (igData != null) {
boolean ok = igData.isOk();
Log.w(TAG, "ok = " + ok);
boolean hadNextPage = igData.hadNextPage();
Log.w(TAG, "hadNextPage = " + hadNextPage);
}
}
});
}
public void directToAuthorization() {
IgDialog igDialog = new IgDialog(context, AUTH_URL_SERVICE, new IgDialog.OAuthDialogListener() {
@Override
public void onComplete(String code) {
Log.w(TAG, "code = " + code);
SpUtil.saveStr(IgConstant.IG_SP_KEY_CODE, code);
Log.w(TAG, "获取到Code后获取AccessToken------");
accessToken(code);
}
@Override
public void onError(String error) {
Log.w(TAG, "error = " + error);
}
});
igDialog.show();
}
private void accessToken(final String code) {
executorService.execute(new Runnable() {
@Override
public void run() {
HashMap<String, String> params = createParams(code);
String accessTokenJsonStr = NetUtil.connectByPost(TOKEN_URL, params);
Log.w(TAG, "accessTokenJsonStr = " + accessTokenJsonStr);
igAccessToken = GsonUtil.json2Object(accessTokenJsonStr, IgAccessToken.class);
if (igAccessToken != null) {
SpUtil.saveStr(IgConstant.IG_SP_KEY_ACCESS_TOKEN, igAccessToken.access_token);
myHandler.sendEmptyMessage(WHAT_ACCESS_TOKE_SUC);
} else {
myHandler.sendEmptyMessage(WHAT_ACCESS_TOKE_FAIL);
}
}
});
}
private HashMap<String, String> createParams(String code) {
HashMap<String, String> params = new HashMap<>();
params.put("client_id", IgConstant.CLIENT_ID);
params.put("client_secret", IgConstant.CLIENT_SECRET);
params.put("grant_type", "authorization_code");
params.put("redirect_uri", IgConstant.REDIRECT_URL);
params.put("code", code);
return params;
}
}
|
package com.atguigu.mr.index;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob;
import org.apache.hadoop.mapreduce.lib.jobcontrol.JobControl;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
/*
* 1.指定多个Job串行运行
* 使用JobControl对象,来指定一组Job,指定其依赖关系。
*
* JobControl.addJob(ControledJob): 向一个JobControl对象中添加需要运行的Job
*
* ControldJob: 可以调用 new ControldJob(Configuration)来基于配置创建一个ControldJob对象!
* ControldJob. addDependingJob(ControlledJob dependingJob): 指定依赖关系!
*/
public class IndexDriver {
public static void main(String[] args) throws IOException {
//指定路径
Path inputPath=new Path("e:/mrinput/index");
Path outputPath=new Path("e:/mroutput/index");
Path finaloutputPath=new Path("e:/mroutput/finalindex");
Configuration conf1= new Configuration();
Configuration conf2= new Configuration();
// 设置分隔符
conf2.set("mapreduce.input.keyvaluelinerecordreader.key.value.separator", "-");
FileSystem fs=FileSystem.get(conf1);
if (fs.exists(outputPath)) {
fs.delete(outputPath, true);
}
if (fs.exists(finaloutputPath)) {
fs.delete(finaloutputPath, true);
}
// ①创建Job1
Job job1 = Job.getInstance(conf1);
job1.setMapperClass(IndexMapper1.class);
job1.setReducerClass(IndexReducer1.class);
job1.setMapOutputKeyClass(Text.class);
job1.setMapOutputValueClass(IntWritable.class);
job1.setOutputKeyClass(Text.class);
job1.setOutputValueClass(IntWritable.class);
FileInputFormat.setInputPaths(job1, inputPath);
// 输出格式,负责将reducer输出的key-value写入到指定目录
FileOutputFormat.setOutputPath(job1, outputPath);
job1.setJobName("index1");
job1.setJarByClass(IndexDriver.class);
// ②构建Job2
Job job2 = Job.getInstance(conf2);
job2.setMapperClass(IndexMapper2.class);
job2.setReducerClass(IndexReducer2.class);
job2.setMapOutputKeyClass(Text.class);
job2.setMapOutputValueClass(Text.class);
job2.setOutputKeyClass(Text.class);
job2.setOutputValueClass(Text.class);
job2.setInputFormatClass(KeyValueTextInputFormat.class);
FileInputFormat.setInputPaths(job2, outputPath);
// 输出格式,负责将reducer输出的key-value写入到指定目录
FileOutputFormat.setOutputPath(job2, finaloutputPath);
job2.setJobName("index2");
job2.setJarByClass(IndexDriver.class);
// ③基于Job1,Job2的配置,再构建其ControldJob,并指定依赖关系
ControlledJob controlledJob1 = new ControlledJob(job1.getConfiguration());
ControlledJob controlledJob2 = new ControlledJob(job2.getConfiguration());
controlledJob2.addDependingJob(controlledJob1);
// ④创建JobControl,添加要运行的ControldJob,运行JobControl
JobControl jobControl = new JobControl("index");
jobControl.addJob(controlledJob1);
jobControl.addJob(controlledJob2);
// 运行
new Thread(jobControl).start();
while(true) {
if (jobControl.allFinished()) {
System.out.println(jobControl.getSuccessfulJobList());
break;
}
}
}
}
|
package cn.ctw.spider.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* 单个电影历史每日数据(1天)
*
* @author jack
*
*/
@Entity
@Table(name = "everyDayBoxOffice")
public class EveryDayBoxOffice implements Serializable {
private static final long serialVersionUID = -6739328982375850612L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ID")
private long id;
// 电影id
@Column(name="Mid")
private String mid;
// 日期
@Column(name="InsertDate")
private String InsertDate;
// 星期几
@Column(name="ReleaseDay")
private String ReleaseDay;
// 票房
@Column(name="Boxoffice")
private String Boxoffice;
// 票房占比
@Column(name="BoxPercent")
private String BoxPercent;
// 拍片占比
@Column(name="ShowPercent")
private String ShowPercent;
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getInsertDate() {
return InsertDate;
}
public void setInsertDate(String insertDate) {
InsertDate = insertDate;
}
public String getReleaseDay() {
return ReleaseDay;
}
public void setReleaseDay(String releaseDay) {
ReleaseDay = releaseDay;
}
public String getBoxoffice() {
return Boxoffice;
}
public void setBoxoffice(String boxoffice) {
Boxoffice = boxoffice;
}
public String getBoxPercent() {
return BoxPercent;
}
public void setBoxPercent(String boxPercent) {
BoxPercent = boxPercent;
}
public String getShowPercent() {
return ShowPercent;
}
// 为了生成表 暂时修改此方法
public EveryDayBoxOffice setShowPercent(String showPercent) {
ShowPercent = showPercent;
return this;
}
}
|
package uow.finalproject.webapp.entityType;
public enum Nationality {
Australian("Australian", "Australia"),
USA("USA", "United State"),
British("British", "England"),
Chinese("Chinese", "China"),
French("French", "France"),
Vietnam("Vietnam", "Vietnam"),
Pakistan("Pakistan", "Pakistan"),
Indian("Indian", "India"),
Singapore("Singapore", "Singapore");
private String name;
private String countryName;
Nationality(String name, String countryName) {
this.name = name;
this.countryName = countryName;
}
public String getName() {
return name;
}
public String getCountryName() {
return countryName;
}
}
|
package org.aksw.autosparql.server;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import org.aksw.autosparql.server.search.Search;
import org.aksw.autosparql.server.search.SolrSearch;
import org.apache.log4j.spi.LoggerFactory;
public class AutoSPARQLCLI {
private static final String SOLR_SERVER_URL = "http://139.18.2.173:8080/apache-solr-1.4.1/dbpedia_resources/";
private Scanner scanner;
private Search search;
public AutoSPARQLCLI(){
scanner = new Scanner(System.in);
search = new SolrSearch(SOLR_SERVER_URL);
}
private String readFromCLI(){
return scanner.nextLine();
}
public void start(){
System.out.print("Query:");
String query = readFromCLI();
List<String> suggestions = search.getResources(query, 10);
for(int i = 0; i < suggestions.size(); i++){
System.out.println(i+1 + ": \t" + suggestions.get(i));
}
List<String> posExamples = new ArrayList<String>();
System.out.println("Choose positive examples from list(Abort with \"n\")");
String input = scanner.next();
while(!input.equalsIgnoreCase("n")){
if(input.matches("[1-9,10]")){
posExamples.add(suggestions.get(Integer.valueOf(input)+1));
}
input = scanner.next();
}
while(posExamples.size() < 2){
System.out.format("We need %d more positive example(s).\n", 2-posExamples.size());
System.out.print("http://dbpedia.org/resource/");
String example = readFromCLI();
posExamples.add(example);
}
}
/**
* @param args
*/
public static void main(String[] args) {
LogManager.getLogManager().getLogger("global").setLevel(Level.WARNING);
new AutoSPARQLCLI().start();
}
}
|
package com.android.gestiondesbiens;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.android.gestiondesbiens.model.Transactions;
public class UserTransactionActivity extends Activity {
List<Transactions> transactionsList;
ArrayList<HashMap<String, String>> arrHeader, arrDetails;
HashMap<String, String> mapReservedWorkHeader, mapReservedWorkDetails;
ListAdapter adHeader, adDetails;
ListView lstHeader, lstReservedWorkDetails;
int intTransactionID = 0;
public void btnNewTransaction_Click(View v){
Intent I = new Intent(this, EditTransactionDetails.class);
I.putExtra("transaction_id", "0");
startActivity(I);
}
public void btnSaveTransaction_Click(View v){
new Thread(new Runnable(
) {
@Override
public void run() {
try
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("item_id","1"));
nameValuePairs.add(new BasicNameValuePair("username", ClsUser.CONNECTED_USER_NAME));
nameValuePairs.add(new BasicNameValuePair("location_id_src", "2"));
nameValuePairs.add(new BasicNameValuePair("location_id_dest", "1"));
nameValuePairs.add(new BasicNameValuePair("transport_id", "1"));
// nameValuePairs.add(new BasicNameValuePair("deviceId","1"));
//nameValuePairs.add(new BasicNameValuePair("onlineUserId", String.valueOf(2)));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.100:80/Insert_Transaction.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}
});
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
}
}).start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transactions);
this.lstHeader = (ListView)findViewById(R.id.lstTransactionHeader);
this.lstReservedWorkDetails = (ListView)findViewById(R.id.lstTransactionDetails);
this.LoadGridHeader();
this.lstReservedWorkDetails.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent I = new Intent(getApplicationContext(), EditTransactionDetails.class);
I.putExtra("transaction_id", arrDetails.get(position).get("transaction_id"));
I.putExtra("item_id", arrDetails.get(position).get("ItemCode"));
I.putExtra("username", arrDetails.get(position).get("ItemName"));
I.putExtra("location_id_src", arrDetails.get(position).get("ItemSpecification"));
I.putExtra("location_id_dest", arrDetails.get(position).get("TypeName"));
I.putExtra("transport_id", arrDetails.get(position).get("ItemDateCreated"));
I.putExtra("status", arrDetails.get(position).get("CenterName"));
I.putExtra("transaction_date", arrDetails.get(position).get("SalleName"));
startActivity(I);
}
});
new Thread() {
public void run(){
LoadGridDetails();
while(true){
if(blnReloadGrid){
LoadGridDetails();
blnReloadGrid = false;
}
}
}
}.start();
}
public static boolean blnReloadGrid = false;
public void LoadGridDetails()
{
String result = PhpScriptExecuter.getDataFromPhpScript("Select_Transaction.php");
LoadGridDetails(result);
}
void LoadGridHeader(){
try{
this.adHeader = null;
this.lstHeader.setAdapter(this.adHeader);
this.arrHeader = new ArrayList<HashMap<String, String>>();
this.mapReservedWorkHeader = new HashMap<String, String>();
this.mapReservedWorkHeader.put("ItemCode", "Item ID");
this.mapReservedWorkHeader.put("ItemName", "User Name");
this.mapReservedWorkHeader.put("ItemSpecification", "Location Id Source");
this.mapReservedWorkHeader.put("TypeName", "Location Id Destination");
this.mapReservedWorkHeader.put("ItemDateCreated", "Transport Id");
this.mapReservedWorkHeader.put("CenterName", "Status");
this.mapReservedWorkHeader.put("SalleName", "Date Transaction");
this.arrHeader.add(this.mapReservedWorkHeader);
this.adHeader = new SimpleAdapter(this, arrHeader, R.layout.gridb_template, new String[] {"ItemCode", "ItemName", "ItemSpecification", "TypeName", "ItemDateCreated", "CenterName", "SalleName", "PersonnelName"}, new int[] {R.id.labItemCode, R.id.labItemName, R.id.labItemSpecification, R.id.labTypeName, R.id.labItemDateCreated, R.id.labCenterName, R.id.labSalleName, R.id.labPersonnelName});
this.lstHeader.setAdapter(this.adHeader);
}
catch(Exception e){
e.printStackTrace();
}
}
void LoadGridDetails(String strResult){
try{
adDetails = null;
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
lstReservedWorkDetails.setAdapter(adDetails);
}
});
this.arrDetails = new ArrayList<HashMap<String, String>>();
String rows[] = strResult.split(";");
String col[];
for(int i = 0; i < rows.length - 1; i++){
col = rows[i].split(",");
this.mapReservedWorkDetails = new HashMap<String, String>();
this.mapReservedWorkDetails.put("transaction_id", col[0]);
this.mapReservedWorkDetails.put("ItemCode", col[1]);
this.mapReservedWorkDetails.put("ItemName", col[2]);
this.mapReservedWorkDetails.put("ItemSpecification", col[3]);
this.mapReservedWorkDetails.put("TypeName", col[4]);
this.mapReservedWorkDetails.put("ItemDateCreated", col[5]);
this.mapReservedWorkDetails.put("CenterName", col[6]);
this.mapReservedWorkDetails.put("SalleName", col[7]);
this.arrDetails.add(this.mapReservedWorkDetails);
}
this.adDetails = new SimpleAdapter(this, arrDetails, R.layout.gridb_template, new String[] {"ItemCode", "ItemName", "ItemSpecification", "TypeName", "ItemDateCreated", "CenterName", "SalleName", "PersonnelName"}, new int[] {R.id.labItemCode, R.id.labItemName, R.id.labItemSpecification, R.id.labTypeName, R.id.labItemDateCreated, R.id.labCenterName, R.id.labSalleName, R.id.labPersonnelName});
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
lstReservedWorkDetails.setAdapter(adDetails);
}
});
}
catch(Exception e){
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_transaction, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.example.sypark9646.item01;
public class CreateShapeFromNameFactory extends ShapeFactory {
private static Circle CIRCLE = new Circle();
private static Rectangle RECTANGLE = new Rectangle();
@Override
Shape createShape(String name) {
switch (name) {
case "circle":
return CIRCLE;
case "rectangle":
return RECTANGLE;
}
return null;
}
}
|
package com.badawy.carservice.fragment;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;
import com.badawy.carservice.R;
import com.badawy.carservice.activity.HomepageActivity;
import com.badawy.carservice.adapters.NavAppointmentsAdapter;
import com.badawy.carservice.adapters.NavOrdersAdapter;
import com.badawy.carservice.models.BookingModel;
import com.badawy.carservice.models.OrderModel;
import com.badawy.carservice.utils.Constants;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Objects;
/**
* A simple {@link Fragment} subclass.
*/
public class NavAppointmentsFragment extends Fragment {
private ArrayList<BookingModel> appointmentList;
private ArrayList<OrderModel> ordersList;
private FirebaseAuth auth;
private DatabaseReference appointmentsRef, ordersRef;
private String userId;
private ImageView navMenuBtn;
private ConstraintLayout appointmentsLayout, ordersLayout, emptyLayout;
private RecyclerView appointmentRV, ordersRV;
private Activity activity;
private ScrollView mainLayout;
private int appointmentsCount, ordersCount;
public NavAppointmentsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_nav_appointments_orders, container, false);
activity = getActivity();
initializeUi(view);
// Hide the RecyclerViews to prevent them from loading before the data is fetched from firebase
mainLayout.setVisibility(View.GONE);
appointmentsLayout.setVisibility(View.INVISIBLE);
ordersLayout.setVisibility(View.INVISIBLE);
// Get User UID from Auth Service
auth = FirebaseAuth.getInstance();
userId = Objects.requireNonNull(auth.getCurrentUser()).getUid();
// Initialize Database References
appointmentsRef = FirebaseDatabase.getInstance().getReference();
ordersRef = FirebaseDatabase.getInstance().getReference();
// Fetch Appointments
fetchAppointmentsFromFirebase(new AppointmentsCallBack() {
@Override
public void bindAppointmentsData(ArrayList<BookingModel> fetchedAppointmentsList) {
// This Method is called when the data is fetched from firebase
bindAppointmentsDataToAdapter(fetchedAppointmentsList);
}
});
// Fetch Orders
fetchOrdersDataFromFirebase(new OrdersCallBack() {
@Override
public void bindOrdersData(ArrayList<OrderModel> fetchedOrdersList) {
// This Method is called when the data is fetched from firebase
bindOrderDataToAdapter(fetchedOrdersList);
}
});
// Click on menu icon
navMenuBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HomepageActivity.openDrawer();
}
});
return view;
}
private void initializeUi(View view) {
appointmentRV = view.findViewById(R.id.nav_appointments_appointmentsRV);
ordersRV = view.findViewById(R.id.nav_appointments_ordersRV);
appointmentsLayout = view.findViewById(R.id.nav_appointmentsOrders_appointmentsConstraintLayout);
emptyLayout = view.findViewById(R.id.nav_appointments_emptyLayout);
ordersLayout = view.findViewById(R.id.nav_appointmentsOrders_ordersConstraintLayout);
navMenuBtn = view.findViewById(R.id.nav_appointments_navMenuBtn);
mainLayout = view.findViewById(R.id.nav_appointments_mainLayout);
}
// [[ APPOINTMENTS ]]
private interface AppointmentsCallBack {
void bindAppointmentsData(ArrayList<BookingModel> fetchedAppointmentsList);
}
private void fetchAppointmentsFromFirebase(final AppointmentsCallBack appointmentsCallBack) {
// Start the progress Bar
showProgress();
// root of user`s appointments
appointmentsRef
.child(Constants.USERS)
.child(userId)
.child(Constants.APPOINTMENTS_ORDERS).child(Constants.APPOINTMENTS)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// check if user have any appointments Id`s
if (dataSnapshot.hasChildren()) {
// get number of appointments .. so after the last appointment data is added to our list .. we can call the Appointments CallBack
appointmentsCount = (int) dataSnapshot.getChildrenCount();
// if true ... create a new appointment list
appointmentList = new ArrayList<>();
// for each appointment id ... go fetch the appointment data from Booking root
for (final DataSnapshot ds : dataSnapshot.getChildren()) {
// root of booking appointments
appointmentsRef
.child(Constants.BOOKING)
.child(Constants.APPOINTMENTS)
.child(Objects.requireNonNull(ds.getKey()))
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// retrieve appointment data and add it to the list
appointmentList.add(dataSnapshot.getValue(BookingModel.class));
appointmentsCount--;
// repeat until every appointment is added to the list
// when last one is added .. call the CAll back and pass the list to it
if (appointmentsCount == 0) {
appointmentsCallBack.bindAppointmentsData(appointmentList);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}// Else if user don`t have any appointments .. pass null to the call back
else {
appointmentsCallBack.bindAppointmentsData(null);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void bindAppointmentsDataToAdapter(ArrayList<BookingModel> fetchedAppointmentList) {
// if the fetched list is not null .. it means that the user HAVE appointments
if (fetchedAppointmentList != null) {
// prepare the Adapter
NavAppointmentsAdapter appointmentsAdapter = new NavAppointmentsAdapter(getActivity(), fetchedAppointmentList);
appointmentRV.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
appointmentRV.setAdapter(appointmentsAdapter);
// Stop the progress bar and Show appointments recycler View
hideProgress();
appointmentsLayout.setVisibility(View.VISIBLE);
checkForEmptyAppointmentsAndOrders();
}
// else if fetched list is null .. user have no appointments
else {
// stop the progress bar and hide appointment layout
hideProgress();
appointmentsLayout.setVisibility(View.GONE);
checkForEmptyAppointmentsAndOrders();
}
}
// [[ ORDERS ]]
private interface OrdersCallBack {
void bindOrdersData(ArrayList<OrderModel> orderList);
}
private void fetchOrdersDataFromFirebase(final OrdersCallBack ordersCallBack) {
// Start the progress Bar
showProgress();
// root of user`s orders
ordersRef
.child(Constants.USERS)
.child(userId)
.child(Constants.APPOINTMENTS_ORDERS).child(Constants.ORDERS)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// check if user have any Orders Id`s
if (dataSnapshot.hasChildren()) {
// get number of Orders .. so after the last order data is added to our list .. we can call the Orders CallBack
ordersCount = (int) dataSnapshot.getChildrenCount();
// if true ... create a new orders list
ordersList = new ArrayList<>();
// for each order id ... go fetch the order data from Booking root
for (DataSnapshot ds : dataSnapshot.getChildren()
) {
// root of booking Orders
ordersRef
.child(Constants.BOOKING)
.child(Constants.ORDERS)
.child(Objects.requireNonNull(ds.getKey()))
.orderByChild("timestamp")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// retrieve order data and add it to the list
ordersList.add(dataSnapshot.getValue(OrderModel.class));
ordersCount--; // decrease the counter by 1 = indicates how many other orders are left to be added
// repeat until every order is added to the list
// when last order is added (counter = 0).. call the CAll back and pass the list to it
if (ordersCount == 0) {
ordersCallBack.bindOrdersData(ordersList);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
} // Else if user don`t have any orders .. pass null to the call back
else {
ordersCallBack.bindOrdersData(null);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void bindOrderDataToAdapter(ArrayList<OrderModel> fetchedOrdersList) {
if (fetchedOrdersList != null) {
// prepare the adapter
NavOrdersAdapter ordersAdapter = new NavOrdersAdapter(getActivity(), fetchedOrdersList);
ordersRV.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
ordersRV.setAdapter(ordersAdapter);
// hide the progress bar then show the recycler view
hideProgress();
ordersLayout.setVisibility(View.VISIBLE);
checkForEmptyAppointmentsAndOrders();
} else {
// stop the progress bar and hide appointment layout
hideProgress();
ordersLayout.setVisibility(View.GONE);
checkForEmptyAppointmentsAndOrders();
}
}
private void checkForEmptyAppointmentsAndOrders() {
// if user don`t have appointments and orders then show the Icon
if (ordersLayout.getVisibility() == View.GONE && appointmentsLayout.getVisibility() == View.GONE) {
emptyLayout.setVisibility(View.VISIBLE);
} else {
mainLayout.setVisibility(View.VISIBLE);
emptyLayout.setVisibility(View.GONE);
}
}
private void showProgress() {
if (getActivity() instanceof HomepageActivity) {
((HomepageActivity) getActivity()).showProgressBar(true);
}
}
private void hideProgress() {
if (getActivity() instanceof HomepageActivity) {
((HomepageActivity) getActivity()).showProgressBar(false);
}
}
private void fakeDataTest() {
// private ArrayList<NavOrdersModel> ordersList = new ArrayList<>();
// private ArrayList<NavAppointmentsModel> appointmentList = new ArrayList<>();
// String [] serviceLabel = {"Car Care","Oil Change"};
// String [] serviceType = {"Automated In-Bay Car Wash","Engine Oil"};
// String [] servicePrice = {"150 EGP","250 EGP"};
// String [] serviceDate = {"30 March, 2020","2 April, 2020"};
// String [] serviceTime = {"1:00 PM","7:00 PM"};
// String [] serviceAddress = {"Culture & Science City, Second 6th of October","Culture & Science City, Second 6th of October"};
//
// int[] productImage={R.drawable.tire};
// String[] productName={"Hankook KINERGY ECO 2 K435"};
// String[] productPartNumber={"8808563301211"};
// String[] productPrice={"2500.00 EGP"};
// String[] orderDate={"24 March, 2020"};
// String[] orderTime={"3:00 PM"};
// String[] orderNumber={"124550"};
//
//
// RecyclerView appointmentRV = view.findViewById(R.id.nav_appointments_appointmentsRV);
// RecyclerView ordersRV = view.findViewById(R.id.nav_appointments_ordersRV);
//
// for (int i = 0 ; i< serviceLabel.length;i++)
// {
// appointmentList.add(new NavAppointmentsModel(serviceLabel[i],serviceType[i],servicePrice[i],serviceDate[i],serviceTime[i],serviceAddress[i]));
//
// }
//
//
//
// NavAppointmentsAdapter appointmentsAdapter = new NavAppointmentsAdapter(getActivity(),appointmentList);
// appointmentRV.setLayoutManager(new LinearLayoutManager(getActivity(),RecyclerView.VERTICAL,false));
// appointmentRV.setAdapter(appointmentsAdapter);
//
// for (int i = 0 ; i< orderNumber.length;i++)
// {
// ordersList.add(new NavOrdersModel(productImage[i],productName[i],productPartNumber[i],productPrice[i],orderNumber[i],orderDate[i],orderTime[i]));
//
// }
//
// NavOrdersAdapter ordersAdapter = new NavOrdersAdapter(getActivity(),ordersList);
// ordersRV.setLayoutManager(new LinearLayoutManager(getActivity(),RecyclerView.VERTICAL,false));
// ordersRV.setAdapter(ordersAdapter);
}
}
|
package otus.apiHelpers.apiHelpersHomework;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApiHelpersHomeworkApplication {
public static void main(String[] args) {
SpringApplication.run(ApiHelpersHomeworkApplication.class, args);
}
}
|
/*
* 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.
*/
package ejercicio1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author David
*/
public class Ejercicio1 {
/**
* @param args the command line arguments
*/
private static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
@SuppressWarnings("empty-statement")
public static void main(String[] args) throws IOException {
// TODO code application logic here
try{
int i;
String input="";
//Pedimos por pantalla el numero de elementos de nuestro array
System.out.print("Introduce el numero de elementos del array\n");
input = stdin.readLine();
int n = Integer.parseInt(input);
//Si los n elementos del array son positivos ,calculará aleatoriamente n elementos mediante
///el Math.random de 0 a 100.
if(n>0){
int x[ ] = new int[n+10];
for( i=0;i<n;i++)
{
x[i]=(int)(100.0 * Math.random());
System.out.println("\nx["+i+"]="+x[i]+"\n");
}
//==============> ALERTA: cal tenir present que n augmenta.
//Aqui solicitamos una posición del vector y le asociamos el valor
System.out.print("\nIntroduce una posicion=");
input = stdin.readLine();
int pos = Integer.parseInt(input);
System.out.print("\nvalor=");
input = stdin.readLine();
int valor = Integer.parseInt(input);
//establecemos que la posiciones mayor que 0 y menor que los n elementos del array
//si se cumple procederemos a mostrar los resultados que se nos pide mediante las
//funciones que hemos establecido
if (pos>0 || pos<n){
AddValorPos(n,pos,valor,x);
ValorMaxMin(n,x);
HighAverage(n,x);
}
//Esto son el caso contrario a las condiciones y saltarán una serie de excepciones
//en caso contrario
else{
throw new ArrayIndexOutOfBoundsException();
}
}
if(n<0){
throw new NegativeArraySizeException();
}
}
catch(NegativeArraySizeException ex){
System.out.println("El numero de elementos del array debe ser positivo "+ ex);
}
catch(ArrayIndexOutOfBoundsException es){
System.out.println("Posicion incorrecta y valores"+es);
}
}
//Funcion para añadir una posicion y un valor y después mostrar el nuevo vector con la posicion
public static void AddValorPos(int n,int pos,int valor,int x[]) throws IOException {
int i;
if(pos>0 && pos<n){
for(i = n; i>=pos;i--) x[i]=x[i-1];
x[pos]=valor;
n++; //============================> Augmenta la n.
for(i=0;i<n;i++) System.out.print("\nx["+i+"]="+x[i]+"\n");
}
}
//Funcion para calcular los valores máximos y minimos del vector
public static void ValorMaxMin(int n,int x[]) throws IOException {
float max = x[0];
float min = x[0];
for( int i=0;i<n;i++){
if (x[i]>max){
max = x[i];
}
if(x[i]<min){
min = x[i];
}
}
System.out.println("\nmax="+max);
System.out.println("\nmin ="+min);
}
//Funcion para mostrar los valores que estan por encima y por debajo de la media
public static void HighAverage(int n,int x[]) throws IOException {
int i;
float mitjana=0.f;
for( i=0;i<n;i++)
{
mitjana=mitjana+x[i];
}
mitjana=mitjana/n;
System.out.print("\nmitjana = "+mitjana);
//c) Elements que es troben per sota i per sobre de la mitjana
System.out.print("\nPer sobre la mitjana...");
for( i=0;i<n;i++) if (x[i]>mitjana)System.out.println("\nx["+i+"]="+x[i]);
System.out.print("\nPer sota la mitjana...");
for(i=0;i<n;i++)if (x[i]<mitjana)System.out.println("\nx["+i+"]="+x[i]);
}
}
|
package by.bytechs.ndcParser.request;
import by.bytechs.ndcParser.enums.LastTransactionStatus;
import by.bytechs.ndcParser.interfaces.NdcParser;
import by.bytechs.ndcParser.request.commands.OperatingBuffer;
import by.bytechs.ndcParser.request.commands.TransactionRequestCommand;
import by.bytechs.ndcParser.request.interfaces.TerminalParserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Romanovich Andrei
*/
@Service
public class TerminalParserServiceImpl implements TerminalParserService {
@Autowired
private NdcParser ndcParser;
@Override
public Object parseCommand(byte[] command) {
try {
String[] strFormatCommand = ndcParser.asciiToUtf(command);
if (strFormatCommand != null) {
String messageType = strFormatCommand[0];
switch (messageType) {
case "11":
return parseTransactionRequestCommand(strFormatCommand);
default:
return null;
}
}
return null;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
@Override
public TransactionRequestCommand parseTransactionRequestCommand(String[] command) {
try {
TransactionRequestCommand requestCommand = new TransactionRequestCommand();
for (int index = 1; index < command.length; index++) {
if (command[index].length() != 0) {
switch (index) {
case 1: {
requestCommand.setTerminalId(command[index]);
break;
}
case 3: {
requestCommand.setTimeNumber(command[index]);
}
case 4: {
requestCommand.setTopReceipt(command[index].substring(0, 1).equals("1"));
requestCommand.setMessageCoordinationNumber(Integer.parseInt(command[index].substring(1)));
break;
}
case 5: {
Pattern trackPattern = Pattern.compile(";(\\d+)=");
Matcher trackMatcher = trackPattern.matcher(command[index]);
if (trackMatcher.find()) {
requestCommand.setMaskedTrack2(ndcParser.maskingTrack2(trackMatcher.group(1), 'X'));
}
break;
}
case 6: {
requestCommand.setTrack3(command[index]);
break;
}
case 7: {
requestCommand.setOperatingBuffer(new OperatingBuffer(command[index]));
break;
}
case 8: {
requestCommand.setUserAmount(new BigDecimal(Double.parseDouble(command[index])).
setScale(BigDecimal.ROUND_HALF_UP, 2).doubleValue());
break;
}
case 9: {
requestCommand.setPIN(command[index]);
break;
}
case 10: {
requestCommand.setGeneralPurposeBufferB(command[index]);
break;
}
case 11: {
requestCommand.setGeneralPurposeBufferC(command[index]);
break;
}
case 12: {
requestCommand.setTrack1(command[index]);
break;
}
default:
if (command[index].length() > 1) {
switch (command[index].substring(0, 1)) {
case "2": {
requestCommand.setLastTransactionNumber(command[index].substring(1, 5));
requestCommand.setLastTransactionStatus(LastTransactionStatus.getObject(command[index].charAt(5)));
break;
}
case "U": {
requestCommand.setCPSData(command[index].substring(1));
break;
}
case "V": {
requestCommand.setConfirmationCPSData(command[index].substring(1));
break;
}
case "5": {
requestCommand.setSmartCardData(command[index].substring(1));
break;
}
default:
break;
}
}
break;
}
}
}
return requestCommand;
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
}
|
package slimeknights.tconstruct.library.client;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.IItemPropertyGetter;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nullable;
public abstract class BooleanItemPropertyGetter implements IItemPropertyGetter {
@Override
@SideOnly(Side.CLIENT)
public final float apply(ItemStack stack, @Nullable World worldIn, @Nullable EntityLivingBase entityIn) {
return applyIf(stack, worldIn, entityIn) ? 1f : 0f;
}
@SideOnly(Side.CLIENT)
public abstract boolean applyIf(ItemStack stack, @Nullable World worldIn, @Nullable EntityLivingBase entityIn);
}
|
package webley;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class WebleyCombinations {
public List<List<Double>> findCombinations(WebleyData webleydata){
List<List<Double>> combinations = new ArrayList<List<Double>>(); //variable to store all possible combinations
List<Double> prices = new ArrayList<Double>(); //variable to store the prices as a list
List<List<Double>> combinationOfPrices = new ArrayList<>(); //variable to store specific combinations that equal the target
Map<Integer,Double> priceList = webleydata.getPriceList(); //retrieving prices to convert to list
double target = webleydata.getTargetPrice(); //retrieving target price to check if sum of combination = target price
for(int i=2; i<=priceList.size(); i++){ //creating a new list that has all prices
prices.add(priceList.get(i)); //i=1 has target price...so exclude that
}
for(int i=1; i<=prices.size(); i++){
combinations.addAll(combination(prices,i)); //call the recursive function that finds all combinations
}
for(List<Double> singleCombination : combinations){ //iterate through all combinations
double sum = 0;
for(int i=0; i<singleCombination.size(); i++){
sum = sum + singleCombination.get(i);
}
if(sum==target) combinationOfPrices.add(singleCombination); //find the combination whose sum equals the target price
}
return combinationOfPrices; //return the list of all correct combinations whose sum equals target
}
public List<List<Double>> combination(List<Double> prices, int size){
List<List<Double>> Allcombinations = new ArrayList<List<Double>>(); //variable that stores all combinations and sends it to the calling method
List<Double> remaining = new ArrayList<Double>(prices); //variable that will store all remaining prices during each recursion
if (size == 0) { //when all elements are combined and the there is no element left, return a singleton list
return Arrays.asList(Collections.<Double> emptyList());
}
if (prices.isEmpty()) { //when one recursion is over, return an empty list and move to the next recursion
return Collections.emptyList();
}
double next = prices.iterator().next(); //select the next element. If new list, first element is selected
List<List<Double>> combinations = combination(remaining,size-1); //call recursion of same method on the remaining elements
for(List<Double> combo : combinations){
List<Double> recursiveCombo = new ArrayList<Double>(combo); //variable that stores the combination for each recursion
recursiveCombo.add(0,next); //add duplicates to the list of combinations
Allcombinations.add(recursiveCombo); //add list of combinations to the list of all combinations
}
remaining.remove(next); //remove the selected "next" element. removal of the "next" element
//here makes the program add duplicates to the combination
Allcombinations.addAll(combination(remaining,size)); //call the same method recursively with n-1 elements and repeat till size is 0.
return Allcombinations;
}
}
|
package com.shahab.pagestat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PageStatApplication {
public static void main(String[] args) {
SpringApplication.run(PageStatApplication.class, args);
}
}
|
package com.cbs.edu.jdbc.objects;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AbstractEntity {
protected Integer id;
}
|
package com.intentsg.service.tour;
import com.intentsg.service.tour.controller.TourController;
import com.intentsg.service.tour.model.Tour;
import com.intentsg.service.tour.model.UserTour;
import com.intentsg.service.tour.repository.TourRepository;
import com.intentsg.service.tour.repository.UserTourRepository;
import com.intentsg.service.tour.service.TourService;
import com.intentsg.service.tour.service.TourServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TourServiceApplication.class)
@WebAppConfiguration
public class TourServiceApplicationTest {
@Autowired
private TourController controller;
@Autowired
private Tour tour;
@Autowired
private UserTour userTour;
@Autowired
private TourService tourService;
@Autowired
private TourRepository tourRepository;
@Autowired
private UserTourRepository userTourRepository;
@Autowired
private TourServiceImpl tourServiceImpl;
@Test
public void main() {
TourServiceApplication.main(new String[]{});
}
@Test
public void contextLoadsTourController() {
assertNotEquals(controller, null);
}
@Test
public void contextLoadsTour() {
assertNotEquals(tour, null);
}
@Test
public void contextLoadsUserTour() {
assertNotEquals(userTour, null);
}
@Test
public void contextLoadsTourService() {
assertNotEquals(tourService, null);
}
@Test
public void contextLoadsTourRepository() {
assertNotEquals(tourRepository, null);
}
@Test
public void contextLoadsUserTourRepository() {
assertNotEquals(userTourRepository, null);
}
@Test
public void contextLoadsTourServiceImpl() {
assertNotEquals(tourServiceImpl, null);
}
}
|
package com.kata.foo;
public class MathOperation implements IMath {
protected int left;
protected int right;
@Override
public int doOperation() {
return 0;
}
}
|
package com.springboot.web.controller;
import java.util.logging.Logger;
import org.slf4j.*;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.springboot.web.controller.*;
import com.springboot.web.model.*;
import com.springboot.web.service.*;
import com.springboot.web.service.EditService;
@Controller
public class EditController {
@Autowired
EditService service;
private static Logger logger = LoggerFactory.getLogger(searchController.class);
@RequestMapping(value = "/useredit", method = RequestMethod.GET)
public String showUserEdit(ModelMap model) {
logger.info("Inside search User");
model.addAttribute("userEdit", new UserInfoEntity());
return "useredit";
}
@RequestMapping(value = "/useredit", method = RequestMethod.POST)
public String processEdit(@ModelAttribute("userSearch")UserInfoEntity updateUser, ModelMap model) {
logger.info("Inside processEdit fileName = EditController.java");
if (!updateUser.equals(null) && updateUser.getFirstName() != "" && updateUser.getLastName() != "" && updateUser.getEmail() != "" && updateUser.getLocation() != "") {
service.updateUser(updateUser);
return "userupdated";
}
logger.warning("Blank TextField Detected");
model.addAttribute("update", "Please fill the fields");
return "useredit";
}
}
|
package com.lsm.springboot.service;
import com.alibaba.fastjson.JSONObject;
import com.lsm.springboot.BaseTest;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.*;
@Slf4j
public class IRedisHashServiceTest extends BaseTest {
@Autowired
private IRedisHashService redisHashServiceImpl;
@Autowired
private RedisTemplate<String, String> redisTemplate;
private static final String key = "hash_init";
@Before
public void flushDb() {
redisTemplate.execute((RedisConnection connection) -> {
connection.flushDb();
return "ok";
});
/*redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushDb();
return "ok";
}
});*/
Map<String, String> map = new HashMap<>();
map.put("id", "1001");
map.put("name", "lishenming");
map.put("age", "25");
map.put("phoneNum", "18621949186");
map.put("birthday", "1992-01-16");
redisHashServiceImpl.hMSet(key, map);
}
@Test
public void hSet() throws Exception {
redisHashServiceImpl.hSet(key, "name2", "value2");
}
@Test
public void hSetNX() throws Exception {
Boolean setNX1 = redisHashServiceImpl.hSetNX(key, "name", "lsm1");
Boolean setNX2 = redisHashServiceImpl.hSetNX(key, "name2", "lsm2");
log.info("setNX1: {}, setNX2: {}", setNX1, setNX2);
}
@Test
public void hDel() throws Exception {
Long del = redisHashServiceImpl.hDel(key, "name", "name2");
log.info("del: {}", del);
}
@Test
public void hExists() throws Exception {
Boolean hExists1 = redisHashServiceImpl.hExists(key, "name");
Boolean hExists2 = redisHashServiceImpl.hExists(key, "name2");
log.info("hExists1: {}, hExists2: {}", hExists1, hExists2);
}
@Test
public void hGet() throws Exception {
String hGet1 = redisHashServiceImpl.hGet(key, "name");
String hGet2 = redisHashServiceImpl.hGet(key, "name2");
log.info("hGet1: {}, hGet2: {}", hGet1, hGet2);
}
@Test
public void hMGet() throws Exception {
List<String> hMGet = redisHashServiceImpl.hMGet(key, Arrays.asList("name", "name2", "age"));
log.info("hMGet: {}", JSONObject.toJSONString(hMGet));
}
@Test
public void hIncrBy() throws Exception {
Long age1 = redisHashServiceImpl.hIncrBy(key, "age2", 18);
Long age2 = redisHashServiceImpl.hIncrBy(key, "age2", -5);
Double age3 = redisHashServiceImpl.hIncrBy(key, "age2", 1.5);
Double age4 = redisHashServiceImpl.hIncrBy(key, "age2", -3.5);
log.info("age1: {}, age2: {}, age3: {}, age4: {}", age1, age2, age3, age4);
}
@Test
public void hKeys() throws Exception {
Set<String> hKeys = redisHashServiceImpl.hKeys(key);
log.info("hKeys: {}", JSONObject.toJSONString(hKeys));
}
@Test
public void hLen() throws Exception {
Long hLen = redisHashServiceImpl.hLen(key);
log.info("hLen: {}", hLen);
}
@Test
public void hVals() throws Exception {
List<String> hVals = redisHashServiceImpl.hVals(key);
log.info("hVals: {}", hVals);
}
@Test
public void hGetAll() throws Exception {
Map<String, String> map = redisHashServiceImpl.hGetAll(key);
log.info("map: {}", JSONObject.toJSONString(map));
}
}
|
package com.blurack.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.blurack.R;
/**
* Preferences class to manage
* Preferences from single place.
* This class provides interface to saving
* and getting data form Preferences.
* Created by Rakesh on 01/09/14.
*/
public class Preferences {
private SharedPreferences mPrefs = null;
private Context context;
private static final String TAG = Preferences.class.getCanonicalName();
private Preferences(){}
public static Preferences getInstance(Context activity){
Preferences prefrences = new Preferences();
prefrences.context = activity;
prefrences.mPrefs = activity.getSharedPreferences(activity.getString(R.string.app_name), Context.MODE_PRIVATE);
return prefrences;
}
public void setString(String key,String value)
{
try{
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(key, value);
editor.commit();
}catch(Exception e){
Log.i(TAG,e.getMessage());
}
}
public String getString(String key){
try{
return mPrefs.getString(key, null);
}catch(Exception e){
Log.i(TAG,e.getMessage());
}
return null;
}
public String getString(String key,String defaultValue){
try{
return mPrefs.getString(key, defaultValue);
}catch(Exception e){
Log.i(TAG,e.getMessage());
}
return defaultValue;
}
public void setLong(String key,long value)
{
try{
SharedPreferences.Editor editor = mPrefs.edit();
editor.putLong(key, value);
editor.commit();
}catch(Exception e){
Log.i(TAG,e.getMessage());
}
}
public long getLong(String key){
try{
return mPrefs.getLong(key, -1L);
}catch(Exception e){
Log.i(TAG,e.getMessage());
}
return -1L;
}
public void clearSharedPref(){
try{
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear();
editor.commit();
}catch(Exception e){
Log.i(TAG,e.getMessage());
}
}
public void setBoolean(String key,Boolean value)
{
try{
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(key, value);
editor.commit();
}catch(Exception e){
Log.i(TAG,e.getMessage());
}
}
public Boolean getBoolean(String key){
try{
return mPrefs.getBoolean(key, false);
}catch(Exception e){
Log.i(TAG,e.getMessage());
}
return false;
}
public SharedPreferences getPreferences()
{
return mPrefs;
}
}
|
package com.mqld.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class JdbcUtil {
public static void release(ResultSet rs,Statement statement,Connection conn) {
if (rs!=null) {
try {
rs.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
rs=null;
}
if (statement!=null) {
try {
statement.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
statement=null;
}
if (conn!=null) {
try {
conn.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
conn=null;
}
}
}
|
import java.rmi.RemoteException;
import java.util.ArrayList;
public class CalculatorImpl implements Calculator {
@Override
public double [] calculate(int a, int b, int c) throws RemoteException {
double d = b * b - 4 * a * c;
double x1 = ( -b - Math.sqrt(d) ) / ( 2 * a );
double x2 = ( -b + Math.sqrt(d) ) / ( 2 * a );
ArrayList<Double> xArray = new ArrayList<>();
xArray.add(x1);
if (x1 != x2)
xArray.add(x2);
return xArray.stream().mapToDouble(Double::doubleValue).toArray();
}
}
|
package com.example.starter;
import io.vertx.core.Vertx;
public class Run {
public static void main(String[] args) {
Vertx v = Vertx.vertx();
v.deployVerticle(new MainVerticle());
}
}
|
package by.client.android.railwayapp.model;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Утилитный класс для работы с {@link Parcelable}
*
* @author PRV
*/
public class ParcelableUtils {
public static <T> T readValue(Parcel parcelable, Class clas) {
return (T) parcelable.readValue(clas.getClassLoader());
}
public static <T extends Parcelable> T readParcelable(Parcel parcelable, Class clas) {
return parcelable.readParcelable(clas.getClassLoader());
}
public static Date readDate(Parcel parcelable) {
long tmpDepartureDate = parcelable.readLong();
return tmpDepartureDate == -1 ? null : new Date(tmpDepartureDate);
}
public static long getDateTime(Date date) {
return date != null ? date.getTime() : -1;
}
}
|
package com.hcl.dctm.data.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSysObject;
import com.hcl.dctm.data.exceptions.DctmException;
import com.hcl.dctm.data.params.CopyObjectParam;
class CopyContentImpl extends DctmImplBase {
public CopyContentImpl(IDfSession session) {
super(session);
}
public boolean copyContent(CopyObjectParam params) throws DctmException{
try{
boolean status = false;
GetObjectFromIdentity getObjectFromIdentity = new GetObjectFromIdentity(getSession());
IDfSysObject srcObject = getObjectFromIdentity.getObject(params.getSrcObjectIdentity());
IDfSysObject destObject = getObjectFromIdentity.getObject(params.getDestIdentity());
//System.out.println(srcObject.getObjectId() + "," + destObject.getObjectId());
if(null == srcObject || null == destObject) return false;
if(srcObject.getContentSize()>0){
ByteArrayInputStream bis = srcObject.getContentEx3(srcObject.getFormat().getName(), 0, null, false);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[8192];
while(bis.available()>0){
bis.read(data);
bos.write(data);
}
status = destObject.setContentEx2(bos, srcObject.getFormat().getName(), 0, false);
bis.close();
bos.close();
}
if(srcObject.getOtherFileSize(0, srcObject.getFormat().getName(), null) > 0){
ByteArrayInputStream bis = srcObject.getContentEx3(srcObject.getFormat().getName(), 0, null, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[8192];
while(bis.available()>0){
bis.read(data);
bos.write(data);
}
status = status || destObject.setContentEx2(bos, srcObject.getFormat().getName(), 0, true);
bis.close();
bos.close();
}
destObject.save();
return status;
}
catch(Throwable e){
throw new DctmException(e);
}
}
// private void createFolder() throws Exception {
// log("** Testing folder creation");
// folder = (IDfFolder) session.newObject("dm_folder");
// folder.setObjectName(DIR_NAME);
// folder.link("/Temp");
// folder.save();
// log("created folder " + folder.getId("r_object_id"));
// assertEquals("unexpected folder path", DIR_PATH, folder.getFolderPath(0));
// }
//
// private void createFile() throws Exception {
// log("** Testing file creation");
// document = (IDfDocument) session.newObject("dm_document");
// document.setObjectName(FILE_NAME);
// document.setContentType("crtext");
// document.setFile("E:/clipboard.txt"); // add content to this dm_document document.save();
// log("created file" + document.getId("r_object_id"));
// }
//
// private void linkFileToFolder() throws Exception {
// log("** Testing file linking to folder");
// document.link(DIR_PATH); document.save();
// log(FILE_PATH);
// assertNotNull("unexpected folder path", session.getObjectByPath( FILE_PATH));
// }
//
// private void modifyFile() throws Exception {
// log("** Testing file modification");
// document.checkout();
// int numAuthors = document.getAuthorsCount();
// document.setAuthors(numAuthors, DOC_AUTHOR); //doc.checkin(false, "Prevents promotion to CURRENT");
// document.checkin(false, null); // When a null version label is provided, // DFC automatically gives the new version // an implicit version label (1.1, 1.2, etc.) // and the symbolic label "CURRENT". }
//
// private void fetchFolderContents() throws Exception {
// log("** Testing folder contents");
// // (1) Fetch using IDfFolder object
// IDfFolder folder = session.getFolderByPath(DIR_PATH);
// assertNotNull("folder is null", folder);
// IDfCollection collection = null;
// IDfDocument doc = null; int count = 0;
// try { collection = folder.getContents("r_object_id");
// while (collection.next()) { count++; IDfId id = collection.getId("r_object_id");
// doc = (IDfDocument) session.getObject(id); log(id + ": " + doc.getObjectName()); } }
// finally {
// // ALWAYS! clean up your collections
// if (collection != null) { collection.close(); } }
// assertEquals("wrong number of files in folder", 1, count);
// assertEquals("unexpected doc name", FILE_NAME, doc.getObjectName());
// // (2) Fetch using DQL folder(..)
// String dql = "SELECT r_object_id, object_name from dm_document where folder('"+DIR_PATH+"');";
// // Or we can fetch the contents of our folder and all of its subfolders using // // folder('/Temp/Subdir', descend) // // But since we haven't added any subfolders, this will return the same set of dm_documents. //
// // String dql = "SELECT r_object_id, object_name from dm_document where folder('"+DIR_PATH+"', descend);";
// IDfQuery query = new DfQuery(); query.setDQL(dql);
// collection = null; String docName = null; count = 0;
// try { collection = query.execute(session, IDfQuery.DF_READ_QUERY);
// while (collection.next()) {
// count++; String id = collection.getString("r_object_id");
// docName = collection.getString("object_name");
// log(id + ": " + docName); } }
// finally { // ALWAYS! clean up your collections
// if (collection != null) { collection.close(); } }
// assertEquals("wrong number of files in folder", 1, count);
// assertEquals("unexpected doc name", FILE_NAME, docName); }
// private void queryFiles() throws Exception { log("** Testing file query");
// // (1) load by path
// IDfDocument doc = (IDfDocument) session.getObjectByPath(FILE_PATH);
// assertNotNull("null doc returned", doc);
// assertEquals("unexpected doc name", FILE_NAME, doc.getObjectName());
// // (2) load by query // NOTE: Authors is a "repeating attribute" in Documentum terminology, // meaning it is multi-valued. So we need to use the ANY DQL keyword here. doc = null;
// String dql = "SELECT r_object_id" + " FROM dm_document" + " WHERE object_name = '" + FILE_NAME + "'" + " AND ANY authors = '" + DOC_AUTHOR + "'";
// IDfQuery query = new DfQuery();
// query.setDQL(dql);
// IDfCollection collection = query.execute(session, IDfQuery.DF_READ_QUERY);
// try { assertTrue("query did not return any results", collection.next());
// doc = (IDfDocument) session.getObject(collection.getId("r_object_id"));
// } finally { // ALWAYS! clean up your collections if (collection != null) { collection.close(); } } assertNotNull("null doc returned", doc); assertEquals("unexpected doc name", FILE_NAME, doc.getObjectName());
// }
// }
//
// private void deleteFile() throws Exception {
// if (document != null) { log("** Testing file deletion"); document.destroyAllVersions();
// } }
//
// private void deleteFolder() throws Exception {
// if (folder != null) { log("** Testing folder deletion");
// folder.destroyAllVersions(); } }
// private void initialize() { // If something bad happened during the previous run, this will // make sure we're back in a good state for this test run. try { session.getObjectByPath(FILE_PATH).destroy(); } catch (Exception e) { // ignore } try { session.getObjectByPath(DIR_PATH).destroy(); } catch (Exception e) { // ignore } } }
// }
// }
// }
}
|
package com.blurack.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.blurack.AppController;
import com.blurack.R;
import com.blurack.activities.HomeActivity;
import com.blurack.adapters.CockRecipesCatAdapter;
import com.blurack.adapters.CockRecipesRecyclerViewAdapter;
import com.blurack.constants.Constants;
import com.blurack.dto.RecipeCategoryItem;
import com.blurack.utils.Preferences;
import com.blurack.utils.ToastUtils;
import com.blurack.views.EmptyRecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;
/**
* A fragment representing a list of Items.
*/
public class CocktailRecipesFragment extends Fragment implements CockRecipesRecyclerViewAdapter.CockTailListener {
private static final String TAG_COCKTAIL_RECIPES = "COCKTAIL_RECIPES";
private static final String ARG_COLUMN_COUNT = "column-count";
private int mColumnCount = 1;
private CockRecipesCatAdapter recyclerViewAdapter;
private EmptyRecyclerView recyclerView;
private AutoCompleteTextView editSearch;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public CocktailRecipesFragment() {
}
public static CocktailRecipesFragment newInstance(int columnCount) {
CocktailRecipesFragment fragment = new CocktailRecipesFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recyclerViewAdapter = null;
// Cancel all pending requests if any.
AppController.getInstance().cancelPendingRequests(TAG_COCKTAIL_RECIPES);
// Fetch data for categories.
if(savedInstanceState==null)
populateData();
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recipies_list, container, false);
View view = rootView.findViewById(R.id.list);
LinearLayout searchBar = (LinearLayout) rootView.findViewById(R.id.search_bar);
searchBar.setVisibility(View.VISIBLE);
editSearch = (AutoCompleteTextView) searchBar.findViewById(R.id.edit_search);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
recyclerView = (EmptyRecyclerView) view;
GridLayoutManager mLayoutManager = new GridLayoutManager(context, 2);
recyclerView.setLayoutManager(mLayoutManager);
View emptyView = rootView.findViewById(R.id.emptyLayout);
recyclerView.setEmptyView(emptyView);
mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch (recyclerViewAdapter.getItemViewType(position)){
case CockRecipesRecyclerViewAdapter.RECIPES:
return 1;
default:
return 2;
}
}
});
SlideInLeftAnimator animator = new SlideInLeftAnimator();
animator.setInterpolator(new OvershootInterpolator());
if(recyclerViewAdapter==null) {
recyclerViewAdapter = new CockRecipesCatAdapter(createListForAdapter(),this);
if(recyclerView!=null){
recyclerView.setAdapter(recyclerViewAdapter);
}
}
recyclerView.setAdapter(recyclerViewAdapter);
searchBar.findViewById(R.id.searchButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String query = editSearch.getText().toString();
// Check if no view has focus:
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
if (!TextUtils.isEmpty(query)) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, RecipesFragment.newSearchInstance(query)).addToBackStack(null).commit();
}
}
});
}
return rootView;
}
private ArrayList<RecipeCategoryItem> createListForAdapter(){
ArrayList<RecipeCategoryItem> list = new ArrayList<>();
list.add(new RecipeCategoryItem("header","0"));
return list;
}
private void populateData(){
if(recyclerViewAdapter==null) {
recyclerViewAdapter = new CockRecipesCatAdapter(createListForAdapter(),this);
if(recyclerView!=null){
recyclerView.setAdapter(recyclerViewAdapter);
}
}
String[] cocktails = getResources().getStringArray(R.array.cocktails);
if(cocktails!=null){
for (int i = 0; i < cocktails.length; i++) {
try {
recyclerViewAdapter.add(new RecipeCategoryItem(cocktails[i],null));
}catch (Exception e){
VolleyLog.d(TAG_COCKTAIL_RECIPES, "Error::populateData(): " + e.getMessage());
}
}
}
}
@Override
public void onResume(){
super.onResume();
if(getActivity() instanceof HomeActivity) {
// Set title bar
((HomeActivity) getActivity()).setActionBarTitle("Cocktail Recipes");
}
}
@Override
public void onCategorySelected(String category) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, RecipesFragment.newInstance(category)).addToBackStack(null).commit();
}
}
|
public class Solution {
public int[] quickSort(int[] array) {
// Write your solution here
if (array == null || array.length <= 1) {
return array;
}else {
int left = 0;
int right = array.length - 1;
sort(array,left,right);
return array;
}
//time complexity: worst case:O(n^2), average: O(n*logn)
/*解释:最坏情况下,每次选取的pivot都是当前array里的最小值,导致需要n次recursion完成排序。
在每层recursion中,需要O(n)的时间,故总时间复杂度为O(n*n)*/
//space complexity: worst O(n), average: O(log(n))
/*解释:空间复杂度来自于recursion时的call stack,和最大recursion深度有关。
最坏情况下,需要进行n次recursion,每层recursion的空间复杂度为O(1),故总空间复杂度为O(n)*/
}
private static void sort(int[] array, int left, int right) {
if (left >= right) {
return;
}
if (array == null || array.length <= 1) {
return;
}
int i = 0;
int pivot = right;
int k = pivot - 1;
while (i <= k) {
if (array[i] <= array[pivot]) {
i++;
}else {
swap(array,i,k);
k--;
}
}
swap(array,i,pivot);
sort(array,left,i-1);//如果这里写为sort(array,left,i)会陷入死循环因为在最坏情况下,这样写会导致下次的pivot和这次相等。
sort(array,i+1,right);
}
private static void swap(int[] array, int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}
|
package com.worldchip.bbp.ect.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.worldchip.bbp.ect.R;
public class FestivalActivity extends Activity{
private Button backButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int flag = getIntent().getIntExtra("flag", -1);
switch (flag) {
case 0:
setContentView(R.layout.birthday_layout);
break;
case 1:
setContentView(R.layout.yuandan);
break;
case 2:
setContentView(R.layout.childrenday);
break;
case 3:
setContentView(R.layout.lunar_new_year);
break;
case 4:
setContentView(R.layout.duanwu_layout);
break;
}
backButton = (Button) findViewById(R.id.back_button);
backButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
|
package exercises.chapter7.ex18;
/**
* @author Volodymyr Portianko
* @date.created 22.03.2016
*/
public class Exercise18 {
static final String STATIC_TEXT = "STATIC TEXT";
final String TEXT = "TEXT";
public static void main(String[] args) {
System.out.println(Exercise18.STATIC_TEXT);
System.out.println(new Exercise18().TEXT);
}
}
|
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Locators_PartialLinkText_CSS_TagName {
public static void main(String[] args) {
// first linktext method then partial linktext & CSS
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://newtours.demoaut.com/");
//here list of all the links is created and stored in the LinkList
// all the links are find by anchor tag 'a'
java.util.List<WebElement> LinkList = driver.findElements(By.tagName("a"));
//list size is calculated
System.out.println(LinkList.size());
for(int i=0; i<LinkList.size(); i++)
{
String Linktext = LinkList.get(i).getText();
if(Linktext.equalsIgnoreCase("Register Here"))
{
LinkList.get(i).click();
break;
}
}
driver.get("https://www.facebook.com/");
//driver.findElement(By.linkText(""))
driver.findElement(By.cssSelector("#u_0_w")).click();
driver.findElement(By.cssSelector(".fb_logo.img.sp_IIuy94UEXRV.sx_6bf598")).click();
}
}
|
package com.example.mmr;
public class Config {
public static final String MAP_KEY="pk.eyJ1IjoiaWxpYXNzLWRhaG1hbiIsImEiOiJja29nOWt3MHUwZGFoMm5wbGR4cHFidDJyIn0.HVa5FiG2bWJnMz2XrBM9pA";
public static final String URL="https://e-mmr.000webhostapp.com";
public static final String EMAIL="binome1920@gmail.com";
public static final String PASSWORD="adnane_iliass";
}
|
package com.crmiguez.aixinainventory.entities;
import com.fasterxml.jackson.annotation.JsonInclude;
import javax.persistence.*;
import java.io.Serializable;
@Entity(name = "movement")
@Table
public class Movement implements Serializable {
@Id
@GeneratedValue
@Column(name = "movementId")
private Long movementId;
@Column(name = "movementDate")
private String movementDate;
@JoinColumn(name = "moveTypeId", referencedColumnName = "moveTypeId", nullable = false)
@ManyToOne
private MoveType moveType;
@JoinColumn(name = "itemSetId", referencedColumnName = "itemSetId")
@ManyToOne
private ItemSet itemSet;
@JoinColumn(name = "itemId", referencedColumnName = "itemId")
@ManyToOne
private Item item;
@JoinColumn(name = "employeeSourceId", referencedColumnName = "employeeId")
@ManyToOne
private Employee employeeSource;
@JoinColumn(name = "employeeDestinationId", referencedColumnName = "employeeId")
@ManyToOne
private Employee employeeDestination;
@JoinColumn(name = "departmentSourceId", referencedColumnName = "departmentId")
@ManyToOne
private Department departmentSource;
@JoinColumn(name = "departmentDestinationId", referencedColumnName = "departmentId")
@ManyToOne
private Department departmentDestination;
@JoinColumn(name = "locationSourceId", referencedColumnName = "locationId")
@ManyToOne
private Location locationSource;
@JoinColumn(name = "locationDestinationId", referencedColumnName = "locationId")
@ManyToOne
private Location locationDestination;
@JoinColumn(name = "invoiceId", referencedColumnName = "invoiceId")
@ManyToOne
private Invoice invoice;
@JoinColumn(name = "employeeId", referencedColumnName = "employeeId")
@ManyToOne
private Employee employee;
@Column(name = "movementUnits")
private Long movementUnits;
@Column(name = "movementReason")
private String movementReason;
public Movement() {
}
public Movement(Long movementId, String movementDate, MoveType moveType, ItemSet itemSet, Item item, Employee employeeSource, Employee employeeDestination, Department departmentSource, Department departmentDestination, Location locationSource, Location locationDestination, Invoice invoice, Employee employee, Long movementUnits, String movementReason) {
this.movementId = movementId;
this.movementDate = movementDate;
this.moveType = moveType;
this.itemSet = itemSet;
this.item = item;
this.employeeSource = employeeSource;
this.employeeDestination = employeeDestination;
this.departmentSource = departmentSource;
this.departmentDestination = departmentDestination;
this.locationSource = locationSource;
this.locationDestination = locationDestination;
this.invoice = invoice;
this.employee = employee;
this.movementUnits = movementUnits;
this.movementReason = movementReason;
}
public Long getMovementId() {
return movementId;
}
public void setMovementId(Long movementId) {
this.movementId = movementId;
}
public String getMovementDate() {
return movementDate;
}
public void setMovementDate(String movementDate) {
this.movementDate = movementDate;
}
public MoveType getMoveType() {
return moveType;
}
public void setMoveType(MoveType moveType) {
this.moveType = moveType;
}
public ItemSet getItemSet() {
return itemSet;
}
public void setItemSet(ItemSet itemSet) {
this.itemSet = itemSet;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public Employee getEmployeeSource() {
return employeeSource;
}
public void setEmployeeSource(Employee employeeSource) {
this.employeeSource = employeeSource;
}
public Employee getEmployeeDestination() {
return employeeDestination;
}
public void setEmployeeDestination(Employee employeeDestination) {
this.employeeDestination = employeeDestination;
}
public Department getDepartmentSource() {
return departmentSource;
}
public void setDepartmentSource(Department departmentSource) {
this.departmentSource = departmentSource;
}
public Department getDepartmentDestination() {
return departmentDestination;
}
public void setDepartmentDestination(Department departmentDestination) {
this.departmentDestination = departmentDestination;
}
public Location getLocationSource() {
return locationSource;
}
public void setLocationSource(Location locationSource) {
this.locationSource = locationSource;
}
public Location getLocationDestination() {
return locationDestination;
}
public void setLocationDestination(Location locationDestination) {
this.locationDestination = locationDestination;
}
public Invoice getInvoice() {
return invoice;
}
public void setInvoice(Invoice invoice) {
this.invoice = invoice;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Long getMovementUnits() {
return movementUnits;
}
public void setMovementUnits(Long movementUnits) {
this.movementUnits = movementUnits;
}
public String getMovementReason() {
return movementReason;
}
public void setMovementReason(String movementReason) {
this.movementReason = movementReason;
}
}
|
package com.ut.healthelink.security;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
public class CustomWebAuthenticationDetails extends
WebAuthenticationDetailsSource {
@Override
public WebAuthenticationDetails buildDetails(HttpServletRequest context) {
return new MyAuthenticationDetails(context);
}
@SuppressWarnings("serial")
class MyAuthenticationDetails extends WebAuthenticationDetails {
private final String loginAsUser;
public MyAuthenticationDetails(HttpServletRequest request) {
super(request);
this.loginAsUser = request.getParameter("loginAsUser");
}
public String getLoginAsUser() {
return loginAsUser;
}
}
}
|
package com.example.peti.wateringsystem;
import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.os.AsyncTask;
import java.util.List;
public class MeasurementRepository {
private MeasurementDAO mMeasurementDao;
private LiveData<List<Measurement>> mAllMeasurements;
MeasurementRepository(Application application) {
MeasurementRoomDatabase db = MeasurementRoomDatabase.getDatabase(application);
mMeasurementDao = db.measurementDao();
mAllMeasurements = mMeasurementDao.getAllMeasurement();
}
LiveData<List<Measurement>> getmAllMeasurements() {
return mAllMeasurements;
}
public void insert (Measurement measurement) {
new insertAsyncTask(mMeasurementDao).execute(measurement);
}
public void deleteAll(){
new deleteAsyncTask(mMeasurementDao).execute();
}
List<Measurement> getAllMeasurementsStatic() {
return mMeasurementDao.getAllMeasurementStatic();
}
private static class insertAsyncTask extends AsyncTask<Measurement, Void, Void> {
private MeasurementDAO mAsyncTaskDao;
insertAsyncTask(MeasurementDAO dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(final Measurement... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
}
private static class deleteAsyncTask extends AsyncTask<Measurement, Void, Void> {
private MeasurementDAO mAsyncTaskDao;
deleteAsyncTask(MeasurementDAO dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(final Measurement... params) {
mAsyncTaskDao.deleteAll();
return null;
}
}
}
|
package work1;
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Matrixmultiplication {
private static int[][] a;
private int[][] s;
private static int n;
public Matrixmultiplication() throws IOException {
String filePath = Matrixmultiplication.class.getResource("").getPath()
.replace("file:", "")
+ "/AL103hw1data.txt";
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath), "UTF-8"));
String str = null;
while ((str = reader.readLine()) != null) {
System.out.println("讀取檔案中的內容:"+str);
// 讀取文件後的前處理
int h1 = str.indexOf("A1");
String A1 = str.substring(h1 + 3, h1 + 5);
String A1_1 = str.substring(h1 + 6, h1 + 8);
// System.out.println(A1+" "+A1_1);
int h2 = str.indexOf("A2");
String A2 = str.substring(h2 + 6, h2 + 8);
// System.out.println(A2);
int h3 = str.indexOf("A3");
String A3 = str.substring(h3 + 6, h3 + 7);
// System.out.println(A3);
int h4 = str.indexOf("A4");
String A4 = str.substring(h4 + 5, h4 + 7);
// System.out.println(A4);
int h5 = str.indexOf("A5");
String A5 = str.substring(h5 + 6, h5 + 8);
// System.out.println(A5);
int[] p = { Integer.valueOf(A1), Integer.valueOf(A1_1),
Integer.valueOf(A2), Integer.valueOf(A3),
Integer.valueOf(A4), Integer.valueOf(A5) };
// int[] p = { 35, 15, 5, 10, 20 };
// int[] p = { 30,35, 15, 5, 10, 20,25 };
// The number of matrices in the chain
n = p.length - 1;
// used so we don't use 0 in our multiplication
a = new int[n + 1][n + 1];
// used so we don't use 0 in our sub-multiplications
s = new int[n + 1][n + 1];
// the algorithm
matrixChainOrder(p);
}
}
private void matrixChainOrder(int[] p) {
// deals with the empty sub problems
for (int i = 1; i <= n; i++)
a[i][i] = 0;
// deals with chains of link 1
System.out.println("最小相乘成本值的過程:");
for (int l = 2; l <= n; l++) {
for (int i = 1; i <= n - l + 1; i++) {
int j = i + l - 1;
a[i][j] = Integer.MAX_VALUE;
System.out.println("------------------------");
for (int k = i; k < j; k++) {
int q = a[i][k] + a[k + 1][j] + p[i - 1] * p[k] * p[j];
if (q < a[i][j]) {
a[i][j] = q;
s[i][j] = k;
System.out.println(a[i][j] + "-->m[" + i + "][" + j
+ "]" + "m[" + (k + 1) + "][" + j + "] p[i-1]:"
+ p[i - 1] + " p[k]" + p[k] + " p[j]" + p[j]);
}
}
}
}
}
private String printOptimalParens(int i, int j) {
if (i == j)
return "A[" + i + "]";
else
return "(" + printOptimalParens(i, s[i][j])
+ printOptimalParens(s[i][j] + 1, j) + ")";
}
public String toString() {
return "\n鏈結先後順序:"+printOptimalParens(1, n);
}
public static void main(String[] args) throws IOException {
Matrixmultiplication mult = new Matrixmultiplication();
System.out.println(mult);
JFrame demo = new JFrame();
demo.setSize(400, 300);
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
demo.getContentPane().add(BorderLayout.NORTH , label);
}
}
|
package com.example.tests;
public class ContactData implements Comparable<ContactData>{
public String first_name;
public String last_name;
public String address;
public String tel_home;
public String tel_mob;
public String tel_work;
public String email1;
public String email2;
public String day;
public String month;
public String year;
public String group;
public String second_address;
public String second_tel_home;
public ContactData(String last_name, String first_name, String address,
String tel_home, String tel_mob, String tel_work, String email1,
String email2, String day, String month, String year, String group,
String second_address, String second_tel_home) {
this.last_name = last_name;
this.first_name = first_name;
this.address = address;
this.tel_home = tel_home;
this.tel_mob = tel_mob;
this.tel_work = tel_work;
this.email1 = email1;
this.email2 = email2;
this.day = day;
this.month = month;
this.year = year;
this.group = group;
this.second_address = second_address;
this.second_tel_home = second_tel_home;
}
public ContactData() {
}
@Override
public String toString() {
return "ContactData [last_name=" + last_name + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
//result = prime * result
//+ ((last_name == null) ? 0 : last_name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ContactData other = (ContactData) obj;
if (last_name == null) {
if (other.last_name != null)
return false;
} else if (!last_name.equals(other.last_name))
return false;
return true;
}
@Override
public int compareTo(ContactData other) {
int lastNameResult = this.last_name.toLowerCase().compareTo(other.last_name.toLowerCase());
if (lastNameResult != 0) {
return lastNameResult;
} else {
return this.first_name.toLowerCase().compareTo(other.first_name.toLowerCase());
}
}
}
|
package com.legaoyi.storer.handler;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.legaoyi.common.message.ExchangeMessage;
import com.legaoyi.mq.MQMessageProducer;
import com.legaoyi.storer.dao.DeviceUpMessageDao;
import com.legaoyi.storer.util.Constants;
@Component(Constants.ELINK_MESSAGE_STORER_BEAN_PREFIX + "1205_2016" + Constants.ELINK_MESSAGE_STORER_MESSAGE_HANDLER_BEAN_SUFFIX)
public class JTT808_1205_2016_MessageHandler extends MessageHandler {
@Autowired
@Qualifier("platformNotifyProducer")
private MQMessageProducer platformNotifyProducer;
@Autowired
@Qualifier("deviceUpMessageDao")
private DeviceUpMessageDao deviceUpMessageDao;
@SuppressWarnings("unchecked")
@Override
public void handle(ExchangeMessage message) throws Exception {
Map<?, ?> map = (Map<?, ?>) message.getMessage();
Map<String, Object> messageBody = (Map<String, Object>) map.get(Constants.MAP_KEY_MESSAGE_BODY);
Map<?, ?> device = (Map<?, ?>) message.getExtAttribute(Constants.MAP_KEY_DEVICE);
String deviceId = (String) device.get(Constants.MAP_KEY_DEVICE_ID);
Map<?, ?> messageHeader = (Map<?, ?>) map.get(Constants.MAP_KEY_MESSAGE_HEADER);
int messageSeq = (Integer) messageHeader.get(Constants.MAP_KEY_MESSAGE_SEQ);
int respMessageSeq = (Integer) messageBody.get(Constants.MAP_KEY_MESSAGE_SEQ);
deviceUpMessageDao.updateFileUploadState(deviceId, respMessageSeq, 3, messageSeq);
}
}
|
package Ges_Matiere_module;
import java.net.URL;
import java.util.ResourceBundle;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXTextField;
import coucheControler.Metier;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import partieConsole.Matiere;
import partieConsole.Module;
import partieConsole.Salle;
public class ControllerMatiereSalleModule implements Initializable {
Metier metier = new Metier();
ObservableList<String> DispoList = FXCollections.observableArrayList("OUI","NON");
ObservableList<Integer> listModule = FXCollections.observableArrayList(1,2,3,4,5);
ObservableList<Matiere> matList = FXCollections.observableArrayList(metier.AfficherMatiere());
//matList.addAll(metier.AfficherMatiere());
@FXML
private AnchorPane anchorPrincipale;
@FXML
private JFXTextField tIdSalle;
@FXML
private JFXTextField tNomSalle;
@FXML
private JFXTextField tCapaciteSalle;
@FXML
private JFXComboBox<String> cDispoSalle;
@FXML
private TableView<Salle> tViewSalle;
@FXML
private TableColumn<Salle, Integer> viewId;
@FXML
private TableColumn<Salle, String> viewNom;
@FXML
private TableColumn<Salle, Integer> viewCapacite;
@FXML
private TableColumn<Salle, String> DispoView;
@FXML
private JFXButton ajoutSalle;
@FXML
private JFXButton annulerSalle;
@FXML
private JFXButton afficherSalle;
@FXML
private JFXTextField tSaisirCapaciteSalle;
@FXML
private JFXButton validerSalle;
@FXML
private TableView<Matiere> tViewMatiere;
@FXML
private TableColumn<Matiere, Integer> viewIdMat;
@FXML
private TableColumn<Matiere, String> viewNomMat;
@FXML
private TableColumn<Matiere, String> viewLibMat;
@FXML
private TableColumn<Matiere, String> viewLangMat;
@FXML
private TableColumn<Matiere, String> viewNivMat;
@FXML
private TableColumn<Matiere, Integer> viewModuleMat;
@FXML
private JFXTextField tIdMatiere;
@FXML
private JFXTextField tNomMatiere;
@FXML
private JFXTextField tLibelleMatiere;
@FXML
private JFXTextField tLangueMatiere;
@FXML
private JFXTextField tNiveauMatiere;
@FXML
private JFXTextField tNbreHeures;
@FXML
private JFXComboBox<Integer> cMatiere;
@FXML
private JFXButton ajoutMatiere;
@FXML
private JFXButton annulerMatiere;
@FXML
private JFXButton SupMatiere;
@FXML
private JFXButton AfficherMatiere;
@FXML
private JFXTextField tSupMatiere;
@FXML
private JFXTextField tIdModule;
@FXML
private JFXTextField tNomModule;
@FXML
private JFXButton ajoutModule;
@FXML
private JFXButton annulerModule;
public AnchorPane getAnchorPrincipale() {
return anchorPrincipale;
}
public void setAnchorPrincipale(AnchorPane anchorPrincipale) {
this.anchorPrincipale = anchorPrincipale;
}
public JFXTextField gettIdSalle() {
return tIdSalle;
}
public void settIdSalle(JFXTextField tIdSalle) {
this.tIdSalle = tIdSalle;
}
public JFXTextField gettNomSalle() {
return tNomSalle;
}
public void settNomSalle(JFXTextField tNomSalle) {
this.tNomSalle = tNomSalle;
}
public JFXTextField gettCapaciteSalle() {
return tCapaciteSalle;
}
public void settCapaciteSalle(JFXTextField tCapaciteSalle) {
this.tCapaciteSalle = tCapaciteSalle;
}
public JFXComboBox<String> getcDispoSalle() {
return cDispoSalle;
}
public void setcDispoSalle(JFXComboBox<String> cDispoSalle) {
this.cDispoSalle = cDispoSalle;
}
public TableView<Salle> gettViewSalle() {
return tViewSalle;
}
public void settViewSalle(TableView<Salle> tViewSalle) {
this.tViewSalle = tViewSalle;
}
public JFXButton getAjoutSalle() {
return ajoutSalle;
}
public void setAjoutSalle(JFXButton ajoutSalle) {
this.ajoutSalle = ajoutSalle;
}
public JFXButton getAnnulerSalle() {
return annulerSalle;
}
public void setAnnulerSalle(JFXButton annulerSalle) {
this.annulerSalle = annulerSalle;
}
public JFXButton getAfficherSalle() {
return afficherSalle;
}
public void setAfficherSalle(JFXButton afficherSalle) {
this.afficherSalle = afficherSalle;
}
public JFXTextField gettSaisirCapaciteSalle() {
return tSaisirCapaciteSalle;
}
public void settSaisirCapaciteSalle(JFXTextField tSaisirCapaciteSalle) {
this.tSaisirCapaciteSalle = tSaisirCapaciteSalle;
}
public JFXButton getValiderSalle() {
return validerSalle;
}
public void setValiderSalle(JFXButton validerSalle) {
this.validerSalle = validerSalle;
}
public TableView<?> gettViewMatiere() {
return tViewMatiere;
}
public void settViewMatiere(TableView<Matiere> tViewMatiere) {
this.tViewMatiere = tViewMatiere;
}
public JFXTextField gettIdMatiere() {
return tIdMatiere;
}
public void settIdMatiere(JFXTextField tIdMatiere) {
this.tIdMatiere = tIdMatiere;
}
public JFXTextField gettNomMatiere() {
return tNomMatiere;
}
public void settNomMatiere(JFXTextField tNomMatiere) {
this.tNomMatiere = tNomMatiere;
}
public JFXTextField gettLibelleMatiere() {
return tLibelleMatiere;
}
public void settLibelleMatiere(JFXTextField tLibelleMatiere) {
this.tLibelleMatiere = tLibelleMatiere;
}
public JFXTextField gettLangueMatiere() {
return tLangueMatiere;
}
public void settLangueMatiere(JFXTextField tLangueMatiere) {
this.tLangueMatiere = tLangueMatiere;
}
public JFXTextField gettNiveauMatiere() {
return tNiveauMatiere;
}
public void settNiveauMatiere(JFXTextField tNiveauMatiere) {
this.tNiveauMatiere = tNiveauMatiere;
}
public JFXTextField gettNbreHeures() {
return tNbreHeures;
}
public void settNbreHeures(JFXTextField tNbreHeures) {
this.tNbreHeures = tNbreHeures;
}
public JFXComboBox<?> getcMatiere() {
return cMatiere;
}
public void setcMatiere(JFXComboBox<Integer> cMatiere) {
this.cMatiere = cMatiere;
}
public JFXButton getAjoutMatiere() {
return ajoutMatiere;
}
public void setAjoutMatiere(JFXButton ajoutMatiere) {
this.ajoutMatiere = ajoutMatiere;
}
public JFXButton getAnnulerMatiere() {
return annulerMatiere;
}
public void setAnnulerMatiere(JFXButton annulerMatiere) {
this.annulerMatiere = annulerMatiere;
}
public JFXButton getSupMatiere() {
return SupMatiere;
}
public void setSupMatiere(JFXButton supMatiere) {
SupMatiere = supMatiere;
}
public JFXButton getAfficherMatiere() {
return AfficherMatiere;
}
public void setAfficherMatiere(JFXButton afficherMatiere) {
AfficherMatiere = afficherMatiere;
}
public JFXTextField gettSupMatiere() {
return tSupMatiere;
}
public void settSupMatiere(JFXTextField tSupMatiere) {
this.tSupMatiere = tSupMatiere;
}
public JFXTextField gettIdModule() {
return tIdModule;
}
public void settIdModule(JFXTextField tIdModule) {
this.tIdModule = tIdModule;
}
public JFXTextField gettNomModule() {
return tNomModule;
}
public void settNomModule(JFXTextField tNomModule) {
this.tNomModule = tNomModule;
}
public JFXButton getAjoutModule() {
return ajoutModule;
}
public void setAjoutModule(JFXButton ajoutModule) {
this.ajoutModule = ajoutModule;
}
public JFXButton getAnnulerModule() {
return annulerModule;
}
public void setAnnulerModule(JFXButton annulerModule) {
this.annulerModule = annulerModule;
}
@FXML
void AfficherMatiere(ActionEvent event) {
viewIdMat.setCellValueFactory(new PropertyValueFactory<>("idMatiere"));
viewNomMat.setCellValueFactory(new PropertyValueFactory<>("nomMatiere"));
viewLibMat.setCellValueFactory(new PropertyValueFactory<>(" libelleMatiere"));
viewLangMat.setCellValueFactory(new PropertyValueFactory<>("langLibelleMatiere"));
viewNivMat.setCellValueFactory(new PropertyValueFactory<>("nivMatiere"));
viewModuleMat.setCellValueFactory(new PropertyValueFactory<>("module"));
tViewMatiere.setItems(matList);
}
@FXML
void AfficherSalle(ActionEvent event) {
ObservableList<Salle> salleList = FXCollections.observableArrayList();
viewId.setCellValueFactory(new PropertyValueFactory<>(""));
viewNom.setCellValueFactory(new PropertyValueFactory<>(""));
viewCapacite.setCellValueFactory(new PropertyValueFactory<>(""));
DispoView.setCellValueFactory(new PropertyValueFactory<>(""));
tViewSalle.refresh();
tViewSalle.setItems(salleList);
//***********************************
salleList.addAll(metier.AfficherSalle());
viewId.setCellValueFactory(new PropertyValueFactory<>("idSalle"));
viewNom.setCellValueFactory(new PropertyValueFactory<>("nomSalle"));
viewCapacite.setCellValueFactory(new PropertyValueFactory<>("capaciteSalle"));
DispoView.setCellValueFactory(new PropertyValueFactory<>("disponibiliteSalle"));
tViewSalle.setItems(salleList);
}
@FXML
void AjouterMatiere(ActionEvent event) {
if(tIdMatiere.getText()!= null && tLibelleMatiere.getText()!= null && tLangueMatiere.getText()!= null
&& tNomMatiere.getText()!=null &&tNiveauMatiere.getText()!= null && cMatiere.getValue()!= 0) {
int numModule =cMatiere.getValue();
int id =Integer.parseInt(tIdMatiere.getText());
Matiere matiere = new Matiere (id, tNomMatiere.getText(),tLibelleMatiere.getText(),tLangueMatiere.getText(),
tNiveauMatiere.getText()) ;
metier.AjouterMatiere(matiere, numModule);
System.out.println("Succès!!!");
}
else {
System.out.println("Error!!!");
}
tIdMatiere.clear();
tNomMatiere.clear();
tLibelleMatiere.clear();
tLangueMatiere.clear();
tNiveauMatiere.clear();
tNbreHeures.clear();
}
@FXML
void AjouterModule(ActionEvent event) {
int id=Integer.parseInt(tIdModule.getText());
String nom= tNomModule.getText();
Module module = new Module(id,nom);
metier.AjouterModule(module);
tNomModule.clear();
tIdModule.clear();
}
@FXML
void AjouterSalle(ActionEvent event) {
int id=Integer.parseInt(tIdSalle.getText());
String nom= tNomSalle.getText();
int capacite =Integer.parseInt(tCapaciteSalle.getText());
if((tIdSalle.getText()!=null)&&(tNomSalle.getText()!=null)&&(tCapaciteSalle.getText()!= null)&&(cDispoSalle.getValue()!=null)) {
Salle salle = new Salle(id,nom,capacite,cDispoSalle.getValue());
metier.AjouterSalle(salle);
}
tIdSalle.clear();
tNomSalle.clear();
tCapaciteSalle.clear();
}
@FXML
void AnnulerMatiere(ActionEvent event) {
tIdMatiere.clear();
tNomMatiere.clear();
tLibelleMatiere.clear();
tLangueMatiere.clear();
tNiveauMatiere.clear();
tNbreHeures.clear();
}
@FXML
void AnnulerModule(ActionEvent event) {
tNomModule.clear();
tIdModule.clear();
}
@FXML
void AnnulerSalle(ActionEvent event) {
tIdSalle.clear();
tNomSalle.clear();
tCapaciteSalle.clear();
}
@FXML
void SupprimerMatiere(ActionEvent event) {
int id =Integer.parseInt(tSupMatiere.getText());
if(tSupMatiere.getText()!= null) {
metier.SuppridmerMatiere(id);
}
else {
System.out.println("Error de suppression verifier le champ!!!!");
}
tSupMatiere.clear();
}
@FXML
void ValiderRechercheSalle(ActionEvent event) {
int capacite =Integer.parseInt(tSaisirCapaciteSalle.getText());
ObservableList<Salle> ListFetch = FXCollections.observableArrayList(metier.ChercherSalle(capacite));
viewId.setCellValueFactory(new PropertyValueFactory<>("idSalle"));
viewNom.setCellValueFactory(new PropertyValueFactory<>("nomSalle"));
viewCapacite.setCellValueFactory(new PropertyValueFactory<>("capaciteSalle"));
DispoView.setCellValueFactory(new PropertyValueFactory<>("disponibiliteSalle"));
tViewSalle.setItems(ListFetch);
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
tViewSalle.refresh();
tViewSalle.setItems(null);
cDispoSalle.setValue("OUI");
cDispoSalle.setItems(DispoList);
cMatiere.setItems(listModule);
//AfficherSalle(null);
//cDispoSalle.getItems().addAll("OUI","NON");
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.desktopapp.client;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
/**
* Provides a profile update view capable of displaying current profile settings
* and receiving updates from a user. The view uses the GWT Editor / Driver
* framework so that presenter does not need to know too many details of the
* view's implementation and the view does not need to know too many details
* about the models structure.
*
* See <a
* href='http://code.google.com/webtoolkit/doc/latest/DevGuideUiEditors.html'>
* GWT Editors and Drivers</a> for more information.
*/
public interface ProfileView {
/**
* Provides access to the GWT Editor / Driver framework so that the presenter
* can copy data to and from the view without knowing too many details of the
* view or the view knowing too many details of the model.
*
* @return an editor driver capable of copying model data to / from the view
*/
SimpleBeanEditorDriver<ProfileModel, Editor<? super ProfileModel>> getProfileDriver();
/**
* Hides the view.
*/
void hide();
/**
* Informs the user that the Editor / Driver framework reported that there are
* field validation errors.
*/
void onValidationError();
/**
* Shows the view.
*/
void show();
}
|
//вывод на экран самых длинных строк из списка
package Tasks;
import java.io.*;
import java.util.ArrayList;
public class Task17 {
private static ArrayList<String> strings;
public static void main(String[] args) throws IOException {
//ArrayList<String> strings = new ArrayList<>();
strings = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int len = 0;
String str;
String res = "";
for(int i = 0; i < 5; i++) {
str = reader.readLine();
strings.add(str);
if(len < str.length()){
len = str.length();
}
}
for(String a: strings) {
if (len == a.length()) {
System.out.println(a);
}
}
}
}
|
package com.partiel_android_boucher.activities.fragment;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.partiel_android_boucher.R;
import com.partiel_android_boucher.classes.Artist;
import com.partiel_android_boucher.classes.adapters.ArtistsAdapter;
import com.partiel_android_boucher.classes.realm_classes.RealmArtist;
import com.partiel_android_boucher.controllers.ArtistController;
import com.partiel_android_boucher.tools.RealmConfig;
import java.util.ArrayList;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmConfiguration;
public class ArtistsFragment extends Fragment {
private static ListView artistsList;
ArrayList<Artist> artists;
private static View view;
public ArtistsFragment(){
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArtistController.downloadAllArtists(getContext());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_artists, container, false);
}
@Override
public void onResume() {
super.onResume();
view = getView();
setUpAdapter(RealmArtist.getAllArtist(RealmConfig.realm));
}
public static void setUpAdapter(ArrayList<Artist> _artists) {
artistsList = (ListView) view.findViewById(R.id.artistsList);
ArtistsAdapter artistsAdapter = new ArtistsAdapter(view.getContext(), _artists);
artistsList.setAdapter(artistsAdapter);
artistsList.setOnItemClickListener(new OnArtistItemClickListener(artistsAdapter));
}
}
class OnArtistItemClickListener implements ListView.OnItemClickListener {
private ArtistsAdapter artistsAdapter;
public OnArtistItemClickListener(ArtistsAdapter _artistsAdapter) {
this.artistsAdapter = _artistsAdapter;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Artist artist = (Artist) artistsAdapter.getItem(position);
Toast.makeText(view.getContext(), artist.toString(), Toast.LENGTH_SHORT).show();
}
}
|
package com.csc.capturetool.myapplication.constansts;
/**
* Created by SirdarYangK on 2018/11/14
* des: 关于蓝牙数据常量类
*/
public class BlueToothConstants {
public final static String UUIDSERVICE = "0000fee7";//蓝牙server UUID
public final static String UUIDWRITE = "0000fec6";//蓝牙写入数据 UUID
public final static String UUIDNOTIFY = "0000fec5";//蓝牙开启通知读书数据 UUID
public final static String TYPE_DATA = "0";//数据包类型
public final static String TYPE_ANSWER = "1";//应答包类型
public final static String LAUNCH_STATE = "1";//设备投放状态,只有1为正常
public final static String ONLINE = "1";//在线状态,只有1为在线
/**
* 蓝牙控制设备类型及状态
* 蓝牙->1 WiFi->2 启动->1 暂停->0 按摩椅->1 USB->2
*/
public final static int BLE_START_CHAIR = 111;//BLE启动按摩椅
public final static int BLE_END_CHAIR = 110;//BLE暂停按摩椅
public final static int BLE_START_USB = 121;//BLE启动USB
public final static int BLE_END_USB = 120;//BLE暂停USB
public final static int BLE_RESTART = 0;//设备重启
/**
*发送蓝牙数据包后,后台返回设备状态码
*/
public final static String DEVICE_CHAIR = "40";//按摩椅
public final static String DEVICE_USB = "41";//USB
public final static String DEVICE_ON = "01";//启动
public final static String DEVICE_OFF = "03";//暂停
/**
* WiFi控制设备类型及状态
*/
public final static String WIFI_START_CHAIR = "1";//WiFi启动按摩椅
public final static String WIFI_END_CHAIR = "2";//WiFi暂停按摩椅
public final static String WIFI_START_USB = "3";//WiFi启动USB
public final static String WIFI_END_USB = "4";//WiFi暂停USB
}
|
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* StorePanel is a JPanel
* which represents the store screen
*/
public class StorePanel extends JPanel implements GameManagerObserver{
private GameFrame gameFrame; //reference to game frame the panel belongs to
private GameManager gameManager; //reference to game manager
//Titles of item groups
private JLabel storeTitle;
private JLabel planesTitle;
private JLabel pilotsTitle;
private JLabel locksTitle;
private JLabel shootsTitle;
private JLabel explosivesTitle;
private JPanel planesPanel; //panel that holds planes
private JPanel pilotsPanel; //panel that holds pilots
private JPanel locksPanel; //panel that holds locks
private JPanel shootsPanel; //panel that holds shoots
private JPanel explosivesPanel; //panel that holds explosives
private JPanel planesPricePanel; //panel that holds plane prices
private JPanel pilotsPricePanel; //panel that holds pilot prices
private JPanel locksPricePanel; //panel that holds lock prices
private JPanel shootsPricePanel; //panel that holds shoot prices
private JPanel explosivesPricePanel; ////panel that holds explosive prices
private JLabel coinLabel; //label for showing amount of coins
private JButton mainMenuButton; //jbutton to go back to main menu
private List<JButton> allButtons; //
private List<Integer> prices;
private Image scaledBackgroundImage; //background image
//PRICE CONSTANTS OF ITEMS
private final int alderaanCruiserPlanePrice = 0;
private final int tomcatPlanePrice = 250;
private final int f22RaptorPlanePrice = 500;
private final int saabGripenPlanePrice = 1000;
private final int wunderWaffePlanePrice = 1500;
private final int nickPilotPrice = 0;
private final int pennyPilotPrice = 100;
private final int mikePilotPrice = 100;
private final int evaPilotPrice = 500;
private final int neoPilotPrice = 500;
private final int damageLockPrice = 100;
private final int healthLockPrice = 100;
private final int invisibilityLockPrice = 100;
private final int shieldLockPrice = 100;
private final int speedLockPrice = 100;
private final int metalballPrice = 100;
private final int flamegunPrice = 100;
private final int frostlaserPrice = 100;
private final int laserPrice = 100;
private final int bombPrice = 100;
private final int missilePrice = 100;
public StorePanel(GameFrame gameFrame, GameManager gameManager) {
this.gameFrame = gameFrame;
this.gameManager = gameManager;
setLayout(null);
setLayout( new BoxLayout(this, BoxLayout.Y_AXIS));
BufferedImage backgroundImage = ImageConstants.emptyBackgroundImage;
scaledBackgroundImage = backgroundImage.getScaledInstance(gameFrame.getWidth(), gameFrame.getHeight(),
Image.SCALE_SMOOTH);
coinLabel = new JLabel("COINS " + gameManager.getCoins());
coinLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
coinLabel.setBounds(50,50, 1000, 100);
add(coinLabel);
createAndAddTitles();
planesPanel = new JPanel(new FlowLayout());
planesPanel.setOpaque(false);
pilotsPanel = new JPanel(new FlowLayout());
pilotsPanel.setOpaque(false);
//locksPanel = new JPanel(new FlowLayout());
//locksPanel.setOpaque(false);
shootsPanel = new JPanel(new FlowLayout());
shootsPanel.setOpaque(false);
explosivesPanel = new JPanel(new FlowLayout());
explosivesPanel.setOpaque(false);
FlowLayout flow = new FlowLayout();
flow.setHgap(50);
planesPricePanel = new JPanel(flow);
planesPricePanel.setOpaque(false);
pilotsPricePanel = new JPanel(flow);
pilotsPricePanel.setOpaque(false);
//locksPricePanel = new JPanel(flow);
//locksPricePanel.setOpaque(false);
shootsPricePanel = new JPanel(flow);
shootsPricePanel.setOpaque(false);
explosivesPricePanel = new JPanel(flow);
explosivesPricePanel.setOpaque(false);
placePlanes();
placePilots();
//placeLocks();
placeShoots();
placeExplosives();
add(planesTitle);
add(planesPanel);
add(planesPricePanel);
add(pilotsTitle);
add(pilotsPanel);
add(pilotsPricePanel);
//add(locksTitle);
//add(locksPanel);
add(shootsTitle);
add(shootsPanel);
add(shootsPricePanel);
add(explosivesTitle);
add(explosivesPanel);
add(explosivesPricePanel);
mainMenuButton = new JButton();
mainMenuButton.setIcon(new ImageIcon(ImageConstants.homeIconImage));
mainMenuButton.setBounds(50, 50, 200, 200);
mainMenuButton.setOpaque(false);
mainMenuButton.setContentAreaFilled(false);
mainMenuButton.setBorderPainted(false);
add(mainMenuButton);
prices = new ArrayList<Integer>();
prices.add(alderaanCruiserPlanePrice);
prices.add( tomcatPlanePrice);
prices.add(f22RaptorPlanePrice);
prices.add(saabGripenPlanePrice);
prices.add(wunderWaffePlanePrice);
prices.add(nickPilotPrice);
prices.add(pennyPilotPrice);
prices.add(mikePilotPrice);
prices.add(evaPilotPrice);
prices.add(neoPilotPrice);
prices.add( metalballPrice);
prices.add(flamegunPrice);
prices.add(frostlaserPrice);
prices.add(laserPrice);
prices.add(bombPrice);
prices.add(missilePrice);
addActionListeners();
gameManager.subscribe(this);
}
private void addActionListeners() {
mainMenuButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
gameFrame.displayMainMenu();
}
});
for( int i = 0; i < allButtons.size(); i++ ){
final int k = i;
allButtons.get(i).addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if( prices.get(k) <= gameFrame.getGameManager().getCoins()){
gameManager.purchaseItem(k, prices.get(k));
repaint();
}
}
});
}
}
private void createAndAddTitles() {
planesTitle = new JLabel();
planesTitle.setText("PLANES");
planesTitle.setFont(new Font("ComicSans", Font.BOLD, 30));
pilotsTitle = new JLabel();
pilotsTitle.setText("PILOTS");
pilotsTitle.setFont(new Font("ComicSans", Font.BOLD, 30));
//locksTitle = new JLabel();
//locksTitle.setText("BONUS PACKAGE LOCKS");
//locksTitle.setFont(new Font("ComicSans", Font.BOLD, 30));
shootsTitle = new JLabel();
shootsTitle.setText("SHOOTS");
shootsTitle.setFont(new Font("ComicSans", Font.BOLD, 30));
explosivesTitle = new JLabel();
explosivesTitle.setText("EXPLOSIVES");
explosivesTitle.setFont(new Font("ComicSans", Font.BOLD, 30));
}
private void placeExplosives() {
Image image = ImageConstants.bombImage;
JButton bomb = new JButton();
bomb.setIcon(new ImageIcon( image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
bomb.setPreferredSize(new Dimension(200, 200));
bomb.setOpaque(false);
bomb.setContentAreaFilled(false);
bomb.setBorderPainted(false);
explosivesPanel.add(bomb);
image = ImageConstants.missileImage;
JButton missile = new JButton();
missile.setIcon(new ImageIcon( image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
missile.setPreferredSize(new Dimension(200, 200));
missile.setOpaque(false);
missile.setContentAreaFilled(false);
missile.setBorderPainted(false);
explosivesPanel.add(missile);
JLabel bombLabel = new JLabel("PRICE " + bombPrice);
bombLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
explosivesPricePanel.add(bombLabel);
JLabel missileLabel = new JLabel("PRICE " + missilePrice);
missileLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
explosivesPricePanel.add(missileLabel);
allButtons.add(bomb);
allButtons.add(missile);
}
private void placeShoots() {
Image image = ImageConstants.metalBallImage;
JButton metalball = new JButton();
metalball.setIcon(new ImageIcon( image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
metalball.setPreferredSize(new Dimension(200, 200));
metalball.setOpaque(false);
metalball.setContentAreaFilled(false);
metalball.setBorderPainted(false);
shootsPanel.add(metalball);
image = ImageConstants.flameGunImage;
JButton flamegun = new JButton();
flamegun.setIcon(new ImageIcon( image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
flamegun.setPreferredSize(new Dimension(200, 200));
flamegun.setOpaque(false);
flamegun.setContentAreaFilled(false);
flamegun.setBorderPainted(false);
shootsPanel.add(flamegun);
image = ImageConstants.frostLaserImage;
JButton frostlaser = new JButton();
frostlaser.setIcon(new ImageIcon( image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
frostlaser.setPreferredSize(new Dimension(200, 200));
frostlaser.setOpaque(false);
frostlaser.setContentAreaFilled(false);
frostlaser.setBorderPainted(false);
shootsPanel.add(frostlaser);
image = ImageConstants.laserImage;
JButton laser = new JButton();
laser.setIcon(new ImageIcon( image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
laser.setPreferredSize(new Dimension(200, 200));
laser.setOpaque(false);
laser.setContentAreaFilled(false);
laser.setBorderPainted(false);
shootsPanel.add(laser);
JLabel metalballLabel = new JLabel("PRICE " + metalballPrice);
metalballLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
shootsPricePanel.add(metalballLabel);
JLabel flamegunLabel = new JLabel("PRICE " + flamegunPrice);
flamegunLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
shootsPricePanel.add(flamegunLabel);
JLabel frostlaserLabel = new JLabel("PRICE " + frostlaserPrice);
frostlaserLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
shootsPricePanel.add(frostlaserLabel);
JLabel laserLabel = new JLabel("PRICE " + laserPrice);
laserLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
shootsPricePanel.add(laserLabel);
allButtons.add( metalball);
allButtons.add(flamegun);
allButtons.add(frostlaser);
allButtons.add(laser);
}
private void placeLocks() {
Image image = ImageConstants.damagePackageImage;
JButton damageLock = new JButton();
damageLock.setIcon(new ImageIcon( image.getScaledInstance(200, 100, Image.SCALE_SMOOTH)));
damageLock.setPreferredSize(new Dimension(200, 200));
damageLock.setOpaque(false);
damageLock.setContentAreaFilled(false);
damageLock.setBorderPainted(false);
locksPanel.add(damageLock);
image = ImageConstants.healthPackageImage;
JButton healthLock = new JButton();
healthLock.setIcon(new ImageIcon( image.getScaledInstance(200, 100, Image.SCALE_SMOOTH)));
healthLock.setPreferredSize(new Dimension(200, 200));
healthLock.setOpaque(false);
healthLock.setContentAreaFilled(false);
healthLock.setBorderPainted(false);
locksPanel.add(healthLock);
image = ImageConstants.invisibilityPackageImage;
JButton invisibilityLock = new JButton();
invisibilityLock.setIcon(new ImageIcon( image.getScaledInstance(200, 100, Image.SCALE_SMOOTH)));
invisibilityLock.setPreferredSize(new Dimension(200, 200));
invisibilityLock.setOpaque(false);
invisibilityLock.setContentAreaFilled(false);
invisibilityLock.setBorderPainted(false);
locksPanel.add(invisibilityLock);
image = ImageConstants.shieldPackageImage;
JButton shieldLock = new JButton();
shieldLock.setIcon(new ImageIcon( image.getScaledInstance(200, 100, Image.SCALE_SMOOTH)));
shieldLock.setPreferredSize(new Dimension(200, 200));
shieldLock.setOpaque(false);
shieldLock.setContentAreaFilled(false);
shieldLock.setBorderPainted(false);
locksPanel.add(shieldLock);
image = ImageConstants.speedPackageImage;
JButton speedLock = new JButton();
speedLock.setIcon(new ImageIcon( image.getScaledInstance(200, 100, Image.SCALE_SMOOTH)));
speedLock.setPreferredSize(new Dimension(200, 200));
speedLock.setOpaque(false);
speedLock.setContentAreaFilled(false);
speedLock.setBorderPainted(false);
locksPanel.add(speedLock);
JLabel damageLockLabel = new JLabel("PRICE " + damageLockPrice);
damageLockLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
locksPricePanel.add(damageLockLabel);
JLabel healthLockLabel = new JLabel("PRICE " + healthLockPrice);
healthLockLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
locksPricePanel.add( healthLockLabel);
JLabel invisibilityLockLabel = new JLabel("PRICE " + invisibilityLockPrice);
invisibilityLockLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
locksPricePanel.add( invisibilityLockLabel);
JLabel shieldLockLabel = new JLabel("PRICE " + shieldLockPrice);
shieldLockLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
locksPricePanel.add(shieldLockLabel);
JLabel speedLockLabel = new JLabel("PRICE " + speedLockPrice);
speedLockLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
locksPricePanel.add( speedLockLabel);
}
private void placePilots() {
Image image = ImageConstants.nickPilotImage;
JButton nickPilot = new JButton();
nickPilot.setIcon(new ImageIcon( image.getScaledInstance(150, 200, Image.SCALE_SMOOTH)));
nickPilot.setPreferredSize(new Dimension(200, 200));
nickPilot.setOpaque(false);
nickPilot.setContentAreaFilled(false);
nickPilot.setBorderPainted(false);
pilotsPanel.add(nickPilot);
image = ImageConstants.pennyPilotImage;
JButton pennyPilot = new JButton();
pennyPilot.setIcon(new ImageIcon( image.getScaledInstance(100, 200, Image.SCALE_SMOOTH)));
pennyPilot.setPreferredSize(new Dimension(200, 200));
pennyPilot.setOpaque(false);
pennyPilot.setContentAreaFilled(false);
pennyPilot.setBorderPainted(false);
pilotsPanel.add(pennyPilot);
image = ImageConstants.mikePilotImage;
JButton mikePilot = new JButton();
mikePilot.setIcon(new ImageIcon( image.getScaledInstance(150, 200, Image.SCALE_SMOOTH)));
mikePilot.setPreferredSize(new Dimension(200, 200));
mikePilot.setOpaque(false);
mikePilot.setContentAreaFilled(false);
mikePilot.setBorderPainted(false);
pilotsPanel.add(mikePilot);
image = ImageConstants.evaPilotImage;
JButton evaPilot = new JButton();
evaPilot.setIcon(new ImageIcon( image.getScaledInstance(150, 200, Image.SCALE_SMOOTH)));
evaPilot.setPreferredSize(new Dimension(200, 200));
evaPilot.setOpaque(false);
evaPilot.setContentAreaFilled(false);
evaPilot.setBorderPainted(false);
pilotsPanel.add(evaPilot);
image = ImageConstants.neoPilotImage;
JButton neoPilot = new JButton();
neoPilot.setIcon(new ImageIcon( image.getScaledInstance(150, 200, Image.SCALE_SMOOTH)));
neoPilot.setPreferredSize(new Dimension(200, 200));
neoPilot.setOpaque(false);
neoPilot.setContentAreaFilled(false);
neoPilot.setBorderPainted(false);
pilotsPanel.add(neoPilot);
JLabel nickPilotLabel = new JLabel("PRICE " + nickPilotPrice);
nickPilotLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
pilotsPricePanel.add( nickPilotLabel);
JLabel pennyPilotLabel = new JLabel("PRICE " + pennyPilotPrice);
pennyPilotLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
pilotsPricePanel.add( pennyPilotLabel);
JLabel mikePilotLabel = new JLabel("PRICE " + mikePilotPrice);
mikePilotLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
pilotsPricePanel.add( mikePilotLabel);
JLabel evaPilotLabel = new JLabel("PRICE " + evaPilotPrice);
evaPilotLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
pilotsPricePanel.add( evaPilotLabel);
JLabel neoPilotLabel = new JLabel("PRICE " + neoPilotPrice);
neoPilotLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
pilotsPricePanel.add( neoPilotLabel);
allButtons.add(nickPilot);
allButtons.add(pennyPilot);
allButtons.add(mikePilot);
allButtons.add(evaPilot);
allButtons.add(neoPilot);
}
private void placePlanes() {
Image image = ImageConstants.alderaanCruiserUserPlaneImage;
JButton alderaanCruiserPlane = new JButton();
alderaanCruiserPlane.setIcon(new ImageIcon( image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
alderaanCruiserPlane.setPreferredSize(new Dimension(200, 200));
alderaanCruiserPlane.setOpaque(false);
alderaanCruiserPlane.setContentAreaFilled(false);
alderaanCruiserPlane.setBorderPainted(false);
planesPanel.add(alderaanCruiserPlane);
image = ImageConstants.tomcatUserPlaneImage;
JButton tomcatPlane = new JButton();
tomcatPlane.setIcon(new ImageIcon(image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
tomcatPlane.setPreferredSize(new Dimension(200, 200));
tomcatPlane.setOpaque(false);
tomcatPlane.setContentAreaFilled(false);
tomcatPlane.setBorderPainted(false);
planesPanel.add(tomcatPlane);
image = ImageConstants.f22RaptorUserPlaneImage;
JButton f22RaptorPlane = new JButton();
f22RaptorPlane.setIcon(new ImageIcon(image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
f22RaptorPlane.setPreferredSize(new Dimension(200, 200));
f22RaptorPlane.setOpaque(false);
f22RaptorPlane.setContentAreaFilled(false);
f22RaptorPlane.setBorderPainted(false);
planesPanel.add(f22RaptorPlane);
image = ImageConstants.saabGripenUserPlaneImage;
JButton saabGripenPlane = new JButton();
saabGripenPlane.setIcon(new ImageIcon(image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
saabGripenPlane.setPreferredSize(new Dimension(200, 200));
saabGripenPlane.setOpaque(false);
saabGripenPlane.setContentAreaFilled(false);
saabGripenPlane.setBorderPainted(false);
planesPanel.add(saabGripenPlane);
image = ImageConstants.wunderwaffeUserPlaneImage;
JButton wunderWaffePlane = new JButton();
wunderWaffePlane.setIcon(new ImageIcon(image.getScaledInstance(200, 200, Image.SCALE_SMOOTH)));
wunderWaffePlane.setPreferredSize(new Dimension(200, 200));
wunderWaffePlane.setOpaque(false);
wunderWaffePlane.setContentAreaFilled(false);
wunderWaffePlane.setBorderPainted(false);
planesPanel.add(wunderWaffePlane);
JLabel alderaanCruiserPlaneLabel = new JLabel("PRICE " + alderaanCruiserPlanePrice);
alderaanCruiserPlaneLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
planesPricePanel.add( alderaanCruiserPlaneLabel);
JLabel tomcatPlaneLabel = new JLabel("PRICE " + tomcatPlanePrice);
tomcatPlaneLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
planesPricePanel.add(tomcatPlaneLabel);
JLabel f22RaptorPlaneLabel = new JLabel("PRICE " + f22RaptorPlanePrice);
f22RaptorPlaneLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
planesPricePanel.add( f22RaptorPlaneLabel);
JLabel saabGripenPlaneLabel = new JLabel("PRICE " + saabGripenPlanePrice);
saabGripenPlaneLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
planesPricePanel.add( saabGripenPlaneLabel);
JLabel wunderWaffePlaneLabel = new JLabel("PRICE " + wunderWaffePlanePrice);
wunderWaffePlaneLabel.setFont(new Font("ComicSans", Font.BOLD, 30));
planesPricePanel.add( wunderWaffePlaneLabel);
allButtons = new ArrayList<JButton>();
allButtons.add(alderaanCruiserPlane);
allButtons.add( tomcatPlane);
allButtons.add(f22RaptorPlane);
allButtons.add(saabGripenPlane);
allButtons.add(wunderWaffePlane);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(scaledBackgroundImage, 0, 0, null);
coinLabel.setText("COINS " + gameFrame.getGameManager().getCoins());
for( int i = 0; i < allButtons.size(); i++ ){
if( prices.get(i) > gameManager.getCoins()){
allButtons.get(i).setEnabled(false);
}
if( prices.get(i) <= gameManager.getCoins()){
allButtons.get(i).setEnabled(true);
}
if( gameManager.purchasedPlanesContains(i))
allButtons.get(i).setEnabled(false);
if( gameManager.purchasedPilotsContains(i-5) )
{
allButtons.get(i).setEnabled(false);
}
}
}
public void update(){
repaint();
}
}
|
package com.eegeo.mapapi.precaching;
import androidx.annotation.UiThread;
/**
* Defines the signature for a method that is called when a precache operation is completed or
* cancelled.
*/
public interface OnPrecacheOperationCompletedListener
{
/**
* A method to be executed when a precache operation completes.
*
* @param result the completed precache operation's status
*/
@UiThread
void onPrecacheOperationCompleted(PrecacheOperationResult result);
}
|
package com.weili.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import com.shove.data.DataException;
import com.shove.data.DataSet;
import com.shove.util.BeanMapUtils;
import com.weili.database.Dao;
public class RegionDao {
/**
* 查询省市区信息
* @Title: queryRegionList
* @Description: TODO
* @param conn 数据库连接
* @param regionId 地区ID
* @param parentId 地区父ID
* @param regionType 地区类型
* @return
* @throws SQLException
* @throws DataException
* @return List<Map<String,Object>>
* @throws
*/
public List<Map<String, Object>> queryRegionList(Connection conn, Long regionId, Long parentId, Integer regionType) throws SQLException, DataException{
Dao.Tables.t_region region = new Dao(). new Tables(). new t_region();
StringBuffer condition = new StringBuffer();
condition.append(" 1=1 ");
if (regionId != null && regionId > 0) {
condition.append(" AND regionId=" + regionId);
}
if (parentId != null && parentId > 0) {
condition.append(" AND parentId=" + parentId);
}
if (regionType != null && regionType > 0) {
condition.append(" AND regionType=" + regionType);
}
DataSet dataSet = region.open(conn, "*", condition.toString(), "", -1, -1);
dataSet.tables.get(0).rows.genRowsMap();
return dataSet.tables.get(0).rows.rowsMap;
}
/**
* 根据获取到的名字查询省市关联
* @param conn 数据库连接
* @param name 地区名
* @return
* @throws SQLException
* @throws DataException
*/
public Map<String,String> queryMap(Connection conn,String name,Long parentId,Integer regionType) throws SQLException, DataException{
Dao.Tables.t_region region = new Dao(). new Tables(). new t_region();
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (StringUtils.isNotBlank(name)) {
condition.append(" AND regionName like '" +name.trim()+"'");
}if (parentId !=null && parentId >0) {
condition.append(" AND parentId ="+parentId);
}
if (regionType !=null && regionType >=0) {
condition.append(" AND regionType ="+regionType);
}
DataSet ds = region.open(conn, "",condition.toString(), " ",-1,-1);
return BeanMapUtils.dataSetToMap(ds);
}
/**
* 通过名称得到id
* @param conn
* @param name
* @return
* @throws DataException
*/
public Map<String, String> queryAddId(Connection conn,String name) throws DataException {
Dao.Tables.t_region region = new Dao(). new Tables(). new t_region();
StringBuffer condition = new StringBuffer();
condition.append(" 1=1");
if (StringUtils.isNotBlank(name)) {
condition.append(" AND regionName like '" +name.trim()+"'");
}
DataSet ds = region.open(conn, "",condition.toString(), " ",-1,-1);
return BeanMapUtils.dataSetToMap(ds);
}
/**
* 根据id查询该id的所有父级并按顺序返回
* @param id
* @return List<Map<String,Object>>
* @throws DataException
* @throws SQLException
* @throws
*/
public List<Map<String, Object>> queryAllParentList(Connection conn,Long id) throws DataException, SQLException{
DataSet ds = new DataSet();
List<Object> outParameterValues = new ArrayList<Object>();
Dao.Procedures.p_region(conn, ds, outParameterValues, id);
ds.tables.get(0).rows.genRowsMap();
return ds.tables.get(0).rows.rowsMap;
}
public Map<String,String> queryRegionById(Connection conn,long id) throws DataException{
Dao.Tables.t_region region = new Dao().new Tables().new t_region();
DataSet ds = region.open(conn, " ", " id = "+id, " ", -1, -1);
return BeanMapUtils.dataSetToMap(ds);
}
}
|
package it.greenvulcano.gvesb.adapter.hdfs.operations;
import java.io.IOException;
import org.w3c.dom.Node;
import it.greenvulcano.configuration.XMLConfig;
import it.greenvulcano.configuration.XMLConfigException;
import it.greenvulcano.gvesb.buffer.GVBuffer;
import it.greenvulcano.gvesb.buffer.GVException;
import it.greenvulcano.gvesb.virtual.VCLException;
import it.greenvulcano.util.metadata.PropertiesHandler;
import it.greenvulcano.util.metadata.PropertiesHandlerException;
public class ReadFile extends BaseOperation {
private String file = null;
@Override
public void init(Node node) throws XMLConfigException {
super.init(node);
file = XMLConfig.get(node, "@file");
}
@Override
public GVBuffer perform(GVBuffer gvBuffer) throws PropertiesHandlerException, VCLException {
super.perform(gvBuffer);
file = PropertiesHandler.expand(file, gvBuffer);
try {
gvBuffer.setObject(hdfs.readFile(file).array());
}
catch (IllegalArgumentException | GVException | IOException e) {
throw new VCLException(e.getMessage(), e);
}
return gvBuffer;
}
}
|
package strategy;
import java.time.LocalDate;
import java.util.LinkedList;
import java.util.List;
public class FrequentWithdrawalFeeStrategy implements FeeCalculationStrategy {
private final int withdrawalPeriod;
private final int withdrawalCount;
private final int fee;
public FrequentWithdrawalFeeStrategy(int withdrawalPeriod, int withdrawalCount, int fee) {
this.withdrawalPeriod = withdrawalPeriod;
this.withdrawalCount = withdrawalCount;
this.fee = fee;
}
@Override
public int calculateFee(int balance, int amount, LocalDate today, List<Transaction> history) {
// count transactions within cut-off period
LocalDate cutOffDate = today.minusDays(withdrawalPeriod);
long txnCount = history.stream()
.filter(txn -> txn.getDate().isAfter(cutOffDate))
.count();
// then report fee based on count of recent transactions
// remember if this succeeds, this transaction counts but is
// not yet in the history
int rv = (txnCount >= withdrawalCount) ? fee : 0;
return rv;
}
}
|
package org.example.common.utils;
import org.example.common.exception.BaseException;
import org.example.common.exception.server.ExceptionInternalServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggerUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerUtil.class);
public LoggerUtil() {
}
public static void logFilter(Exception e) {
LOGGER.error(e.getClass().getSimpleName() + " " + e.getMessage(), e);
}
public static void logFilter(BaseException e) {
if (isServerException(e)) {
LOGGER.error(e.getClass().getSimpleName() + " " + e.getMessage(), e);
} else {
LOGGER.warn(e.getClass().getSimpleName() + " " + e.getMessage());
}
}
public static void logFilter(BaseException e, String desc, Object... args) {
if (isServerException(e)) {
LOGGER.error(printStr(desc, args), e);
} else {
LOGGER.warn(printStr(desc, args));
}
}
private static boolean isServerException(BaseException e) {
return e instanceof ExceptionInternalServer;
}
public static void logFilter(Exception e, String desc, Object... args) {
if (e instanceof BaseException) {
logFilter((BaseException) e, desc, args);
} else {
LOGGER.error(printStr(desc, args), e);
}
}
public static void logFilter(Object e, String desc, Object... args) {
if (e instanceof Throwable) {
logFilter((Exception) ((Throwable) e).getCause(), desc, args);
} else {
LOGGER.error(printStr(desc, args), e);
}
}
private static String printStr(String desc, Object... args) {
String[] arr = desc.split("\\{}");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; ++i) {
sb.append(arr[i]);
if (args.length != 0 && args.length >= i) {
sb.append(args[i]);
}
}
return sb.toString();
}
}
|
/**
*
*/
package net.sf.taverna.t2.component.ui.menu.registry;
import static net.sf.taverna.t2.component.ui.preference.ComponentPreferenceUIFactory.DISPLAY_NAME;
import static net.sf.taverna.t2.component.ui.serviceprovider.ComponentServiceIcon.getIcon;
import static net.sf.taverna.t2.workbench.ui.impl.configuration.ui.T2ConfigurationFrame.showConfiguration;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
/**
* @author alanrw
*
*/
public class ComponentRegistryManageAction extends AbstractAction {
private static final long serialVersionUID = 8993945811345164194L;
private static final String MANAGE_REGISTRY = "Manage registries...";
public ComponentRegistryManageAction() {
super(MANAGE_REGISTRY, getIcon());
}
@Override
public void actionPerformed(ActionEvent arg0) {
showConfiguration(DISPLAY_NAME);
}
}
|
package ma.adria.banque.repository;
import java.util.Collection;
import ma.adria.banque.entities.Abonne;
import ma.adria.banque.entities.Compte;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Repository Compte
* @author ouakrim
* @since 02/2016
* @version 1.0.0
*/
@Repository
public interface CompteRepository extends JpaRepository<Compte, Long> {
/**
* cette methode retourne la liste des comptes d'un abonné
* @param abonne
* @return une collection d'objet de type Compte
*/
public Collection<Compte> findByAbonne(Abonne abonne);
public Compte findByNumeroCompte(String numeroCompte);
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* {@link Resource} implementation for a given {@link InputStream}.
* <p>Should only be used if no other specific {@code Resource} implementation
* is applicable. In particular, prefer {@link ByteArrayResource} or any of the
* file-based {@code Resource} implementations where possible.
*
* <p>In contrast to other {@code Resource} implementations, this is a descriptor
* for an <i>already opened</i> resource - therefore returning {@code true} from
* {@link #isOpen()}. Do not use an {@code InputStreamResource} if you need to
* keep the resource descriptor somewhere, or if you need to read from a stream
* multiple times.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 28.12.2003
* @see ByteArrayResource
* @see ClassPathResource
* @see FileSystemResource
* @see UrlResource
*/
public class InputStreamResource extends AbstractResource {
private final InputStream inputStream;
private final String description;
private boolean read = false;
/**
* Create a new InputStreamResource.
* @param inputStream the InputStream to use
*/
public InputStreamResource(InputStream inputStream) {
this(inputStream, "resource loaded through InputStream");
}
/**
* Create a new InputStreamResource.
* @param inputStream the InputStream to use
* @param description where the InputStream comes from
*/
public InputStreamResource(InputStream inputStream, @Nullable String description) {
Assert.notNull(inputStream, "InputStream must not be null");
this.inputStream = inputStream;
this.description = (description != null ? description : "");
}
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean exists() {
return true;
}
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean isOpen() {
return true;
}
/**
* This implementation throws IllegalStateException if attempting to
* read the underlying stream multiple times.
*/
@Override
public InputStream getInputStream() throws IOException, IllegalStateException {
if (this.read) {
throw new IllegalStateException("InputStream has already been read - " +
"do not use InputStreamResource if a stream needs to be read multiple times");
}
this.read = true;
return this.inputStream;
}
/**
* This implementation returns a description that includes the passed-in
* description, if any.
*/
@Override
public String getDescription() {
return "InputStream resource [" + this.description + "]";
}
/**
* This implementation compares the underlying InputStream.
*/
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof InputStreamResource that &&
this.inputStream.equals(that.inputStream)));
}
/**
* This implementation returns the hash code of the underlying InputStream.
*/
@Override
public int hashCode() {
return this.inputStream.hashCode();
}
}
|
package yunanl;
import java.math.BigInteger;
public class Request {
private String id;
private BigInteger e;
private BigInteger n;
private String operation;
private String variable1;
private String variable2;
private String signature;
public void setId(String id){
this.id = id;
}
public void setE(BigInteger e){
this.e = e;
}
public void setN(BigInteger n){
this.n = n;
}
public void setOperation(String operation){
this.operation = operation;
}
public void setVariable1(String variable1){
this.variable1 = variable1;
}
public void setVariable2(String variable2){
this.variable2 = variable2;
}
public void setSignature(String signature){
this.signature = signature;
}
public String getId(){
return id;
}
public BigInteger getE(){
return e;
}
public BigInteger getN() {
return n;
}
public String getOperation() {
return operation;
}
public String getVariable1() {
return variable1;
}
public String getVariable2() {
return variable2;
}
public String getSignature() {
return signature;
}
}
|
package com.legaoyi.client.util;
public class Constants {
public static final String MESSAGE_HANDLER_BEAN_PREFIX = "elink_";
public static final String MESSAGE_HANDLER_BEAN_SUFFIX = "_messageHandler";
public static final String MESSAGE_BUILDER_BEAN_PREFIX = "elink_";
public static final String MESSAGE_BUILDER_BEAN_SUFFIX = "_messageBuilder";
}
|
package io.nuls.common;
import io.nuls.core.basic.ModuleConfig;
import io.nuls.core.basic.VersionChangeInvoker;
import io.nuls.core.core.annotation.Component;
import io.nuls.core.core.annotation.Configuration;
import io.nuls.core.rpc.model.ModuleE;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Transaction module setting
* @author: Charlie
* @date: 2019/03/14
*/
@Component
@Configuration(domain = ModuleE.Constant.NERVE_CORE)
public class NerveCoreConfig extends ConfigBean implements ModuleConfig {
/*-------------------------[Common]-----------------------------*/
/** ROCK DB 数据库文件存储路径*/
private String dataPath;
/** 主链链ID*/
private int mainChainId;
/** 主链主资产ID*/
private int mainAssetId;
/** 编码*/
private String encoding;
/**
* 国际化
*/
private String language;
/**
* 链ID
*/
private int chainId;
private int assetId;
private int decimals = 8;
private String symbol;
private String addressPrefix;
/**
* 日志级别
*/
private String logLevel;
/*-------------------------[Transaction]-----------------------------*/
/** 黑洞公钥*/
private String blackHolePublicKey;
/** 交易时间所在区块时间的默认范围值(在区块时间±本值范围内)*/
private long blockTxTimeRangeSec;
/** 孤儿交易生命时间,超过会被清理**/
private int orphanLifeTimeSec;
/** 未确认交易过期时间秒 */
private long unconfirmedTxExpireSec;
/** 单个交易数据最大值(B)*/
private long txMaxSize;
/** coinTo 不支持金额等于0 的协议生效高度*/
private long coinToPtlHeightFirst;
/** coinTo 支持金额等于0, 只禁止金额为0的锁定 的协议生效高度*/
private long coinToPtlHeightSecond;
private String blackListPath;
private String accountBlockManagerPublicKeys;
/*-------------------------[Protocol]-----------------------------*/
/*-------------------------[Network]-----------------------------*/
private int port;
private long packetMagic;
private int maxInCount;
private int maxOutCount;
private byte reverseCheck = 1;
private int maxInSameIp;
private String selfSeedIps;
private List<String> seedIpList;
private int crossPort;
private int crossMaxInCount;
private int crossMaxOutCount;
private int crossMaxInSameIp;
private String moonSeedIps;
private List<String> moonSeedIpList;
private boolean moonNode;
private List<String> localIps = new ArrayList<>();
private int updatePeerInfoType = 0;
/**
* 中心化网络服务接口
*/
private String timeServers;
/*-------------------------[Ledger]-----------------------------*/
private int unconfirmedTxExpired;
private int assetRegDestroyAmount = 200;
/*-------------------------[CrossChain]-----------------------------*/
private int crossCtxType;
private boolean mainNet;
/**默认链接到的跨链节点*/
private String crossSeedIps;
/**
* 本链种子节点地址
*/
private Set<String> seedNodeSet;
private Long version1_6_0_height;
/*-------------------------[Block]-----------------------------*/
/**
* 分叉链监视线程执行间隔
*/
private int forkChainsMonitorInterval;
/**
* 孤儿链监视线程执行间隔
*/
private int orphanChainsMonitorInterval;
/**
* 孤儿链维护线程执行间隔
*/
private int orphanChainsMaintainerInterval;
/**
* 数据库监视线程执行间隔
*/
private int storageSizeMonitorInterval;
/**
* 网络监视线程执行间隔
*/
private int networkResetMonitorInterval;
/**
* 节点数量监控线程执行间隔
*/
private int nodesMonitorInterval;
/**
* BZT缓存数据清理监控线程执行间隔
*/
private int blockBZTClearMonitorInterval;
/**
* TxGroup请求器线程执行间隔
*/
private int txGroupRequestorInterval;
/**
* TxGroup请求器任务执行延时
*/
private int txGroupTaskDelay;
/**
* 启动后自动回滚多少个区块
*/
private int testAutoRollbackAmount;
/**
* 回滚到指定高度
*/
private int rollbackHeight;
/*-------------------------[Account]-----------------------------*/
/**
* key store 存储文件夹
*/
private String keystoreFolder;
private int sigMode = 0;
private String sigMacUrl ;
private String sigMacApiKey ;
private String sigMacAddress;
private String blockAccountManager;
/*-------------------------[Consensus]-----------------------------*/
/**
* 跨链交易手续费主链收取手续费比例
* Cross-Chain Transaction Fee Proportion of Main Chain Fee Collection
* */
private int mainChainCommissionRatio;
private int maxCoinToOfCoinbase;
private long minRewardHeight;
public int getMainChainCommissionRatio() {
return mainChainCommissionRatio;
}
public void setMainChainCommissionRatio(int mainChainCommissionRatio) {
this.mainChainCommissionRatio = mainChainCommissionRatio;
}
@Override
public int getMaxCoinToOfCoinbase() {
return maxCoinToOfCoinbase;
}
@Override
public void setMaxCoinToOfCoinbase(int maxCoinToOfCoinbase) {
this.maxCoinToOfCoinbase = maxCoinToOfCoinbase;
}
@Override
public long getMinRewardHeight() {
return minRewardHeight;
}
@Override
public void setMinRewardHeight(long minRewardHeight) {
this.minRewardHeight = minRewardHeight;
}
public List<String> getLocalIps() {
return localIps;
}
public String getLogLevel() {
return logLevel;
}
public void setLogLevel(String logLevel) {
this.logLevel = logLevel;
}
public String getExternalIp() {
if (localIps.size() > 0) {
return localIps.get(localIps.size() - 1);
}
return null;
}
public String getAccountBlockManagerPublicKeys() {
return accountBlockManagerPublicKeys;
}
public void setAccountBlockManagerPublicKeys(String accountBlockManagerPublicKeys) {
this.accountBlockManagerPublicKeys = accountBlockManagerPublicKeys;
}
public String getBlackListPath() {
return blackListPath;
}
public void setBlackListPath(String blackListPath) {
this.blackListPath = blackListPath;
}
public String getBlackHolePublicKey() {
return blackHolePublicKey;
}
public void setBlackHolePublicKey(String blackHolePublicKey) {
this.blackHolePublicKey = blackHolePublicKey;
}
public String getDataPath() {
return dataPath;
}
public void setDataPath(String dataPath) {
this.dataPath = dataPath;
}
public int getMainChainId() {
return mainChainId;
}
public void setMainChainId(int mainChainId) {
this.mainChainId = mainChainId;
}
public int getMainAssetId() {
return mainAssetId;
}
public void setMainAssetId(int mainAssetId) {
this.mainAssetId = mainAssetId;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public long getUnconfirmedTxExpireSec() {
return unconfirmedTxExpireSec;
}
public void setUnconfirmedTxExpireSec(long unconfirmedTxExpireSec) {
this.unconfirmedTxExpireSec = unconfirmedTxExpireSec;
}
public long getBlockTxTimeRangeSec() {
return blockTxTimeRangeSec;
}
public void setBlockTxTimeRangeSec(long blockTxTimeRangeSec) {
this.blockTxTimeRangeSec = blockTxTimeRangeSec;
}
public int getOrphanLifeTimeSec() {
return orphanLifeTimeSec;
}
public void setOrphanLifeTimeSec(int orphanLifeTimeSec) {
this.orphanLifeTimeSec = orphanLifeTimeSec;
}
public long getTxMaxSize() {
return txMaxSize;
}
public void setTxMaxSize(long txMaxSize) {
this.txMaxSize = txMaxSize;
}
public long getCoinToPtlHeightFirst() {
return coinToPtlHeightFirst;
}
public void setCoinToPtlHeightFirst(long coinToPtlHeightFirst) {
this.coinToPtlHeightFirst = coinToPtlHeightFirst;
}
public long getCoinToPtlHeightSecond() {
return coinToPtlHeightSecond;
}
public void setCoinToPtlHeightSecond(long coinToPtlHeightSecond) {
this.coinToPtlHeightSecond = coinToPtlHeightSecond;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
@Override
public int getChainId() {
return chainId;
}
@Override
public void setChainId(int chainId) {
this.chainId = chainId;
}
@Override
public int getAssetId() {
return assetId;
}
@Override
public void setAssetId(int assetId) {
this.assetId = assetId;
}
public int getDecimals() {
return decimals;
}
public void setDecimals(int decimals) {
this.decimals = decimals;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getAddressPrefix() {
return addressPrefix;
}
public void setAddressPrefix(String addressPrefix) {
this.addressPrefix = addressPrefix;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public long getPacketMagic() {
return packetMagic;
}
public void setPacketMagic(long packetMagic) {
this.packetMagic = packetMagic;
}
public int getMaxInCount() {
return maxInCount;
}
public void setMaxInCount(int maxInCount) {
this.maxInCount = maxInCount;
}
public int getMaxOutCount() {
return maxOutCount;
}
public void setMaxOutCount(int maxOutCount) {
this.maxOutCount = maxOutCount;
}
public byte getReverseCheck() {
return reverseCheck;
}
public void setReverseCheck(byte reverseCheck) {
this.reverseCheck = reverseCheck;
}
public int getMaxInSameIp() {
return maxInSameIp;
}
public void setMaxInSameIp(int maxInSameIp) {
this.maxInSameIp = maxInSameIp;
}
public String getSelfSeedIps() {
return selfSeedIps;
}
public void setSelfSeedIps(String selfSeedIps) {
this.selfSeedIps = selfSeedIps;
}
public List<String> getSeedIpList() {
return seedIpList;
}
public void setSeedIpList(List<String> seedIpList) {
this.seedIpList = seedIpList;
}
public int getCrossPort() {
return crossPort;
}
public void setCrossPort(int crossPort) {
this.crossPort = crossPort;
}
public int getCrossMaxInCount() {
return crossMaxInCount;
}
public void setCrossMaxInCount(int crossMaxInCount) {
this.crossMaxInCount = crossMaxInCount;
}
public int getCrossMaxOutCount() {
return crossMaxOutCount;
}
public void setCrossMaxOutCount(int crossMaxOutCount) {
this.crossMaxOutCount = crossMaxOutCount;
}
public int getCrossMaxInSameIp() {
return crossMaxInSameIp;
}
public void setCrossMaxInSameIp(int crossMaxInSameIp) {
this.crossMaxInSameIp = crossMaxInSameIp;
}
public String getMoonSeedIps() {
return moonSeedIps;
}
public void setMoonSeedIps(String moonSeedIps) {
this.moonSeedIps = moonSeedIps;
}
public List<String> getMoonSeedIpList() {
return moonSeedIpList;
}
public void setMoonSeedIpList(List<String> moonSeedIpList) {
this.moonSeedIpList = moonSeedIpList;
}
public boolean isMoonNode() {
return moonNode;
}
public void setMoonNode(boolean moonNode) {
this.moonNode = moonNode;
}
public void setLocalIps(List<String> localIps) {
this.localIps = localIps;
}
public int getUpdatePeerInfoType() {
return updatePeerInfoType;
}
public void setUpdatePeerInfoType(int updatePeerInfoType) {
this.updatePeerInfoType = updatePeerInfoType;
}
public String getTimeServers() {
return timeServers;
}
public void setTimeServers(String timeServers) {
this.timeServers = timeServers;
}
public int getUnconfirmedTxExpired() {
return unconfirmedTxExpired;
}
public void setUnconfirmedTxExpired(int unconfirmedTxExpired) {
this.unconfirmedTxExpired = unconfirmedTxExpired;
}
public int getAssetRegDestroyAmount() {
return assetRegDestroyAmount;
}
public void setAssetRegDestroyAmount(int assetRegDestroyAmount) {
this.assetRegDestroyAmount = assetRegDestroyAmount;
}
public int getCrossCtxType() {
return crossCtxType;
}
public void setCrossCtxType(int crossCtxType) {
this.crossCtxType = crossCtxType;
}
public boolean isMainNet() {
return mainNet;
}
public void setMainNet(boolean mainNet) {
this.mainNet = mainNet;
}
public String getCrossSeedIps() {
return crossSeedIps;
}
public void setCrossSeedIps(String crossSeedIps) {
this.crossSeedIps = crossSeedIps;
}
public Set<String> getSeedNodeSet() {
return seedNodeSet;
}
public void setSeedNodeSet(Set<String> seedNodeSet) {
this.seedNodeSet = seedNodeSet;
}
public Long getVersion1_6_0_height() {
return version1_6_0_height;
}
public void setVersion1_6_0_height(Long version1_6_0_height) {
this.version1_6_0_height = version1_6_0_height;
}
public int getForkChainsMonitorInterval() {
return forkChainsMonitorInterval;
}
public void setForkChainsMonitorInterval(int forkChainsMonitorInterval) {
this.forkChainsMonitorInterval = forkChainsMonitorInterval;
}
public int getOrphanChainsMonitorInterval() {
return orphanChainsMonitorInterval;
}
public void setOrphanChainsMonitorInterval(int orphanChainsMonitorInterval) {
this.orphanChainsMonitorInterval = orphanChainsMonitorInterval;
}
public int getOrphanChainsMaintainerInterval() {
return orphanChainsMaintainerInterval;
}
public void setOrphanChainsMaintainerInterval(int orphanChainsMaintainerInterval) {
this.orphanChainsMaintainerInterval = orphanChainsMaintainerInterval;
}
public int getStorageSizeMonitorInterval() {
return storageSizeMonitorInterval;
}
public void setStorageSizeMonitorInterval(int storageSizeMonitorInterval) {
this.storageSizeMonitorInterval = storageSizeMonitorInterval;
}
public int getNetworkResetMonitorInterval() {
return networkResetMonitorInterval;
}
public void setNetworkResetMonitorInterval(int networkResetMonitorInterval) {
this.networkResetMonitorInterval = networkResetMonitorInterval;
}
public int getNodesMonitorInterval() {
return nodesMonitorInterval;
}
public void setNodesMonitorInterval(int nodesMonitorInterval) {
this.nodesMonitorInterval = nodesMonitorInterval;
}
public int getBlockBZTClearMonitorInterval() {
return blockBZTClearMonitorInterval;
}
public void setBlockBZTClearMonitorInterval(int blockBZTClearMonitorInterval) {
this.blockBZTClearMonitorInterval = blockBZTClearMonitorInterval;
}
public int getTxGroupRequestorInterval() {
return txGroupRequestorInterval;
}
public void setTxGroupRequestorInterval(int txGroupRequestorInterval) {
this.txGroupRequestorInterval = txGroupRequestorInterval;
}
public int getTxGroupTaskDelay() {
return txGroupTaskDelay;
}
public void setTxGroupTaskDelay(int txGroupTaskDelay) {
this.txGroupTaskDelay = txGroupTaskDelay;
}
public int getTestAutoRollbackAmount() {
return testAutoRollbackAmount;
}
public void setTestAutoRollbackAmount(int testAutoRollbackAmount) {
this.testAutoRollbackAmount = testAutoRollbackAmount;
}
public int getRollbackHeight() {
return rollbackHeight;
}
public void setRollbackHeight(int rollbackHeight) {
this.rollbackHeight = rollbackHeight;
}
public String getKeystoreFolder() {
return keystoreFolder;
}
public void setKeystoreFolder(String keystoreFolder) {
this.keystoreFolder = keystoreFolder;
}
public int getSigMode() {
return sigMode;
}
public void setSigMode(int sigMode) {
this.sigMode = sigMode;
}
public String getSigMacUrl() {
return sigMacUrl;
}
public void setSigMacUrl(String sigMacUrl) {
this.sigMacUrl = sigMacUrl;
}
public String getSigMacApiKey() {
return sigMacApiKey;
}
public void setSigMacApiKey(String sigMacApiKey) {
this.sigMacApiKey = sigMacApiKey;
}
public String getSigMacAddress() {
return sigMacAddress;
}
public void setSigMacAddress(String sigMacAddress) {
this.sigMacAddress = sigMacAddress;
}
public String getBlockAccountManager() {
return blockAccountManager;
}
public void setBlockAccountManager(String blockAccountManager) {
this.blockAccountManager = blockAccountManager;
}
@Override
public VersionChangeInvoker getVersionChangeInvoker() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> aClass = Class.forName("io.nuls.transaction.rpc.upgrade.TxVersionChangeInvoker");
return (VersionChangeInvoker) aClass.getDeclaredConstructor().newInstance();
}
}
|
package SessionShopping;
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 java.awt.print.Book;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
/**
* Created by dell on 2016-12-27.
* 列出所有书
*/
@WebServlet(name = "ServletListBook",urlPatterns = "/ListBook")
public class ServletListBook extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("本网站有如下商品<br/>");
}
}
|
package br.unaerp.DAO;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTable {
public static void createTables() throws SQLException {
String enableForennig = "PRAGMA foreign_keys = ON;";
String tableTime = "create table if not exists time\n" +
"(\n" +
" id INTEGER primary key autoincrement,\n" +
" name varchar(100) NOT NULL\n" +
");";
String tableJogador = "create table if not exists jogador\n" +
"(\n" +
" id INTEGER primary key autoincrement,\n" +
" name varchar(100) NOT NULL,\n" +
" time_id INTEGER NOT NULL,\n" +
" foreign key (time_id) references \"time\" (id)\n" +
");";
Statement forenign = ConnectionFactory.getInstance().createStatement();
forenign.execute(enableForennig);
Statement table1 = ConnectionFactory.getInstance().createStatement();
table1.execute(tableTime);
Statement table2 = ConnectionFactory.getInstance().createStatement();
table2.execute(tableJogador);
}
}
|
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class ViewResultServlet extends HttpServlet
{
private List<CustomBinThree> list;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
String result = req.getParameter("tree");
out.print("<div class='send'>" + result + "</div>");
try {
int val = Integer.parseInt(result);
if (val < list.size() && val >= 0)
{
list.get(val).balance();
String flag;
if (list.get(val).getRoot().getLeft() != null && list.get(val).getRoot().getRight() != null)
{
int res = list.get(val).getRoot().getLeft().getN() - list.get(val).getRoot().getRight().getN();
flag = res <=2 || res >= -2? "balance": "not balance";
}
else
flag = "balance";
out.print("<div class='res'>"+ flag + "</div>");
}
else {
out.print("<div class='res'>Not correct value</div>");
}
}catch (Exception e)
{
out.print("<div class='res'>Input error</div>");
}
finally
{
out.close();
}
}
@Override
public void init() throws ServletException
{
super.init();
list = new ArrayList<>();
list.add(new CustomBinThree(createFirstTree()));
list.add(new CustomBinThree(create2Tree()));
list.add(new CustomBinThree(create3Tree()));
list.add(new CustomBinThree(create4Tree()));
}
private Node create2Tree() {
Node root = new Node("root", "root", 0);
return root;
}
private Node create4Tree() {
return null;
}
private Node create3Tree() {
Node root = new Node("root", "root", 1);
Node right = new Node("right", "right", 0);
root.setRight(right);
Node left = new Node("left", "left", 0);
root.setLeft(left);
return root;
}
private Node createFirstTree(){
Node root = new Node("root", "root", 3);
Node right = new Node("right", "right", 0);
root.setRight(right);
Node left = new Node("left", "left", 2);
root.setLeft(left);
Node leftRight = new Node("leftRight", "leftRight", 0);
Node leftLeft = new Node("leftLeft", "leftLeft", 1);
Node leftLeftLeft = new Node("leftLeftLeft", "leftLeftLeft", 0);
left.setRight(leftRight);
left.setLeft(leftLeft);
leftLeft.setLeft(leftLeftLeft);
List<Node> listAfter = new ArrayList<>();
listAfter.add(root);
listAfter.add(left);
listAfter.add(leftLeft);
listAfter.add(leftLeftLeft);
listAfter.add(leftRight);
listAfter.add(right);
List<Node> listBefore = new ArrayList<>();
listBefore.add(left);
listBefore.add(leftLeft);
listBefore.add(leftLeftLeft);
listBefore.add(root);
listBefore.add(leftRight);
listBefore.add(right);
return root;
}
}
|
package com.lsjr.zizisteward.coustom.adapter;
import android.text.Editable;
import android.text.TextWatcher;
/**
* Created by admin on 2017/5/20.
*/
public abstract class MyEditTextChangeListener implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
}
|
package com.qx.wechat.comm.sdk.request.query;
import com.qx.wechat.comm.sdk.request.msg.PassiveMsgType;
/**
*
* @author Macky(liuyunsh@cn.ibm.com)
*
* @date: Apr 12, 2020 4:10:12 PM
*
* @since: 1.0.0
*
*/
public class RobotGroupMemberInfoQuery extends BasicQuery {
private static final long serialVersionUID = 8962056880260850646L;
private String robot_wxid;
private String group_wxid;// 群id
private String member_wxid;// 群成员id
public RobotGroupMemberInfoQuery() {
super.setType(PassiveMsgType.ROBOT_GROUP_MEMBER_MSG.getValue());
}
public String getRobot_wxid() {
return robot_wxid;
}
public RobotGroupMemberInfoQuery setRobot_wxid(String robot_wxid) {
this.robot_wxid = robot_wxid;
return this;
}
public String getGroup_wxid() {
return group_wxid;
}
public RobotGroupMemberInfoQuery setGroup_wxid(String group_wxid) {
this.group_wxid = group_wxid;
return this;
}
public String getMember_wxid() {
return member_wxid;
}
public RobotGroupMemberInfoQuery setMember_wxid(String member_wxid) {
this.member_wxid = member_wxid;
return this;
}
}
|
public class Caixa extends Funcionario{
private int numeroDoGuiche=0;
public int getNumeroDoGuiche() {
return numeroDoGuiche;
}
public void setNumeroDoGuiche(int numeroDoGuiche) {
this.numeroDoGuiche = numeroDoGuiche;
}
@Override
double getBonificacao() {
return this.salario * 0.15;
}
}
|
package net.imglib2.trainable_segmention;
import net.imglib2.FinalInterval;
import net.imglib2.Interval;
import net.imglib2.RandomAccessible;
import net.imglib2.converter.Converters;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.NumericType;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.Intervals;
import org.junit.Test;
import java.util.function.BiConsumer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Matthias Arzt
*/
public class RevampUtilsTest {
@Test
public void testGaussRequiredInput() {
double[] sigmas = { 5.0, 2.0 };
Interval output = new FinalInterval(new long[] { 2, 5 }, new long[] { 9, 10 });
Interval input = RevampUtils.gaussRequiredInput(output, sigmas);
testRequiredInput(output, input, (i, o) -> RevampUtils.gauss(Utils.ops(), i, o, sigmas));
}
@Test
public void TestDeriveXRequiredInput() {
Interval output = new FinalInterval(new long[] { 2, 5 }, new long[] { 9, 10 });
Interval input = RevampUtils.deriveXRequiredInput(output);
testRequiredInput(output, input, (in, out) -> RevampUtils.deriveX(Utils.ops(), in, out));
}
@Test
public void TestDeriveYRequiredInput() {
Interval output = new FinalInterval(new long[] { 2, 5 }, new long[] { 9, 10 });
Interval input = RevampUtils.deriveYRequiredInput(output);
testRequiredInput(output, input, (in, out) -> RevampUtils.deriveY(Utils.ops(), in, out));
}
private void testRequiredInput(Interval outputInterval, Interval inputInterval,
BiConsumer<RandomAccessible<FloatType>, Interval> operation)
{
Img<ByteType> inputAccessed = Utils.ops().create().img(inputInterval, new ByteType());
RandomAccessible<FloatType> input = recordAccessView(inputAccessed);
operation.accept(input, outputInterval);
inputAccessed.forEach(x -> assertEquals(1, x.get()));
}
/**
* Initially all pixels of "accessed" are set to zero. For each read access to a
* pixel of the returned {@link RandomAccessible<FloatType>}, the according
* pixel of "accessed" is set to one.
*/
private static RandomAccessible<FloatType> recordAccessView(
Img<? extends NumericType<?>> accessed)
{
accessed.forEach(NumericType::setZero);
return Converters.convert(
(RandomAccessible<? extends NumericType<?>>) accessed,
(in, out) -> {
in.setOne();
out.setZero();
}, new FloatType());
}
@Test
public void testIntervalRemoveDimension() {
Interval input = Intervals.createMinMax(1, 2, 3, 4, 5, 6, 7, 8);
Interval result = RevampUtils.intervalRemoveDimension(input, 1);
assertTrue(Intervals.equals(Intervals.createMinMax(1, 3, 4, 5, 7, 8), result));
}
}
|
package com.oxymore.practice.controller;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.oxymore.practice.LocaleController;
import com.oxymore.practice.Practice;
import com.oxymore.practice.configuration.match.Kit;
import com.oxymore.practice.configuration.match.MatchMode;
import com.oxymore.practice.configuration.ui.ItemPlaceholder;
import com.oxymore.practice.documents.EloDocument;
import com.oxymore.practice.documents.KitDocument;
import com.oxymore.practice.match.*;
import com.oxymore.practice.match.arena.Arena;
import com.oxymore.practice.match.arena.MatchArena;
import com.oxymore.practice.match.party.Party;
import com.oxymore.practice.match.party.PartyPlayerList;
import com.oxymore.practice.match.queue.MatchQueue;
import com.oxymore.practice.match.queue.impl.MatchQueueEntry;
import com.oxymore.practice.match.queue.impl.RankedMatchQueue;
import com.oxymore.practice.match.queue.impl.RankedMatchQueueEntry;
import com.oxymore.practice.match.queue.impl.UnrankedMatchQueue;
import com.oxymore.practice.util.NMSUtil;
import com.oxymore.practice.view.gui.PlayerMatchStatsGUI;
import com.oxymore.practice.view.match.MatchSelector;
import com.oxymore.practice.view.match.ModeSelectorView;
import lombok.Getter;
import org.bson.conversions.Bson;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.PotionEffect;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.mongodb.client.model.Updates.inc;
@Getter
public final class MatchingController implements Match.MatchBroadcaster, ModeSelectorView.ModeSelectedConsumer {
private final Practice plugin;
private final Random random = new Random();
private final Map<MatchType, MatchSelector> selectors;
private final Map<MatchType, MatchQueue<?>> queues;
private final Map<UUID, Match> currentMatches;
private final Map<Player, Match> spectating;
private final Map<UUID, PlayerMatchStatsGUI.PlayerMatchStatsSnapshot> playerSnapshots;
private final Multimap<Player, KitDocument> maySelectKits;
public MatchingController(Practice plugin) throws ControllerInitException {
this.plugin = plugin;
this.selectors = new HashMap<>();
this.queues = new HashMap<>();
for (MatchType matchType : MatchType.values()) {
final String prefix = "modes." + (matchType.isRanked() ? "ranked" : "unranked") + ".selector";
selectors.put(matchType, new MatchSelector(plugin, listSupportedModes(matchType), matchType, this, prefix));
if (matchType.isJoinable() && matchType.isRanked()) {
queues.put(matchType, new RankedMatchQueue(matchType.isSingle() ? 2 : 4));
} else if (matchType.isJoinable() && matchType.isUnranked()) {
queues.put(matchType, new UnrankedMatchQueue(matchType.isSingle() ? 2 : 4));
}
}
this.currentMatches = new HashMap<>();
this.spectating = new HashMap<>();
this.playerSnapshots = new HashMap<>();
this.maySelectKits = ArrayListMultimap.create();
}
private List<MatchMode> listSupportedModes(MatchType matchType) {
return plugin.getConfiguration().matchModes.stream()
.filter(mode -> mode.supportTypes.contains(matchType))
.collect(Collectors.toList());
}
// match creation
public Match createMatch(MatchMode matchMode, MatchType matchType, String arenaName, List<Player> team1, List<Player> team2)
throws MatchCreationException {
if (arenaName == null && !matchMode.arenas.isEmpty()) {
arenaName = matchMode.arenas.get(random.nextInt(matchMode.arenas.size()));
}
final ArenaController arenaController = plugin.getArenaController();
final Arena arena = arenaName != null ? arenaController.getArenas().get(arenaName) : null;
if (arena == null) {
throw new MatchCreationException("match.create.failed.arena");
}
if (arena.getSpawnLocations().size() < 2) {
throw new MatchCreationException("match.create.failed.missing-spawn");
}
final MatchArena matchArena = arenaController.makeMatchArena(arena);
if (matchArena == null) {
throw new MatchCreationException("match.create.failed.arena");
}
// make players forfeit their current matches
final List<Player> allPlayers = new ArrayList<>();
allPlayers.addAll(team1);
if (team2 != null) {
allPlayers.addAll(team2);
}
allPlayers.forEach(this::resetState);
allPlayers.forEach(itPlayer -> plugin.getVisibilityController().restrain(itPlayer, allPlayers));
if (allPlayers.stream().distinct().count() != allPlayers.size()) {
throw new MatchCreationException("match.create.failed.duplicate");
}
final MatchTeam matchTeam1 = new MatchTeam(team1.toArray(new Player[0]));
final MatchTeam matchTeam2 = team2 != null ? new MatchTeam(team2.toArray(new Player[0])) : null;
final World arenaWorld = arenaController.getWorld();
Location centerPoint = matchArena.relativeLoc(arena.getCenterPoint(), arenaWorld);
if (centerPoint != null) {
final Block block = centerPoint.getBlock();
if (block != null) {
block.setType(arena.getConfiguration().centerBlockReplace);
}
} else {
centerPoint = matchArena.relativeLoc(arena.getSpawnLocations().get(0), arenaWorld);
}
final Map<MatchTeam, Location> spawnLocations = new HashMap<>();
spawnLocations.put(matchTeam1, matchArena.relativeLoc(arena.getSpawnLocations().get(0), arenaWorld));
if (matchTeam2 != null) {
spawnLocations.put(matchTeam2, matchArena.relativeLoc(arena.getSpawnLocations().get(1), arenaWorld));
}
spawnLocations.values().forEach(value -> value.add(0, 1, 0));
arena.getSpawnLocations().stream()
.map(rel -> matchArena.relativeLoc(rel, arenaWorld))
.forEach(loc -> {
final Block block = loc.getBlock();
if (block != null) {
block.setType(arena.getConfiguration().spawnBlockReplace);
}
});
final Match match = new Match(matchMode, matchType, matchArena, centerPoint, spawnLocations,
matchTeam1, matchTeam2, this);
final ViewController viewController = plugin.getViewController();
for (Player player : allPlayers) {
viewController.getPlayerPanel(player).setPlayerView(null, null);
player.closeInventory();
plugin.getScoreboardController().destroyScoreboard(player);
currentMatches.put(player.getUniqueId(), match);
stuff(match, player);
match.teleportToSpawn(player);
}
return match;
}
// queue
public boolean isInQueue(Player player) {
return queues.values().stream()
.anyMatch(queue -> queue.isQueued(player));
}
public void removeFromQueue(Player player) {
queues.values().stream()
.filter(queue -> queue.isQueued(player))
.findAny()
.ifPresent(queue -> {
final MatchQueueEntry queueEntry = queue.getPlayerEntry(player);
final Collection<Player> removed;
if (queueEntry.getPlayers() instanceof PartyPlayerList) {
final PartyPlayerList partyPlayerList = (PartyPlayerList) queueEntry.getPlayers();
if (partyPlayerList.getParty().getLeader().equals(player) || partyPlayerList.size() <= 1) {
removed = queue.deQueuePlayer(player).getPlayers();
} else if (partyPlayerList.remove(player)) {
partyPlayerList.getParty().broadcast(plugin.getLocale().get("party.player-left-queue")
.var("player", player.getName()));
removed = Collections.singletonList(player);
} else {
return;
}
} else {
removed = queue.deQueuePlayer(player).getPlayers();
}
removed.forEach(itPlayer -> plugin.getViewController().updateSpawnView(itPlayer, false));
});
}
public boolean queue(Collection<Player> players, MatchType matchType, MatchMode matchMode, String arena, int elo) {
final MatchQueue<?> matchQueue = queues.get(matchType);
if (matchQueue == null) {
return false;
}
if (matchQueue instanceof UnrankedMatchQueue) {
((UnrankedMatchQueue) matchQueue).push(new MatchQueueEntry(players, matchMode, arena));
} else if (matchQueue instanceof RankedMatchQueue) {
((RankedMatchQueue) matchQueue).push(new RankedMatchQueueEntry(players, matchMode, arena, elo));
} else {
return false;
}
players.forEach(player -> plugin.getViewController().updateSpawnView(player, false));
return true;
}
// queries
public Match getCurrentMatch(Player player) {
return currentMatches.get(player.getUniqueId());
}
public boolean isInMatch(Player player) {
final Match currentMatch = getCurrentMatch(player);
return currentMatch != null && currentMatch.getState() == MatchState.PLAYING;
}
public int getFightingPlayerCount() {
return currentMatches.size();
}
public Collection<Match> getDistinctMatches() {
return currentMatches.values().stream()
.distinct()
.collect(Collectors.toList());
}
public boolean isSpawn(Player player) {
return !isInMatch(player) && !spectating.containsKey(player);
}
// direct actions
public void stuff(Match match, Player player) {
player.setGameMode(GameMode.SURVIVAL);
if (match.getState() == MatchState.STARTING) {
resetPlayer(player);
maySelectKits.removeAll(player);
plugin.getDatabaseController().async(db -> {
final List<KitDocument> maySelect = new ArrayList<>();
db.kits
.find(Filters.and(Filters.eq("owner", player.getUniqueId()), Filters.eq("modeId", match.getMode().id)))
.forEach((Consumer<? super KitDocument>) maySelect::add);
maySelect.add(new KitDocument(null, null, 8, "Default", match.getMode().defaultKit));
db.syncIfOnline(player, () -> {
final ItemPlaceholder kitIcon = new ItemPlaceholder(Material.BOOK, (short) 0, 1,
"${kit.choose.title}", "${kit.choose.desc}");
for (KitDocument kitDocument : maySelect) {
final Map<String, String> variables = new HashMap<>();
variables.put("name", kitDocument.getDisplayName());
final ItemStack kitItem = kitIcon.buildFromVariables(plugin.getLocale(), variables);
if (kitDocument.getSlot() == 8) {
final ItemMeta itemMeta = kitItem.getItemMeta();
itemMeta.addEnchant(Enchantment.DURABILITY, 1, true);
kitItem.setItemMeta(itemMeta);
}
player.getInventory().setItem(kitDocument.getSlot(), NMSUtil.setItemFlags(kitItem, NMSUtil.ItemFlag.HIDE_ENCHANTS));
}
maySelectKits.putAll(player, maySelect);
});
});
} else if (match.getState() == MatchState.PLAYING) {
final int noDamageTicks = match.getMode().noDamageTicks;
if (noDamageTicks != -1) {
player.setMaximumNoDamageTicks(noDamageTicks);
}
if (match.getMatchType() != MatchType.FFA) {
match.teleportToSpawn(player);
}
}
}
public void selectKit(Player player, Kit kit) {
player.getInventory().clear();
kit.apply(player.getInventory(), true);
player.updateInventory();
}
public void killPlayer(Player player, Match.DeathCause deathCause) {
maySelectKits.removeAll(player);
final Match match = currentMatches.get(player.getUniqueId());
if (match == null) {
return;
}
currentMatches.remove(player.getUniqueId());
final MatchTeam matchTeam = match.getTeam2() != null ? match.getTeam(player) : match.getTeam1();
if (matchTeam == null) {
return;
}
if (matchTeam.getFightingPlayers().remove(player)) {
matchTeam.getDeadPlayers().add(player);
if (match.getState() == MatchState.ENDED) {
return;
}
final Player killer = player.getKiller() != null && match.isAlive(player.getKiller())
? player.getKiller() : null;
final String messageKey;
if (deathCause == Match.DeathCause.KILLED) {
if (killer != null) {
messageKey = "match.game.death.killed";
} else {
messageKey = "match.game.death.killed-no-killer";
}
} else if (deathCause == Match.DeathCause.FORFEIT) {
messageKey = "match.game.death.forfeit";
} else {
throw new IllegalStateException();
}
match.getPlayerStatistics().get(player).dead = true;
if (killer != null) {
match.getPlayerStatistics().get(killer).kills++;
}
snapshot(match, player);
spectate(player, match);
match.getDead().add(player);
match.broadcast(null, locale -> locale.get(messageKey)
.var("victim", player.getName())
.var("killer", killer != null ? killer.getName() : null)
.toString());
match.getFightingPlayers().forEach(itPlayer -> plugin.getVisibilityController().hideIfShown(itPlayer, player));
if (match.getTeam2() != null && match.getTeam1().getFightingPlayers().isEmpty()) {
endMatch(match, match.getTeam2());
} else if (match.getTeam2() != null && match.getTeam2().getFightingPlayers().isEmpty()) {
endMatch(match, match.getTeam1());
} else if (match.getTeam2() == null && match.getTeam1().getFightingPlayers().size() == 1) {
endMatch(match, match.getTeam(match.getTeam1().getFightingPlayers().get(0)));
}
}
}
private void snapshot(Match match, Player player) {
UUID temp;
do {
temp = UUID.randomUUID();
} while (playerSnapshots.containsKey(temp));
final UUID snapshotId = temp;
final PlayerMatchStatsGUI.PlayerMatchStatsSnapshot snapshot = new PlayerMatchStatsGUI.PlayerMatchStatsSnapshot(
snapshotId, player,
player.getInventory().getContents(), player.getInventory().getArmorContents(),
Math.max(0, player.getHealth()), match.getPlayerStatistics().get(player)
);
playerSnapshots.put(snapshotId, snapshot);
match.getPlayerStatistics().values().stream()
.filter(stats -> stats.snapshotId != null)
.map(stats -> playerSnapshots.get(stats.snapshotId))
.filter(itSnapshot -> itSnapshot.next == null)
.findAny()
.ifPresent(itSnapshot -> {
itSnapshot.next = snapshotId;
snapshot.previous = itSnapshot.id;
});
match.getPlayerStatistics().get(player).snapshotId = snapshotId;
}
public void endMatch(Match match, MatchTeam winningTeam) {
match.setState(MatchState.ENDED);
match.setPlaytime(0);
for (Player player : match.getFightingPlayers()) {
snapshot(match, player);
resetPlayer(player);
}
// cycle through snapshots: tail <-> head
PlayerMatchStatsGUI.PlayerMatchStatsSnapshot headSnapshot = null,
tailSnapshot = null;
for (PlayerMatchStats playerMatchStats : match.getPlayerStatistics().values()) {
if (playerMatchStats.snapshotId != null) {
PlayerMatchStatsGUI.PlayerMatchStatsSnapshot itSnapshot = playerSnapshots.get(playerMatchStats.snapshotId);
if (itSnapshot.previous == null) {
headSnapshot = itSnapshot;
}
if (itSnapshot.next == null) {
tailSnapshot = itSnapshot;
}
}
}
if (headSnapshot != null && tailSnapshot != null) {
tailSnapshot.next = headSnapshot.id;
headSnapshot.previous = tailSnapshot.id;
}
// end message
final LocaleController locale = plugin.getLocale();
final LocaleController.MessageContext endMessageCtx = locale.get("match.end");
for (int i = 0; i < 2; i++) {
final Collection<OfflinePlayer> expansionPlayers = i == 0 ? winningTeam.getPlayers()
: match.getOpposingTeam(winningTeam).getPlayers();
endMessageCtx
.expansion(i == 0 ? "winners" : "losers", expansionPlayers.stream()
.map(player -> (LocaleController.ExpansionElement) ctx -> ctx
.var("player", player.getName())
.var("stats-id", match.getPlayerStatistics().get(player).snapshotId.toString())
)
.collect(Collectors.toList()));
}
match.getReceivers(null).forEach(endMessageCtx::send);
// ranked stats
if (match.getMatchType().isRanked()) {
plugin.getDatabaseController().async(db -> {
final Map<MatchTeam, Integer> teamBaseElos = new HashMap<>();
final Bson modeQuery = Filters.and(Filters.eq("mode", match.getMode().id),
Filters.eq("aux", match.getMatchType().getAux()));
for (MatchTeam team : match.getTeams()) {
teamBaseElos.put(team, db.getAverageElo(getTeamQuery(team, modeQuery)));
}
for (Map.Entry<OfflinePlayer, PlayerMatchStats> entry : match.getPlayerStatistics().entrySet()) {
final OfflinePlayer player = entry.getKey();
final PlayerMatchStats stats = entry.getValue();
final boolean won = winningTeam.isInTeam(player.getUniqueId());
final MatchTeam opposingTeam = match.getOpposingTeam(player);
// stats
Bson update = null;
if (stats.kills > 0) {
update = Updates.inc("kills", stats.kills);
}
if (stats.dead) {
final Bson localUpdate = inc("deaths", 1);
update = update != null ? Updates.combine(update, localUpdate) : localUpdate;
}
if (update != null) {
db.players.updateOne(Filters.eq("playerId", player.getUniqueId()), update);
}
// elo
final Bson query = Filters.and(Filters.eq("playerId", player.getUniqueId()), modeQuery);
final EloDocument eloDoc = db.elo.find(query).first();
final int baseElo = eloDoc != null ? eloDoc.getElo() : 1000;
final int opponentsElo = teamBaseElos.get(opposingTeam);
final int diff = Math.abs(opponentsElo - baseElo);
final int eloGain = (int) Math.min(5, Math.max(22, diff * 0.17));
if (eloDoc != null) {
db.elo.updateOne(query, Updates.inc("elo", won ? eloGain : -eloGain));
} else {
db.elo.insertOne(new EloDocument(player.getUniqueId(), match.getMode().id,
match.getMatchType().getAux(), baseElo + (won ? eloGain : -eloGain)));
}
plugin.getDatabaseController().queryCacheUpdate(player, false);
}
});
}
}
private Bson getTeamQuery(MatchTeam team, Bson modeQuery) {
Bson query = null;
for (OfflinePlayer opponent : team.getPlayers()) {
final Bson localQuery = Filters.and(Filters.eq("playerId", opponent.getUniqueId()), modeQuery);
query = query != null ? Filters.or(query, localQuery) : localQuery;
}
return query;
}
// hooks
public void resetState(Player player) {
killPlayer(player, Match.DeathCause.FORFEIT);
removeFromQueue(player);
plugin.getVisibilityController().liftRestrain(player);
final Match matchSpectate = spectating.remove(player);
if (matchSpectate != null) {
matchSpectate.getSpectators().remove(player);
}
}
public void onDisconnect(Player player) {
resetState(player);
plugin.getPartyController().onDisconnect(player);
}
// player management
public void spectate(Player player, Match match) {
resetState(player);
match.getSpectators().add(player);
spectating.put(player, match);
}
public void autoGo(Player player) {
if (spectating.containsKey(player)) {
plugin.getScoreboardController().destroyScoreboard(player);
resetPlayer(player);
player.setGameMode(GameMode.ADVENTURE);
player.setAllowFlight(true);
final Match match = spectating.get(player);
player.teleport(match.getCenterLocation());
} else {
sendToSpawn(player);
}
}
public void sendToSpawn(Player player) {
final World spawnWorld = Bukkit.getWorlds().get(0);
player.teleport(spawnWorld.getSpawnLocation());
resetPlayer(player);
player.setAllowFlight(player.hasPermission("oxymore.practice.spawn-fly"));
plugin.getViewController().updateSpawnView(player, true);
plugin.getScoreboardController().destroyScoreboard(player);
plugin.getScoreboardController().toLobby(player);
}
private void resetPlayer(Player player) {
player.getInventory().clear();
player.getInventory().setArmorContents(new ItemStack[4]);
for (PotionEffect potionEffect : player.getActivePotionEffects()) {
player.removePotionEffect(potionEffect.getType());
}
player.setGameMode(GameMode.SURVIVAL);
player.setMaximumNoDamageTicks(20);
player.setMaxHealth(20);
player.setHealth(20);
player.setFoodLevel(20);
player.setSaturation(10);
player.setAllowFlight(false);
player.setFallDistance(0);
player.setLevel(0);
player.setExp(0);
}
// impl
@Override
public void broadcast(Collection<Player> receivers, Function<LocaleController, String> getMessage) {
final String message = getMessage.apply(plugin.getLocale());
if (message == null) {
return;
}
receivers.forEach(receiver -> receiver.sendMessage(message));
}
// callbacks
@Override
public void onModeSelect(Player player, MatchType matchType, MatchMode matchMode, String arena) {
final Party party = plugin.getPartyController().getParty(player);
if (party != null) {
if (!party.getLeader().equals(player)) {
plugin.getLocale().get("party.start-no-leader")
.send(player);
return;
}
}
final MatchQueue<?> matchQueue = queues.get(matchType);
if (matchQueue == null) {
return;
}
final Collection<Player> players;
if (party != null) {
players = new PartyPlayerList(party);
final int maxPlayers = matchQueue.getRequiredPlayers();
players.add(player);
final List<Player> partyPlayers = party.getPlayers();
for (int i = 0; i < partyPlayers.size(); i++) {
final Player itPlayer = partyPlayers.get(i);
if (players.contains(itPlayer)) {
continue;
}
// priorities goes to fulfilling the queue rather than letting players finish their match
// but try to avoid queuing players already in match if the number of players allows it
final int remaining = (int) partyPlayers.stream()
.filter(itPartyPlayer -> !players.contains(itPartyPlayer))
.count();
if (remaining > maxPlayers && getCurrentMatch(player) != null) {
continue;
}
players.add(itPlayer);
}
} else {
players = Collections.singletonList(player);
}
if (players instanceof PartyPlayerList && players.size() > matchQueue.getRequiredPlayers() / 2) {
plugin.getLocale().get("party.prevent-boost")
.send(player);
return;
}
plugin.getDatabaseController().async(db -> {
final int elo;
if (matchType.isRanked()) {
final Bson filter = Filters.and(
Filters.and(players.stream()
.map(itPlayer -> Filters.eq("playerId", itPlayer.getUniqueId()))
.collect(Collectors.toList())),
Filters.eq("mode", matchMode.id),
Filters.eq("aux", matchType.getAux()));
elo = db.getAverageElo(filter);
} else {
elo = -1;
}
db.syncIfOnline(player, () -> {
if (!Objects.equals(party, plugin.getPartyController().getParty(player)) ||
(party != null && !party.getLeader().equals(player))) {
return;
}
if (players instanceof PartyPlayerList) {
//noinspection ConstantConditions
players.removeIf(itPlayer -> !itPlayer.isOnline());
}
if (queue(players, matchType, matchMode, arena, elo)) {
plugin.getLocale().get("join.queued." + (matchType.isRanked() ? "ranked" : "unranked"))
.var("mode", matchMode.name)
.var("mode_aux", matchType.getAux())
.var("arena", arena)
.send(players);
}
});
});
}
// classes
public static class MatchCreationException extends Exception {
public MatchCreationException(String messageKey) {
super(messageKey);
}
}
}
|
public class Executors {
public static void executors() {
/**
* Simple executor with single thread
* The difference from doing this manually is that this one
* never stops. Executors have to be stopped explicitly -
* otherwise they keep listening for new tasks.
**/
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
String threadName = Thread.concurrentThread().getName();
System.out.println("hello, I'm "+threadName);
});
//shutting down the executors softly
try {
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedExection e) {
e.printStackTrace();
} finally {
if(!executor.isTerminated())
System.out.println("Now shutting down unfinished tasks");
executor.shutdownNow();
}
/**
* ---------------------------
* TYPES OF EXECUTOR FACTORIES
* ---------------------------
**/
/**
* Executor service with a single thread executor
**/
executor = Executors.newSingleThreadExecutor();
/**
* Executor service backed by a thread-pool of size of the argument
* passed
**/
executor = Executors.newFixedThreadPool(2);
/**
* Of the type ForkJoinPool, which means:
* Instead of using a fixed size thread-pool ForkJoinPools are
* created for a given parallelism size which per default is the
* number of available cores of the hosts CPU.
**/
executor = Executors.newWorkStealingPool();
}
public static void callablesAndFutures() {
/**
* In additions to Runnable theres another kind of task:
* Callable, the difference is that it has a return value,
* instead of void (like Runnable has).
**/
Callable<Integer> task = () -> {
try {
TimeUnit.SECONDS.sleep(1);
return 1829;
} catch (InterruptedExection e) {
throw new IllegalStateException("task interrupted", e);
}
};
/**
* To retrieve the returned value from the callable
* we must use a Future
**/
ExecutorService executor = Executor.newFixedThreadPool(1);
Future<Integer> future = executor.submit(task);
//Check if the execution is finished
if(future.isDone())
System.out.println("Yeey");
//Block the current thread to wait for the callable to complete
Integer result = future.get();
/**
* In the worst case a callable runs forever - thus making your
* application unresponsive. You can simply counteract those
* scenarios by passing a timeout when getting the results
**/
Future<Integer> future = executor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(2);
return 1829;
} catch (InterruptedExection e) {
throw new IllegalStateException("task interrupted", e);
}
});
// This will result in a TimeoutExecption since we timeout after
// one second, while the task takes 2 seconds to complete.
future.get(1, TimeUnit.SECONDS);
/**
* Call multiple Callables with invokeAll()
* Here the string will be printed from all the callables
**/
ExecutorService executor = Executors.newWorkStealingPool();
List<Callable<String>> callables = Arrays.asList(
()->"task1", ()->"task2", ()->"task3");
executor.invokeAll(callables)
.stream()
.map(future -> {
try {
return future.get();
}
catch (Exception e) {
throw new IllegalStateException(e);
}
})
.forEach(System.out::println);
/**
* You can also get the return value of the firsts one to complete
* by using invokeAny.
* This blocks the current thread until it gets a result.
**/
String result = executor.invokeAny(callables);
}
/**
* In order to periodically run common tasks multiple times,
* we can utilize scheduled thread pools
**/
public static void scheduledExecutors() {
/**
* This will schedule the task to run after an initial delay
**/
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> System.out.println("Coolbeans");
ScheduledFuture<?> future = executor.schedule(task, 3, TimeUnit.SECONDS);
//We can also get the remaining time
long remaining = future.getDelay(TimeUnit.MILLISECONDS);
/**
* In order to schedule tasks to be executed periodically,
* executors provide the two methods scheduleAtFixedRate()
* and scheduleWithFixedDelay()
**/
//This capable of executing tasks with a fixed time rate
int initialDelay = 0, period = 5;
executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
/**
* scheduleAtFixedRate() doesn't take into account the actual
* duration of the task.
* However scheduleWithFixedDelay() does. It will start the wait-
* period after the previous run has ended.
**/
executor.scheduleWithFixedDelay(task, initialDelay, period, TimeUnit.SECONDS);
}
}
//Source: http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/
|
package com.algaworks.curso.jpa2.dao;
import java.io.Serializable;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import com.algaworks.curso.jpa2.modelo.Aluguel;
public class AluguelDAO implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;
@Inject
private ApoliceSeguroDAO apoliceSeguroDAO;
public void salvar(Aluguel aluguel) {
apoliceSeguroDAO.salvar(aluguel.getApoliceSeguro());
manager.merge(aluguel);
}
}
|
package xiao.yang.microservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@EnableCircuitBreaker//对hystrixR熔断机制的支持
@EnableFeignClients()
@EnableEurekaClient //在启动该微服务的时候就能去加载我们的自定义Ribbon配置类,从而使配置生效
@SpringBootApplication
public class MicroservicecloudConsumerDept8080Application {
public static void main(String[] args) {
SpringApplication.run(MicroservicecloudConsumerDept8080Application.class, args);
}
}
|
package WebShop.web;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import java.io.IOException;
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 WebShop.model.Category;
import WebShop.model.Client;
import WebShop.model.Product;
import WebShop.services.CategoryService;
import WebShop.services.ProductService;
@ManagedBean
@SessionScoped
@WebServlet("/newProduct")
public class ProductController extends HttpServlet implements Serializable{
private Product newProduct = new Product();
private Product showProduct = new Product();
private String categoryName = new String();
boolean categoryView = false;
private List<Product> products = null;
private String searchedName="";
public String getSearchedName() {
return searchedName;
}
boolean editing = false;
private Product current;
public Product getCurrent() {
if (current == null)
current = new Product();
return current;
}
public void setCurrent(Product current) {
this.current = current;
}
public boolean isEditing() {
return editing;
}
public void setEditing(boolean editing) {
this.editing = editing;
}
private DataModel<Product> items = null;
public DataModel<Product> getItems() {
if (items == null)
items = new ListDataModel<Product>(productService.findAll());
return items;
}
public void setItems(DataModel<Product> items) {
this.items = items;
}
public void setSearchedName(String searchedName) {
this.searchedName = searchedName;
}
@EJB
ProductService productService;
@EJB
CategoryService categoryController;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Product getNewProduct() {
return newProduct;
}
public void setNewProduct(Product newProduct) {
this.newProduct = newProduct;
}
/*public String createProduct(){
productService.create(newProduct, categoryName);
newProduct = new Product();
return null;
}*/
public List<Product> getProducts() {
if(searchedName.isEmpty()){
products = productService.findAll();
}
else {
products=productService.productsWithName(searchedName);
}
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Product getShowProduct() {
return showProduct;
}
public void setShowProduct(Product showProduct) {
this.showProduct = showProduct;
}
public String prepareShowProduct() {
return FacesUtil.pageWithRedirect("shop_item.html");
}
public List<Product> productsByCategory(String categoryName){
products = productService.filterWithCategory(categoryName);
return products;
}
public String prepareList() {
items = null;
return FacesUtil.pageWithRedirect("list_product.xhtml");
}
public String prepareNew() {
editing = false;
current = null;
return FacesUtil.pageWithRedirect("edit_product.xhtml");
}
public String prepareEdit() {
editing = true;
current = getItems().getRowData();
return FacesUtil.pageWithRedirect("edit_product.xhtml");
}
public String save() {
Category cat = categoryController.getCategoryWithName(categoryName);
current.setCategory(cat);
if (editing){
productService.edit(current);
}
else{
productService.create(current);
}
FacesUtil.addInfoMessage("Entity successfully saved");
items = null;
current = null;
return FacesUtil.pageWithRedirect("list_product.xhtml");
}
public String remove() {
productService.remove(getItems().getRowData());
FacesUtil.addInfoMessage("Entity successfully removed");
items = new ListDataModel<Product>(productService.findAll());
return FacesUtil.pageWithRedirect("list_product.xhtml");
}
}
|
package fighterTest;
public class FighterTest {
public static void main(String[] args) {
fighter f = new fighter();
if (f instanceof unit)
System.out.println("f는 unit 클래스의 자손입니다");
if (f instanceof fightable)
System.out.println("f는 fightable 클래스의 자손입니다");
if (f instanceof movable)
System.out.println("f는 movable 클래스의 자손입니다");
if (f instanceof attackable)
System.out.println("f는 attackable 클래스의 자손입니다");
if (f instanceof Object)// 모든것은 결국에는 오브젝트의 자손임
System.out.println("f는 Object 클래스의 자손입니다");
}
}
class fighter extends unit implements fightable {// 구현을 해준다
public void move(int x, int y) {
System.out.println(x + "+" + y + "로 이동하였습니다");
}
public void attack(unit u) {
}
}
class unit {
int hp;
int x;
int y;
}
interface fightable extends movable, attackable {// movable과 attackable을 한곳에 합치는 부분
}
interface movable {
void move(int x, int y);
}
interface attackable {
void attack(unit u);
}
|
/*
* 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.
*/
package nl.fontys.pts61a.vps.service;
import java.util.Date;
import java.util.List;
import nl.fontys.pts61a.vps.model.Cartracker;
import nl.fontys.pts61a.vps.model.Gebruiker;
import nl.fontys.pts61a.vps.model.Movement;
/**
*
* @author Jesper
*/
public interface MovementService {
public Movement getMovementById(Long Id, Long Mid);
public List<Movement> getMovementsByDate(Long cId, Date startDate, Date endDate);
public Cartracker checkCartrackerId(Long carTrackerId, String verificatieCode);
public void addMovement(Movement movement);
public void createCartracker(Cartracker cartracker);
public void setCartracketNextId(Cartracker cartracker, Long nextId);
public Cartracker getCartrackerById(Long id);
public Boolean editCartrackerId(Long id, Long newId);
public List<Movement> getMovementsByCartracker(Long id);
public List<Cartracker> getAllCartrackers();
public boolean changeState(Long id, String state);
public Gebruiker getUser(String name, String authKey);
}
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
import java.lang.*;
/*
* 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.
*/
/**
*
* @author x230
*/
public class Recommender {
public static double weighted_average(int[] userRating, int[][] ratingList) {
int result = 0;
return result;
}
public static void score(double[] p2Sim, double p1, int[] userRating, int[][] ratingList) {// caculates cosine similarity score
double result = 0;
int both = 0;
int row = 0;
int col = 0;
int interval = 0;
for (int i = 0; i < ratingList.length; i++) {
System.out.println(row+"-"+col);
if (userRating[i] == ratingList[row][col]) {
both = userRating[i] * ratingList[row][col];
col++;
}
if (col == 19) {
row++;
result = (both / (p1 * p2Sim[i]));
interval++;
System.out.println("The cosine similarity between you and this person is " + result);
col=0;
i=0;
} else if (row == 29) {
break;
}else{
col++;
}
}
}
public static void similarity(int[] userRating, int[][] ratingList) { //store similarties in an int array and then caculate similarities
int[] userSim = new int[21]; //length 21 to include user similarity
double[] p2Sim = new double[30];
System.out.println("Similarity Checkpoint 2...");
for (int index = 0; index < userRating.length; index++) {
userSim[index] = userRating[index];
}
double result = 0;
double sum = 0;
double product;
double user = 0;
double p2 = 0;
//int both;
for (int i = 0; i < userSim.length; i++) {
if (userSim[i] != -1) {
product = (userSim[i] * userSim[i]);
sum += product;
}
}
result = Math.sqrt(sum);
user = result;
System.out.println("Similarity Checkpoint 3...");
for (int j = 0; j < 30; j++) {
result = 0;
p2 = 0;
sum = 0;
for (int k = 0; k < 20; k++) {
if (ratingList[j][k] != -1) {
product = ratingList[j][k] * ratingList[j][k];
sum += product;
}
if (k == 19) {
result = Math.sqrt(sum);
p2 = result;
p2Sim[j] = p2;
}
}
}
score(p2Sim, user, userRating, ratingList);
//cosine similarity method
/*int row = 0;
int col = 0;
int interval = 1;
for(int l = 0;l<userRating.length;l++){
if(userRating[l]==ratingList[row][col]){
both = userRating[l]*ratingList[row][col];
}
col++;
if(col==20){
row++;
interval++;
}
else if(interval==30){
break;
}
}*/
}
public static int[][] recommendation(String filename) throws FileNotFoundException {
Scanner in = new Scanner(new File(filename));
int[][] ratingList = new int[30][20];
int row = 0;
int col = 0;
while (in.hasNext()) {
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 20; j++) {
String number = in.next();
ratingList[i][j] = Integer.parseInt(number);
col++;
}
if (col == 20) {
col = 0;
}
row++;
if (row == 31) {
break;
}
}
}
return ratingList;
}
public static void main(String[] args) throws FileNotFoundException {
Scanner movies = new Scanner(new File("movies.txt"));
Scanner ratings = new Scanner(new File("ratings.txt"));
Scanner kb = new Scanner(System.in);
int[] userRating = new int[20];
String line;
int counter = 1;
int index = 0;
System.out.println("Please enter your rating for the following movies from 1 to 5. If you have not seen the movie, enter -1: ");
while (movies.hasNext()) {
line = movies.nextLine();
System.out.println("-" + counter + "-");
System.out.print("Enter your rating for " + line + ": ");
int rate = kb.nextInt();
userRating[index] = rate;
index++;
counter++;
}
int[][] ratingList = recommendation("ratings.txt"); //receives recommendation
System.out.println("Similarity Checkpoint 1...");
similarity(userRating, ratingList);
}
}
|
package lotro.gui;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.TableCellRenderer;
import lotro.models.Relationship;
public class RelationshipRenderer extends JLabel implements TableCellRenderer
{
private static final long serialVersionUID = 1;
public RelationshipRenderer()
{
setOpaque (true); // must do this for background to show up
setHorizontalAlignment (SwingConstants.CENTER);
}
public Component getTableCellRendererComponent (final JTable table,
final Object value,
final boolean isSelected,
final boolean hasFocus,
final int row,
final int viewColumn)
{
Relationship relationship = (Relationship) value;
decorate (relationship);
return this;
}
public void decorate (final Relationship relationship)
{
setText (getText (relationship));
setBackground (getColor (relationship));
}
public static String getText (final Relationship relationship)
{
switch (relationship)
{
case JOIN: return "Join";
case AVOID: return "Avoid";
default: return "";
}
}
public static Color getColor (final Relationship relationship)
{
switch (relationship)
{
case NORMAL: return Color.WHITE;
case JOIN: return Color.GREEN;
case AVOID: return Color.PINK;
default: return Color.LIGHT_GRAY;
}
}
}
|
package br.com.liberdad.semiaberto.model;
public class Jornada {
private long jornada;
private long almoco;
public Jornada(long j) {
this.jornada = j;
calcularAlmoco();
}
public long getJornada() {
return jornada;
}
public void setJornada(long j){
this.jornada = j;
calcularAlmoco();
}
public long getAlmoco() {
return almoco;
}
private void calcularAlmoco(){
if (jornada > 6*60*60*1000)
almoco = 30*60*1000; // MUDOU PRA MEIA HORA (30 minutos)
else
almoco = 15*60*1000;
}
}
|
package com.infoworks.lab.components.rest.source;
import com.infoworks.lab.components.crud.components.datasource.GridDataSource;
import com.infoworks.lab.components.db.source.SqlDataSource;
import com.it.soul.lab.sql.entity.Entity;
import com.it.soul.lab.sql.query.SQLSelectQuery;
import com.vaadin.flow.data.provider.Query;
public class RestDataSource<E extends Entity> extends SqlDataSource<E> {
@Override
public GridDataSource addSearchFilter(String filter) {
return super.addSearchFilter(filter);
}
@Override
public SQLSelectQuery getSearchQuery(Query<E, String> query) {
return super.getSearchQuery(query);
}
@Override
public SQLSelectQuery getSelectQuery(Query<E, String> query) {
return super.getSelectQuery(query);
}
}
|
package com.innova.timetable.dao;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import com.innova.timetable.models.Task;
import java.util.List;
import static com.innova.timetable.models.Task.TASK_TABLE;
@Dao
public interface TaskDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insertTask(Task task);
@Insert(onConflict = OnConflictStrategy.REPLACE)
long[] insertTasks(List<Task> tasks);
@Query("DELETE FROM " + TASK_TABLE)
void deleteAll();
@Delete
void deleteTask(Task task);
@Delete
void deleteTasks(List<Task> tasks);
@Query("SELECT * from " + TASK_TABLE + " ORDER BY is_done DESC")
LiveData<List<Task>> getAllTasks();
@Query("SELECT * FROM " + TASK_TABLE + " WHERE id = :id")
LiveData<Task> getTask(long id);
}
|
package f.star.iota.milk.ui.zerochan;
import f.star.iota.milk.base.BaseBean;
class ZerochanBean extends BaseBean {
private String preview;
private String url;
private String info;
private String description;
public ZerochanBean() {
}
public String getPreview() {
return preview;
}
public void setPreview(String preview) {
this.preview = preview;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
package com.example.http.weather;
import java.util.List;
public class ResultBean {
/**
* city : 苏州
* realtime : {"temperature":"4","humidity":"82","info":"阴","wid":"02","direct":"西北风","power":"3级","aqi":"80"}
* future : [{"date":"2019-02-22","temperature":"1/7℃","weather":"小雨转多云","wid":{"day":"07","night":"01"},"direct":"北风转西北风"},{"date":"2019-02-23","temperature":"2/11℃","weather":"多云转阴","wid":{"day":"01","night":"02"},"direct":"北风转东北风"},{"date":"2019-02-24","temperature":"6/12℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"东北风转北风"},{"date":"2019-02-25","temperature":"5/12℃","weather":"小雨转多云","wid":{"day":"07","night":"01"},"direct":"东北风"},{"date":"2019-02-26","temperature":"5/11℃","weather":"多云转小雨","wid":{"day":"01","night":"07"},"direct":"东北风"}]
*/
private String city;
private RealtimeBean realtime;
private List<FutureBean> future;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public RealtimeBean getRealtime() {
return realtime;
}
public void setRealtime(RealtimeBean realtime) {
this.realtime = realtime;
}
public List<FutureBean> getFuture() {
return future;
}
public void setFuture(List<FutureBean> future) {
this.future = future;
}
}
|
package inheritance2;
//Dikkat Class Abstract isaretli
public abstract class Logger {
// This method muss be defined (overrided) in derived Class
public abstract void MussBeDefined();
//This method can not be changed (overrided) in derived Class
public final void CanNotBeChanged () {
System.out.println("Can not be Changed");
}
public void log () {
}
}
|
package com.hackathon.domain.repo;
import com.hackathon.domain.entity.School;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface SchoolRepo extends JpaRepository<School, Long> {
Optional<School> findByCode(String code);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.