text
stringlengths 10
2.72M
|
|---|
/**
* MapStruct mappers for mapping domain objects and Data Transfer Objects.
*/
package org.ycx.gateway.service.mapper;
|
import java.awt.*;
import java.applet.*;
public class staafdiagram extends Applet {
public void init() {
}
public void paint(Graphics g) {
g.drawLine(20, 200, 250, 200);
g.drawLine(20, 200, 20, 50);
g.setColor(Color. red);
g.fillRect(30, 150, 35, 50);
g.drawRect(30, 150, 35, 50);
g.setColor(Color. blue);
g.fillRect(110, 55, 30, 145);
g.drawRect(110, 55, 30, 145);
g.setColor(Color. orange);
g.fillRect(190, 80, 30, 120);
g.drawRect(190, 80, 30, 120);
g.setColor(Color. black);
g.drawString("Valerie", 30, 215);
g.drawString("Jeroen", 105, 215);
g.drawString("Hans", 190, 215);
g.drawString("KG", 15, 40);
g.drawString("20", 5 , 180);
g.drawString("40", 5 , 150);
g.drawString("60", 5 , 120);
g.drawString("80", 5 , 90);
g.drawString("100", -1 , 60);
}
}
|
package com.codigo.smartstore.database.domain.domain;
import java.io.Serializable;
import javax.persistence.Version;
public abstract class Domain<PK extends Serializable>
implements Serializable {
private static final long serialVersionUID = 1L;
@Version
// @Column(name = "VERSION", nullable = false)
private Long version;
public Domain(final PK id, final Long version) {
this.version = version;
}
public Domain() {
}
public abstract PK getId();
public abstract void setId(PK id);
public Long getVersion() {
return this.version;
}
public void setVersion(final Long version) {
this.version = version;
}
@Override
public String toString() {
return "Bean [id=" + this.getId()
+ ", version="
+ this.version
+ "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((this.getId() == null)
? 0
: this.getId()
.hashCode());
result = (prime * result) + ((this.version == null) ? 0 : this.version.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
final Domain<?> other = Domain.class.cast(obj);
if (this.getId() == null) {
if (other.getId() != null)
return false;
} else if (!this.getId()
.equals(other.getId()))
return false;
if (this.version == null) {
if (other.version != null)
return false;
} else if (!this.version.equals(other.version))
return false;
return true;
}
}
|
package com.web.common.util;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.log4j.Logger;
// Referenced classes of package com.audien.common.util:
// LogUtil
public class SortUtil
{
public SortUtil()
{
}
public static void main(String args[])
{
String strArray[] = {
"0", "4", "0", "0", "3", "0", "4", "0", "8", "0",
"0", "3", "0", "0", "0", "2", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "1",
"10", "225", "28", "47", "6", "7", "70"
};
ArrayList list = sortByIndexString(strArray, "ASC");
}
public static Object[] sort(Object array[])
{
Arrays.sort(array);
return array;
}
public static ArrayList sortByIndexInt(Integer array[], String sortType)
{
ArrayList list = new ArrayList();
int temp[] = new int[array.length];
for(int i = 0; i < array.length; i++)
temp[i] = array[i].intValue();
array = (Integer[])sort(array);
if("ASC".equals(sortType))
{
for(int i = 0; i < array.length; i++)
{
int idx = 0;
for(int j = 0; j < array.length; j++)
{
if(temp[j] != array[i].intValue())
continue;
idx = j;
temp[j] = -1;
break;
}
list.add((new StringBuffer(String.valueOf(idx))).toString());
}
} else
{
for(int i = array.length - 1; i > -1; i--)
{
int idx = 0;
for(int j = 0; j < array.length; j++)
{
if(temp[j] != array[i].intValue())
continue;
idx = j;
temp[j] = -1;
break;
}
list.add((new StringBuffer(String.valueOf(idx))).toString());
}
}
return list;
}
public static ArrayList sortByIndexLong(Long array[], String sortType)
{
ArrayList list = new ArrayList();
long temp[] = new long[array.length];
for(int i = 0; i < array.length; i++)
temp[i] = array[i].longValue();
array = (Long[])sort(array);
if("ASC".equals(sortType))
{
for(int i = 0; i < array.length; i++)
{
int idx = 0;
for(int j = 0; j < array.length; j++)
{
if(temp[j] != array[i].longValue())
continue;
idx = j;
temp[j] = -1L;
break;
}
list.add((new StringBuffer(String.valueOf(idx))).toString());
}
} else
{
for(int i = array.length - 1; i > -1; i--)
{
int idx = 0;
for(int j = 0; j < array.length; j++)
{
if(temp[j] != array[i].longValue())
continue;
idx = j;
temp[j] = -1L;
break;
}
list.add((new StringBuffer(String.valueOf(idx))).toString());
}
}
return list;
}
public static ArrayList sortByIndexFloat(Float array[], String sortType)
{
ArrayList list = new ArrayList();
float temp[] = new float[array.length];
for(int i = 0; i < array.length; i++)
temp[i] = array[i].floatValue();
array = (Float[])sort(array);
if("ASC".equals(sortType))
{
for(int i = 0; i < array.length; i++)
{
int idx = 0;
for(int j = 0; j < array.length; j++)
{
if(temp[j] != array[i].floatValue())
continue;
idx = j;
temp[j] = -1F;
break;
}
list.add((new StringBuffer(String.valueOf(idx))).toString());
}
} else
{
for(int i = array.length - 1; i > -1; i--)
{
int idx = 0;
for(int j = 0; j < array.length; j++)
{
if(temp[j] != array[i].floatValue())
continue;
idx = j;
temp[j] = -1F;
break;
}
list.add((new StringBuffer(String.valueOf(idx))).toString());
}
}
return list;
}
public static ArrayList sortByIndexString(String array[], String sortType)
{
ArrayList list = new ArrayList();
String temp[] = new String[array.length];
for(int i = 0; i < array.length; i++)
temp[i] = array[i];
array = (String[])sort(array);
if("ASC".equals(sortType))
{
for(int i = 0; i < array.length; i++)
{
int idx = 0;
for(int j = 0; j < array.length; j++)
{
if(!temp[j].equals(array[i]))
continue;
idx = j;
temp[j] = "";
break;
}
list.add((new StringBuffer(String.valueOf(idx))).toString());
}
} else
{
for(int i = array.length - 1; i > -1; i--)
{
int idx = 0;
for(int j = 0; j < array.length; j++)
{
if(!temp[j].equals(array[i]))
continue;
idx = j;
temp[j] = "";
break;
}
list.add((new StringBuffer(String.valueOf(idx))).toString());
}
}
return list;
}
private static Logger logger = LogUtil.getLogger("consoleLogger");
static
{
LogUtil.instance();
}
}
|
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
public class MuOnline {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] rooms = scanner.nextLine().split("\\|");
int playerHealth = 100;
int playerBitcoins = 0;
boolean winTheGame = true;
String[]inRoomCommands;
int bestRoom = 0;
for (int i = 0; i < rooms.length; i++) {
inRoomCommands = rooms[i].split("\\s+");
String command = inRoomCommands[0];
int valueOfCommand = Integer.parseInt(inRoomCommands[1]);
if(command.equals("potion")){
if (playerHealth + valueOfCommand > 100){
valueOfCommand = 100 - playerHealth;
}
playerHealth += valueOfCommand;
System.out.printf("You healed for %d hp.%n", valueOfCommand);
System.out.printf("Current health: %d hp.%n", playerHealth);
}else if(command.equals("chest")){
playerBitcoins+=valueOfCommand;
System.out.printf("You found %d bitcoins.%n", valueOfCommand);
}else {
playerHealth -=valueOfCommand;
if (playerHealth > 0){
System.out.printf("You slayed %s.%n", command);
}else {
System.out.printf("You died! Killed by %s.%n", command);
System.out.printf("Best room: %d%n", i+1);
winTheGame = false;
break;
}
}
//System.out.println(command +"---"+valueOfCommand);
}
if (winTheGame){
System.out.printf("You've made it!%nBitcoins: %d%nHealth: %d", playerBitcoins, playerHealth);
}
}
}
|
package com.google.zxing.client.android.config;
/**
* Created by wangkp on 2017/9/18.
*/
public class Constants {
public static final int SCREEN_ORIENTATION_LANDSCAPE = 0;
public static final int SCREEN_ORIENTATION_PORTRAITE = 1;
}
|
import javax.sound.sampled.*;
import java.io.*;
public class SayNumbers implements Runnable{
private int number;
public static boolean sayingTheNumber = false;
public void say(int number) {
if (!sayingTheNumber) {
this.number = number;
new Thread(this).start();
}
}
public void run() {
int splitNumber[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 30, 40, 50, 60, 70, 80, 90,
100, 200, 300, 400, 500, 600, 700, 800, 900,
1000
};
int i = 0;
int ones;
int thousands;
int millions;
int milliards;
sayingTheNumber = true;
if (number < 0) {
SayWord(43);
number = 0 - number;
}
ones = number % 1000;
thousands = number / 1000 % 1000;
millions = number / 1000000 % 1000;
milliards = number / 1000000000;
if (number == 0) {
SayWord(0);
} else {
if (milliards > 0){
while (milliards > 0) {
for (i = 0; splitNumber[i] <= milliards; i++) {
}
SayWord(i - 1);
milliards -= splitNumber[i - 1];
}
switch (i - 1) {
case 1: SayWord(41); break;
case 2: SayWord(42); break;
}
}
if (millions > 0) {
while (millions > 0) {
for (i = 0; splitNumber[i] <= millions; i++) {
}
SayWord(i - 1);
millions -= splitNumber[i - 1];
}
switch (i - 1) {
case 1: SayWord(39); break;
default: SayWord(40); break;
}
}
if (thousands > 0) {
while (thousands > 0) {
for (i = 0; splitNumber[i] <= thousands; i++) {
}
SayWord(i - 1);
thousands -= splitNumber[i - 1];
}
switch (i - 1) {
case 1: SayWord(37); break;
default: SayWord(38); break;
}
}
if (ones > 0) {
while (ones > 0) {
for (i = 0; splitNumber[i] <= ones;i++) {
}
SayWord(i - 1);
ones -= splitNumber[i - 1];
}
}
}
sayingTheNumber = false;
}
public void SayWord(int wordID) {
if (wordID < 0) {
wordID = 0;
}
if (wordID > 43) {
wordID = 43;
}
String[] theWord = {
"0", //0
"1", //1
"2", //2
"3", //3
"4", //4
"5", //5
"6", //6
"7", //7
"8", //8
"9", //9
"10", //10
"11", //11
"12", //12
"13", //13
"14", //14
"15", //15
"16", //15
"17", //17
"18", //18
"19", //19
"20", //20
"30", //21
"40", //22
"50", //23
"60", //24
"70", //25
"80", //26
"90", //27
"100", //28
"200", //29
"300", //30
"400", //31
"500", //32
"600", //33
"700", //34
"800", //35
"900", //36
"1000", //37
"1000ds", //38
"1000000", //39
"1000000ns", //40
"1000000000", //41
"1000000000ns", //42
"minus", //43
};
try {
AudioInputStream source = AudioSystem.getAudioInputStream(getClass().getResource("SoundDigits/" + theWord[wordID] + ".wav"));
Clip newClip = (Clip) AudioSystem.getLine(new DataLine.Info(Clip.class, source.getFormat()));
newClip.open(source);
newClip.start();
Thread.sleep(10);
while (newClip.isRunning()) {
Thread.sleep(10);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
package Problem_15624;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
@SuppressWarnings("resource")
int n = new Scanner(System.in).nextInt();
int a = n;
if(n <= 3) n = 3;
long[] arr = new long[n+1];
arr[1] = 1;
for(int i = 2; i<=n; i++) {
arr[i] = (arr[i-1] + arr[i-2]) % 1000000007;
}
System.out.println(arr[a]);
}
}
|
package com.distributie.view;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.distributie.adapters.MasiniAdapter;
import com.distributie.beans.Borderou;
import com.distributie.enums.EnumOperatiiBorderou;
import com.distributie.enums.EnumOperatiiSofer;
import com.distributie.listeners.BorderouriDAOListener;
import com.distributie.listeners.SoferiListener;
import com.distributie.model.BorderouriDAOImpl;
import com.distributie.model.HandleJSONData;
import com.distributie.model.OperatiiSoferi;
import com.distributie.model.UserInfo;
public final class NrMasina extends Activity implements SoferiListener, BorderouriDAOListener {
private OperatiiSoferi opSoferi;
private TextView textNrAuto;
private Button btnSelectAuto;
private ListView listViewMasini;
private List<String> listAuto;
private Button btnContinua;
private String nrAutoBorderou;
private boolean existaBorderou;
private boolean isAltaMasina;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.LRTheme);
setContentView(R.layout.nr_masina);
ActionBar actionBar = getActionBar();
actionBar.setTitle("Nr auto");
actionBar.setDisplayHomeAsUpEnabled(true);
opSoferi = new OperatiiSoferi(this);
opSoferi.setSoferiListener(this);
setupLayout();
getMasinaSofer();
}
private void setupLayout() {
textNrAuto = (TextView) findViewById(R.id.textNrAuto);
btnSelectAuto = (Button) findViewById(R.id.btnSelectAuto);
listViewMasini = (ListView) findViewById(R.id.listViewMasini);
btnContinua = (Button) findViewById(R.id.btnContinua);
setListenerBtnSelectAuto();
setListMasiniListener();
setListenerBtnContinua();
}
private void setListenerBtnSelectAuto() {
btnSelectAuto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
getMasiniFiliala();
}
});
}
private void setListMasiniListener() {
listViewMasini.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String autoSel = (String) parent.getAdapter().getItem(position);
if (!autoSel.equals(UserInfo.getInstance().getNrAuto()))
isAltaMasina = true;
else
isAltaMasina = false;
textNrAuto.setText(autoSel);
listViewMasini.setVisibility(View.INVISIBLE);
}
});
}
private void setListenerBtnContinua() {
btnContinua.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
UserInfo.getInstance().setNrAuto(textNrAuto.getText().toString());
getKmMasinaDeclarati();
}
});
}
private void getBorderouActiv() {
BorderouriDAOImpl bord = BorderouriDAOImpl.getInstance(this);
bord.setBorderouEventListener(NrMasina.this);
bord.getBorderouri(UserInfo.getInstance().getId(), "d", "-1");
}
private void getKmMasinaDeclarati() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("nrMasina", textNrAuto.getText().toString());
opSoferi.getKmMasinaDeclarati(params);
}
private void goToNextScreen(String isKmDeclarati) {
Intent nextScreen = null;
if (!existaBorderou) {
nextScreen = new Intent(getApplicationContext(), InfoNrAuto.class);
String infoStr = "Nu exista borderouri.";
nextScreen.putExtra("infoStr", infoStr);
} else if (!isNrAutoBorderou()) {
nextScreen = new Intent(getApplicationContext(), InfoNrAuto.class);
} else if (Boolean.valueOf(isKmDeclarati)) {
getBorderouMasina();
} else {
nextScreen = new Intent(getApplicationContext(), KmMasina.class);
}
UserInfo.getInstance().setNrAuto(textNrAuto.getText().toString());
startActivity(nextScreen);
finish();
}
private void getBorderouMasina() {
BorderouriDAOImpl bord = BorderouriDAOImpl.getInstance(this);
bord.setBorderouEventListener(NrMasina.this);
bord.getBorderouriMasina(UserInfo.getInstance().getNrAuto(), UserInfo.getInstance().getId());
}
private void verificaBorderou(String strBorderouri) {
HandleJSONData objListBorderouri = new HandleJSONData(this, strBorderouri);
ArrayList<Borderou> listBorderouri = objListBorderouri.decodeJSONBorderouri();
if (!listBorderouri.isEmpty()) {
valideazaSoferBorderou(listBorderouri.get(0));
} else {
showInfoScreen("Nu exista borderouri.");
}
}
private void valideazaSoferBorderou(Borderou borderou) {
if (borderou.getCodSofer().equals(UserInfo.getInstance().getId())) {
Intent nextScreen = new Intent(getApplicationContext(), MainMenu.class);
startActivity(nextScreen);
finish();
} else
showInfoScreen("Borderoul " + borderou.getNumarBorderou()
+ " alocat pe aceasta masina unui alt sofer nu este finalizat. Contactati contabila de distributie pentru finalizarea acestuia!");
}
private void valideazaSoferBorderou(String soferBorderou) {
if (soferBorderou.equals(UserInfo.getInstance().getId())) {
Intent nextScreen = new Intent(getApplicationContext(), MainMenu.class);
startActivity(nextScreen);
finish();
} else
showInfoScreen("Nu exista borderouri.");
}
private void showInfoScreen(String infoMsg) {
Intent nextScreen = new Intent(getApplicationContext(), InfoNrAuto.class);
nextScreen.putExtra("infoStr", infoMsg);
startActivity(nextScreen);
finish();
}
private void getMasiniFiliala() {
if (listAuto == null) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("codFiliala", UserInfo.getInstance().getFiliala());
opSoferi.getMasiniFiliala(params);
} else
listViewMasini.setVisibility(View.VISIBLE);
}
private void getMasinaSofer() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("codSofer", UserInfo.getInstance().getId());
opSoferi.getMasinaSofer(params);
}
private void afisMasinaSofer(String nrAuto) {
if (nrAuto.trim().isEmpty()) {
Intent nextScreen = new Intent(getApplicationContext(), InfoNrAuto.class);
String infoStr = "Nu aveti alocata nicio masina. Contactati departamentul logistica.";
nextScreen.putExtra("infoStr", infoStr);
startActivity(nextScreen);
finish();
} else {
textNrAuto.setText(nrAuto);
UserInfo.getInstance().setNrAuto(nrAuto);
getBorderouActiv();
}
}
private void afisMasiniFiliala(String strAuto) {
String[] arrayAuto = strAuto.split(",");
listAuto = new ArrayList<String>(Arrays.asList(arrayAuto));
MasiniAdapter masiniAdapter = new MasiniAdapter(getApplicationContext(), listAuto);
listViewMasini.setAdapter(masiniAdapter);
listViewMasini.setVisibility(View.VISIBLE);
}
private boolean isNrAutoBorderou() {
if (!isAltaMasina)
return textNrAuto.getText().toString().replace("-", "").replace(" ", "").equals(nrAutoBorderou);
return true;
}
private void setNrAutoBorderou(String strBorderouri) {
HandleJSONData objListBorderouri = new HandleJSONData(this, strBorderouri);
ArrayList<Borderou> listBorderouri = objListBorderouri.decodeJSONBorderouri();
if (!listBorderouri.isEmpty() && listBorderouri.get(0).getNrAuto() != "null") {
nrAutoBorderou = listBorderouri.get(0).getNrAuto();
existaBorderou = true;
} else {
existaBorderou = false;
}
}
@Override
public void operationSoferiComplete(EnumOperatiiSofer numeOperatie, Object result) {
switch (numeOperatie) {
case GET_MASINA:
afisMasinaSofer((String) result);
break;
case GET_MASINI_FILIALA:
afisMasiniFiliala((String) result);
break;
case GET_KM_MASINA_DECLARATI:
goToNextScreen((String) result);
break;
default:
break;
}
}
@Override
public void loadComplete(String result, EnumOperatiiBorderou methodName) {
switch (methodName) {
case GET_BORDEROURI:
setNrAutoBorderou(result);
break;
case GET_BORDEROURI_MASINA:
verificaBorderou(result);
break;
default:
break;
}
}
}
|
/*
@author apodx
*/
import java.io.*;
import java.net.*;
import java.util.*;
class UDPClient {
public static void main(String args[]) throws Exception
{
DatagramSocket clientSocket = new DatagramSocket();
Set<Integer> randomNum =new HashSet<Integer>();
// String ip = args[0];
// int port = Integer.parseInt(args[1]);
// String fileName = args[2];
// double d =Double.parseDouble(args[3]);
String ip = "127.0.0.1";
int port = 9876;
String fileName = "TestFile.html";
double d =0.5;
InetAddress IPAddress = InetAddress.getByName(ip);
byte[] sendData;
byte[] receiveData = new byte[1024];
String sentence = "GET "+fileName+" HTTP/1.0";
ArrayList<byte[]> byteList = new ArrayList<>();
ArrayList<String> rawData = new ArrayList<>();
sendData = sentence.getBytes();
sendMessage(clientSocket,sendData,IPAddress,port);
byte[] data = receiveMessage(clientSocket,receiveData);
String modifiedSentence =
new String(data,0,data.length);
byteList.add(new String(data,138,1024-138-1).getBytes());
rawData.add(modifiedSentence);
clientSocket.setSoTimeout(2000);
ArrayList<Integer> checkList = new ArrayList<>();
for (String str :rawData) {
int checkNum = Integer.parseInt(str.split("checkNum:")[1].substring(0,7));
checkList.add(checkNum);
}
for (String str:rawData
) {
System.out.println(str);
}
// ArrayList<byte[]> damagePackets = Germlin(byteList,d,randomNum);
// for (Integer i:randomNum
// ) {
// System.out.println(i+"");
// }
// for(int i =0;i<byteList.size();i++){
// byte[] damagePacketData= damagePackets.get(i);
// int clientCheck = dataCheck(damagePacketData);
// int serverCheck = checkList.get(i);
//// System.out.print(clientCheck+"\t"+serverCheck+"\t");
//
// if(clientCheck==serverCheck){
// System.out.println("Congratulation!");
// System.out.println("The packet is correct");
// System.out.println("The sequence number of the current package is "+(i+1));
// System.out.println();
// System.out.println("The message content :"+new String(damagePacketData));
// System.out.println("--------------I'm the dividing line--------------------");
// }else {
// System.out.println("Sorry!");
// System.out.println("The packet is error");
// System.out.println("The sequence number of the current package is "+(i+1)+"");
// System.out.println();
// System.out.println("The message content :"+new String(damagePacketData));
//
// System.out.println("--------------I'm the dividing line--------------------");
// }
// }
// String fileName_receive = fileName.split("[.]")[0]+"_receive";
// String fileSuffix_receive=fileName.split("[.]")[1];
// InputStream is;
// OutputStream out = new FileOutputStream(fileName_receive+"."+fileSuffix_receive);
// for (byte[] b: damagePackets) {
// is = new ByteArrayInputStream(b);
// byte[] buff = new byte[1024];
// int len = 0;
// while((len=is.read(buff))!=-1){
// out.write(buff, 0, len);
// }
//
// }
// out.close();
}
public static void sendMessage(DatagramSocket clientSocket,byte[] sendData,InetAddress IPAddress,int port){
try {
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
clientSocket.send(sendPacket);
}catch (Exception e){
}
}
public static byte[] receiveMessage(DatagramSocket clientSocket,byte[] receiveData) throws IOException {
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
byte[] data = new byte[1024];
while (receivePacket.getLength()!=0){
clientSocket.receive(receivePacket);
data = receivePacket.getData();
return data;
}
return data;
}
public static int dataCheck(byte[] bytes){
int i =0;
for (int j = 0; j < bytes.length; j++) {
i+=bytes[j];
}
return i;
}
/**
* @autor apodx
* @param bytesList packet
* @param d Probability of packet destruction
*/
public static ArrayList<byte[]> Germlin(ArrayList<byte[]> bytesList,double d,Set<Integer> randomNum){
int len = bytesList.size();
// the number of all damage packet
int damagePacket = (int)(d*len);
// damage One Byte Num
int damageOneByteNum=(int)(d*len*0.5);
// damage TwoByte Num
int damageTwoByteNum=(int)(d*len*0.3);
// damage Three Byte Num
int damageThreeByteNum=(int)(d*len*0.2);
//4 1 3 9
while (randomNum.size()<damagePacket){
Random random = new Random();
int i = random.nextInt(len);
randomNum.add(i);
}
int i = 1 ;
Iterator<Integer> it = randomNum.iterator();
while (it.hasNext()){
byte[] packetContent = bytesList.get(it.next());
int packetLength= packetContent.length;
int random = randomInt(138,packetLength);
if(i<=damageOneByteNum){
packetContent[random] = 1;
}
if(i>damageOneByteNum&&i<=(damageOneByteNum+damageTwoByteNum)){
if(random+1>packetLength-1){
random = random-1;
}
packetContent[random] = 2;
packetContent[random+1] = 2;
}
if(i>(damageOneByteNum+damageTwoByteNum)&&i<=(damageOneByteNum+damageTwoByteNum+damageThreeByteNum)){
if(random+2>packetLength-1){
random = random-2;
}
packetContent[random] = 3;
packetContent[random+1] = 3;
packetContent[random+2] = 3;
}
i++;
}
return bytesList;
}
// Generates a random number in the specified range
private static int randomInt(int min, int max){
return new Random().nextInt(max)%(max-min+1) + min;
}
}
|
/**
*
*/
package algorithm.sorting;
import java.util.Arrays;
/**
* @author absin The selection sort algorithm sorts an array by repeatedly
* finding the minimum element (considering ascending order) from
* unsorted part and putting it at the beginning. The algorithm
* maintains two subarrays in a given array.
*
* 1) The subarray which is already sorted. 2) Remaining subarray which
* is unsorted.
*
* In every iteration of selection sort, the minimum element
* (considering ascending order) from the unsorted subarray is picked
* and moved to the sorted subarray.
*
* Time Complexity: O(n2) as there are two nested loops.
*
* Auxiliary Space: O(1) The good thing about selection sort is it never
* makes more than O(n) swaps and can be useful when memory write is a
* costly operation.
*
* Important thing to note down here is that there is a swapping action
* involved between the end of the unsorted array and the minimum
* element found. Can you think why?
*
*/
public class SelectionSort {
/**
* @param args
*/
public static void main(String[] args) {
int arr[] = { 64, 25, 12, 22, 11 };
// Iterative(arr);
recursive(arr, 0);
}
public static void recursive(int[] arr, int sortedIndex) {
int tempMinIndex = sortedIndex;
for (int i = sortedIndex; i < arr.length; i++) {
if (arr[tempMinIndex] > arr[i])
tempMinIndex = i;
}
if (sortedIndex < tempMinIndex) {
int temp = arr[tempMinIndex];
arr[tempMinIndex] = arr[sortedIndex];
arr[sortedIndex] = temp;
}
if (sortedIndex < arr.length)
recursive(arr, sortedIndex + 1);
else {
System.out.println(Arrays.toString(arr));
return;
}
}
public static void Iterative(int[] arr) {
int sortedIndex = 0;
while (sortedIndex < arr.length) {
int tempMinIndex = sortedIndex;
for (int i = sortedIndex; i < arr.length; i++) {
if (arr[tempMinIndex] < arr[i])
tempMinIndex = i;
}
if (sortedIndex < tempMinIndex) {
int temp = arr[tempMinIndex];
arr[tempMinIndex] = arr[sortedIndex];
arr[sortedIndex] = temp;
}
sortedIndex++;
}
System.out.println(Arrays.toString(arr));
}
}
|
package ar.edu.unlam.pb1.tp03.dominio;
/* 6. Implementa la clase Cuenta, sabiendo que:
a. Cuando se crea una cuenta, su saldo es cero.
b. Solo es posible extraer un importe menor o igual al saldo que se tenga en la cuenta. */
public class Cuenta {
/* Atributos propios de la clase que reflejan el estado de la clase Punto */
private String titular;
private double saldo;
private double cantidadAextraer = 0;
/* Constructor: Le asignamos valores a los atributos de ese objeto y los inicializamos */
public Cuenta(String titular) {
this.titular = titular;
this.saldo = 0.0;
} // end Constructor1
/* Constructor: Le asignamos valores a los atributos de ese objeto y los inicializamos */
public Cuenta(String titular, double saldoInicial) {
this.titular = titular;
this.saldo = saldoInicial;
} // end Constructor2
/* Métodos: van a describir el comportamiento de la clase de tipo Cuenta */
public String getTitular() { // tiene que devolver el contenido del atributo
return this.titular;
} // end getTitular
public void setTitular(String titular) { // void-> no va a devolver nada, va a actualizar el valor del atributo
this.titular = titular;
} // end setTitular
public double getSaldo() { // tiene que devolver el contenido del atributo
return this.saldo;
} // end getSaldo
public String toString() { // Método que vamos a utilizar para hacer referencia al atributo del objeto, el estado de éste
String estadoTitular= null ;
estadoTitular = "Titular de la cuenta: " + this.titular;
return estadoTitular;
} // end toString
public void depositar(double cantidad) { // void-> no va a devolver nada, va a actualizar el valor del atributo
this.saldo =+ cantidad;
} // end depositar
public void retirar(double cantidad) { // void-> no va a devolver nada, va a actualizar el valor del atributo
this.cantidadAextraer = cantidad;
} // end retirar
/* Estado de la aprobación de la extracción */
public boolean verificarExtraccion() {
boolean estadoExtraccion;
if (this.cantidadAextraer <= this.saldo) {
estadoExtraccion = true;
} else {
estadoExtraccion = false;
} return estadoExtraccion;
} // end verificarExtraccion
/* Movimiento de la extracción */
public double ExtraerDinero() {
double saldoActualizado =0;
if (verificarExtraccion() == true) {
this.saldo = getSaldo() - cantidadAextraer;
}
return this.saldo;
} // end ExtraerDinero
} // end Cuenta class
|
package com.pago.core.quotes.api.util;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
public class DozerModule extends AbstractModule {
@Provides
private DozerMapperService getDozerBeanMapper(DozerConfiguration dozerConfiguration) {
return new DozerMapperService(dozerConfiguration);
}
}
|
package com.gaoshin.coupon.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.gaoshin.coupon.bean.CategoryList;
import com.gaoshin.coupon.dao.CategoryDao;
import com.gaoshin.coupon.entity.Category;
@Repository
public class CategoryDaoImpl extends GenericDaoImpl implements CategoryDao {
@Override
public CategoryList listTopCategories() {
CategoryList cl = new CategoryList();
String sql = "select * from Category where parentId is null";
List<Category> list = queryBySql(Category.class, null, sql);
cl.setItems(list);
return cl;
}
}
|
/** https://www.spoj.com/problems/MICEMAZE/ #shortest-path #bfs #dijkstra reverse graph */
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Scanner;
class MiceMaze {
public static void Dijktra(ArrayList<ArrayList<Node>> graph, int[] timeArr, int startVertex) {
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.add(new Node(startVertex, 0));
while (!pq.isEmpty()) {
Node node = pq.poll();
int id = node.id;
int w = node.time;
for (int i = 0; i < graph.get(id).size(); i++) {
Node neighbor = graph.get(id).get(i);
int newTime = w + neighbor.time;
if (newTime < timeArr[neighbor.id]) {
timeArr[neighbor.id] = newTime;
pq.add(new Node(neighbor.id, timeArr[neighbor.id]));
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int exitVertex = sc.nextInt();
int limitTime = sc.nextInt();
int m = sc.nextInt();
ArrayList<ArrayList<Node>> graph = new ArrayList<>(n + 1);
for (int i = 0; i < n + 1; i++) {
graph.add(new ArrayList<Node>());
}
for (int i = 0; i < m; i++) {
int sr = sc.nextInt();
int ds = sc.nextInt();
int time = sc.nextInt();
graph.get(ds).add(new Node(sr, time));
}
int[] timeArr = new int[n + 1];
for (int i = 0; i < timeArr.length; i++) {
timeArr[i] = Integer.MAX_VALUE;
}
Dijktra(graph, timeArr, exitVertex);
// result
int sum = 1;
for (int i : timeArr) {
if (i <= limitTime) sum += 1;
}
System.out.println(sum);
}
}
class Node implements Comparable<Node> {
Integer id;
Integer time;
Node(Integer id, Integer time) {
this.id = id;
this.time = time;
}
@Override
public int compareTo(Node other) {
return Integer.compare(this.time, other.time);
}
}
|
package egovframework.adm.cmg.prt.controller;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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 egovframework.adm.cmg.prt.service.PracticeStudyService;
import egovframework.com.cmm.EgovMessageSource;
@Controller
public class PracticeStudyController {
/** log */
protected static final Log log = LogFactory.getLog(PracticeStudyController.class);
/** EgovMessageSource */
@Resource(name = "egovMessageSource")
EgovMessageSource egovMessageSource;
/** practiceStudyService */
@Resource(name = "practiceStudyService")
PracticeStudyService practiceStudyService;
@RequestMapping(value="/adm/cmg/prt/practiceStudyList.do")
public String listPage(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
HttpSession session = request.getSession();
String p_gadmin = session.getAttribute("gadmin") !=null ? (String)session.getAttribute("gadmin") : "" ;
//System.out.println("p_gadmin -----> "+p_gadmin);
List list = null;
if(p_gadmin.equals("Q1")){
list = practiceStudyService.subjmanPracticeStudyList(commandMap);
}else{
commandMap.put("p_gadmin", p_gadmin);
commandMap.put("userid", (String)session.getAttribute("userid"));
list = practiceStudyService.practiceStudyList(commandMap);
}
model.addAttribute("list", list);
model.addAllAttributes(commandMap);
return "adm/cmg/prt/practiceStudyList";
}
@RequestMapping(value="/adm/cmg/prt/practiceStudySubList.do")
public String subListPage(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
List list = practiceStudyService.practiceStudySubList(commandMap);
model.addAttribute("list", list);
model.addAllAttributes(commandMap);
return "adm/cmg/prt/practiceStudySubList";
}
}
|
package com.edu.realestate.model;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
@Entity
@Table(name="user_data")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="user_type", discriminatorType=DiscriminatorType.STRING)
public abstract class User {
@Id
private String username;
private String password;
// @OneToMany (mappedBy="user")
// private List<Favorite> favorites;
public User() {}
public User(String username, String password) {
this.username = username;
this.password = password;
// this.favorites = new ArrayList<>();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
// public List<Favorite> getFavorites() {
// return favorites;
// }
//
// public void setFavorites(List<Favorite> favorites) {
// this.favorites = favorites;
// }
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
// return "User [username=" + username + ", password=" + password + ", favorites=" + favorites + "]";
}
}
|
package Embeddable1;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import java.util.HashMap;
import java.util.Map;
import static org.hibernate.cfg.AvailableSettings.*;
public class HibernateUtil {
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
// Create registry builder
final StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
final Map<String, String> settings = new HashMap<>();
settings.put(URL, "jdbc:mysql://localhost:3306/demo");
settings.put(USER, "root");
settings.put(PASS, "");
settings.put(DIALECT, "org.hibernate.dialect.MySQL55Dialect");
settings.put(HBM2DDL_AUTO, "create-drop");
settings.put(SHOW_SQL, "true");
settings.put(FORMAT_SQL, "true");
settings.put(STORAGE_ENGINE, "innodb");
// settings.put(PHYSICAL_NAMING_STRATEGY, "io.github.atuladhar.aman.SnakeCaseNamingStrategy");
// Apply settings
registryBuilder.applySettings(settings);
// Create registry
registry = registryBuilder.build();
// Create MetadataSources
final MetadataSources sources = new MetadataSources(registry);
sources.addAnnotatedClass(Student.class);
// Create Metadata
final Metadata metadata = sources.getMetadataBuilder()
.build();
// Create SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
return sessionFactory;
}
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
|
package com.example.drinkhost;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class DrinkFragment extends Fragment {
private LinearLayout screen;
private Activity parent;
private static ArrayList<Drink> drinks = new ArrayList<Drink>();
private int[] drinkIds = {0, 1, 2};
public DrinkFragment() {}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_drink, container, false);
setHasOptionsMenu(true);
parent = this.getActivity();
screen = (LinearLayout) rootView.findViewById(R.id.screen);
//drinks = new ArrayList<Drink>();
for(Drink drink: getDrinks()) {
screen.addView(new DrinkLayout(parent, drink.getName(), drink.getDrinkAmts(), drinkIds));
}
Button addDrink = (Button) rootView.findViewById(R.id.addDrink);
addDrink.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
createDrinkMenuItem();
}
});
return rootView;
}
public ArrayList<Drink> getDrinkList() {
return getDrinks();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.drinkCreate:
// Do Fragment menu item stuff here
createDrinkMenuItem();
return true;
default:
break;
}
return false;
}
private void createDrinkMenuItem() {
// TODO Auto-generated method stub
final EditText nameEdit = new EditText(parent);
final TextView enterName = new TextView(parent);
enterName.setText("Drink Name:");
//Set input style to capitalize individual words (how names are usually written)
nameEdit.setRawInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
final LinearLayout finalLayout = new LinearLayout(parent);
finalLayout.setOrientation(LinearLayout.VERTICAL);
final ScrollView scrollview = new ScrollView(parent);
finalLayout.addView(enterName);
finalLayout.addView(nameEdit);
List<String> SpinnerArray = new ArrayList<String>();
for(int id: drinkIds) {
SpinnerArray.add(getDrinkName(id));
}
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(parent, android.R.layout.simple_spinner_item, SpinnerArray);
// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// ArrayList<Spinner> spinners = new ArrayList<Spinner>();
final ArrayList<NumberPicker> pickers = new ArrayList<NumberPicker>();
for(int i = 0; i < drinkIds.length; i++) {
LinearLayout layout = new LinearLayout(parent);
TextView parts = new TextView(parent);
TextView drinkName = new TextView(parent);
drinkName.setText(getDrinkName(i));
drinkName.setTextSize(25);
parts.setText(" parts ");
layout.setOrientation(LinearLayout.HORIZONTAL);
//spinners.add(new Spinner(parent));
pickers.add(new NumberPicker(parent));
pickers.get(i).setOrientation(NumberPicker.HORIZONTAL);
//spinners.get(i).setAdapter(adapter);
layout.addView(pickers.get(i));
layout.addView(parts);
layout.addView(drinkName);
//layout.addView(spinners.get(i));
finalLayout.addView(layout);
}
final Context context = parent.getApplicationContext();
scrollview.addView(finalLayout);
//Pops up a place to input player names, then creates and adds PlayerLayout
new AlertDialog.Builder(parent)
.setTitle("Create Drink")
.setView(scrollview)
.setNeutralButton("Create", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int[] amounts = new int[drinkIds.length];
for (int i = 0; i < amounts.length; i++) {
amounts[i] = pickers.get(i).getValue();
}
Drink drink = new Drink(nameEdit.getText().toString(), amounts, drinkIds);
if (drink.getName() != "") {
getDrinks().add(drink);
screen.addView(new DrinkLayout(context, nameEdit.getText().toString(), amounts, drinkIds));
}
}
}).show();
}
private String getDrinkName(int i) {
// TODO Auto-generated method stub
String[] names = {"Coke", "Pepsi", "Fanta", "", "", "", ""};
return names[i];
}
public static ArrayList<Drink> getDrinks() {
return drinks;
}
public static void setDrinks(ArrayList<Drink> drinks) {
DrinkFragment.drinks = drinks;
}
class RecipeLayout extends LinearLayout {
private TextView drinkName;
private TextView recipe;
public RecipeLayout(Context context, TextView drinkName, TextView recipe) {
super(context);
this.drinkName = drinkName;
this.recipe = recipe;
this.initialize(context);
// TODO Auto-generated constructor stub
}
public void initialize(Context context) {
this.setOrientation(LinearLayout.VERTICAL);
this.addView(drinkName);
this.addView(recipe);
}
}
class DrinkLayout extends LinearLayout {
private String drink;
private int[] drinkIds;
private int[] drinkAmts;
/*
* Drink Layout
* Preconditions: drinkIds.length = drinkAmts.length
*/
public DrinkLayout(Context context, String drink, int[] drinkAmts, int[] drinkIds) {
super(context);
this.drink = drink;
this.drinkIds = drinkIds;
this.drinkAmts = drinkAmts;
this.initialize(getActivity());
// TODO Auto-generated constructor stub
}
public void initialize(Context context) {
this.setOrientation(LinearLayout.HORIZONTAL);
final TextView drinkView = new TextView(context);
drinkView.setTextSize(25);
drinkView.setText(drink);
final Button editButton = new Button(context);
editButton.setText("Edit");
editButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
final TextView drinkRecipe = new TextView(context);
String recipe = "";
for(int i = 0; i < drinkIds.length; i++) {
if(drinkAmts[i] != 0) {
recipe += drinkAmts[i] + " parts " + getDrinkName(drinkIds[i]);
if(i < drinkIds.length - 1) {
recipe += "\n";
}
}
}
drinkRecipe.setText(recipe);
RecipeLayout recipeLayout = new RecipeLayout(context, drinkView, drinkRecipe);
this.addView(recipeLayout);
this.addView(editButton);
}
private String getDrinkName(int i) {
// TODO Auto-generated method stub
String[] names = {"Coke", "Pepsi", "Fanta", "", "", "", ""};
return names[i];
}
}
}
|
package ProjectCustomerSeller;
class product{
//Product ID
// quantity
// price
// Name
private String productID;
private int quantity;
private int price;
private String name;
//changleable
public product(String productID){
this.productID = productID;
}
//parameterized constructor 1
public product( String productID, String name){
this.productID = productID;
this.name = name;
}
//parameterized constructor 2
public product( String productID, String name, int price){
this.productID = productID;
this.name = name;
setPrice(price);
}
//parameterized constructor 3
public product( String productID, String name, int price, int quantity){
this.productID = productID;
this.name = name;
setPrice(price);
setQuantity(quantity);
}
void display( ){
System.out.println("");
System.out.println("Product ID: " + productID);
System.out.println("Product Name: "+name);
System.out.println("Product Price:"+price);
System.out.println("Quantity: " + quantity);
System.out.println("");
}
//changleable
public int getPrice(){
return price;
}
public void setPrice(int price){
this.price = price;
}
public int getquantity(){
return quantity;
}
public void setQuantity(int quantity){
this.quantity = quantity;
}
//Non-Changeable
public String getName(){
return name;
}
public String getProduct(){
return productID;
}
}
class customer{
// cus Name
// cus ID
// cus address
// cus phone
private String customerID; //Not Changeable
private String customerAddress; //changleable
private String customerPhone; //changleable
private String customerName; // not changeable
public customer(String customerID, String customerAddress, String customerPhone,String customerName){
this.customerID = customerID;
setCustomerAddress(customerAddress);
setCustomerPhone(customerPhone);
this.customerName = customerName;
}
public customer(String customerID, String customerName, String customerPhone){
this.customerID = customerID;
setCustomerAddress(customerAddress);
setCustomerPhone(customerPhone);
}
public customer(String customerID, String customerName){
this.customerID = customerID;
this.customerName = customerName;
}
//non-changeable
public String getCustomerID(){
return customerID;
}
public String getCustomerName(){
return customerName;
}
//Changeable
public String getCustomerPhone(){
return customerPhone;
}
public String getCustomerAddress(){
return customerAddress;
}
public void setCustomerPhone(String customerPhone){
this.customerPhone = customerPhone;
}
public void setCustomerAddress(String customerAddress){
this.customerAddress = customerAddress;
}
void displayCust(){
System.out.println("");
System.out.println("Customer ID: " + customerID);
System.out.println("Customer address: " + customerAddress);
System.out.println("Customer phone: " + customerPhone);
System.out.println("Customer name: " + customerName);
}
}
public class projectCust {
public static void main(String[] args) {
product p1=new product("66AUZ76","Heaphone",800,3);
customer c1=new customer("666-54-34","Halishahar,K block","0183467990","Shafayet karim");
product p2= new product("666AUZ77","KZ-ProHeadgear",1900,1);
customer c2=new customer("666-54-38","agrabad","01839261","Meharaj");
p1.display();
c1.displayCust();
p2.display();
c2.displayCust();
}
}
|
package com.jgermaine.fyp.rest.util;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.jgermaine.fyp.rest.config.WebApplication;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = WebApplication.class)
public class SpringUtilTest {
@Test
public void testIsNullOrEmptySuccess() {
assertTrue(StringUtil.isNotNullOrEmpty("value"));
}
@Test
public void testIsNullOrEmptyFailureNull() {
assertFalse(StringUtil.isNotNullOrEmpty(null));
}
@Test
public void testIsNullOrEmptyFailureEmpty() {
assertFalse(StringUtil.isNotNullOrEmpty(""));
}
}
|
package com.simbiosyscorp.tutorials.complexviews;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class DatePicker extends Activity {
DatePickerDialog datePickerDialog;
Calendar defaultDate, datePicked;
TextView mainTextView, textLabel;
SimpleDateFormat dateFormatter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_picker);
mainTextView = (TextView) findViewById(R.id.textView);
textLabel = (TextView) findViewById(R.id.textView2);
//SimpleDateFormat formats the date object to given format
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
defaultDate = Calendar.getInstance();
datePicked = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//Getting the new Date selected
datePicked.set(year, monthOfYear, dayOfMonth);
//Making labels visible
textLabel.setVisibility(View.VISIBLE);
mainTextView.setVisibility(View.VISIBLE);
//Setting the new Date in the TextView
mainTextView.setText(dateFormatter.format(datePicked.getTime()));
}
}, defaultDate.YEAR, defaultDate.MONTH, defaultDate.DAY_OF_MONTH);
}
public void getDate(View view) {
datePickerDialog.show();
}
}
|
package com.tuyu.sharding;
import com.tuyu.sharding.entity.ActionLog;
import com.tuyu.sharding.mappper.ActionLogMapper;
import com.tuyu.sharding.repository.ActionLogRepository;
import com.tuyu.sharding.service.ActionLogService;
import com.tuyu.sharding.sql.SqlMapper;
import com.tuyu.sharding.util.MyMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
@SpringBootApplication
//@EnableScheduling
//@MapperScan(basePackages = "com.tuyu.sharding.mapper",markerInterface = MyMapper.class)
public class SpringBootShardingJdbcApplication implements CommandLineRunner{
@Autowired
ActionLogService actionLogService;
@Autowired
SqlMapper sqlMapper;
@Autowired
ActionLogRepository actionLogRepository;
@Autowired
@Qualifier("acDataSource")
DataSource dataSource;
// @Autowired
// ActionLogMapper actionLogMapper;
public static void main(String[] args) {
SpringApplication.run(SpringBootShardingJdbcApplication.class, args);
}
@Override
public void run(String... strings) throws Exception {
//查询逻辑表数据——测试通过
// actionLogService.selectAll();
//根据时间和租户Id查找所有行为日志
// List<ActionLog> list = sqlMapper.selectAll("20161226","20161227","30");
// for (ActionLog actionLog : list){
// System.out.println(actionLog);
// }
//根据时间、租户Id进行serv排行,需要自己合并,排序
// List<Map<String,Object>> sorvSortlist = sqlMapper.servSortEnhance("20161226","20161227","30");
// Map<String,Integer> servSortMap = formateServOrApp(sorvSortlist,"serv");
// List<Map.Entry<String,Integer>> sortList = new ArrayList<Map.Entry<String,Integer>>(servSortMap.entrySet());
// Collections.sort(sortList, new Comparator<Map.Entry<String, Integer>>() {
// @Override
// public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
// return o2.getValue().compareTo(o1.getValue());
// }
// });
// int i = 0 ;
// Map<String,Object> returnMap = new LinkedHashMap<String ,Object>();
// for (Map.Entry<String,Integer> entry : sortList){
// if (i<5){
// returnMap.put(entry.getKey(),entry.getValue());
// i++;
// }
// }
// System.out.println(returnMap);
//根据时间、租户Id对于流量的serv进行排行
// List<Map<String,Object>> fluxServSortList = sqlMapper.fluxServSort("20161226","20161227","30");
// for(Map<String,Object> map : fluxServSortList){
// System.out.println(map);
// }
//用户排行
// List<Map<String,Object>> userNameSortList = sqlMapper.userNameSort("20161226","20161227","30");
// System.out.println(formatUserNameSort(userNameSortList, 9));
//向逻辑表插入数据——测试成功
ActionLog actionLog = new ActionLog();
actionLog.setId(44444l);
actionLog.setDate("20161226");
actionLog.setName("17");
actionLogRepository.insertWithId(actionLog);
//查询ac网关源数据——测试成功
// String sql = "select * from 20161226_action limit 2";
// JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
// List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
// for (Map<String,Object> map : list){
// System.out.println("user=" + map.get("user").toString());
// System.out.println("record_id=" + map.get("record_id").toString());
// }
//定时任务——测试成功
//MyTask是定时任务
}
public Map<String,Integer> formateServOrApp(List<Map<String,Object>> originList,String servOrApp){
if (originList == null || originList.size() == 0)
return null;
Map<String,Integer> resultMap = new HashMap<String,Integer>();
Map<String,Object> originMap = new HashMap<String,Object>();
for (Map<String,Object> map : originList){
String name = map.get(servOrApp).toString();
String user = map.get("name").toString();
if (originMap.containsKey(name + "_" + user)){
}else {
originMap.put(name + "_" + user,map.get("name"));
if (resultMap.containsKey(name)){
resultMap.put(name,resultMap.get(name) + 1);
}else {
resultMap.put(name,1);
}
}
}
return resultMap;
}
public static Map<String,Object> formatUserNameSort(List<Map<String,Object>> originList,int topx){
if (originList == null || originList.size() == 0)
return null;
Map<String,Integer> resultMap = new HashMap<String,Integer>();
for (Map<String,Object> map : originList){
String name = map.get("name").toString();
int num = Integer.parseInt(map.get("num").toString());
if (resultMap.containsKey(name)){
resultMap.put(name,resultMap.get(name) + num);
}else {
resultMap.put(name,num);
}
}
List<Map.Entry<String,Integer>> resultList = new ArrayList<Map.Entry<String,Integer>>(resultMap.entrySet());
Collections.sort(resultList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
int returnValue = o2.getValue().compareTo(o1.getValue());
//当map的value相等时就比较key,以key的升序排列
if (returnValue == 0){
return o1.getKey().compareTo(o2.getKey());
}else {
return returnValue;
}
}
});
Map<String,Object> map = new LinkedHashMap<String,Object>();
for (int i = 0 ; i < topx ; i++){
map.put(resultList.get(i).getKey(),resultList.get(i).getValue());
}
return map;
}
}
|
package edu.neu.ccs.cs5010;
import java.util.Map;
public interface IQueue<E> {
void enqueue(Map.Entry mapEntry);
E dequeue();
boolean isEmpty();
}
|
package com.xgy.elasticsearchjava.service;
import com.xgy.elasticsearchjava.entity.Person;
import com.xgy.elasticsearchjava.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Random;
@Component
public class OperatorImpl {
@Autowired
private PersonRest personRest;
@Autowired
private Tools tools;
public void addPerson(Person person){
person.setId(new Random().nextLong());
person.setUser(tools.randomName());
person.setAge(new Random().nextInt(150));
person.setDesc(tools.getChinese());
personRest.save(person);
}
}
|
package com.gaoshin.points.server.shard;
import java.io.Serializable;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.shards.ShardId;
import org.hibernate.shards.id.ShardEncodingIdentifierGenerator;
public abstract class PointsShardIdEncodedGenerator<T> implements ShardEncodingIdentifierGenerator {
private UuidGenerator uuidGenerator = new UuidGenerator();
@Override
public ShardId extractShardId(Serializable id) {
return uuidGenerator.extractShardId(id);
}
@Override
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
return generateId(session, (T)object);
}
public abstract Serializable generateId(SessionImplementor session, T object) throws HibernateException;
}
|
package twice.pbdtest.UselessGPS;
import android.app.ActionBar;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import twice.pbdtest.R;
public class LocationViewer extends AppCompatActivity {
private LocationManager mLocationManager;
private LocationFinder mLocationFinder;
private TextView mTextMessage;
private void initLocationFinder() {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationFinder = new LocationFinder();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_viewer);
mTextMessage = (TextView) findViewById(R.id.message);
initLocationFinder();
mLocationFinder.getLocation(this, mLocationManager, new LocationFinder.OnLocationFoundListener() {
@Override
public void onLocationFound(Location location) {
handleLocationChange(location);
}
});
}
private void handleLocationChange(Location location) {
String latitude = Double.toString(location.getLatitude());
String longitude = Double.toString(location.getLongitude());
mTextMessage.setText("You are at lat=" + latitude + ", lon=" + longitude);
}
}
|
package com.ilecreurer.drools.samples.sample2.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ilecreurer.drools.samples.sample2.conf.AreaProperties;
import com.ilecreurer.drools.samples.sample2.event.PositionEvent;
import com.ilecreurer.drools.samples.sample2.service.CollisionService;
import com.ilecreurer.drools.samples.sample2.service.CollisionServiceException;
import com.ilecreurer.drools.samples.sample2.util.Constants;
/**
* TransactionController class.
* @author ilecreurer.
*/
@RestController
@RequestMapping("/events")
public class PositionEventController {
/**
* Logger.
*/
private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(PositionEventController.class);
@Autowired
private AreaProperties areaProperties;
/**
* Collision service.
*/
@Autowired
private CollisionService collisionService;
@PostMapping(value = "/insert",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public final ResponseEntity<ResponseMessage> insertPositionEvents(
@RequestBody final MultiplePositionEventsPayload payload,
final HttpServletResponse response) {
LOGGER.debug("Entering insertPositionEvents...");
LOGGER.debug("numberItems: {}", payload.getNumberItems());
if (payload.getPositionEvents() == null) {
LOGGER.warn("Missing positionEvents attribute");
return new ResponseEntity<>(new ResponseMessage("Missing positionEvents attribute",
ErrorCode.MISSING_POSITION_EVENTS_ATTR.getCode()),
HttpStatus.BAD_REQUEST);
}
if (payload.getNumberItems() == null) {
return new ResponseEntity<>(new ResponseMessage("Missing numberItems attribute",
ErrorCode.MISSING_NUMBER_ITEMS_ATTR.getCode()),
HttpStatus.BAD_REQUEST);
}
if (payload.getNumberItems().intValue() != payload.getPositionEvents().size()) {
return new ResponseEntity<>(new ResponseMessage("Number of items mismatch",
ErrorCode.NUMBER_ITEMS_MISMATCH.getCode()),
HttpStatus.BAD_REQUEST);
}
if (payload.getNumberItems().intValue() == 0) {
return new ResponseEntity<>(new ResponseMessage("0 items",
ErrorCode.EMPTY_ITEMS_ATTR.getCode()),
HttpStatus.BAD_REQUEST);
}
if (payload.getPositionEvents() != null && payload.getPositionEvents().size() > 0) {
LOGGER.debug("timestamp: {}", payload.getPositionEvents().get(0).getTimestamp());
}
try {
collisionService.insertPositionEvents(payload.getPositionEvents());
} catch (CollisionServiceException e) {
return new ResponseEntity<>(new ResponseMessage("Failed: " + e.getMessage(),
ErrorCode.SERVICE_ERROR.getCode()),
HttpStatus.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException e) {
return new ResponseEntity<>(new ResponseMessage("Invalid payload: " + e.getMessage(),
ErrorCode.SERVICE_ERROR.getCode()),
HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new ResponseMessage("Success", 0),
HttpStatus.ACCEPTED);
}
@PostMapping("/insert/csv")
public final ResponseEntity<ResponseMessage> insertPositionEventsCSV(final
@RequestParam("file") MultipartFile file) {
LOGGER.debug("Entering insertPositionEventsCSV...");
if (file == null) {
return new ResponseEntity<>(new ResponseMessage("Invalid payload: file is null",
ErrorCode.SERVICE_ERROR.getCode()),
HttpStatus.BAD_REQUEST);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
try (BufferedReader fileReader = new BufferedReader(
new InputStreamReader(file.getInputStream(), "UTF-8"))) {
long t0 = System.currentTimeMillis();
long t1 = t0;
long delta = 0;
int registers = 0;
long t0Local = t0;
long t1Local = t0;
long deltaLocal = 0;
int registersLocal = 0;
int registersInserted = 0;
int registersTotal = 0;
String[] ar;
String line;
List<PositionEvent> positionEvents = new ArrayList<PositionEvent>();
while ((line = fileReader.readLine()) != null) {
ar = line.split(",");
// CHECKSTYLE:OFF - Reason: Allow basic array index
if (ar.length != 6) {
return new ResponseEntity<>(new ResponseMessage("Missing positionEvents attribute",
ErrorCode.MISSING_POSITION_EVENTS_ATTR.getCode()),
HttpStatus.BAD_REQUEST);
}
PositionEvent pe = new PositionEvent(
ar[1], ar[2], ar[3], sdf.parse(ar[0]),
Double.parseDouble(ar[4]), Double.parseDouble(ar[5])
);
// CHECKSTYLE:ON
positionEvents.add(pe);
registersTotal++;
if (positionEvents.size() >= Constants.MAX_POSITION_EVENTS_SIZE) {
registersInserted = collisionService.insertPositionEvents(positionEvents);
positionEvents.clear();
registers = registers + registersInserted;
registersLocal = registersLocal + registersInserted;
t1 = System.currentTimeMillis();
delta = t1 - t0;
t1Local = t1;
deltaLocal = t1Local - t0Local;
LOGGER.info("Added {} regs in {} ms, avg: {} regs/s, total regs: {}, global average: {}",
registersLocal,
deltaLocal,
((float) registersLocal / (float) deltaLocal) * Constants.MILLIS_IN_SECOND,
registers,
((float) registers / (float) delta) * Constants.MILLIS_IN_SECOND
);
registersLocal = 0;
t0Local = t1Local;
}
}
registersInserted = collisionService.insertPositionEvents(positionEvents);
positionEvents.clear();
registers = registers + registersInserted;
registersLocal = registersLocal + registersInserted;
t1 = System.currentTimeMillis();
delta = t1 - t0;
t1Local = t1;
deltaLocal = t1Local - t0Local;
LOGGER.info("Added {} regs in {} ms, avg: {} regs/s, total regs: {}, global average: {}",
registersLocal,
deltaLocal,
((float) registersLocal / (float) deltaLocal) * Constants.MILLIS_IN_SECOND,
registers,
((float) registers / (float) delta) * Constants.MILLIS_IN_SECOND
);
LOGGER.info("inserted {} registers out of {}", registers, registersTotal);
} catch (IOException e) {
return new ResponseEntity<>(new ResponseMessage("Failed to read file",
ErrorCode.SERVICE_ERROR.getCode()),
HttpStatus.BAD_REQUEST);
} catch (ParseException e) {
return new ResponseEntity<>(
new ResponseMessage("Invalid positionEvents attribute: " + e.getMessage(),
ErrorCode.MISSING_POSITION_EVENTS_ATTR.getCode()),
HttpStatus.BAD_REQUEST);
} catch (CollisionServiceException e) {
return new ResponseEntity<>(new ResponseMessage("Failed: " + e.getMessage(),
ErrorCode.SERVICE_ERROR.getCode()),
HttpStatus.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException e) {
return new ResponseEntity<>(new ResponseMessage("Invalid payload: " + e.getMessage(),
ErrorCode.SERVICE_ERROR.getCode()),
HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new ResponseMessage("Success", 0),
HttpStatus.ACCEPTED);
}
}
|
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int randomN = (int) (Math.random()*10);
int randomM = (int) (Math.random()*10);
int[][] matrix0 = new int[randomN][randomM];
int[][] matrix1 = new int[randomN][randomM];
int[] matrixSize = new int[2];
matrixSize[0] = randomN;
matrixSize[1] = randomM;
Main.setupArray(matrix0);
Main.setupArray(matrix1);
System.out.println("Перавая матрица: "+ Arrays.deepToString(matrix0));
System.out.println("Вторая матрица: "+ Arrays.deepToString(matrix1));
System.out.println("Сумма матриц: ");
Main.sumOfArrays(matrix0,matrix1,matrixSize);
}
}
|
package generator.util;
import server.data.Exercise;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ExerciseStatistics {
private String template;
private List<Exercise> exerciseList;
public ExerciseStatistics(String template, List<Exercise> exerciseList) {
this.template = template;
this.exerciseList = exerciseList;
}
public String getTemplate() {
return template;
}
public List<Exercise> getExerciseList() {
return exerciseList;
}
/**
* Iterates over every exercise and counts exercises that are duplicates
* @return
*/
public int getDuplicateExercises(boolean debugDuplicates) {
final HashMap<String, Integer> exerciseMap = new HashMap<>();
this.exerciseList.forEach(e -> {
if (exerciseMap.containsKey(e.getCode())) {
exerciseMap.put(e.getCode(), exerciseMap.get(e.getCode()) + 1);
if (debugDuplicates) System.out.println(e.getIndex() + " is a duplicate: " + e.getCode());
} else {
exerciseMap.put(e.getCode(), 1);
}
});
return this.exerciseList.size() - exerciseMap.size();
}
/**
* Iterates over every exercise and counts exercises that are duplicates
* @return
*/
public int getDuplicateExercises() {
return getDuplicateExercises(false);
}
}
|
package day0227;
import java.awt.BorderLayout;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ShowList {
SignIn main;
JPanel jp_ltotal ;
JTextArea listTxta;
ShowList(){
}
ShowList(SignIn main){
this.main = main;
jp_ltotal = main.jp_ltotal;
}
void showList() {
main.switching("list");
listTxta = new JTextArea();
listTxta.setSize(10, 30);
listTxta.append("======================목록=======================\n");
listTxta.append("이름\t나이\t아이디\t비밀번호\n");
listTxta.append("================================================\n");
for(UserVO vo: main.voList) {
listTxta.append(vo.getUserName()+"\t");
listTxta.append(Integer.toString(vo.getUserAge())+"\t");
listTxta.append(vo.getUserID()+"\t");
listTxta.append(vo.getUserPW()+"\t");
listTxta.append("\n");
}
jp_ltotal.add(listTxta);
main.add(jp_ltotal,BorderLayout.CENTER);
main.setVisible(true);
}
}
|
package org.rundeck.client.api.model.scheduler;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class TakeoverServerItem {
public String uuid;
public Boolean all;
public String getUuid() {
return uuid;
}
public TakeoverServerItem setUuid(String uuid) {
this.uuid = uuid;
return this;
}
public Boolean getAll() {
return all;
}
public TakeoverServerItem setAll(Boolean all) {
this.all = all;
return this;
}
@Override
public String toString() {
return "{" +
"uuid='" + uuid + '\'' +
", all=" + all +
'}';
}
}
|
public class Amflag {
public static void main(String[] args)
{
for(int r=0; r<15; r++)
{
System.out.println();
for(int i=0; i<46; i++)
{
if(r<9 && i<6)
{
if (r%2==0)
System.out.print("* ");
else
if(i<5)
System.out.print(" *");
else System.out.print(" ");
}
else
if(r<9 && i>39)
break;
else
System.out.print("=");
}
}
}
}
|
package toolsForSale;
/**
* Represents a ProtractorTool.
* @author Desislava Dontcheva
* @version 1.0
*/
import exceptions.ToolMeasureException;
public class ProtractorTool extends GeometryTool {
/**
* Constructor with parameters for class ProtractorTool.
* @param measure This is the measure of ProtractorTool.
*/
public ProtractorTool(GeometryToolMeasure measure){
super();
validationMeasure(new ProtractorTool(measure));
}
/**
* This method validates if the measure of ProtractorTool
* is correct or not.
* @param protractor Object of class ProtractorTool.
* @see ToolMeasureException#protractorValidation(ProtractorTool, String)
*/
public void validationMeasure(ProtractorTool protractor){
ToolMeasureException exception = new ToolMeasureException();
exception.protractorValidation(protractor, "Invalid protractor measure");
}
}
|
/*
* Copyright 2002-2022 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.aot.hint.predicate;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.function.Predicate;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.ExecutableMode;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeReference;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for {@link ReflectionHintsPredicates}
*
* @author Brian Clozel
*/
class ReflectionHintsPredicatesTests {
private static Constructor<?> privateConstructor;
private static Constructor<?> publicConstructor;
@SuppressWarnings("unused")
private static Method publicMethod;
@SuppressWarnings("unused")
private static Field publicField;
private final ReflectionHintsPredicates reflection = new ReflectionHintsPredicates();
private final RuntimeHints runtimeHints = new RuntimeHints();
@BeforeAll
static void setupAll() throws Exception {
privateConstructor = SampleClass.class.getDeclaredConstructor(String.class);
publicConstructor = SampleClass.class.getConstructor();
publicMethod = SampleClass.class.getMethod("publicMethod");
publicField = SampleClass.class.getField("publicField");
}
@Nested
class ReflectionOnType {
@Test
void shouldFailForNullType() {
assertThatIllegalArgumentException().isThrownBy(() -> reflection.onType((TypeReference) null));
}
@Test
void reflectionOnClassShouldMatchIntrospection() {
runtimeHints.reflection().registerType(SampleClass.class);
assertPredicateMatches(reflection.onType(SampleClass.class));
}
@Test
void reflectionOnTypeReferenceShouldMatchIntrospection() {
runtimeHints.reflection().registerType(SampleClass.class);
assertPredicateMatches(reflection.onType(TypeReference.of(SampleClass.class)));
}
@Test
void reflectionOnDifferentClassShouldNotMatchIntrospection() {
runtimeHints.reflection().registerType(Integer.class);
assertPredicateDoesNotMatch(reflection.onType(TypeReference.of(SampleClass.class)));
}
@Test
void typeWithMemberCategoryFailsWithNullCategory() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS);
assertThatIllegalArgumentException().isThrownBy(() ->
reflection.onType(SampleClass.class).withMemberCategory(null));
}
@Test
void typeWithMemberCategoryMatchesCategory() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS);
assertPredicateMatches(reflection.onType(SampleClass.class)
.withMemberCategory(MemberCategory.INTROSPECT_PUBLIC_METHODS));
}
@Test
void typeWithMemberCategoryDoesNotMatchOtherCategory() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS);
assertPredicateDoesNotMatch(reflection.onType(SampleClass.class)
.withMemberCategory(MemberCategory.INVOKE_PUBLIC_METHODS));
}
@Test
void typeWithMemberCategoriesMatchesCategories() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS,
MemberCategory.INTROSPECT_PUBLIC_METHODS);
assertPredicateMatches(reflection.onType(SampleClass.class)
.withMemberCategories(MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS, MemberCategory.INTROSPECT_PUBLIC_METHODS));
}
@Test
void typeWithMemberCategoriesDoesNotMatchMissingCategory() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS);
assertPredicateDoesNotMatch(reflection.onType(SampleClass.class)
.withMemberCategories(MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS, MemberCategory.INTROSPECT_PUBLIC_METHODS));
}
@Test
void typeWithAnyMemberCategoryFailsWithNullCategories() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS);
assertThatIllegalArgumentException().isThrownBy(() ->
reflection.onType(SampleClass.class).withAnyMemberCategory(new MemberCategory[0]));
}
@Test
void typeWithAnyMemberCategoryMatchesCategory() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS,
MemberCategory.INVOKE_PUBLIC_METHODS);
assertPredicateMatches(reflection.onType(SampleClass.class)
.withAnyMemberCategory(MemberCategory.INTROSPECT_PUBLIC_METHODS));
}
@Test
void typeWithAnyMemberCategoryDoesNotMatchOtherCategory() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS,
MemberCategory.INVOKE_PUBLIC_METHODS);
assertPredicateDoesNotMatch(reflection.onType(SampleClass.class)
.withAnyMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS));
}
}
@Nested
class ReflectionOnConstructor {
@Test
void constructorIntrospectionDoesNotMatchMissingHint() {
assertPredicateDoesNotMatch(reflection.onConstructor(publicConstructor).introspect());
}
@Test
void constructorIntrospectionMatchesConstructorHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
typeHint.withConstructor(Collections.emptyList(), ExecutableMode.INTROSPECT));
assertPredicateMatches(reflection.onConstructor(publicConstructor).introspect());
}
@Test
void constructorIntrospectionMatchesIntrospectPublicConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS);
assertPredicateMatches(reflection.onConstructor(publicConstructor).introspect());
}
@Test
void constructorIntrospectionMatchesInvokePublicConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
assertPredicateMatches(reflection.onConstructor(publicConstructor).introspect());
}
@Test
void constructorIntrospectionMatchesIntrospectDeclaredConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS);
assertPredicateMatches(reflection.onConstructor(publicConstructor).introspect());
}
@Test
void constructorIntrospectionMatchesInvokeDeclaredConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
assertPredicateMatches(reflection.onConstructor(publicConstructor).introspect());
}
@Test
void constructorInvocationDoesNotMatchConstructorHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.
withConstructor(Collections.emptyList(), ExecutableMode.INTROSPECT));
assertPredicateDoesNotMatch(reflection.onConstructor(publicConstructor).invoke());
}
@Test
void constructorInvocationMatchesConstructorInvocationHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.
withConstructor(Collections.emptyList(), ExecutableMode.INVOKE));
assertPredicateMatches(reflection.onConstructor(publicConstructor).invoke());
}
@Test
void constructorInvocationDoesNotMatchIntrospectPublicConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS);
assertPredicateDoesNotMatch(reflection.onConstructor(publicConstructor).invoke());
}
@Test
void constructorInvocationMatchesInvokePublicConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
assertPredicateMatches(reflection.onConstructor(publicConstructor).invoke());
}
@Test
void constructorInvocationDoesNotMatchIntrospectDeclaredConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS);
assertPredicateDoesNotMatch(reflection.onConstructor(publicConstructor).invoke());
}
@Test
void constructorInvocationMatchesInvokeDeclaredConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
assertPredicateMatches(reflection.onConstructor(publicConstructor).invoke());
}
@Test
void privateConstructorIntrospectionMatchesConstructorHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
typeHint.withConstructor(TypeReference.listOf(String.class), ExecutableMode.INTROSPECT));
assertPredicateMatches(reflection.onConstructor(privateConstructor).introspect());
}
@Test
void privateConstructorIntrospectionDoesNotMatchIntrospectPublicConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS);
assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).introspect());
}
@Test
void privateConstructorIntrospectionDoesNotMatchInvokePublicConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).introspect());
}
@Test
void privateConstructorIntrospectionMatchesIntrospectDeclaredConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS);
assertPredicateMatches(reflection.onConstructor(privateConstructor).introspect());
}
@Test
void privateConstructorIntrospectionMatchesInvokeDeclaredConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
assertPredicateMatches(reflection.onConstructor(privateConstructor).introspect());
}
@Test
void privateConstructorInvocationDoesNotMatchConstructorHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
typeHint.withConstructor(TypeReference.listOf(String.class), ExecutableMode.INTROSPECT));
assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).invoke());
}
@Test
void privateConstructorInvocationMatchesConstructorInvocationHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
typeHint.withConstructor(TypeReference.listOf(String.class), ExecutableMode.INVOKE));
assertPredicateMatches(reflection.onConstructor(privateConstructor).invoke());
}
@Test
void privateConstructorInvocationDoesNotMatchIntrospectPublicConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS);
assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).invoke());
}
@Test
void privateConstructorInvocationDoesNotMatchInvokePublicConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).invoke());
}
@Test
void privateConstructorInvocationDoesNotMatchIntrospectDeclaredConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS);
assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).invoke());
}
@Test
void privateConstructorInvocationMatchesInvokeDeclaredConstructors() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
assertPredicateMatches(reflection.onConstructor(privateConstructor).invoke());
}
}
@Nested
class ReflectionOnMethod {
@Test
void methodIntrospectionMatchesMethodHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
typeHint.withMethod("publicMethod", Collections.emptyList(), ExecutableMode.INTROSPECT));
assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").introspect());
}
@Test
void methodIntrospectionFailsForUnknownType() {
assertThatThrownBy(() -> reflection.onMethod("com.example.DoesNotExist", "publicMethod").introspect())
.isInstanceOf(ClassNotFoundException.class);
}
@Test
void methodIntrospectionMatchesIntrospectPublicMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS);
assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").introspect());
}
@Test
void methodIntrospectionMatchesInvokePublicMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_PUBLIC_METHODS);
assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").introspect());
}
@Test
void methodIntrospectionMatchesIntrospectDeclaredMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_DECLARED_METHODS);
assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").introspect());
}
@Test
void methodIntrospectionMatchesInvokeDeclaredMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_DECLARED_METHODS);
assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").introspect());
}
@Test
void methodInvocationDoesNotMatchMethodHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
typeHint.withMethod("publicMethod", Collections.emptyList(), ExecutableMode.INTROSPECT));
assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
}
@Test
void methodInvocationMatchesMethodInvocationHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
typeHint.withMethod("publicMethod", Collections.emptyList(), ExecutableMode.INVOKE));
assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
}
@Test
void methodInvocationDoesNotMatchIntrospectPublicMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS);
assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
}
@Test
void methodInvocationMatchesInvokePublicMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_PUBLIC_METHODS);
assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
}
@Test
void methodInvocationDoesNotMatchIntrospectDeclaredMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_DECLARED_METHODS);
assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
}
@Test
void methodInvocationMatchesInvokeDeclaredMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_DECLARED_METHODS);
assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
}
@Test
void privateMethodIntrospectionMatchesMethodHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
typeHint.withMethod("privateMethod", Collections.emptyList(), ExecutableMode.INTROSPECT));
assertPredicateMatches(reflection.onMethod(SampleClass.class, "privateMethod").introspect());
}
@Test
void privateMethodIntrospectionDoesNotMatchIntrospectPublicMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS);
assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").introspect());
}
@Test
void privateMethodIntrospectionDoesNotMatchInvokePublicMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_PUBLIC_METHODS);
assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").introspect());
}
@Test
void privateMethodIntrospectionMatchesIntrospectDeclaredMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_DECLARED_METHODS);
assertPredicateMatches(reflection.onMethod(SampleClass.class, "privateMethod").introspect());
}
@Test
void privateMethodIntrospectionMatchesInvokeDeclaredMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_DECLARED_METHODS);
assertPredicateMatches(reflection.onMethod(SampleClass.class, "privateMethod").introspect());
}
@Test
void privateMethodInvocationDoesNotMatchMethodHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
typeHint.withMethod("privateMethod", Collections.emptyList(), ExecutableMode.INTROSPECT));
assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
}
@Test
void privateMethodInvocationMatchesMethodInvocationHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
typeHint.withMethod("privateMethod", Collections.emptyList(), ExecutableMode.INVOKE));
assertPredicateMatches(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
}
@Test
void privateMethodInvocationDoesNotMatchIntrospectPublicMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_PUBLIC_METHODS);
assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
}
@Test
void privateMethodInvocationDoesNotMatchInvokePublicMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_PUBLIC_METHODS);
assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
}
@Test
void privateMethodInvocationDoesNotMatchIntrospectDeclaredMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INTROSPECT_DECLARED_METHODS);
assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
}
@Test
void privateMethodInvocationMatchesInvokeDeclaredMethods() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.INVOKE_DECLARED_METHODS);
assertPredicateMatches(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
}
}
@Nested
class ReflectionOnField {
@Test
void shouldFailForMissingField() {
assertThatIllegalArgumentException().isThrownBy(() -> reflection.onField(SampleClass.class, "missingField"));
}
@Test
void shouldFailForUnknownClass() {
assertThatThrownBy(() -> reflection.onField("com.example.DoesNotExist", "missingField"))
.isInstanceOf(ClassNotFoundException.class);
}
@Test
void fieldReflectionMatchesFieldHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withField("publicField"));
assertPredicateMatches(reflection.onField(SampleClass.class, "publicField"));
}
@Test
void fieldReflectionDoesNotMatchNonRegisteredFielddHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withField("publicField"));
assertPredicateDoesNotMatch(reflection.onField(SampleClass.class, "privateField"));
}
@Test
void fieldReflectionMatchesPublicFieldsHint() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.PUBLIC_FIELDS);
assertPredicateMatches(reflection.onField(SampleClass.class, "publicField"));
}
@Test
void fieldReflectionMatchesDeclaredFieldsHint() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.DECLARED_FIELDS);
assertPredicateMatches(reflection.onField(SampleClass.class, "publicField"));
}
@Test
void privateFieldReflectionMatchesFieldHint() {
runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withField("privateField"));
assertPredicateMatches(reflection.onField(SampleClass.class, "privateField"));
}
@Test
void privateFieldReflectionDoesNotMatchPublicFieldsHint() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.PUBLIC_FIELDS);
assertPredicateDoesNotMatch(reflection.onField(SampleClass.class, "privateField"));
}
@Test
void privateFieldReflectionMatchesDeclaredFieldsHint() {
runtimeHints.reflection().registerType(SampleClass.class, MemberCategory.DECLARED_FIELDS);
assertPredicateMatches(reflection.onField(SampleClass.class, "privateField"));
}
}
private void assertPredicateMatches(Predicate<RuntimeHints> predicate) {
assertThat(predicate).accepts(this.runtimeHints);
}
private void assertPredicateDoesNotMatch(Predicate<RuntimeHints> predicate) {
assertThat(predicate).rejects(this.runtimeHints);
}
@SuppressWarnings("unused")
static class SampleClass {
private String privateField;
public String publicField;
public SampleClass() {
}
private SampleClass(String message) {
}
public void publicMethod() {
}
private void privateMethod() {
}
}
}
|
package com.bloodl1nez.analytics.vk.api.likes;
public enum LikeType {
POST("post"),
PHOTO("photo");
private final String value;
LikeType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
|
/*
* 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 witchinn;
import audio.AudioEvent;
import audio.AudioEventListenerIntf;
/**
*
* @author mayajones
*/
class AudioEventListener implements AudioEventListenerIntf {
public AudioEventListener() {
}
@Override
public void onAudioEvent(AudioEvent event, String trackName) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
package pl.dkiszka.bank.controllers;
import io.vavr.control.Option;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import pl.dkiszka.bank.dto.UserLookupResponse;
import pl.dkiszka.bank.services.UserQueryGatewayException;
import pl.dkiszka.bank.services.UserQueryService;
import java.util.Optional;
import java.util.function.Predicate;
/**
* @author Dominik Kiszka {dominikk19}
* @project bank-application
* @date 24.04.2021
*/
@RestController
@RequestMapping(path = "/api/v1/users")
@RequiredArgsConstructor
@Slf4j
class UserQueryController {
private static final Predicate<UserLookupResponse> isUsersNotEmpty = resp -> !resp.getUsers().isEmpty();
private final UserQueryService userQueryService;
@GetMapping
@ResponseBody
@PreAuthorize("hasAuthority('READ_PRIVILEGE')")
public ResponseEntity<UserLookupResponse> getAllUsers() {
return Option.of(userQueryService.getAllUsers())
.filter(isUsersNotEmpty)
.map(ResponseEntity::ok)
.getOrElse(ResponseEntity.noContent()::build);
}
@GetMapping(path = "/{id}")
@ResponseBody
@PreAuthorize("hasAuthority('READ_PRIVILEGE')")
public ResponseEntity<UserLookupResponse> getUserById(@PathVariable("id") String id) {
return Option.of(userQueryService.getUserById(id))
.filter(isUsersNotEmpty)
.map(ResponseEntity::ok)
.getOrElse(ResponseEntity.noContent()::build);
}
@GetMapping(value = "/byFilter")
@ResponseBody
@PreAuthorize("hasAuthority('READ_PRIVILEGE')")
public ResponseEntity<UserLookupResponse> searchUserByFilter(@RequestParam String filter) {
return Option.of(userQueryService.findUsersByFilter(filter))
.filter(isUsersNotEmpty)
.map(ResponseEntity::ok)
.getOrElse(ResponseEntity.noContent()::build);
}
@ExceptionHandler(value = {UserQueryGatewayException.class})
ResponseEntity<String> userQueryGatewayException(UserQueryGatewayException ex) {
log.warn("UserQueryGatewayException with msg {}", ex.getLocalizedMessage());
return ResponseEntity.of(Optional.of(ex.getLocalizedMessage()))
.status(HttpStatus.I_AM_A_TEAPOT)
.build();
}
}
|
package com.netty.zerocopy;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
public class oldClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket();
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",19999);
socket.connect(inetSocketAddress);
String filename = "xxxxx";
FileInputStream fileInputStream = new FileInputStream(filename);
DataOutputStream dataOutputStream = (DataOutputStream) socket.getOutputStream();
long total = 0;
int readByte = 0;
byte [] buffer = new byte[4096];
long currentTimeMillis = System.currentTimeMillis();
while ((readByte = fileInputStream.read(buffer) )!= -1){
dataOutputStream.write(buffer,0,buffer.length);
total += readByte;
}
System.out.println("传输字节:" + total + "耗时:" + (System.currentTimeMillis() - currentTimeMillis ));
dataOutputStream.close();
fileInputStream.close();
}
}
|
package com.netcracker.repositories;
import com.netcracker.entities.Journey;
import com.netcracker.entities.PaidJourney;
import org.springframework.data.repository.CrudRepository;
import com.netcracker.entities.User;
import java.util.Collection;
import java.util.Optional;
public interface PaidJourneyRepository extends CrudRepository<PaidJourney, Long> {
Collection<PaidJourney> findAllByUser(User user);
Optional<PaidJourney> findPaidJourneyByUserAndJourney(User user, Journey journey);
}
|
package com.androidbook.layout;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class DialogDisplay extends
Activity {
@Override
protected void onCreate(
Bundle savedInstanceState) {
// TODO Auto-generated method stub
super
.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
Button b = (Button)findViewById(R.id.do_dialog_btn);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(
View v) {
new AlertDialog.Builder(DialogDisplay.this)
.setMessage("Please press agree to continue...")
.setPositiveButton("Agree", null)
.show();
}
});
}
}
|
package com.ard333.springbootwebfluxjjwt.rest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ard333.springbootwebfluxjjwt.model.security.AuthRequest;
import com.ard333.springbootwebfluxjjwt.model.security.AuthResponse;
import com.ard333.springbootwebfluxjjwt.security.JWTUtil;
import com.ard333.springbootwebfluxjjwt.security.PBKDF2Encoder;
import com.ard333.springbootwebfluxjjwt.service.UserService;
import reactor.core.publisher.Mono;
@RestController
public class AuthenticationREST {
private JWTUtil jwtUtil;
private PBKDF2Encoder passwordEncoder;
private UserService userService;
public AuthenticationREST(JWTUtil jwtUtil, PBKDF2Encoder passwordEncoder, UserService userService) {
super();
this.jwtUtil = jwtUtil;
this.passwordEncoder = passwordEncoder;
this.userService = userService;
}
@PostMapping("/login")
public Mono<ResponseEntity<AuthResponse>> login(@RequestBody AuthRequest ar) {
return userService.findByUsername(ar.getUsername())
.filter(userDetails -> passwordEncoder.encode(ar.getPassword()).equals(userDetails.getPassword()))
.map(userDetails -> ResponseEntity.ok(new AuthResponse(jwtUtil.generateToken(userDetails))))
.switchIfEmpty(Mono.just(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()));
}
}
|
package com.project.phase2;
import java.util.ArrayList;
import java.util.Random;
import com.project.Crew;
public class Planet extends MapObject{
private ShopMenu shop;
private ArrayList<Crew> crew = new ArrayList<Crew>();
private Random rand;
public Planet(MapTile tile) {
super(tile);
rand = new Random();
hasQuest= rand.nextBoolean();
objImg.changeImage("res/shop.png", true);
shop = new ShopMenu();
if(hasQuest) {
quest =new Quest("Find your Ass.",shop.shopKeep);
shop.setQuest(quest);
}
}
public void interact(MapShip ship) {
System.out.println("Hey there X plorer");
shop.setShip((MapPlayerShip)ship);
Phase2.setShop(shop);
}
}
|
package com.lsjr.zizi.chat.helper;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import com.lsjr.bean.ObjectResult;
import com.lsjr.bean.Result;
import com.lsjr.callback.ChatObjectCallBack;
import com.lsjr.utils.HttpUtils;
import com.lsjr.zizi.AppConfig;
import com.lsjr.zizi.mvp.home.HomeActivity;
import com.lsjr.zizi.mvp.home.ConfigApplication;
import com.lsjr.zizi.chat.bean.LoginAuto;
import com.lsjr.zizi.chat.bean.LoginRegisterResult;
import com.lsjr.zizi.chat.bean.ResultCode;
import com.lsjr.zizi.chat.dao.UserDao;
import com.lsjr.zizi.chat.db.User;
import com.lsjr.zizi.util.DeviceInfoUtil;
import com.ymz.baselibrary.utils.L_;
import com.ymz.baselibrary.utils.UIUtils;
/**
* 当前登陆用户的帮助类
*
*
*/
public class LoginHelper {
public static final String ACTION_LOGIN = UIUtils.getPackageName() + ".action.login";// 登陆
public static final String ACTION_LOGOUT = UIUtils.getPackageName() + ".action.logout";// 用户手动注销登出
public static final String ACTION_CONFLICT = UIUtils.getPackageName()+ ".action.conflict";// 登陆冲突(另外一个设备登陆了)
// 用户需要重新登陆,更新本地数据(可能是STATUS_USER_TOKEN_OVERDUE,STATUS_USER_NO_UPDATE,STATUS_USER_TOKEN_CHANGE三种状态之一)
public static final String ACTION_NEED_UPDATE = UIUtils.getPackageName() + ".action.need_update";
public static final String ACTION_LOGIN_GIVE_UP = UIUtils.getPackageName() + ".action.login_give_up";// 在下载资料的时候,没下载完就放弃登陆了
// 获取登陆和登出的action filter
public static IntentFilter getLogInOutActionFilter() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_LOGIN);
intentFilter.addAction(ACTION_LOGOUT);
intentFilter.addAction(ACTION_CONFLICT);
intentFilter.addAction(ACTION_NEED_UPDATE);
intentFilter.addAction(ACTION_LOGIN_GIVE_UP);
return intentFilter;
}
// 登陆广播,且登陆的用户为MyApplication.getInstance().mLoginUser
public static void broadcastLogin(Context context) {
Intent intent = new Intent(ACTION_LOGIN);
context.sendBroadcast(intent);
}
// 登出广播
public static void broadcastLogout(Context context) {
Intent intent = new Intent(ACTION_LOGOUT);
context.sendBroadcast(intent);
}
// 放弃登陆
public static void broadcastLoginGiveUp(Context context) {
Intent intent = new Intent(ACTION_LOGIN_GIVE_UP);
context.sendBroadcast(intent);
}
// 登陆冲突(另外一个设备登陆了)
public static void broadcastConflict(Context context) {
L_.e("另外一个设备登陆了");
Intent intent = new Intent(ACTION_CONFLICT);
context.sendBroadcast(intent);
}
public static void broadcastNeedUpdate(Context context) {
Intent intent = new Intent(ACTION_NEED_UPDATE);
context.sendBroadcast(intent);
}
/* 信息完整程度由低到高,从第2级别开始,MyApplication中的mLoginUser是有值得 */
/* 没有用户,即游客(不需要进行其他操作) */
public static final int STATUS_NO_USER = 0;
/* 有用户,但是不完整,只有手机号,可能是之前注销过(不需要进行其他操作) */
public static final int STATUS_USER_SIMPLE_TELPHONE = 1;
/* 有用户,但是本地Token已经过期了(需要弹出对话框提示:本地Token已经过期,重新登陆) */
public static final int STATUS_USER_TOKEN_OVERDUE = 2;
/*
* 有用户,本地Token未过期,但是可能信息不是最新的,即在上次登陆之后,没有更新完数据就退出了app (需要检测Token是否变更,变更即提示登陆,未变更则提示更新资料)
*/
public static final int STATUS_USER_NO_UPDATE = 3;
/*
* 用户资料全部完整,但是Token已经变更了,提示重新登陆
*/
public static final int STATUS_USER_TOKEN_CHANGE = 4;
/*
* 用户资料全部完整,但是还要检测Token是否变更 (需要检测Token是否变更,变更即提示登陆) 此状态比较特殊,因为有可能Token没有变更,不需要在进行登陆操作。<br/> 在检测Token接口调用失败的情况下,默认为一个不需要重新登陆的用户。
* 在检测Token接口调用成功的情况下,此状态会立即过度到STATUS_USER_VALIDATION状态。
*/
public static final int STATUS_USER_FULL = 5;
/*
* 用户资料全部完整,并且已经检测Token没有变更,或者新登录更新完成 (不需要进行其他操作)
*/
public static final int STATUS_USER_VALIDATION = 6;//
/* 进入MainActivity,判断当前是游客,还是之前已经登陆过的用户 */
public static int prepareUser(Context context) {
int userStatus = STATUS_NO_USER;
boolean idIsEmpty = TextUtils.isEmpty(UserSp.getInstance().getUserId());
boolean telephoneIsEmpty = TextUtils.isEmpty(UserSp.getInstance().getTelephone());
if (!idIsEmpty && !telephoneIsEmpty) {// 用户标识都不为空,那么就能代表一个完整的用户
// 进入之前,加载本地已经存在的数据
String userId = UserSp.getInstance().getUserId();
User user = UserDao.getInstance().getUserByUserId(userId);
if (!LoginHelper.isUserValidation(user)) {// 用户数据错误,那么就认为是一个游客
userStatus = STATUS_NO_USER;
} else {
ConfigApplication.instance().mLoginUser = user;
ConfigApplication.instance().mAccessToken = UserSp.getInstance().getAccessToken(null);
ConfigApplication.instance().mExpiresIn = UserSp.getInstance().getExpiresIn(0);
if (LoginHelper.isTokenValidation()) {// Token未过期
boolean isUpdate = UserSp.getInstance().isUpdate(true);
if (isUpdate) {
userStatus = STATUS_USER_FULL;
} else {
userStatus = STATUS_USER_NO_UPDATE;
}
} else {// Token过期
userStatus = STATUS_USER_TOKEN_OVERDUE;
}
}
} else if (!idIsEmpty) {// (适用于切换账号之后的操作)手机号不为空
userStatus = STATUS_USER_SIMPLE_TELPHONE;
} else {
userStatus = STATUS_NO_USER;
}
ConfigApplication.instance().mUserStatus = userStatus;
return userStatus;
}
// User数据是否能代表一个有效的用户
public static boolean isUserValidation(User user) {
if (user == null) {
return false;
}
if (TextUtils.isEmpty(user.getUserId())) {
return false;
}
if (TextUtils.isEmpty(user.getTelephone())) {
return false;
}
if (TextUtils.isEmpty(user.getPassword())) {
return false;
}
if (TextUtils.isEmpty(user.getNickName())) {
return false;
}
return true;
}
/**
* AccessToken 是否是有效的
*
* @return
*/
public static boolean isTokenValidation() {
if (TextUtils.isEmpty(ConfigApplication.instance().mAccessToken)) {
return false;
}
if (ConfigApplication.instance().mExpiresIn < System.currentTimeMillis()) {
return false;
}
return true;
}
public static boolean setLoginUser(Context context, String telephone, String password, ObjectResult<LoginRegisterResult> result) {
if (result == null) {
return false;
}
if (result.getResultCode() != Result.CODE_SUCCESS) {
return false;
}
if (result.getData() == null) {
return false;
}
// 保存当前登陆的用户信息和Token信息作为全局变量,方便调用
User user = ConfigApplication.instance().mLoginUser;
user.setTelephone(telephone);
user.setPassword(password);
user.setUserId(result.getData().getUserId());
user.setNickName(result.getData().getNickName());
if (!LoginHelper.isUserValidation(user)) {// 请求下来的用户数据不完整有错误
return false;
}
ConfigApplication.instance().mAccessToken = result.getData().getAccess_token();
long expires_in = result.getData().getExpires_in() * 1000L + System.currentTimeMillis();
// long expires_in = 60 * 1000L + System.currentTimeMillis();// 测试 1分钟就过期的Token
ConfigApplication.instance().mExpiresIn = expires_in;
if (result.getData().getLogin() != null) {
user.setOfflineTime(result.getData().getLogin().getOfflineTime());
}
// 保存基本信息到数据库
boolean saveAble = UserDao.getInstance().saveUserLogin(user);
if (!saveAble) {
return false;
}
// 保存最后一次登录的用户信息到Sp,用于免登陆
UserSp.getInstance().setUserId(result.getData().getUserId());
UserSp.getInstance().setTelephone(telephone);
UserSp.getInstance().setAccessToken(result.getData().getAccess_token());
UserSp.getInstance().setExpiresIn(expires_in);
ConfigApplication.instance().mUserStatusChecked = true;
ConfigApplication.instance().mUserStatus = STATUS_USER_VALIDATION;
return true;
}
public static interface OnCheckedFailedListener {// 检查Token失败才回调,然后外部在继续下一次检测
void onCheckFailed();
}
/**
* 检测Status,是否要弹出更新用户状态的对话框
*
* @param activity
* 是否弹出对话框有本方法内部逻辑决定。<br/>
* 是否继续循环检测(检测未成功的情况下),<br/>
* 由 MyApplication.getInstance().mUserStatusChecked值决定,( 因为方法内部有异步操作,不能直接返回值来判断) 在MainActivity中进行重复检测的判定
*/
public static void checkStatusForUpdate(final HomeActivity activity, final OnCheckedFailedListener listener) {
if (ConfigApplication.instance().mUserStatusChecked) {
return;
}
final int status = ConfigApplication.instance().mUserStatus;
if (status == STATUS_NO_USER || status == STATUS_USER_SIMPLE_TELPHONE) {
ConfigApplication.instance().mUserStatusChecked = true;
return;
}
final User user = ConfigApplication.instance().mLoginUser;
if (!isUserValidation(user)) {// 如果是用户数据不完整,那么就可能是数据错误,将状态变为STATUS_NO_USER和STATUS_USER_SIMPLE_TELPHONE
boolean telephoneIsEmpty = TextUtils.isEmpty(UserSp.getInstance().getTelephone());
if (telephoneIsEmpty) {
ConfigApplication.instance().mUserStatus = STATUS_NO_USER;
} else {
ConfigApplication.instance().mUserStatus = STATUS_USER_SIMPLE_TELPHONE;
}
return;
}
if (status == STATUS_USER_VALIDATION) {
ConfigApplication.instance().mUserStatusChecked = true;
broadcastLogin(activity);
return;
}
if (status == STATUS_USER_TOKEN_CHANGE) {// Token已经变更,直接提示,不需要再检测Token是否变更
ConfigApplication.instance().mUserStatusChecked = true;
broadcastNeedUpdate(activity);
return;
}
/**
* 能往下执行的只有三种状态 <br/>
* public static final int STATUS_USER_TOKEN_OVERDUE = 2;<br/>
* public static final int STATUS_USER_NO_UPDATE = 3;<br/>
* public static final int STATUS_USER_FULL = 5;<br/>
*/
Map<String, String> params = new HashMap<String, String>();
params.put("access_token", ConfigApplication.instance().mAccessToken);
params.put("userId", user.getUserId());
params.put("serial", DeviceInfoUtil.getDeviceId(activity));
// 地址信息
//double latitude = ConfigApplication.instance().getBdLocationHelper().getLatitude();
//double longitude = ConfigApplication.instance().getBdLocationHelper().getLongitude();
// if (latitude != 0)
params.put("latitude", String.valueOf(100));
// if (longitude != 0)
params.put("longitude", String.valueOf(100));
HttpUtils.getInstance().postServiceData(AppConfig.USER_LOGIN_AUTO, params, new ChatObjectCallBack<LoginAuto>(LoginAuto.class) {
@Override
protected void onXError(String exception) {
}
@Override
protected void onSuccess(ObjectResult<LoginAuto> result) {
boolean success = ResultCode.defaultParser(result, false);
if (success && result.getData() != null) {
ConfigApplication.instance().mUserStatusChecked = true;// 检测Token成功
int tokenExists = result.getData().getTokenExists();// 1=令牌存在、0=令牌不存在
int serialStatus = result.getData().getSerialStatus();// 1=没有设备号、2=设备号一致、3=设备号不一致
Log.d("wang","tokenExists"+tokenExists);
Log.d("wang","serialStatus"+serialStatus);
if (serialStatus == 2) {// 设备号一致,说明没有切换过设备
if (tokenExists == 1) {// Token也存在,说明不用登陆了
if (status == STATUS_USER_FULL) {// 本地数据完整,那么就免登陆使用
ConfigApplication.instance().mUserStatus = STATUS_USER_VALIDATION;
} else {
// do no thing 依然保持其他的状态
}
} else {// Token 不存在
if (status == STATUS_USER_FULL) {// 数据也完整,那么就是Token过期
ConfigApplication.instance().mUserStatus = STATUS_USER_TOKEN_OVERDUE;
} else {
// do no thing 依然保持其他的状态
}
}
} else {// 设备号不一致,那么就是切换过手机
ConfigApplication.instance().mUserStatus = STATUS_USER_TOKEN_CHANGE;
}
// 最后判断是否要跳转弹出对话框
if (ConfigApplication.instance().mUserStatus != STATUS_USER_VALIDATION) {
broadcastNeedUpdate(activity);
} else {// 如果是用户已经完整验证,那么发出用户登录的广播
broadcastLogin(activity);
}
} else {
if (listener != null) {
listener.onCheckFailed();
}
}
}
});
}
}
|
package com.onairm.recordtool4android.activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.onairm.recordtool4android.R;
import com.onairm.recordtool4android.base.BaseActivity;
import com.onairm.recordtool4android.player.JCVideoPlayerStandard;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import java.util.ArrayList;
import java.util.List;
/**
* Created by bqy on 2018/1/25.
*/
public class VideoPublishActivity extends BaseActivity implements View.OnTouchListener{
private TagFlowLayout pbTagLayout;
private JCVideoPlayerStandard palyer;
private EditText etName;
private EditText etClass;
private TextView tvMore;
private EditText etIdea;
private Button btnPublish;
private ImageView ivBack;
private TagAdapter<String> tagAdapter;
private List<String> tagList;
private String videoUrl;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_publish);
Intent intent=getIntent();
if(null != intent){
videoUrl=intent.getStringExtra("videoUrl");
}
pbTagLayout = findViewById(R.id.pbTagLayout);
palyer = findViewById(R.id.player);
etName = findViewById(R.id.etName);
etClass = findViewById(R.id.etClass);
etIdea = findViewById(R.id.etIdea);
tvMore = findViewById(R.id.tvMore);
btnPublish = findViewById(R.id.btnPublish);
ivBack = findViewById(R.id.ivBack);
palyer.backButton.setVisibility(View.GONE);
palyer.setUp(videoUrl, "");
palyer.startButton.performClick();
tagList = new ArrayList<>();
tagList.add("hai hai hai hai");
tagList.add("hai hai hai hai");
tagList.add("hai hai hai hai");
tagList.add("hai hai hai hai");
tagList.add("hai hai hai hai");
tagList.add("hai hai hai hai");
tagList.add("hai hai hai hai");
etIdea.setOnTouchListener(this);
tvMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(VideoPublishActivity.this, TopicSearchActivity.class);
startActivityForResult(intent, 2);
}
});
tagAdapter = new TagAdapter<String>(tagList) {
@Override
public View getView(FlowLayout parent, int position, String s) {
TextView tv = (TextView) LayoutInflater.from(VideoPublishActivity.this).inflate(R.layout.view_tag,
pbTagLayout, false);
tv.setText(tagList.get(position));
return tv;
}
};
pbTagLayout.setAdapter(tagAdapter);
tagAdapter.setSelected(0, tagList.get(0));
tagAdapter.setSelectedList(0);
btnPublish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
publishDialog();
}
});
ivBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2){
if (resultCode == RESULT_OK){
if (data != null) {
String tag = data.getStringExtra("topic");
tagList.set(0, tag);
tagAdapter.notifyDataChanged();
tagAdapter.setSelected(0, tagList.get(0));
tagAdapter.setSelectedList(0);
}
}
}
}
@Override
public boolean onTouch(View view, MotionEvent event) {
//触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理;否则将事件交由其父类处理
if ((view.getId() == R.id.etIdea && canVerticalScroll(etIdea))) {
view.getParent().requestDisallowInterceptTouchEvent(true);
if (event.getAction() == MotionEvent.ACTION_UP) {
view.getParent().requestDisallowInterceptTouchEvent(false);
}
}
return false;
}
/**
* EditText竖直方向是否可以滚动
* @param editText 需要判断的EditText
* @return true:可以滚动 false:不可以滚动
*/
private boolean canVerticalScroll(EditText editText) {
//滚动的距离
int scrollY = editText.getScrollY();
//控件内容的总高度
int scrollRange = editText.getLayout().getHeight();
//控件实际显示的高度
int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() -editText.getCompoundPaddingBottom();
//控件内容总高度与实际显示高度的差值
int scrollDifference = scrollRange - scrollExtent;
if(scrollDifference == 0) {
return false;
}
return (scrollY > 0) || (scrollY < scrollDifference - 1);
}
private void publishDialog() {
final Dialog dialog = new Dialog(this, R.style.DialogStyle);
Window window = dialog.getWindow();
window.setContentView(R.layout.dialog_publish_success);
window.setGravity(Gravity.CENTER);
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.width = (int) (display.getWidth());
dialog.getWindow().setAttributes(lp);
dialog.show();
}
public static void jumpToVideoPublishActivity(Context context,String videoUrl){
Intent intent = new Intent(context,VideoPublishActivity.class);
intent.putExtra("videoUrl",videoUrl);
context.startActivity(intent);
}
}
|
package com.atguigu.java;
/*
* 父类
*/
public class Person extends Creature {
String name = "personname";
public void show(){
System.out.println("person show");
}
public void say(){
System.out.println("person say");
}
}
|
package com.org.exercise;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.lang.String;
public class EmployeeService {
List<Employee> list = new ArrayList<Employee>();
public void add(Employee e) {
// TODO Auto-generated method stub
list.add(e);
}
public String find(int a) {
for (Employee emp : list) {
if (emp.getId() == a)
return emp.getName();
}
return "Id is not present";
}
public Iterable<Employee> display() {
return list;
}
public void sortId() {
Collections.sort(list, (e1, e2) -> e1.getId() - e2.getId());
}
public void sortName() {
Collections.sort(list, (e1, e2) -> e1.getName().compareTo(e2.getName()));
}
public void sortSalary() {
Collections.sort(list, (e1, e2) -> e1.getSalary() - e2.getSalary());
}
public void sortDOB() {
Collections.sort(list, (e1, e2) -> e1.getDob().compareTo(e2.getDob()));
}
}
|
package com.grandsea.ticketvendingapplication.constant;
/**
* Created by Grandsea09 on 2017/10/17.
*/
public class Constant {
public static final String DEPART_CITY_ID="depart_city_id";
public static final String DEPART_CITY_NAME="depart_city_name";
public static final String DEPART_STATION_ID="depart_station_id";
public static final String DEPART_STATION_NAME="depart_station_name";
public static final String DEFAULT_UID="default_uid";
}
|
package com.nbu.barker;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import java.io.StringReader;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
public class CreateWalkActivity extends AppCompatActivity {
FusedLocationProviderClient pLocClient = null;
EditText etMessage;
TextView tvLocation;
Button bCreate;
LocationRequest pLocRequest = null;
@Override
public void onBackPressed() {
returnToWalks();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_walk);
etMessage = (EditText) findViewById(R.id.etCreateWalkMessage);
tvLocation = (TextView) findViewById(R.id.tvCreateWalkLocationChangable);
bCreate = (Button) findViewById(R.id.bCreateWalkCreate);
pLocRequest = new LocationRequest();
pLocRequest.setInterval(30000);
pLocRequest.setFastestInterval(5000);
pLocRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
String sLocation = "";
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
} else {
returnToHomeScreen("Your android version is not high enough to use this function");
}
}
LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
//TODO: UI updates.
String sResult = Double.toString(location.getLatitude());
Log.println(Log.ERROR,"location", sResult);
Geocoder pGeocoder = new Geocoder(CreateWalkActivity.this);
try {
List<Address> pAddresses = pGeocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
tvLocation.setText(pAddresses.get(0).getAddressLine(0));
} catch (Exception e) {
Log.println(Log.ERROR,"GEOCODER LOCATION", "ERROR RECEIVING LOCATION:" + e.getMessage());
}
}
}
}
};
LocationServices.getFusedLocationProviderClient(CreateWalkActivity.this).requestLocationUpdates(pLocRequest, mLocationCallback, null);
bCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String sMessage = etMessage.getText().toString();
String sLocation = tvLocation.getText().toString();
if (sMessage.isEmpty()) {
Toast.makeText(CreateWalkActivity.this, "Please write a message", Toast.LENGTH_SHORT).show();
return;
}
else if(sLocation.isEmpty() || sLocation.equals("Location"))
{
Toast.makeText(CreateWalkActivity.this, "There was a problem finding your locaton", Toast.LENGTH_SHORT).show();
return;
}
String sRequest = "<Barker requestType=\"createWalk\">\n" +
" <createWalk>\n" +
" <email>" + SessionParameters.getApplicationUser().getEmail() + "</email>\n" +
" <location>" + sLocation + "</location>\n" +
" <message>" + sMessage + "</message>\n" +
" </createWalk>\n" +
"</Barker>";
String sResponse = "";
try {
sResponse = Tools.sendRequest(sRequest);
Log.println(Log.ERROR, "Response is: ", sResponse);
if (sResponse == "Error" || sResponse.isEmpty()) {
Toast.makeText(CreateWalkActivity.this, "There was an error creating walk.Please try again", Toast.LENGTH_LONG).show();
return;
}
Document pDoc = null;
DocumentBuilder pBuilder = null;
DocumentBuilderFactory pFactory = DocumentBuilderFactory.newInstance();
pBuilder = pFactory.newDocumentBuilder();
pDoc = pBuilder.parse(new InputSource(new StringReader(sResponse)));
XPathFactory pXpathFactory = XPathFactory.newInstance();
XPath pXpath = pXpathFactory.newXPath();
XPathExpression pExp = null;
pExp = pXpath.compile("Barker/statusCode");
double nTmp = (double) pExp.evaluate(pDoc, XPathConstants.NUMBER);
int nStatusCode = (int) nTmp;
if (nStatusCode == Constants.requestStatusToCode(Constants.RequestServerStatus.SUCCESS)) {
returnToWalks("Successfully created walk");
}
else
{
Toast.makeText(CreateWalkActivity.this, "Couldn't create walk. Please try again", Toast.LENGTH_SHORT).show();
return;
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(CreateWalkActivity.this, "Couldn't create walk. Please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
private void returnToHomeScreen(String sMessage)
{
Intent pIntent = new Intent(CreateWalkActivity.this,HomeActivity.class);
pIntent.putExtra("message", sMessage);
startActivity(pIntent);
}
private void returnToWalks()
{
Intent pIntent = new Intent(CreateWalkActivity.this,FindWalkActivity.class);
startActivity(pIntent);
}
private void returnToWalks(String sMessage)
{
Intent pIntent = new Intent(CreateWalkActivity.this,FindWalkActivity.class);
pIntent.putExtra("message", sMessage);
startActivity(pIntent);
}
}
|
package com.dta.tp;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
public class Rectangle extends Figure implements Surfacable, Serializable {
private static final long serialVersionUID = 4330513109081964108L;
private Point basGauche, basDroit, hautGauche, hautDroit;
public Rectangle(Point p, int largeur, int hauteur){
this(Couleur.getCouleurDefaut(), p, largeur, hauteur);
}
public Rectangle(Couleur c, Point p, int largeur, int hauteur){
super(c);
basGauche = new Point( p.getX() , p.getY() );
basDroit = new Point( p.getX() + largeur , p.getY() );
hautGauche = new Point( p.getX() , p.getY() + hauteur );
hautDroit = new Point( p.getX() + largeur , p.getY() + hauteur );
}
public Point getPointBasGauche(){
return basGauche;
}
public Point getPointBasDroit(){
return basDroit;
}
public Point getPointHautGauche(){
return hautGauche;
}
public Point getPointHautDroit(){
return hautDroit;
}
protected String getType(){
return "RECT";
}
public String toString(){
return "[" +getType()
+" "
+getCouleur().getCode()
+" "
+getPointBasDroit()
+" "
+getPointBasGauche()
+" "
+getPointHautGauche()
+" "
+getPointHautDroit()
+" ]";
}
@Override
public Point getCentre() {
int x = (this.getPointBasDroit().getX() + this.getPointHautGauche().getX() ) / 2;
int y = (this.getPointBasDroit().getY() + this.getPointHautGauche().getY() ) / 2;
return new Point(x, y);
}
@Override
public double surface() {
int largeur = this.getPointHautDroit().getX() - this.getPointBasGauche().getX();
int hauteur = this.getPointHautDroit().getY() - this.getPointBasGauche().getY();
return largeur * hauteur;
}
@Override
public Collection<Point> getPoints() {
// Il n'y a pas de doublon, il n'y a pas d'ordre
Collection<Point> collection = new HashSet<Point>();
collection.add(getPointBasDroit());
collection.add(getPointBasGauche());
collection.add(getPointHautGauche());
collection.add(getPointHautDroit());
return collection;
}
@Override
public boolean couvre(Point p) {
if(p.getX() < getPointBasGauche().getX()){
return false;
}
if(p.getX() > getPointHautDroit().getX()){
return false;
}
if(p.getY() < getPointBasGauche().getY()){
return false;
}
if(p.getY() > getPointHautDroit().getY()){
return false;
}
return true;
}
public boolean equals(Object o){
if(o instanceof Rectangle){
Rectangle r = (Rectangle) o;
return this.getPointBasDroit().equals(r.getPointBasDroit())
&& this.getPointHautGauche().equals(r.getPointHautGauche())
&& (this.getCouleur() == r.getCouleur());
} else {
return false;
}
}
@Override
public Collection<Point> getPointsExtremes() {
return getPoints();
}
}
|
package graph;
import java.util.HashMap;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Run extends Application {
Pane containerPane ;
HashMap<String,Element> allItem = new HashMap<>(); ;
Element m;
Element addedChild,lastChild;
@Override
public void start(Stage primaryStage) throws Exception {
feedData();
VBox root = new VBox();
containerPane = new Pane();
TextArea searchTextArea = new TextArea();
searchTextArea.setPrefHeight(20);
Button searchButton = new Button("Search");
searchButton.setOnAction(e->{
for(Element m :allItem.values()) {
if(m.name.equals(searchTextArea.getText())) {
containerPane.getChildren().clear();
this.m=m;
rootLabel();
getDescendent(this.m);
}
}
});
root.getChildren().addAll(searchTextArea,searchButton,containerPane);
Scene scene = new Scene(root,400,400);
primaryStage.setScene(scene);
primaryStage.show();
}
private Element getElement(String label) {
if(label==null) return null;
Element m = new Element(label);
if(!allItem.containsKey(label)) {
allItem.put(label, m);
}
return m;
}
private void feedData() {
Element mA = getElement("A.SOURCE");
Element mA1 = getElement("A.CHILD1");
mA.addChild(mA1);
Element mA11 = getElement("A.CHILD11");
mA1.addChild(mA11);
Element mA2 = getElement("A.CHILD2");
mA.addChild(mA2);
Element mA3 = getElement("A.CHILD3");
mA.addChild(mA3);
Element mA4 = getElement("A.CHILD4");
mA.addChild(mA4);
Element mA5 = getElement("A.CHILD5");
mA.addChild(mA5);
Element mA51 = getElement("A.CHILD51");
mA5.addChild(mA51);
Element mA52 = getElement("A.CHILD52");
mA5.addChild(mA52);
/* Element mA11 = getElement("A.CHILD1.CHILD1");
mA1.addChild(mA11);
mA11.addParent(mA1);*/
// Element mA111 = getElement("A.CHILD1.CHILD2");
// mA1.addChild(mA111);
// mA111.addParent(mA1);
// Element mA22 = getElement("A.CHILD2.CHILD1");
// mA2.addChild(mA22);
// mA22.addParent(mA2);
// / Element mA23 = getElement("A.SECOND.SECOND.CHILD");
// mA2.addChild(mA23);
// mA23.addParent(mA2);
}
private void rootLabel() {
containerPane.getChildren().clear();
this.m.createLabel();
this.m.getLabel().relocate(50, 20);
containerPane.getChildren().add(this.m.getLabel());
}
private void getDescendent(Element m) {
for(Element child:m.childList) {
child.createLabel();
getCurrentChildPositionRelativeToParent(child);
containerPane.getChildren().add(child.getLabel());
addedChild=child;
getDescendent(child);
}
}
private void getCurrentChildPositionRelativeToParent(Element child) {
if(addedChild == null)
{
child.getLabel().layoutXProperty().bind(this.m.getLabel().layoutXProperty().add(50));
child.getLabel().layoutYProperty().bind(this.m.getLabel().layoutYProperty().add(30));
}
else
{
if(addedChild.childList.size()>0) {
child.getLabel().layoutXProperty().bind(addedChild.getLabel().layoutXProperty().add(50));
child.getLabel().layoutYProperty().bind(addedChild.getLabel().layoutYProperty().add(30));
}else {
child.getLabel().layoutXProperty().bind(addedChild.getLabel().layoutXProperty().subtract(50));
child.getLabel().layoutYProperty().bind(addedChild.getLabel().layoutYProperty().add(30));
}
}
}
public static void main(String args[]){
launch(args);
}
}
|
package tk.jimmywang.attendance.app.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.custom.JsonObjectPostRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import tk.jimmywang.attendance.app.R;
import tk.jimmywang.attendance.app.activity.WorkerActivity;
import tk.jimmywang.attendance.app.model.JsonResponse;
import tk.jimmywang.attendance.app.model.Worker;
import tk.jimmywang.attendance.app.util.Common;
/**
* Created by WangJin on 2014/7/5.
*/
public class WorkerFragment extends BaseFragment implements View.OnClickListener {
private Button addWorkerButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_worker, container, false);
addWorkerButton = (Button) view.findViewById(R.id.button_addWorker);
addWorkerButton.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_addWorker:
Intent intent = new Intent();
intent.setClass(getActivity(), WorkerActivity.class);
startActivityForResult(intent, 1);
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
final String workerName = data.getStringExtra("workerName");
final String workerPhone = data.getStringExtra("workerPhone");
Map<String, String> params = new HashMap<String, String>();
params.put("name", workerName);
params.put("phoneNumber", workerPhone);
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
JsonObjectPostRequest jsonObjectRequest = new JsonObjectPostRequest(Common.REQUEST_URL + "/worker/save", params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
JsonResponse<Worker> worker = JSON.parseObject(response.toString(), new TypeReference<JsonResponse<Worker>>(){});
Toast.makeText(getActivity(), "name:" + worker.getData().getName()+ "|phone:" + worker.getData().getPhoneNumber(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
}
});
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://192.168.1.111:8080/stringrequest", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getActivity(), "response" + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("workerName", workerName);
params.put("workerPhone", workerPhone);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Charset", "UTF-8");
return params;
}
};
requestQueue.add(jsonObjectRequest);
}
}
}
|
package com.minamid.accessiblememorygame.service;
import com.minamid.accessiblememorygame.model.ImageResponse;
import com.minamid.accessiblememorygame.util.Config;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
public interface ImageApi {
@Headers("Cache-Control: max-age=0")
@GET(Config.IMAGE_LIST_ENDPOINT)
Call<ImageResponse> fetchImageList();
}
|
package me.thechoyon.chatapp;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class ChatActivity extends Activity {
private FirebaseAuth user = FirebaseAuth.getInstance();
private ClipboardManager clipboardManager;
AlertDialog.Builder builder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
final FirebaseUser logged_user = user.getCurrentUser();
TextView user_screen = findViewById(R.id.user);
final EditText mail_init = findViewById(R.id.mail_id);
Button chatBtn = findViewById(R.id.start_chat);
Button copy_id = findViewById(R.id.get_id);
if (logged_user != null)
{
StringBuilder myStr = new StringBuilder(logged_user.getEmail());
myStr.append("( ID: ");
myStr.append(logged_user.getUid().substring(0,7));
myStr.append(" )");
user_screen.setText(myStr.toString());
chatBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String mail_addr = mail_init.getText().toString();
if (TextUtils.isEmpty(mail_addr))
{
Toast.makeText(getApplicationContext(), "Please enter Unique ID correctly!", Toast.LENGTH_SHORT).show();
}
else
{
Intent init_a_chat = new Intent(ChatActivity.this, ChatMain.class);
init_a_chat.putExtra("from",mail_addr);
startActivity(init_a_chat);
}
}
});
copy_id.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("content", logged_user.getUid().substring(0,7));
clipboardManager.setPrimaryClip(clip);
Toast.makeText(ChatActivity.this, "Copied to Clipboard!", Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.profile,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (item.toString().equals("Logout"))
{
builder = new AlertDialog.Builder(this);
builder.setTitle("Confirm Exit");
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage("Are you sure to logout?");
builder.setCancelable(false);
builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
user.signOut();
startActivity(new Intent(ChatActivity.this, MainActivity.class));
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
else if (item.toString().equals("My Profile"))
{
startActivity(new Intent(ChatActivity.this, Profile.class));
}
return super.onMenuItemSelected(featureId, item);
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser user_logged_in = user.getCurrentUser();
if (user_logged_in == null)
{
startActivity(new Intent(ChatActivity.this, MainActivity.class));
}
}
}
|
package haw.ci.lib;
/*
* As seen on:
* https://github.com/HAW-AI/CI-SS12-FSTT/blob/master/src/haw/ai/ci/SymbolTable.java
*/
import haw.ci.lib.descriptor.Descriptor;
import java.util.HashMap;
import java.util.Map;
public class SymbolTable {
private Map<String, Integer> addressMap = new HashMap<String, Integer>();
private Map<String, Descriptor> descriptorMap = new HashMap<String,Descriptor>();
private Map<String, Integer> constMap = new HashMap<String,Integer>();
private int currentAddress = 0;
private SymbolTable parentTable;
public SymbolTable(){
this.parentTable = null;
}
public SymbolTable(SymbolTable table){
this.parentTable = table;
}
public static SymbolTable createSymbolTable(){
return new SymbolTable();
}
public void declareConst(String ident, int value){
constMap.put(ident, value);
}
public int getConstVal(String ident){
return constMap.get(ident);
}
public boolean isLocal(String ident) {
return addressMap.containsKey(ident);
}
public void declare(String ident, Descriptor descriptor) {
if(!(addressMap.containsKey(ident))){
descriptorMap.put(ident, descriptor);
addressMap.put(ident, currentAddress);
if(descriptor == null){
System.out.println("---- compile Error-----\n Variable = " + ident);
}
currentAddress += descriptor.size();
}else{
System.out.println("Fehler, zweimal die gleiche Variable deklariert");
}
}
// public void undeclare(String ident){
// descriptorMap.remove(ident);
// addressMap.remove(ident);
//
// }
public Descriptor descriptorFor(String ident) {
Descriptor d = descriptorMap.get(ident);
if(d == null && parentTable != null){
return parentTable.descriptorFor(ident);
}
return d;
}
public int addressOf(String ident) {
if(addressMap.containsKey(ident)){
return addressMap.get(ident);
}
if(parentTable != null){
return parentTable.addressOf(ident);
}
return -1;
}
public int size() {
return currentAddress;
}
public String toString(){
StringBuffer result = new StringBuffer();
for(Map.Entry<String, Integer> e : addressMap.entrySet()){
result.append(e.getKey());
result.append(" : ");
result.append(e.getValue());
result.append("\n");
}
result.append("\n");
for(Map.Entry<String, Descriptor> e : descriptorMap.entrySet()){
result.append(e.getKey());
result.append(" : ");
result.append(e.getValue());
result.append("\n");
}
result.append("\n");
for(Map.Entry<String, Integer> e : constMap.entrySet()){
result.append(e.getKey());
result.append(" : ");
result.append(e.getValue());
result.append("\n");
}
result.append("\n");
result.append("currentAddress: " + currentAddress + "\n");
result.append("-----------------------------------------\n\n");
result.append("parentTable: \n" + parentTable + "\n");
return result.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((addressMap == null) ? 0 : addressMap.hashCode());
result = prime * result
+ ((constMap == null) ? 0 : constMap.hashCode());
result = prime * result + currentAddress;
result = prime * result
+ ((descriptorMap == null) ? 0 : descriptorMap.hashCode());
result = prime * result
+ ((parentTable == null) ? 0 : parentTable.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;
SymbolTable other = (SymbolTable) obj;
if (addressMap == null) {
if (other.addressMap != null)
return false;
} else if (!addressMap.equals(other.addressMap))
return false;
if (constMap == null) {
if (other.constMap != null)
return false;
} else if (!constMap.equals(other.constMap))
return false;
if (currentAddress != other.currentAddress)
return false;
if (descriptorMap == null) {
if (other.descriptorMap != null)
return false;
} else if (!descriptorMap.equals(other.descriptorMap))
return false;
if (parentTable == null) {
if (other.parentTable != null)
return false;
} else if (!parentTable.equals(other.parentTable))
return false;
return true;
}
}
|
package com.opas350.test.service;
import com.opas350.entities.Book;
import com.opas350.test.config.ServiceContextTest;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
/**
* Created by javier.reyes.valdez on 3/2/2017.
*/
public class BookServiceTest extends ServiceContextTest {
@Test
public void findByTitle() {
String titleExpected = "Java for noobs";
List<Book> books = bookService.findByTitle(titleExpected) ;
books.forEach(book -> {
String titleActual = book.getTitle();
System.out.println(titleActual);
Assert.assertTrue(titleActual.contains(titleExpected));
});
}
}
|
package com.nibu.atm;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
public interface ClientInterface extends Remote {
public BankOperationRes authorize(String cardNum, String password) throws RemoteException;
public BankOperationRes changeCreditLimit(String cardNum, long newLimit) throws RemoteException;
public BankOperationRes sendMoney(String cardNumFrom, String cardNumTo, long money) throws RemoteException;
public BankOperationRes addAutoTransaction(String cardNumFrom, String cardNumTo, int dayNumber, long money, String description) throws RemoteException;
public BankOperationRes editAutoTransaction(AutoTransaction transaction, String cardNumTo, int dayNumber, long money, String description) throws RemoteException;
public BankOperationRes setMoneyExcessLimit(String cardNumFrom, String cardNumTo, long limit) throws RemoteException;
public long getMaxCreditLimit(String cardNum) throws RemoteException;
public long getCreditLimit(String cardNum) throws RemoteException;
public String getName(String cardNum) throws RemoteException;
public long getBalance(String cardNum) throws RemoteException;
public ArrayList<AutoTransaction> getAutoTransactions(String cardNum) throws RemoteException;
public void exit() throws RemoteException;
}
|
/**
* 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.client.model;
public class State {
private String abbr;
private String name;
private String slogan;
public State() {
}
public State(String abbr, String name, String slogan) {
this();
setAbbr(abbr);
setName(name);
setSlogan(slogan);
}
public String getSlogan() {
return slogan;
}
public void setSlogan(String slogan) {
this.slogan = slogan;
}
public String getAbbr() {
return abbr;
}
public void setAbbr(String abbr) {
this.abbr = abbr;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package toba.user;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import 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 toba.data.UserDB;
/**
*
* @author Jake
*/
@WebServlet(urlPatterns = {"/PasswordResetServlet"})
public class PasswordResetServlet extends HttpServlet {
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url = "/account_activity.jsp";
User user = (User)request.getSession().getAttribute("user");
if(user != null) {
String newPassword = request.getParameter("NewPassword");
user.setPassword(newPassword);
UserDB.update(user);
} else {
url = "/password_reset.jsp";
request.setAttribute("message", "You are not currently logged in as a user.");
}
getServletContext().getRequestDispatcher(url).forward(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Handles user password change requests for the TOBA system.";
}
}
|
package org.valdi.entities.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.logging.Level;
import javax.xml.bind.DatatypeConverter;
import org.bukkit.command.CommandSender;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.valdi.entities.iDisguise;
import de.robingrether.util.ObjectUtil;
public class UpdateCheck implements Runnable {
public static final int PROJECT_ID = 46941;
public static final String API_URL = "https://api.curseforge.com/servermods/files?projectIds=";
public static final String API_CHECKSUM = "md5";
public static final String API_DOWNLOAD_URL = "downloadUrl";
public static final String API_FILE_NAME = "fileName";
public static final String API_GAME_VERSION = "gameVersion";
public static final String API_NAME = "name";
public static final String API_RELEASE_TYPE = "releaseType";
private iDisguise plugin;
private String pluginVersion;
private String latestVersion;
private CommandSender toBeNotified;
private String downloadUrl;
private String checksum;
private boolean autoDownload;
public UpdateCheck(iDisguise plugin, CommandSender toBeNotified, boolean autoDownload) {
this.plugin = plugin;
this.pluginVersion = plugin.getFullName();
this.toBeNotified = toBeNotified;
this.autoDownload = autoDownload;
}
public void run() {
checkForUpdate();
if(isUpdateAvailable()) {
toBeNotified.sendMessage(plugin.getLanguage().UPDATE_AVAILABLE.replace("%version%", latestVersion));
if(autoDownload) {
downloadUpdate();
} else {
toBeNotified.sendMessage(plugin.getLanguage().UPDATE_OPTION);
}
}
}
private boolean isUpdateAvailable() {
if(latestVersion != null && !pluginVersion.equals(latestVersion)) {
try {
int current = extractVersionNumber(pluginVersion);
int latest = extractVersionNumber(latestVersion);
return latest > current;
} catch(NumberFormatException e) {
} catch(ArrayIndexOutOfBoundsException e) {
}
}
return false;
}
private void checkForUpdate() {
BufferedReader reader = null;
try {
URL url = new URL(API_URL + PROJECT_ID);
URLConnection connection = url.openConnection();
connection.addRequestProperty("User-Agent", pluginVersion.replace(' ', '/') + " (by RobinGrether)");
connection.setDoOutput(true);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine();
JSONArray array = (JSONArray)JSONValue.parse(response);
latestVersion = null;
int latestVersionNumber = 0;
for(Object obj : array) {
JSONObject object = (JSONObject)obj;
int versionNumber = extractVersionNumber((String)object.get(API_NAME));
if(versionNumber > latestVersionNumber) {
latestVersionNumber = versionNumber;
latestVersion = (String)object.get(API_NAME);
downloadUrl = ((String)object.get(API_DOWNLOAD_URL));
checksum = (String)object.get(API_CHECKSUM);
}
}
} catch(Exception e) {
plugin.getLogger().log(Level.WARNING, "Update checking failed: " + e.getClass().getSimpleName());
} finally {
if(reader != null) {
try {
reader.close();
} catch(IOException e) {
}
}
}
}
private void downloadUpdate() {
File oldFile = plugin.getPluginFile();
File newFile = new File(plugin.getServer().getUpdateFolderFile(), oldFile.getName());
if(newFile.exists()) {
toBeNotified.sendMessage(plugin.getLanguage().UPDATE_ALREADY_DOWNLOADED);
} else {
InputStream input = null;
OutputStream output = null;
try {
URL url = new URL(downloadUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.addRequestProperty("User-Agent", pluginVersion.replace(' ', '/') + " (by RobinGrether)");
connection.setDoOutput(true);
if(ObjectUtil.equals(connection.getResponseCode(), 301, 302)) {
downloadUrl = connection.getHeaderField("Location");
downloadUpdate();
return;
} else if(connection.getResponseCode() != 200) {
toBeNotified.sendMessage(plugin.getLanguage().UPDATE_DOWNLOAD_FAILED);
plugin.getLogger().log(Level.WARNING, "Update download failed: HTTP error");
return;
}
toBeNotified.sendMessage(plugin.getLanguage().UPDATE_DOWNLOADING);
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
input = new DigestInputStream(connection.getInputStream(), messageDigest);
plugin.getServer().getUpdateFolderFile().mkdir();
output = new FileOutputStream(newFile);
int fetched;
byte[] data = new byte[4096];
while((fetched = input.read(data)) > 0) {
output.write(data, 0, fetched);
}
input.close();
output.close();
if(DatatypeConverter.printHexBinary(messageDigest.digest()).toLowerCase(Locale.ENGLISH).equals(checksum.toLowerCase(Locale.ENGLISH))) {
toBeNotified.sendMessage(plugin.getLanguage().UPDATE_DOWNLOAD_SUCCEEDED);
} else {
newFile.delete();
toBeNotified.sendMessage(plugin.getLanguage().UPDATE_DOWNLOAD_FAILED);
plugin.getLogger().log(Level.WARNING, "Update download failed: checksum is bad");
}
} catch(IOException | NoSuchAlgorithmException e) {
toBeNotified.sendMessage(plugin.getLanguage().UPDATE_DOWNLOAD_FAILED);
plugin.getLogger().log(Level.WARNING, "Update download failed: " + e.getClass().getSimpleName());
} finally {
if(input != null) {
try {
input.close();
} catch(IOException e) {
}
}
if(output != null) {
try {
output.close();
} catch(IOException e) {
}
}
}
}
}
public static int extractVersionNumber(String versionString) {
try {
String[] numbers = versionString.split(" |-")[1].split("\\.");
int versionNumber = 0;
for(int i = 0; i < numbers.length; i++) {
if(numbers[i].length() > 2)
return 0;
versionNumber += Integer.parseInt(numbers[i]) * Math.pow(10.0, 2 * (numbers.length - i - 1));
}
if(versionString.contains("SNAPSHOT"))
versionNumber--;
return versionNumber;
} catch(ArrayIndexOutOfBoundsException|NumberFormatException e) {
return 0;
}
}
}
|
package com.fajar.employeedataapi.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fajar.employeedataapi.entities.Employee;
import com.fajar.employeedataapi.entities.Salary;
import com.fajar.employeedataapi.exception.ApplicationException;
import com.fajar.employeedataapi.exception.NotFoundException;
import com.fajar.employeedataapi.model.EmployeeModel;
import com.fajar.employeedataapi.repository.EmployeeRepository;
import com.fajar.employeedataapi.repository.SalaryRepository;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class EmployeeService {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private EmployeeRepository employeeRepository;
@Autowired
private SalaryRepository salaryRepository;
public EmployeeModel insert(EmployeeModel employeeModel) {
log.info("insert data : {}", employeeModel);
employeeModel.setId(null);
Transaction tx = null;
Session s = sessionFactory.openSession();
try {
tx = s.beginTransaction();
Employee employee = employeeModel.toEntity();
int employeeId = (Integer) s.save(employee);
Salary salary = employee.getSalary();
salary.setId(employeeId);
s.save(salary);
tx.commit();
log.info("Success inserting data");
employee.setSalary(salary);
return employee.toModel();
} catch (Exception e) {
e.printStackTrace();
if (null != tx) {
tx.rollback();
}
throw new ApplicationException(e);
} finally {
if (null != s)
s.close();
}
}
public List<EmployeeModel> list() {
List<Employee> employees = employeeRepository.findByOrderById();
List<Salary> salaries = new ArrayList<>();
if (employees.size() > 0) {
salaries = salaryRepository.findByIdIn(idList(employees));
mapEmployeesAndSalaries(employees, salaries);
}
return toModel(employees);
}
private List<EmployeeModel> toModel(List<Employee> employees) {
List<EmployeeModel> list = new ArrayList<>();
for (Employee employee : employees) {
list.add(employee.toModel());
}
return list;
}
private static void mapEmployeesAndSalaries(List<Employee> employees, List<Salary> salaries) {
Map<Integer, Salary> map = new HashMap<Integer, Salary>() {
{
for (Salary salary : salaries) {
put(salary.getId(), salary);
}
}
};
for (Employee employee : employees) {
employee.setSalary(map.get(employee.getId()));
}
}
private List<Integer> idList(List<Employee> employees) {
List<Integer> list = new ArrayList<>();
for (Employee employee : employees) {
list.add(employee.getId());
}
return list;
}
public EmployeeModel getById(int id) {
Employee employee = getEmployeeRecord(id);
if (employee != null)
return employee.toModel();
throw new NotFoundException("Employee with id: " + id + " not found");
}
private Employee getEmployeeRecord(int id) {
Optional<Employee> employee = employeeRepository.findById(id);
if (employee.isPresent()) {
Optional<Salary> salary = salaryRepository.findById(employee.get().getId());
if (salary.isPresent()) {
employee.get().setSalary(salary.get());
}
return employee.get();
}
return null;
}
public boolean deleteById(int id) {
Transaction tx = null;
Session s = sessionFactory.openSession();
try {
tx = s.beginTransaction();
Employee employee = s.get(Employee.class, id);
Salary salary = s.get(Salary.class, id);
s.delete(employee);
s.delete(salary);
tx.commit();
return true;
} catch (Exception e) {
if (null != tx) {
tx.rollback();
}
throw new ApplicationException(e);
} finally {
if (null != s)
s.close();
}
}
public EmployeeModel update(int id, EmployeeModel model) {
Transaction tx = null;
Session s = sessionFactory.openSession();
try {
tx = s.beginTransaction();
Employee employee = s.get(Employee.class, id);
Salary salary = s.get(Salary.class, id);
if (null == salary || null == employee) {
throw new NotFoundException("Record not found");
}
employee.setUpdatedField(model);
if (null !=model.getSalary()) {
salary.setSalary(model.getSalary());
}
s.merge(employee);
s.merge(salary);
tx.commit();
employee.setSalary(salary);
return employee.toModel();
} catch (Exception e) {
if (null != tx) {
tx.rollback();
}
throw new ApplicationException(e);
} finally {
if (null != s)
s.close();
}
}
}
|
package com.esum.wp.ims.documentlog;
import java.util.TimeZone;
import com.esum.wp.ims.documentlog.base.BaseDocumentLog;
public class DocumentLog extends BaseDocumentLog {
private static final long serialVersionUID = 1L;
// DataBase Flag
private String dbType;
// for paging
private Integer currentPage;
private Integer itemCountPerPage;
private Integer totalCount;
private Integer index;
private Integer minIndex;
private Integer maxIndex;
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public Integer getMinIndex() {
return minIndex;
}
public void setMinIndex(Integer minIndex) {
this.minIndex = minIndex;
}
public Integer getMaxIndex() {
return maxIndex;
}
public void setMaxIndex(Integer maxIndex) {
this.maxIndex = maxIndex;
}
private Integer itemCount;
private Integer offset;
private String langType;
private String rootPath;
private TimeZone serverTz;
private TimeZone clientTz;
private String svcId;
private String svcType;
private String fromDateTime;
private String toDateTime;
private String fromdate;
private String fromtime;
private String todate;
private String totime;
private String errorContents;
private String action;
private String searchType;
private String searchAckStatus;
private String srType;
// message_log
private String messageNo;
private String procStatus;
private String ackStatus;
private String ackErrorCode;
private String ackErrSeqNo;
private String ackRecvTime;
// user_info
private String sCompName;
private String rCompName;
// DocumentLog Detail
private java.util.List docDetailList;
private java.util.List docErrCodDetailList;
public java.util.List getDocErrCodDetailList() {
return docErrCodDetailList;
}
public void setDocErrCodDetailList(java.util.List docErrCodDetailList) {
this.docErrCodDetailList = docErrCodDetailList;
}
public java.util.List getDocDetailList() {
return docDetailList;
}
public void setDocDetailList(java.util.List docDetailList) {
this.docDetailList = docDetailList;
}
// selectMsgDocLog Bean
private java.util.List msgDocLogList;
public java.util.List getMsgDocLogList() {
return msgDocLogList;
}
public void setMsgDocLogList(java.util.List msgDocLogList) {
this.msgDocLogList = msgDocLogList;
}
// attachDoc List
private Integer attachSeqNo;
private String contentType;
private String contentEncoding;
private String attachLocation;
public Integer getAttachSeqNo() {
return attachSeqNo;
}
public void setAttachSeqNo(Integer attachSeqNo) {
this.attachSeqNo = attachSeqNo;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentEncoding() {
return contentEncoding;
}
public void setContentEncoding(String contentEncoding) {
this.contentEncoding = contentEncoding;
}
public String getAttachLocation() {
return attachLocation;
}
public void setAttachLocation(String attachLocation) {
this.attachLocation = attachLocation;
}
private java.util.List attachDocList;
public java.util.List getAttachDocList() {
return attachDocList;
}
public void setAttachDocList(java.util.List attachDocList) {
this.attachDocList = attachDocList;
}
/* [CONSTRUCTOR MARKER BEGIN] */
public DocumentLog() {
super();
}
/**
* Constructor for primary key
*/
public DocumentLog(java.lang.String logTime) {
super(logTime);
}
/**
* Constructor for required fields
*/
public DocumentLog(java.lang.String logTime, java.lang.Integer docSeqNo) {
super(logTime, docSeqNo);
}
/* [CONSTRUCTOR MARKER END] */
protected void initialize() {
super.initialize();
}
/**
* @return Returns the currentPage.
*/
public Integer getCurrentPage() {
return currentPage;
}
/**
* @param currentPage
* The currentPage to set.
*/
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
/**
* @return Returns the itemCountPerPage.
*/
public Integer getItemCountPerPage() {
return itemCountPerPage;
}
/**
* @param itemCountPerPage
* The itemCountPerPage to set.
*/
public void setItemCountPerPage(Integer itemCountPerPage) {
this.itemCountPerPage = itemCountPerPage;
}
/**
* @return Returns the totalItemCount.
*/
public Integer getTotalCount() {
return totalCount;
}
/**
* @param totalItemCount
* The totalItemCount to set.
*/
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public String getFromDateTime() {
return fromDateTime;
}
public void setFromDateTime(String fromDateTime) {
this.fromDateTime = fromDateTime;
}
public String getToDateTime() {
return toDateTime;
}
public void setToDateTime(String toDateTime) {
this.toDateTime = toDateTime;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getSearchAckStatus() {
return searchAckStatus;
}
public void setSearchAckStatus(String searchAckStatus) {
this.searchAckStatus = searchAckStatus;
}
public String getCheckAckStatus(){
if(searchAckStatus.indexOf("PROC")>0){
return "PROC";
}else{
return "";
}
}
public String getSrType() {
return srType;
}
public void setSrType(String srType) {
this.srType = srType;
}
public String getMessageNo() {
return messageNo;
}
public void setMessageNo(String messageNo) {
this.messageNo = messageNo;
}
public String getProcStatus() {
return procStatus;
}
public void setProcStatus(String procStatus) {
this.procStatus = procStatus;
}
public String getsCompName() {
return sCompName;
}
public void setsCompName(String sCompName) {
this.sCompName = sCompName;
}
public String getrCompName() {
return rCompName;
}
public void setrCompName(String rCompName) {
this.rCompName = rCompName;
}
public String getFromdate() {
return fromdate;
}
public void setFromdate(String fromdate) {
this.fromdate = fromdate;
}
public String getFromtime() {
return fromtime;
}
public void setFromtime(String fromtime) {
this.fromtime = fromtime;
}
public String getTodate() {
return todate;
}
public void setTodate(String todate) {
this.todate = todate;
}
public String getTotime() {
return totime;
}
public void setTotime(String totime) {
this.totime = totime;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getErrorContents() {
return errorContents;
}
public void setErrorContents(String errorContents) {
this.errorContents = errorContents;
}
public String getSvcId() {
return svcId;
}
public void setSvcId(String svcId) {
this.svcId = svcId;
}
public String getSvcType() {
return svcType;
}
public void setSvcType(String svcType) {
this.svcType = svcType;
}
public String getDbType() {
return dbType;
}
public void setDbType(String dbType) {
this.dbType = dbType;
}
public Integer getItemCount() {
return itemCount;
}
public void setItemCount(Integer itemCount) {
this.itemCount = itemCount;
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public String getLangType() {
return langType;
}
public void setLangType(String langType) {
this.langType = langType;
}
public String getRootPath() {
return rootPath;
}
public void setRootPath(String rootPath) {
this.rootPath = rootPath;
}
public TimeZone getServerTz() {
return serverTz;
}
public void setServerTz(TimeZone serverTz) {
this.serverTz = serverTz;
}
public TimeZone getClientTz() {
return clientTz;
}
public void setClientTz(TimeZone clientTz) {
this.clientTz = clientTz;
}
public String getAckStatus() {
return ackStatus;
}
public void setAckStatus(String ackStatus) {
this.ackStatus = ackStatus;
}
public String getAckErrSeqNo() {
return ackErrSeqNo;
}
public void setAckErrSeqNo(String ackErrSeqNo) {
this.ackErrSeqNo = ackErrSeqNo;
}
public String getAckRecvTime() {
return ackRecvTime;
}
public void setAckRecvTime(String ackRecvTime) {
this.ackRecvTime = ackRecvTime;
}
public String getAckErrorCode() {
return ackErrorCode;
}
public void setAckErrorCode(String ackErrorCode) {
this.ackErrorCode = ackErrorCode;
}
}
|
package com.restapi.security.service;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
@Service
public interface TokenAuthenticationService {
Authentication authenticate(HttpServletRequest request);
}
|
package com.metoo.foundation.service;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import com.metoo.core.query.support.IPageList;
import com.metoo.core.query.support.IQueryObject;
import com.metoo.foundation.domain.GroupInfo;
import com.metoo.foundation.domain.User;
public interface IGroupInfoService {
/**
* 保存一个GroupInfo,如果保存成功返回true,否则返回false
*
* @param instance
* @return 是否保存成功
*/
boolean save(GroupInfo instance);
/**
* 根据一个ID得到GroupInfo
*
* @param id
* @return
*/
GroupInfo getObjById(Long id);
/**
* 删除一个GroupInfo
*
* @param id
* @return
*/
boolean delete(Long id);
/**
* 批量删除GroupInfo
*
* @param ids
* @return
*/
boolean batchDelete(List<Serializable> ids);
/**
* 通过一个查询对象得到GroupInfo
*
* @param properties
* @return
*/
IPageList list(IQueryObject properties);
/**
* 更新一个GroupInfo
*
* @param id
* 需要更新的GroupInfo的id
* @param dir
* 需要更新的GroupInfo
*/
boolean update(GroupInfo instance);
/**
*
* @param query
* @param params
* @param begin
* @param max
* @return
*/
List<GroupInfo> query(String query, Map params, int begin, int max);
/**
*
* @param construct
* @param propertyName
* @param value
* @return
*/
GroupInfo getObjByProperty(String construct, String propertyName,
String value);
}
|
package com.dwidobelyu.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dwidobelyu.util.BaseDao;
import com.dwidobelyu.dao.PostDao;
import com.dwidobelyu.dto.PostDto;
@Repository
public class PostDaoImpl extends BaseDao implements PostDao{
@Autowired
private SessionFactory sessionFactory;
public Session session() {
return sessionFactory.getCurrentSession();
}
@Override
public PostDto getPostById(PostDto param) {
String sql = "from PostModel where id = :id";
Object result = session().createQuery(sql).setProperties(param).list().get(0);
return (PostDto) setMapper(result, PostDto.class);
}
@SuppressWarnings("unchecked")
@Override
public List<PostDto> getAllPostHibernate() {
String sql = "from PostModel";
return session().createQuery(sql).list();
}
}
|
package com.weili.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
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 InfoContentDao {
/***************************************************************************
* 添加底部信息
*
* @param conn
* @param title
* @param infoId
* @param content
* @param linkPath
* @param sortIndex
* @param status
* @return
* @throws SQLException
*/
public long addInfoContent(Connection conn, String title, int infoId,
String content, String linkPath,String imgUrl, int sortIndex, int status)
throws SQLException {
Dao.Tables.t_info_content ic = new Dao().new Tables().new t_info_content();
ic.title.setValue(title);
ic.infoId.setValue(infoId);
ic.content.setValue(content);
ic.linkPath.setValue(linkPath);
ic.imgUrl.setValue(imgUrl);
ic.sortIndex.setValue(sortIndex);
ic.status.setValue(status);
ic.addTime.setValue(new Date());
return ic.insert(conn);
}
/**
* 修改底部信息
*
* @param conn
* @param id
* @param title
* @param infoId
* @param content
* @param linkPath
* @param sortIndex
* @param status
* @return
* @throws SQLException
*/
public long updateInfoContent(Connection conn, long id, String title,
int infoId, String content, String linkPath,String imgUrl, int sortIndex,
int status) throws SQLException {
Dao.Tables.t_info_content ic = new Dao().new Tables().new t_info_content();
if (StringUtils.isNotBlank(title)) {
ic.title.setValue(title);
}
if (infoId > 0) {
ic.infoId.setValue(infoId);
}
if (StringUtils.isNotBlank(content)) {
ic.content.setValue(content);
}
if (StringUtils.isNotBlank(linkPath)) {
ic.linkPath.setValue(linkPath);
}
if(StringUtils.isNotBlank(imgUrl)){
ic.imgUrl.setValue(imgUrl);
}
if (sortIndex > 0) {
ic.sortIndex.setValue(sortIndex);
}
if (status > 0) {
ic.status.setValue(status);
}
return ic.update(conn, " id = " + id);
}
/**
* 删除底部信息
*
* @param conn
* @param ids
* @return
* @throws SQLException
*/
public long deleteInfoContent(Connection conn, String ids)
throws SQLException {
Dao.Tables.t_info_content ic = new Dao().new Tables().new t_info_content();
return ic.delete(conn, " id in(" + ids + ") ");
}
/**
* 根据id查询
*
* @param conn
* @param id
* @return
* @throws SQLException
* @throws DataException
*/
public Map<String, String> queryInfoContentById(Connection conn, long id)
throws SQLException, DataException {
Dao.Tables.t_info_content ic = new Dao().new Tables().new t_info_content();
DataSet ds = ic.open(conn, " ", " id = " + id, "", -1, -1);
return BeanMapUtils.dataSetToMap(ds);
}
/**
* 根据id查询视图
*
* @param conn
* @param id
* @return
* @throws SQLException
* @throws DataException
*/
public Map<String, String> queryInfoContentViewById(Connection conn, long id)
throws SQLException, DataException {
Dao.Views.v_t_info_content ic = new Dao().new Views().new v_t_info_content();
DataSet ds = ic.open(conn, " ", " id = " + id, "", -1, -1);
return BeanMapUtils.dataSetToMap(ds);
}
/**
* 根据条件查询
*/
public List<Map<String, Object>> queryInfoContentAll(Connection conn,
String fieldList, String condition, String order)
throws SQLException, DataException {
Dao.Tables.t_info_content ic = new Dao().new Tables().new t_info_content();
DataSet ds = ic.open(conn, fieldList, condition, order, -1, -1);
ds.tables.get(0).rows.genRowsMap();
return ds.tables.get(0).rows.rowsMap;
}
}
|
package com.gossipmongers.mobicomkit.uiwidgets.uilistener;
import com.gossipmongers.mobicommons.people.channel.Channel;
import com.gossipmongers.mobicommons.people.contact.Contact;
public interface CustomToolbarListener {
void setToolbarTitle(String title);
void setToolbarSubtitle(String subtitle);
void setToolbarImage(Contact contact, Channel channel);
void hideSubtitleAndProfilePic();
}
|
package com.comp3717.comp3717;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.comp3717.comp3717.database.RecipeContract;
import com.comp3717.comp3717.utils.ID;
import com.comp3717.comp3717.utils.IngredientFetcher;
import java.util.ArrayList;
import java.util.List;
public class LiquorSelectActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String selectedIngredient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_liquor_select);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.liquorSpinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Creating adapter for spinner
CursorAdapter cursorAdapter = new IngredientFetcher(this).getIngredientByCategory(ID.ID_INGREDIENT_CATEGORY_LIQUOR);
// attaching data adapter to spinner
spinner.setAdapter(cursorAdapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
SimpleCursorAdapter sac = (SimpleCursorAdapter) parent.getAdapter();
Cursor c = sac.getCursor();
c.moveToPosition(position);
selectedIngredient = c.getString(c.getColumnIndex(RecipeContract.RecipeEntry.COLUMN_NAME_NAME));
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void submitSelection(View v) {
MainActivity.myIngredients.add(selectedIngredient);
Intent intent = new Intent(LiquorSelectActivity.this, MainActivity.class);
Toast.makeText(this, selectedIngredient + " added.", Toast.LENGTH_LONG).show();
startActivity(intent);
}
}
|
package co.id.datascrip.mo_sam_div4_dts1.adapter;
import android.content.Context;
import android.graphics.Color;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import co.id.datascrip.mo_sam_div4_dts1.Const;
import co.id.datascrip.mo_sam_div4_dts1.R;
import co.id.datascrip.mo_sam_div4_dts1.object.Kegiatan;
import co.id.datascrip.mo_sam_div4_dts1.object.SalesHeader;
import co.id.datascrip.mo_sam_div4_dts1.sqlite.ItemSQLite;
import co.id.datascrip.mo_sam_div4_dts1.sqlite.SalesHeaderSQLite;
public class Adapter_List_Kegiatan extends ArrayAdapter<Kegiatan> {
private Context context;
private List<Kegiatan> keglist;
private SparseBooleanArray mSelected;
private LayoutInflater inflater;
private int resId;
public Adapter_List_Kegiatan(Context context, int resId, List<Kegiatan> keglist) {
super(context, resId, keglist);
// TODO Auto-generated constructor stub
mSelected = new SparseBooleanArray();
this.context = context;
this.keglist = keglist;
this.resId = resId;
inflater = LayoutInflater.from(this.context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = convertView;
ViewHolder viewHolder = null;
if (view == null) {
viewHolder = new ViewHolder();
view = inflater.inflate(resId, null);
viewHolder.ID = (TextView) view.findViewById(R.id.lkID);
viewHolder.CCode = (TextView) view.findViewById(R.id.lkCCode);
viewHolder.CName = (TextView) view.findViewById(R.id.lkCName);
viewHolder.Waktu = (TextView) view.findViewById(R.id.lkWaktu);
viewHolder.No = (TextView) view.findViewById(R.id.lkNoOrder);
viewHolder.iconCancel = (ImageView) view.findViewById(R.id.icon_cancel);
viewHolder.iconCOS = (ImageView) view.findViewById(R.id.icon_cos);
viewHolder.iconCheckIn = (ImageView) view.findViewById(R.id.icon_checkin);
viewHolder.iconSaved = (ImageView) view.findViewById(R.id.icon_saved);
viewHolder.layout = (LinearLayout) view.findViewById(R.id.layout_keg);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.ID.setText("ID = " + Integer.toString(keglist.get(position).getID()));
viewHolder.CCode.setText(keglist.get(position).getSalesHeader().getCustomer().getCode());
viewHolder.CName.setText(keglist.get(position).getSalesHeader().getCustomer().getName());
viewHolder.Waktu.setText(keglist.get(position).getStartDate().substring(0, 16));
setIconVisible(viewHolder, keglist.get(position));
boolean isError = new ItemSQLite(context).isError(keglist.get(position).getSalesHeader().getHeaderID());
if (isError)
viewHolder.No.setTextColor(Color.RED);
return view;
}
@Override
public void remove(Kegiatan object) {
// TODO Auto-generated method stub
keglist.remove(object);
notifyDataSetChanged();
}
public void removeSelection() {
mSelected = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
mSelected.put(position, value);
else
mSelected.delete(position);
notifyDataSetChanged();
}
public List<Kegiatan> getItems() {
return keglist;
}
public void ToggleSelection(int position) {
selectView(position, !mSelected.get(position));
}
public int getSelectedCount() {
return mSelected.size();
}
public SparseBooleanArray getSelectedId() {
return mSelected;
}
private void setIconVisible(ViewHolder vHolder, Kegiatan k) {
SalesHeaderSQLite s = new SalesHeaderSQLite(context);
SalesHeader h = s.get(k.getID());
if (h != null) {
if (h.getOrderNo() == null) {
vHolder.No.setVisibility(View.GONE);
vHolder.iconSaved.setVisibility(View.GONE);
} else {
if (h.getOrderNo().contains("XXX") || h.getHeaderID() >= Const.DEFAULT_HEADER_ID) {
vHolder.iconSaved.setVisibility(View.VISIBLE);
vHolder.No.setVisibility(View.GONE);
vHolder.layout.setBackgroundResource(R.drawable.bg_light_blue);
} else {
vHolder.No.setVisibility(View.VISIBLE);
vHolder.iconSaved.setVisibility(View.GONE);
vHolder.No.setText(h.getOrderNo());
}
}
if (k.getCheckIn() == 1) {
vHolder.iconCheckIn.setVisibility(View.VISIBLE);
vHolder.iconCancel.setVisibility(View.GONE);
vHolder.iconCOS.setVisibility(View.GONE);
} else vHolder.iconCheckIn.setVisibility(View.GONE);
if (k.getCancel() != 0) {
if (h.getOrderNo() != null)
if (h.getOrderNo().contains("XXX")) {
new SalesHeaderSQLite(context).Delete(k.getID());
vHolder.iconSaved.setVisibility(View.GONE);
}
vHolder.layout.setBackgroundResource(R.drawable.bg_light_red);
vHolder.iconCancel.setVisibility(View.VISIBLE);
vHolder.iconCheckIn.setVisibility(View.GONE);
vHolder.iconCOS.setVisibility(View.GONE);
}
if (h.getStatus() == 1) {
vHolder.layout.setBackgroundResource(R.drawable.bg_light_green);
vHolder.iconCOS.setVisibility(View.VISIBLE);
vHolder.iconCancel.setVisibility(View.GONE);
vHolder.iconCheckIn.setVisibility(View.GONE);
} else vHolder.iconCOS.setVisibility(View.GONE);
} else vHolder.No.setVisibility(View.GONE);
}
@Override
public Kegiatan getItem(int position) {
return keglist.get(position);
}
static class ViewHolder {
TextView ID, CCode, CName, Waktu, No;
ImageView iconCancel, iconCOS, iconCheckIn, iconSaved;
LinearLayout layout;
}
}
|
package demo;
import model.Actor;
import model.Game;
import ui.Board;
/**
* Created by LionC on 07.11.2014.
*/
public class ClickParticler implements Actor {
protected Board inputBoard;
protected Game game;
public ClickParticler(Game aGame) {
this.inputBoard = aGame.getBoard();
this.game = aGame;
}
@Override
public void update() {
if(inputBoard.mouseKeyDown(1)) {
for(int i = 0; i < Math.random() * 50; i++) {
DogCollisionParticle particle = new DogCollisionParticle(this.game, inputBoard.getMouseX(), inputBoard.getMouseY());
game.addActor(particle);
game.getBoard().add(particle);
}
}
}
}
|
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
public class Main {
public static void main(String[] args) throws InterruptedException {
String path = "/Users/fengxinjie/go/src/";
Thread t = new Thread(new ThreadAdded(path, "fxj"));
t.start();
}
}
|
/*
* AddReferenceAlleleToHDF5Plugin
*/
package net.maizegenetics.analysis.data;
import ch.systemsx.cisd.hdf5.HDF5Factory;
import ch.systemsx.cisd.hdf5.IHDF5Reader;
import ch.systemsx.cisd.hdf5.IHDF5Writer;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import org.apache.log4j.Logger;
import net.maizegenetics.util.ArgsEngine;
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import net.maizegenetics.dna.map.GeneralPosition;
import net.maizegenetics.dna.map.Position;
import net.maizegenetics.dna.map.PositionList;
import net.maizegenetics.dna.map.PositionListBuilder;
import net.maizegenetics.dna.snp.GenotypeTable;
import net.maizegenetics.dna.snp.GenotypeTableBuilder;
import net.maizegenetics.dna.snp.ImportUtils;
import net.maizegenetics.dna.snp.NucleotideAlignmentConstants;
import net.maizegenetics.taxa.TaxaList;
import net.maizegenetics.taxa.Taxon;
import net.maizegenetics.util.HDF5Utils;
import net.maizegenetics.util.Utils;
import java.util.List;
/**
*
* @author Jeff Glaubitz (jcg233@cornell.edu)
*/
public class AddReferenceAlleleToHDF5Plugin extends AbstractPlugin {
private static final Logger myLogger = Logger.getLogger(AddReferenceAlleleToHDF5Plugin.class);
private ArgsEngine myArgsEngine = null;
private String inHDF5FileName = null;
private String refGenomeFileStr = null;
private String genomeVersion = null;
private BufferedReader refReader = null;
private PositionListBuilder newPosListBuilder = null;
private int currChr = Integer.MIN_VALUE;
private int currPos = Integer.MIN_VALUE;
private String contextSeq;
private final boolean writePositions = false;
public AddReferenceAlleleToHDF5Plugin() {
super(null, false);
}
public AddReferenceAlleleToHDF5Plugin(Frame parentFrame) {
super(parentFrame, false);
}
private void printUsage() {
myLogger.info(
"\n\n"
+"The options for the TASSEL5 AddReferenceAlleleToHDF5Plugin are as follows:\n"
+" -i Input HDF5 genotype (*.h5) file to be annotated with the reference allele.\n"
+" -ref Path to reference genome in fasta format.\n"
+" -ver Genome version.\n"
+"\n\n"
);
}
@Override
public void setParameters(String[] args) {
if (args == null || args.length == 0) {
printUsage();
try {Thread.sleep(500);} catch(InterruptedException e) {}
throw new IllegalArgumentException("\n\nPlease use the above arguments/options.\n\n");
}
if (myArgsEngine == null) {
myArgsEngine = new ArgsEngine();
myArgsEngine.add("-i", "--input-file", true);
myArgsEngine.add("-ref", "--referenceGenome", true);
myArgsEngine.add("-ver", "--genome-version", true);
}
myArgsEngine.parse(args);
inHDF5FileName = myArgsEngine.getString("-i");
File inFile = null;
if (inHDF5FileName != null) {
inFile = new File(inHDF5FileName);
if (!inFile.exists()) {
printUsage();
try {Thread.sleep(500);} catch(InterruptedException e) {}
String errMessage = "\nThe input HDF5 genotype (*.h5) file name you supplied does not exist:\n"+inHDF5FileName+"\n\n";
myLogger.error(errMessage);
try {Thread.sleep(500);} catch(InterruptedException e) {}
throw new IllegalArgumentException(errMessage);
}
} else {
printUsage();
try {Thread.sleep(500);} catch(InterruptedException e) {}
String errMessage = "\nPlease specify an input HDF5 genotype (*.h5) file to be annotated with the reference allele (-i option)\n\n";
myLogger.error(errMessage);
try {Thread.sleep(500);} catch(InterruptedException e) {}
throw new IllegalArgumentException(errMessage);
}
if (myArgsEngine.getBoolean("-ref")) {
refGenomeFileStr = myArgsEngine.getString("-ref");
File refGenomeFile = new File(refGenomeFileStr);
if (!refGenomeFile.exists() || !refGenomeFile.isFile()) {
printUsage();
try {Thread.sleep(500);} catch(InterruptedException e) {}
String errMessage = "\nCan't find the reference genome fasta file specified by the -ref option:\n "+refGenomeFileStr+"\n\n";
myLogger.error(errMessage);
try {Thread.sleep(500);} catch(InterruptedException e) {}
throw new IllegalArgumentException();
}
refReader = Utils.getBufferedReader(refGenomeFileStr);
} else {
printUsage();
try {Thread.sleep(500);} catch(InterruptedException e) {}
String errMessage = "\nPlease specify a reference genome fasta file (-ref option)\n\n";
myLogger.error(errMessage);
try {Thread.sleep(500);} catch(InterruptedException e) {}
throw new IllegalArgumentException(errMessage);
}
if (myArgsEngine.getBoolean("-ver")) {
genomeVersion = myArgsEngine.getString("-ver");
} else {
printUsage();
try {Thread.sleep(500);} catch(InterruptedException e) {}
String errMessage = "\nPlease specify the name of the reference genome version (e.g. -ver \"B73 RefGen_v2\")\n\n";
myLogger.error(errMessage);
try {Thread.sleep(500);} catch(InterruptedException e) {}
throw new IllegalArgumentException(errMessage);
}
}
@Override
public DataSet performFunction(DataSet input) {
String message = addRefAlleleToHDF5GenoTable();
if(message != null) {
myLogger.error(message);
try {Thread.sleep(500);} catch(Exception e) {}
throw new IllegalStateException(message);
}
try {refReader.close();} catch (IOException e) {}
fireProgress(100);
return null;
}
private String addRefAlleleToHDF5GenoTable() {
String message = populatePositionsWithRefAllele();
if (message != null) return message;
PositionList newPos = newPosListBuilder.build();
if (writePositions) {
String genomeVer = newPos.hasReference() ? newPos.genomeVersion() : "unkown";
System.out.println("\nNew genome version: "+genomeVer+"\n");
}
String outHDF5FileName = inHDF5FileName.replaceFirst("\\.h5$", "_withRef.h5");
GenotypeTableBuilder newGenos = GenotypeTableBuilder.getTaxaIncremental(newPos, outHDF5FileName);
IHDF5Reader h5Reader = HDF5Factory.open(inHDF5FileName);
List<String> taxaNames = HDF5Utils.getAllTaxaNames(h5Reader);
for (String taxonName : taxaNames) {
Taxon taxon = HDF5Utils.getTaxon(h5Reader, taxonName);
byte[] genos = HDF5Utils.getHDF5GenotypesCalls(h5Reader, taxonName);
byte[][] depth = HDF5Utils.getHDF5GenotypesDepth(h5Reader, taxonName);
newGenos.addTaxon(taxon, genos, depth);
}
newGenos.build();
System.out.println("\n\nFinished adding reference alleles to file:");
System.out.println(" "+outHDF5FileName+"\n\n");
return null;
}
private String populatePositionsWithRefAllele() {
IHDF5Writer h5Writer = HDF5Factory.open(inHDF5FileName);
PositionList oldPosList = PositionListBuilder.getInstance(h5Writer);
// h5Writer.close();
newPosListBuilder = new PositionListBuilder();
if (writePositions) {
String genomeVer = oldPosList.hasReference() ? oldPosList.genomeVersion() : "unkown";
System.out.println("\ncurrent genome version: "+genomeVer+"\n");
System.out.println("SNPID\tchr\tpos\tstr\tmaj\tmin\tref\tmaf\tcov\tcontext");
}
for (Position oldPos : oldPosList) {
int chr = oldPos.getChromosome().getChromosomeNumber();
int pos = oldPos.getPosition();
byte strand = oldPos.getStrand();
byte refAllele = retrieveRefAllele(chr, pos, strand);
if (refAllele == Byte.MIN_VALUE) {
return "\nCould not find position "+pos+" on chromosome "+chr+" in the reference genome fasta file.\n\n\n";
}
Position newPos = new GeneralPosition.Builder(oldPos)
// // previous version only copied chr,pos,strand,CM,SNPID,isNucleotide,isIndel from oldPos
// .maf(oldPos.getGlobalMAF())
// .siteCoverage(oldPos.getGlobalSiteCoverage())
// .allele(Position.Allele.GLBMAJ, oldPos.getAllele(Position.Allele.GLBMAJ))
// .allele(Position.Allele.GLBMIN, oldPos.getAllele(Position.Allele.GLBMIN))
// .allele(Position.Allele.ANC, oldPos.getAllele(Position.Allele.ANC))
// .allele(Position.Allele.HIDEP, oldPos.getAllele(Position.Allele.HIDEP))
.allele(Position.Allele.REF, refAllele)
.build();
if (writePositions) writePosition(newPos, contextSeq);
newPosListBuilder.add(newPos);
}
newPosListBuilder.genomeVersion(genomeVersion);
return null;
}
private byte retrieveRefAllele(int chr, int pos, int strand) {
findChrInRefGenomeFile(chr);
char currChar = findPositionInRefGenomeFile(pos);
if (currPos == pos) {
byte refAllele = NucleotideAlignmentConstants.getNucleotideAlleleByte(currChar);
if (strand == -1) refAllele = NucleotideAlignmentConstants.getNucleotideComplement(refAllele);
return refAllele;
} else {
System.out.println("currPos:"+currPos);
return Byte.MIN_VALUE;
}
}
private void findChrInRefGenomeFile(int chr) {
String temp = "Nothing has been read from the reference genome fasta file yet";
try {
while (refReader.ready() && currChr < chr) {
temp = refReader.readLine().trim();
if (temp.startsWith(">")) {
String chrS = temp.replace(">", "");
chrS = chrS.replace("chr", "");
try {
currChr = Integer.parseInt(chrS);
} catch (NumberFormatException e) {
myLogger.error("\n\nAddReferenceAlleleToHDF5Plugin detected a non-numeric chromosome name in the reference genome sequence fasta file: " + chrS
+ "\n\nPlease change the FASTA headers in your reference genome sequence to integers "
+ "(>1, >2, >3, etc.) OR to 'chr' followed by an integer (>chr1, >chr2, >chr3, etc.)\n\n");
System.exit(1);
}
if (!writePositions) myLogger.info("\nCurrently reading chromosome "+currChr+" from reference genome fasa file\n\n");
}
currPos = 0;
}
} catch (IOException e) {
myLogger.error("Exception caught while reading the reference genome fasta file:\n "+e+"\nLast line read:\n "+temp);
try {Thread.sleep(500);} catch(InterruptedException iE) {}
e.printStackTrace();
System.exit(1);
}
if (currChr != chr) {
myLogger.error("\nCould not find chromosome "+chr+" in the reference genome fasta file.\nMake sure that the chromosomes are in numerical order in that file\n\n\n");
try {Thread.sleep(500);} catch(InterruptedException iE) {}
System.exit(1);
}
}
private char findPositionInRefGenomeFile(int pos) {
char currChar = Character.MAX_VALUE;
contextSeq = "";
try {
while (currPos < pos) {
int intChar = refReader.read();
if (intChar == -1) {
currPos = Integer.MAX_VALUE;
return Character.MAX_VALUE;
}
currChar = (char) intChar;
if (!Character.isWhitespace(currChar)) {
currPos++;
if (pos - currPos < 60) {
contextSeq += currChar;
}
}
}
} catch (IOException e) {
myLogger.error("\n\nError reading reference genome file:\n "+e+"\n\n");
System.exit(1);
}
return currChar;
}
private void writePosition(Position pos, String contextSeq) {
System.out.println(
pos.getSNPID()+
"\t"+pos.getChromosome().getChromosomeNumber()+
"\t"+pos.getPosition()+
"\t"+pos.getStrand()+
"\t"+pos.getAllele(Position.Allele.GLBMAJ)+
"\t"+pos.getAllele(Position.Allele.GLBMIN)+
"\t"+pos.getAllele(Position.Allele.REF)+
"\t"+pos.getGlobalMAF()+
"\t"+pos.getGlobalSiteCoverage()+
"\t"+contextSeq
);
}
@Override
public ImageIcon getIcon() {
// URL imageURL = SeparatePlugin.class.getResource("/net/maizegenetics/analysis/images/Merge.gif");
// if (imageURL == null) {
return null;
// } else {
// return new ImageIcon(imageURL);
// }
}
@Override
public String getButtonName() {
return "Add reference allele";
}
@Override
public String getToolTipText() {
return "Add reference allele to HDF5 genotypes";
}
}
|
package com.example.adi18.blood;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
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.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class Search extends AppCompatActivity
{
private RecyclerView recyclerView;
private BloodAdapter adapter;
private List<Users> userlists;
DatabaseReference Dref;
String message,message2,message3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Bundle bun = this.getIntent().getExtras();
message = bun.getString("City");
message2 = bun.getString("Area");
message3=bun.getString("Blood");
recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
userlists = new ArrayList<>();
adapter=new BloodAdapter(this,userlists);
recyclerView.setAdapter(adapter);
//1. SELECT ALL FROM FOO
Dref=FirebaseDatabase.getInstance().getReference("foo");
//2.SELECT ALL FROM FOO WHERE bloodtype = message3
String bloodtype_area=message3+"_"+message2;
Query query=Dref.orderByChild("bloodtype_area").equalTo(bloodtype_area);
query.addListenerForSingleValueEvent(valueEventListener);
}
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
userlists.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Users artist = snapshot.getValue(Users.class);
userlists.add(artist);
}
adapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
}
|
package com.example.Library.mapper;
import com.example.Library.domain.Resources;
import com.example.Library.dto.ResourcesDTO;
import com.example.Library.repository.ResourcesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
public class RecursosMapper {
public Resources fromDTO(ResourcesDTO resourcesDTO){
Resources resources = new Resources();
resources.setResourceId(resourcesDTO.getResourceId());
resources.setTypeOfResource(resourcesDTO.getTypeOfResource());
resources.setTypeOfThematic(resourcesDTO.getTypeOfThematic());
resources.setAvailable(resourcesDTO.getAvailable());
resources.setLoanDate(resourcesDTO.getLoanDate());
return resources;
}
public ResourcesDTO fromEntity(Resources resources){
ResourcesDTO resourcesDTO = new ResourcesDTO();
resourcesDTO.setResourceId(resources.getResourceId());
resourcesDTO.setTypeOfResource(resources.getTypeOfResource());
resourcesDTO.setTypeOfThematic(resources.getTypeOfThematic());
resourcesDTO.setAvailable(resources.getAvailable());
resourcesDTO.setLoanDate(resources.getLoanDate());
return resourcesDTO;
}
public List<ResourcesDTO> fromEntityList(List<Resources> entity){
if(entity == null){
throw new IllegalArgumentException("Recursos vacíos");
}
List<ResourcesDTO> list = new ArrayList<>(entity.size());
Iterator listIterator = entity.iterator();
while (listIterator.hasNext()){
Resources resources = (Resources)listIterator.next();
list.add(fromEntity(resources));
}
return list;
}
}
|
package kafka2jdbc;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.types.Row;
import constants.FlinkSqlConstants;
public class UnboundedKafkaJoinJdbc2Jdbc {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
EnvironmentSettings envSettings = EnvironmentSettings.newInstance()
.useBlinkPlanner()
.inStreamingMode()
.build();
StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env, envSettings);
tableEnvironment.registerFunction("add_one_fun", new AddOneFunc());
tableEnvironment.sqlUpdate(FlinkSqlConstants.ordersTableDDL);
tableEnvironment.sqlUpdate(FlinkSqlConstants.mysqlCurrencyDDL);
String sinkTableDDL = "CREATE TABLE gmv (\n" +
" log_per_min STRING,\n" +
" item STRING,\n" +
" order_cnt BIGINT,\n" +
" currency_time TIMESTAMP(3),\n" +
" gmv DECIMAL(38, 18)," +
" timestamp9 TIMESTAMP(3),\n" +
" time9 TIME(3),\n" +
" gdp DECIMAL(38, 18)\n" +
") WITH (\n" +
" 'connector.type' = 'jdbc',\n" +
" 'connector.url' = 'jdbc:mysql://localhost:3306/test',\n" +
" 'connector.username' = 'root'," +
" 'connector.table' = 'gmv',\n" +
" 'connector.driver' = 'com.mysql.jdbc.Driver',\n" +
" 'connector.write.flush.max-rows' = '5000', \n" +
" 'connector.write.flush.interval' = '2s', \n" +
" 'connector.write.max-retries' = '3'" +
")";
tableEnvironment.sqlUpdate(sinkTableDDL);
String querySQL = "insert into gmv \n" +
"select max(log_ts),\n" +
" item, COUNT(order_id) as order_cnt, max(currency_time), cast(sum(amount_kg) * max(rate) as DOUBLE) as gmv,\n" +
" max(timestamp9), max(time9), max(gdp) \n" +
" from ( \n" +
" select cast(o.ts as VARCHAR) as log_ts, o.item as item, o.order_id as order_id, c.currency_time as currency_time,\n" +
" o.amount_kg as amount_kg, c.rate as rate, c.timestamp9 as timestamp9, c.time9 as time9, c.gdp as gdp \n" +
" from orders as o \n" +
" join currency FOR SYSTEM_TIME AS OF o.proc_time c \n" +
" on o.currency = c.currency_name \n" +
" ) a group by item\n" ;
System.out.println(FlinkSqlConstants.ordersTableDDL);
System.out.println(FlinkSqlConstants.mysqlCurrencyDDL);
System.out.println(sinkTableDDL);
System.out.println(querySQL);
// tableEnvironment.toRetractStream(tableEnvironment.sqlQuery(querySQL), Row.class).print();
tableEnvironment.sqlUpdate(querySQL);
tableEnvironment.execute("KafkaJoinJdbc2Jdbc");
}
public static class AddOneFunc extends ScalarFunction {
public Long eval(long t) {
return t + 1;
}
public TypeInformation<?> getResultType(Class<?>[] signature) {
return Types.LONG;
}
}
}
|
package com.ebanq.web.tests;
import com.ebanq.web.tests.base.BaseTest;
import org.testng.annotations.Test;
public class LoginTest extends BaseTest {
@Test(description = "Sign In")
public void loginTest() {
loginSteps.logIn(testData.ADMIN_USER, testData.ADMIN_PASS);
loginSteps.logOut();
}
}
|
package com.fanfte.map;
import java.util.HashMap;
import java.util.Map;
public class TestHashMap {
String name;
public TestHashMap(String name) {
this.name = name;
}
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("aaa", "111");
map.put("aaa", "222");
System.out.println(map);
}
}
|
package com.yidatec.weixin.message;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* 用户24小时内没有反馈,发送请求已被关闭的消息
* @author tony
*
*/
public class SendCloseMessageQuartz {
private static final Logger log = LogManager.getLogger(SendCloseMessageQuartz.class);
SendCloseMessage sendCloseMessage;
public void setSendCloseMessage(SendCloseMessage sendCloseMessage) {
this.sendCloseMessage = sendCloseMessage;
}
public void work() {
try {
sendCloseMessage.SendClose();
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
}
|
package scut218.pisces.adapters.holder;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import scut218.pisces.R;
import scut218.pisces.base.MyApplication;
import scut218.pisces.beans.Comment;
import scut218.pisces.beans.Moment;
import scut218.pisces.factory.UtilFactory;
import scut218.pisces.utils.MomentUtil;
import scut218.pisces.utils.UserUtil;
import scut218.pisces.utils.impl.ImageUtil;
import scut218.pisces.utils.impl.MomentUtilImpl;
import scut218.pisces.widget.CommentListView;
import scut218.pisces.widget.EditTextPopupWindow;
import scut218.pisces.widget.SnsPopupWindow;
/**
* Created by Leebobo on 2017/5/3.
*/
public abstract class BaseViewHolder extends RecyclerView.ViewHolder {
public final static int TYPE_TEXT = 0;
public final static int TYPE_IMAGE = 1;
public View view;
public int viewType;
public ImageView head;
public TextView name,time,location,imfor;
public TextView deleteBtn;
public ImageView snsBtn;
public LinearLayout commentBody;
//评论列表
public CommentListView commentListView;
//弹出窗口
public SnsPopupWindow popupWindow;
//评论窗口
public EditTextPopupWindow editTextPopupWindow;
public BaseViewHolder(View itemView, int type) {
super(itemView);
view=itemView;
this.viewType=type;
initImage(viewType,view);
head=(ImageView)itemView.findViewById(R.id.headIv);
name=(TextView)itemView.findViewById(R.id.nameTv);
time=(TextView)itemView.findViewById(R.id.timeTv);
location=(TextView)itemView.findViewById(R.id.locationTv);
imfor=(TextView)itemView.findViewById(R.id.imforTv);
deleteBtn=(TextView)itemView.findViewById(R.id.deleteBtn);
snsBtn=(ImageView)itemView.findViewById(R.id.snsBtn);
commentBody=(LinearLayout)itemView.findViewById(R.id.CommentBody);
commentListView=(CommentListView)itemView.findViewById(R.id.commentList);
popupWindow=new SnsPopupWindow(itemView.getContext());
editTextPopupWindow=new EditTextPopupWindow(itemView.getContext());
}
public abstract void initImage(int viewType,View view);
public void setData(Moment moment){
viewType=Integer.valueOf(moment.getType());
imfor.setText(moment.getText());
name.setText(moment.getAuthorId());
location.setText(moment.getLocation());
time.setText(moment.getTime().toString());
commentBody.setVisibility(View.VISIBLE);
//加载头像
ImageUtil.loadIcon(this.head,moment.getAuthorId());
//删除按钮
if(moment.getAuthorId()== UtilFactory.getUserUtil().getMyId()) {
deleteBtn.setVisibility(View.VISIBLE);
}
List<Comment> comments;
if((comments=MomentUtilImpl.commentMap.get(moment.getId()))!=null)
{
commentListView.setVisibility(View.VISIBLE);
setCommentListView((ArrayList)comments);
}
}
public void initPopupWindow(final int tid) {
snsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
popupWindow.showPopupWindow(view);
}
});
popupWindow.setItemClickListener(new PopupItemClickListener(tid));
}
public void setCommentListView(final ArrayList<Comment> list){
commentListView.notifyDataSetChanged(list);
commentListView.setOnItemClickListener(new CommentListView.OnItemClickListener() {
@Override
public void onItemClick(int position) {
//评论
}
});
commentListView.setOnSpanClickListener(new CommentListView.OnSpanClickListener() {
@Override
public void onSpanClick(int position) {
//StartMemberActivity(list.get(position).getUser().getUid());
}
});
}
private class PopupItemClickListener implements SnsPopupWindow.OnItemClickListener{
private long lasttime = 0;
private int tid;
public PopupItemClickListener(final int tid){
this.tid=tid;
}
@Override
public void onItemClick(SnsPopupWindow.ActionItem actionitem, int position) {
lasttime = System.currentTimeMillis();
editTextPopupWindow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.commentEt:
break;
case R.id.sendBtn:
String text=editTextPopupWindow.getComment();
if (text!=null)
{
MomentUtil momentUtil=UtilFactory.getMomentUtil();
Comment comment=new Comment();
comment.setTime(new Timestamp(new Date().getTime()));
comment.setType(1);//不是回复
comment.setReplyUserId("no");
comment.setmId(tid);
comment.setUserId(UtilFactory.getUserUtil().getMyId());
comment.setText(text);
momentUtil.addComment(comment);
setCommentListView((ArrayList<Comment>)MomentUtilImpl.commentMap.get(tid));
}
break;
default:break;
}
}
});
editTextPopupWindow.showPopupWindow(view);
}
}
private void StartMemberActivity(final int uid){
Intent intent=new Intent();
Activity curActivity=(Activity)view.getContext();
//intent.setClass(curActivity, MemberActivity.class);
intent.putExtra("uid",""+uid);
curActivity.startActivity(intent);
}
}
|
package negocio.controlador;
// Generated 24/09/2012 21:42:05 by Hibernate Tools 3.2.0.CR1
import hibernate.util.HibernateUtil;
import java.util.List;
import negocio.basica.Tipochamado;
import negocio.repositorio.RepositorioTipoChamado;
/**
* Interface Service da entidade Tipochamado.
* @see negocio.controlador.Tipochamado
* @author Thiago Ribeiro Tavares
*/
public class ControladorTipochamado {
private RepositorioTipoChamado repositorio = new RepositorioTipoChamado();
public ControladorTipochamado(){
}
public void incluir(Tipochamado pTipochamado){
try {
System.out.println("Incluindo o Tipochamado...");
//Abrindo transação com o banco de dados
HibernateUtil.beginTransaction();
//Salvando um objeto do tipo Tipochamado na sessão aberta
repositorio.incluir(pTipochamado);
//Efetuando um commit na transação (aqui, as informações são persistidas "de fato")
HibernateUtil.commitTransaction();
System.out.println("Inclusão de Tipochamado realizada com sucesso...");
} catch (Exception e) {
HibernateUtil.rollbackTransaction();
throw new RuntimeException("Erro ao tentar incluir Tipochamado",e);
}
}
public void alterar(Tipochamado pTipochamado){
try {
System.out.println("Alterando o Tipochamado...");
//Abrindo transação com o banco de dados
HibernateUtil.beginTransaction();
//Alterando um objeto do tipo Tipochamado na sessão aberta
repositorio.alterar(pTipochamado);
//Efetuando um commit na transação (aqui, as informações são persistidas "de fato")
HibernateUtil.commitTransaction();
System.out.println("Alteração de Tipochamado realizada com sucesso...");
} catch (Exception e) {
HibernateUtil.rollbackTransaction();
throw new RuntimeException("Erro ao tentar alterar Tipochamado",e);
}
}
public void remover(Tipochamado pTipochamado){
try {
System.out.println("Removendo o Tipochamado...");
//Abrindo transação com o banco de dados
HibernateUtil.beginTransaction();
//Removendo um objeto do tipo Tipochamado na sessão aberta
repositorio.remover(pTipochamado);
//Efetuando um commit na transação (aqui, as informações são persistidas "de fato")
HibernateUtil.commitTransaction();
System.out.println("Remoção de Tipochamado realizada com sucesso...");
} catch (Exception e) {
HibernateUtil.rollbackTransaction();
throw new RuntimeException("Erro ao tentar Remover Tipochamado",e);
}
}
public Tipochamado consultarPorChavePrimaria(Tipochamado pTipochamado){
try {
System.out.println("Consultando Tipochamado por chave primária");
Object id = pTipochamado.getId();
//Abrindo transação com o banco de dados
HibernateUtil.beginTransaction();
//Consultando objeto do tipo Tipochamado por chave primária na sessão aberta
pTipochamado = repositorio.consultarPorChavePrimaria(pTipochamado);
//Efetuando um commit na transação (aqui, as informações são persistidas "de fato")
HibernateUtil.commitTransaction();
if (pTipochamado == null)
throw new RuntimeException("Registro não encontrado");
System.out.println("Consulta por chave primária de Tipochamado realizada com sucesso...");
return pTipochamado;
} catch (Exception e) {
HibernateUtil.rollbackTransaction();
throw new RuntimeException("Erro ao tentar Consultar Tipochamado por chave Primária",e);
}
}
public List<Tipochamado> listar(){
List<Tipochamado> retorno;
try {
System.out.println("Consultando Tipochamado por chave primária");
//Abrindo transação com o banco de dados
HibernateUtil.beginTransaction();
//Consultando objeto do tipo Tipochamado por chave primária na sessão aberta
retorno = repositorio.listar();
//Efetuando um commit na transação (aqui, as informações são persistidas "de fato")
HibernateUtil.commitTransaction();
System.out.println("Consulta por chave primária de Tipochamado realizada com sucesso...");
} catch (Exception e) {
HibernateUtil.rollbackTransaction();
throw new RuntimeException("Erro ao tentar Consultar Tipochamado por chave Primária",e);
}
return retorno;
}
}
|
package com.example.android.nusevents;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.android.nusevents.model.ActiveListDetailsActivity;
import com.example.android.nusevents.model.BookmarkDetails;
import com.example.android.nusevents.model.EventInfo;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.List;
import static com.example.android.nusevents.DisplayEventList.event_contact;
import static com.example.android.nusevents.DisplayEventList.event_count;
import static com.example.android.nusevents.DisplayEventList.event_time2;
public class BookmarkList extends AppCompatActivity {
ListView listViewEvents;
List<EventInfo> eventlist;
public static final String event_name="EVENT NAME";
public static final String event_id="id";
public static final String event_own="owner";
public static final String event_loc="location";
public static final String event_time="time";
public static final String event_time2="time2";
public static final String event_info="About";
public static final String event_userid="lol";
public static final String event_contact1="lolol";
public static final String event_num="num";
public static final String date1="date11";
DatabaseReference databaseReferenceEvents;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_event_list);
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser currUser= mAuth.getCurrentUser();
final String userid = currUser.getUid();
eventlist = new ArrayList<>();
databaseReferenceEvents = FirebaseDatabase.getInstance().getReference().child("Bookmark").child(userid);
databaseReferenceEvents.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot eventsnap: dataSnapshot.getChildren()) {
EventInfo temp= eventsnap.getValue(EventInfo.class);
if(temp.getTime()<System.currentTimeMillis()) {
databaseReferenceEvents.child(eventsnap.getKey()).removeValue();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
listViewEvents = (ListView) findViewById(R.id.list);
listViewEvents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EventInfo mevents = eventlist.get(position);
Intent i = new Intent(getApplicationContext(),BookmarkDetails.class);
i.putExtra(event_id,mevents.getId());
i.putExtra(event_name,mevents.getName());
i.putExtra(event_info,mevents.getInfo());
i.putExtra(event_loc,mevents.getLocation());
i.putExtra(event_own,mevents.getOwner());
i.putExtra(event_time,mevents.getTime());
i.putExtra(event_userid,mevents.getUserCreated());
i.putExtra(event_time2,mevents.getFinishTime());
i.putExtra(event_contact1,mevents.getContact());
i.putExtra(event_num,mevents.getCount());
i.putExtra(date1,mevents.getDate());
i.putExtra("image1",mevents.getPhotoUri());
i.putExtra("check1",mevents.getFree());
i.putExtra("check2",mevents.getLink());
i.putExtra("goodie",mevents.getGoodie());
i.putExtra("snacks",mevents.getSnacks());
startActivity(i);
}
});
}
@Override
protected void onStart() {
super.onStart();
databaseReferenceEvents.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
eventlist.clear();
for(DataSnapshot eventsnap: dataSnapshot.getChildren())
{
EventInfo event = eventsnap.getValue(EventInfo.class);
eventlist.add(event);
}
for(int i=0;i<eventlist.size();i++)
{
for(int j=1;j<eventlist.size();j++)
{
if(eventlist.get(j-1).getTime()>eventlist.get(j).getTime())
{
EventInfo temp=eventlist.get(j-1);
eventlist.set(j-1,eventlist.get(j));
eventlist.set(j,temp);
}
}
}
EventsList adapter = new EventsList(BookmarkList.this,eventlist);
listViewEvents.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
|
package com.ecej.nove.base.monitor;
import com.alibaba.dubbo.common.URL;
import com.ecej.nove.base.kafka.SimpleKafkaProducer;
import com.ecej.nove.base.locks.NoveZkSessionManager;
import com.ecej.nove.utils.common.PropertyConfigUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 用于生成必要的KAFKA客户端,并监控ZK状态
* QIANG
*/
public class NoveDubboMonitorFactory extends AbstractNoveMonitorFactory {
private Logger LOG = LoggerFactory.getLogger(NoveDubboMonitorFactory.class);
protected final Watcher monitorWatch;
private AtomicInteger count = new AtomicInteger();
protected final static String NOVE_MONITOR = "/noveMonitor";
public NoveDubboMonitorFactory() {
this.monitorWatch = new MonitorWatch();
}
@Override
protected NoveMonitor createMonitor(URL url) {
String connectionString = PropertyConfigUtils.getProperty("zookeeper.connect");
if (StringUtils.isEmpty(connectionString)) {
return null;
}
NoveZkSessionManager noveZkSessionManager = new NoveZkSessionManager(connectionString.trim(), 30000);
ZooKeeper zk = noveZkSessionManager.getZooKeeper();
SimpleKafkaProducer simpleKafkaProducer = null;
try {
List<String> nodes = zk.getChildren(NOVE_MONITOR, this.monitorWatch);
if (nodes == null || nodes.size() == 0) {
return null;
}
simpleKafkaProducer = new SimpleKafkaProducer(nodes.get(0));
} catch (Exception e) {
if(count.get() <10){
LOG.warn("NoveDubboMonitorFactory创建NoveMonitor出现异常:[{}],持续错误数:【{}】", e.getMessage(),count.get());
count.incrementAndGet();
}
return null;
} finally {
if (noveZkSessionManager != null) {
noveZkSessionManager.closeSession();
}
}
return new NoveDubboMonitor(simpleKafkaProducer);
}
private static class MonitorWatch implements Watcher {
@Override
public void process(WatchedEvent event) {
//TODO 等待扩展
}
}
}
|
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Map;
/**
* Created by futer25 on 27.04.2017.
*/
public class App {
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public ConsoleEventLogger getEventLogger() {
return eventLogger;
}
public void setEventLogger(ConsoleEventLogger eventLogger) {
this.eventLogger = eventLogger;
}
public App(Client client, ConsoleEventLogger eventLogger, Map<EventType, EventLogger> loggers) {
this.client = client;
this.eventLogger = eventLogger;
this.loggers = loggers;
}
private Client client;
private ConsoleEventLogger eventLogger;
private Map<EventType, EventLogger> loggers;
private void logEvent(EventType type, String msg) {
EventLogger logger = loggers.get(type);
if (logger == null) {
logger = loggers.get(EventType.ERROR);
}
logger.logEvent(event);
}
public static void main(String[] args) {
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
App app = (App) ctx.getBean("app");
app.logEvent(EventType.ERROR,"sdfsdfsd");
app.logEvent(EventType.INFO,"sdfsdfsd");
app.logEvent(null,"sdfsdfsd");
ctx.close();
}
}
|
package com.blueware.agent;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.AdviceAdapter;
//定义扫描待修改class的visitor,visitor就是访问者模式
public class TimeClassVisitor extends ClassVisitor {
public static final String EXCLUSIVETIME_NAME = Type.getDescriptor(ExclusiveTime.class);
public static String SETSTARTTIME_DESC;
public static String SETENDTIME_DESC;
public static String GETEXCLUSIVETIME_DESC;
public static String TIMEUTIL_NAME;
static {
try {
SETSTARTTIME_DESC = Type.getMethodDescriptor(TimeUtil.class.getMethod("setStartTime", String.class));
SETENDTIME_DESC = Type.getMethodDescriptor(TimeUtil.class.getMethod("setEndTime", String.class));
GETEXCLUSIVETIME_DESC = Type.getMethodDescriptor(TimeUtil.class.getMethod("getExclusiveTime", String.class, String.class, String.class));
TIMEUTIL_NAME = Type.getInternalName(TimeUtil.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
private String className;
private String annotationDesc;
public TimeClassVisitor(ClassVisitor cv, String className) {
super(Opcodes.ASM5, cv);
this.className = className;
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
this.annotationDesc = desc;
return super.visitAnnotation(desc, visible);
}
//扫描到每个方法都会进入,参数详情下一篇博文详细分析
@Override
public MethodVisitor visitMethod(int access, final String name, final String desc, String signature, String[] exceptions) {
MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
if (annotationDesc != null && annotationDesc.equals(EXCLUSIVETIME_NAME)) {
final String key = className + name + desc;
//过来待修改类的构造函数
if (!name.equals("<init>") && mv != null) {
mv = new AdviceAdapter(Opcodes.ASM5, mv, access, name, desc) {
//方法进入时获取开始时间
@Override
public void onMethodEnter() {
//向栈中压入key,传参
this.visitLdcInsn(key);
this.visitMethodInsn(Opcodes.INVOKESTATIC, TIMEUTIL_NAME, "setStartTime", SETSTARTTIME_DESC, false);
}
//方法退出时获取结束时间并计算执行时间
@Override
public void onMethodExit(int opcode) {
//向栈中压入key,传参
this.visitLdcInsn(key);
this.visitMethodInsn(Opcodes.INVOKESTATIC, TIMEUTIL_NAME, "setEndTime", SETENDTIME_DESC, false);
//向栈中压入类名、方法名、方法描述,传参
this.visitLdcInsn(className);
this.visitLdcInsn(name);
this.visitLdcInsn(desc);
this.visitMethodInsn(Opcodes.INVOKESTATIC, TIMEUTIL_NAME, "getExclusiveTime", GETEXCLUSIVETIME_DESC, false);
}
};
}
}
return mv;
}
}
|
package zda.task.webchat;
import org.junit.Before;
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.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import zda.task.webchat.config.RoleConfig;
import zda.task.webchat.model.*;
import zda.task.webchat.service.Converter;
import zda.task.webchat.service.UserService;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
/**
* Test for Converter
*
* @author Zhevnov D.A.
* @ created 2020-08-08
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class ConverterTests {
@Autowired
public Converter converter;
@MockBean
private UserService userService;
@MockBean
private RoleConfig roleConfig;
public ChatMessage chatMessage;
public ChatMessageDto chatMessageDto;
public User user;
@Before
public void setUp() {
user = new User("User1", "password", "password");
chatMessage= new ChatMessage(MessageType.CHAT, "Привет!", user);
chatMessageDto = new ChatMessageDto(MessageType.CHAT, "Привет!", "User1");
given(userService.isRoleExists(any())).willReturn(true);
given(userService.findUserByUsername("User1")).willReturn(user);
given(userService.findUserByUsername("User1")).willReturn(user);
}
@Test
public void givenChatMessage_whenConvertChatMessage_thenGetChatMessageDto() {
ChatMessageDto newChatMessageDto = converter.toChatMessageDto(chatMessage);
assertEquals(newChatMessageDto.getUsername(), chatMessageDto.getUsername());
assertEquals(newChatMessageDto.getType(), chatMessageDto.getType());
assertEquals(newChatMessageDto.getMessage(),chatMessageDto.getMessage());
}
@Test
public void givenChatMessageDto_whenConvertChatMessageDto_thenGetChatMessage() {
ChatMessage newChatMessage = converter.toChatMessage(chatMessageDto);
assertEquals(newChatMessage.getUser().getUsername(),chatMessage.getUser().getUsername());
assertEquals(newChatMessage.getType(), chatMessage.getType());
assertEquals(newChatMessage.getMessage(), chatMessage.getMessage());
}
}
|
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
try {
shortstorywrite.read(1441);
} catch (com.company.story story) {
story.printStackTrace();
}
}
}
|
package com.scf.web.webservice.param.extend;
import java.io.Serializable;
import com.scf.utils.JacksonObjectMapper;
import com.scf.web.webservice.param.InputParameter;
/**
* 系统间webservice接口输入参数,只含有一个参数:one
*
* @author wubin
*/
public class InputParameterBasic<One> extends InputParameter implements Serializable
{
private static final long serialVersionUID = 3613126383711929421L;
private One conditionOne ; //第一个条件
public One getConditionOne() {
return conditionOne;
}
public void setConditionOne(One conditionO) {
this.conditionOne = conditionO;
}
@Override
public String toString()
{
return JacksonObjectMapper.toJsonString(this);
}
}
|
public class Loader2 {
public static void main(String[] args) {
String phone1 = "+7 900 764-33-04";
String phone2 = "+7 (900) 764-33-04";
String phone3 = "7-900-764-33-04";
String phone4 = "7(900)7643304";
System.out.println(formatPhoneNumber(phone1));
System.out.println(formatPhoneNumber(phone2));
System.out.println(formatPhoneNumber(phone3));
System.out.println(formatPhoneNumber(phone4));
}
// 79007643304
public static String formatPhoneNumber(String phone) {
String regex = "[^0-9]";
return phone.replaceAll(regex, "");
}
}
|
package com.mars.main;
import com.mars.route.StringlJsonRouteBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.main.Main;
/**
* A Camel Application
*/
@Slf4j
public class MainApp {
/**
* A main() so we can easily run these routing rules in our IDE
*/
public static void main(String... args) throws Exception {
// CamelContext context = new DefaultCamelContext(); // (1)
// context.addRoutes(new RouteBuilder() { // (2)
// @Override
// public void configure() {
// from("direct:foo") // (3)
// .to("log:MyCategory"); // (4)
// }
// });
// context.start();
// context.createProducerTemplate().sendBody("direct:foo", "Hello, World!"); // (5)
// CamelContext ctx = new DefaultCamelContext();
// ctx.addRoutes(new RouteBuilder() {
// @Override
// public void configure() throws Exception {
// from("direct:start")
// .to("log:end?level=INFO");
// }
// });
// ctx.start();
// log.info("Camel Server start");
// ctx.createProducerTemplate().sendBody("direct:start", "Hello, world! ");
// ctx.stop();
// log.info("Camel Server Stop");
Main m = new Main();
// m.addRouteBuilder(new StreamTestRouteBuilder());
m.addRouteBuilder(new StringlJsonRouteBuilder());
m.run();
}
}
|
package com.example.qobel.organizator.network;
import com.google.gson.annotations.SerializedName;
/**
* Created by qobel on 3.07.2017.
*/
public class Status {
@SerializedName("Response")
private String response;
@SerializedName("Error")
private String error;
public String getResponse() {
return response;
}
public String getError() {
return error;
}
}
|
/*
* Application: Credit Card Management Service
*/
package com.mcp.ccard.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* The Class AddressEntity.
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = "Address")
public class AddressEntity {
/** The id. */
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/** The door no. */
private String doorNo;
/** The street name. */
private String streetName;
/** The city. */
private String city;
/** The state. */
private String state;
/** The country. */
private String country;
/** The zip code. */
private String zipCode;
/** The address type. */
private String addressType;
}
|
package com.yxkj.facexradix.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import com.yxkj.facexradix.R;
public class Keyboard extends LinearLayout implements View.OnClickListener {
private ImageButton sw1;
private ImageButton sw2;
private ImageButton delete;
private Button done;
private Button Punctuation;
private Button key1;
private Button key2;
private Button key3;
private Button key4;
private Button key5;
private Button key6;
private Button key7;
private Button key8;
private Button key9;
private Button key10;
private Button key11;
private Button key12;
private Button key13;
private Button key14;
private Button key15;
private Button key16;
private Button key17;
private Button key18;
private Button key19;
private Button key20;
private Button key21;
private Button key22;
private Button key23;
private Button key24;
private Button key25;
private Button key26;
private Button key27;
private Button key28;
private Button key29;
private Button key30;
private Button key31;
private Button key32;
private boolean isShift = false;
private boolean isPunctuation = false;
private final Context context;
private View inflate;
private KeyboardListener keyboardListener;
private EditText editText;
public Keyboard(Context context) {
super(context);
this.context = context;
initView();
}
public Keyboard(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
initView();
}
public Keyboard(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
initView();
}
private void initView() {
inflate = LayoutInflater.from(context).inflate(R.layout.keyboard_view, this);
findview();
}
public void switchKey() {
if(!isShift) {
key1.setText("Q");
key2.setText("W");
key3.setText("E");
key4.setText("R");
key5.setText("T");
key6.setText("Y");
key7.setText("U");
key8.setText("I");
key9.setText("O");
key10.setText("P");
key11.setText("A");
key12.setText("S");
key13.setText("D");
key14.setText("F");
key15.setText("G");
key16.setText("H");
key17.setText("J");
key18.setText("K");
key19.setText("L");
key20.setText("Z");
key21.setText("X");
key22.setText("C");
key23.setText("V");
key24.setText("B");
key25.setText("N");
key26.setText("M");
isShift = true;
}else{
key1.setText("q");
key2.setText("w");
key3.setText("e");
key4.setText("r");
key5.setText("t");
key6.setText("y");
key7.setText("u");
key8.setText("i");
key9.setText("o");
key10.setText("p");
key11.setText("a");
key12.setText("s");
key13.setText("d");
key14.setText("f");
key15.setText("g");
key16.setText("h");
key17.setText("j");
key18.setText("k");
key19.setText("l");
key20.setText("z");
key21.setText("x");
key22.setText("c");
key23.setText("v");
key24.setText("b");
key25.setText("n");
key26.setText("m");
isShift = false;
}
isPunctuation = false;
}
public void punctuation() {
if (!isPunctuation) {
key1.setText("1");
key2.setText("2");
key3.setText("3");
key4.setText("4");
key5.setText("5");
key6.setText("6");
key7.setText("7");
key8.setText("8");
key9.setText("9");
key10.setText("0");
key11.setText("@");
key12.setText("#");
key13.setText("$");
key14.setText("%");
key15.setText("&");
key16.setText("-");
key17.setText("+");
key18.setText("(");
key19.setText(")");
key20.setText("\\");
key21.setText("=");
key22.setText("*");
key23.setText("\"");
key24.setText("'");
key25.setText(":");
key26.setText(";");
isPunctuation = true;
}else{
key1.setText("q");
key2.setText("w");
key3.setText("e");
key4.setText("r");
key5.setText("t");
key6.setText("y");
key7.setText("u");
key8.setText("i");
key9.setText("o");
key10.setText("p");
key11.setText("a");
key12.setText("s");
key13.setText("d");
key14.setText("f");
key15.setText("g");
key16.setText("h");
key17.setText("j");
key18.setText("k");
key19.setText("l");
key20.setText("z");
key21.setText("x");
key22.setText("c");
key23.setText("v");
key24.setText("b");
key25.setText("n");
key26.setText("m");
isPunctuation = false;
}
isShift = false;
}
public void delete() {
keyboardListener.onDelete();
}
public void done() {
keyboardListener.onDone();
}
private void findview() {
sw1 = findViewById(R.id.sw1);
sw1.setOnClickListener(this);
sw2 = findViewById(R.id.sw2);
sw2.setOnClickListener(this);
delete = findViewById(R.id.delete);
delete.setOnClickListener(this);
done = findViewById(R.id.done);
done.setOnClickListener(this);
Punctuation = findViewById(R.id.Punctuation);
Punctuation.setOnClickListener(this);
key1 = findViewById(R.id.key1);
key1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key1.getText());
Log.e("Key", key1.getText().toString());
}
});
key2 = findViewById(R.id.key2);
key2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key2.getText());
Log.e("Key", key2.getText().toString());
}
});
key3 = findViewById(R.id.key3);
key3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key3.getText());
Log.e("Key", key3.getText().toString());
}
});
key4 = findViewById(R.id.key4);
key4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key4.getText());
Log.e("Key", key4.getText().toString());
}
});
key5 = findViewById(R.id.key5);
key5.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key5.getText());
Log.e("Key", key5.getText().toString());
}
});
key6 = findViewById(R.id.key6);
key6.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key6.getText());
Log.e("Key", key6.getText().toString());
}
});
key7 = findViewById(R.id.key7);
key7.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key7.getText());
Log.e("Key", key7.getText().toString());
}
});
key8 = findViewById(R.id.key8);
key8.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key8.getText());
Log.e("Key", key8.getText().toString());
}
});
key9 = findViewById(R.id.key9);
key9.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key9.getText());
Log.e("Key", key9.getText().toString());
}
});
key10 = findViewById(R.id.key10);
key10.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key10.getText());
Log.e("Key", key10.getText().toString());
}
});
key11 = findViewById(R.id.key11);
key11.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key11.getText());
Log.e("Key", key11.getText().toString());
}
});
key12 = findViewById(R.id.key12);
key12.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key12.getText());
Log.e("Key", key12.getText().toString());
}
});
key13 = findViewById(R.id.key13);
key13.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key13.getText());
Log.e("Key", key13.getText().toString());
}
});
key14 = findViewById(R.id.key14);
key14.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key14.getText());
Log.e("Key", key14.getText().toString());
}
});
key15 = findViewById(R.id.key15);
key15.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key15.getText());
Log.e("Key", key15.getText().toString());
}
});
key16 = findViewById(R.id.key16);
key16.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key16.getText());
Log.e("Key", key16.getText().toString());
}
});
key17 = findViewById(R.id.key17);
key17.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key17.getText());
Log.e("Key", key17.getText().toString());
}
});
key18 = findViewById(R.id.key18);
key18.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key18.getText());
Log.e("Key", key18.getText().toString());
}
});
key19 = findViewById(R.id.key19);
key19.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key19.getText());
Log.e("Key", key19.getText().toString());
}
});
key20 = findViewById(R.id.key20);
key20.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key20.getText());
Log.e("Key", key20.getText().toString());
}
});
key21 = findViewById(R.id.key21);
key21.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key21.getText());
Log.e("Key", key21.getText().toString());
}
});
key22 = findViewById(R.id.key22);
key22.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key22.getText());
Log.e("Key", key22.getText().toString());
}
});
key23 = findViewById(R.id.key23);
key23.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key23.getText());
Log.e("Key", key23.getText().toString());
}
});
key24 = findViewById(R.id.key24);
key24.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key24.getText());
Log.e("Key", key24.getText().toString());
}
});
key25 = findViewById(R.id.key25);
key25.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key25.getText());
Log.e("Key", key25.getText().toString());
}
});
key26 = findViewById(R.id.key26);
key26.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key26.getText());
Log.e("Key", key26.getText().toString());
}
});
key27 = findViewById(R.id.key27);
key27.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key27.getText());
Log.e("Key", key27.getText().toString());
}
});
key28 = findViewById(R.id.key28);
key28.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key28.getText());
Log.e("Key", key28.getText().toString());
}
});
key29 = findViewById(R.id.key29);
key29.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key29.getText());
Log.e("Key", key29.getText().toString());
}
});
key30 = findViewById(R.id.key30);
key30.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key30.getText());
Log.e("Key", key30.getText().toString());
}
});
key31 = findViewById(R.id.key31);
key31.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key31.getText());
Log.e("Key", key31.getText().toString());
}
});
key32 = findViewById(R.id.key32);
key32.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
keyboardListener.onKey(key32.getText());
Log.e("Key", key32.getText().toString());
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sw1:
switchKey();
break;
case R.id.sw2:
switchKey();
break;
case R.id.Punctuation:
punctuation();
break;
case R.id.delete:
delete();
break;
case R.id.done:
done();
break;
}
}
public void setOnkeyboardListener(KeyboardListener keyboardListener) {
this.keyboardListener = keyboardListener;
}
public void setEditText(EditText editText) {
this.editText = editText;
}
}
|
/**
*
*/
package practice.com.example;
/**
* @author SAMSUNG
*
*/
public class Test {
/**
*
*/
public Test() {
// TODO Auto-generated constructor stub
}
private static int stringReverse(String s) {
// TODO Auto-generated method stub
//System.out.println(s);
int i;
int count = 0;
for(i=0 ; i < s.length() ; i++) {
char ch=s.charAt(i);
if(ch==' ')
//System.out.println(count++);
count++;
}
return count;
}
private static int stringRev(String s) {
// TODO Auto-generated method stub
//System.out.println(s);
int i;
int count = 0;
String rev = null;
for(i=s.length()-1 ; i>=0 ; i--) {
char ch=s.charAt(i);
if(ch==' ')
System.out.println(rev.substring(i, i));
count++;
}
return count;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "My Name Is Puneet";
System.out.println(stringReverse(s));
System.out.println(stringRev(s));
}
}
|
package businesslogicservice.creditblservice;
import util.ResultMessage;
import vo.CreditVO;
import vo.OrderVO;
import java.util.List;
/**
* Created by 段梦洋 on 2016/11/6.
*/
//与界面层交互的接口
public interface CreditBLservice {
public List<CreditVO> getCustomerCreditInfo(String userName);
public double getNumCredit(String userName);
/**
* 信用充值
* @param userName
* @param creditChange
*/
public void increaseCredit(String userName, int creditChange);
/**
* 如果是重值等没有OrderVO的操作产生的信用值变化
* 则orderVO传入NUll
* @param userName
* @param creditVO
* @param orderVO
* @return
*/
public ResultMessage updateCustomerCreditInfo(String userName, CreditVO creditVO, OrderVO orderVO);
}
|
package exercises;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Book {
/* 1 */
// Add three properties to this Book class:
// - A title
// - An author
// - A year of publishing
// What data types do these properties have?
/* 2 */
// Add a constructor that enables you to pass
// a value for each property as an argument
// Add a no-argument constructor
// Specify a default value for each property
/* 3 */
// Write a method that sets the year of publishing to the current year
// You can do this by assigning the right property a hard coded value of 2019, or
// You can do this dynamically using
// Calendar.getInstance().get(Calendar.YEAR);
// Do you need parameters?
// What is the return type of the method?
// Write a method that allows you to overwrite the author with a specified author name
// Do you need parameters?
// What is the return type of the method?
// Write a method that returns a description of the book in the form
// '<title>' by <author> was published in <year>
// Use either string concatenation ("" + "") or String.format()
/* 4 */
// Write a method that creates and fills an array of books
// Three elements is enough!
// You can use any title, author and year of publishing you want
// Write a method that creates and fills a list of books
// Three elements is enough!
// You can use any title, author and year of publishing you want
/* 5 */
// Add a classic for loop to the first method from section 4
// (the one where you added the array)
// Iterate over the array and print the title of every book in the array to the standard output
// Add a foreach loop to the second method from section 4
// (the one where you added the list)
// Iterate over the array and print the title of every book in the list to the standard output
}
|
package code.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public int queryForInt(String sql,String param){
return jdbcTemplate.queryForInt(sql,param);
}
public int addUserbind(String sql,String username,String openid){
return jdbcTemplate.update(sql, new Object[]{username,openid});
}
public Map queryForString(String sql,String param){
return jdbcTemplate.queryForMap(sql, param);
}
}
|
package PA165.language_school_manager.facade;
import PA165.language_school_manager.service.BeanMappingService;
import PA165.language_school_manager.DTO.LectureDTO;
import PA165.language_school_manager.DTO.LecturerCreateDTO;
import PA165.language_school_manager.DTO.LecturerDTO;
import PA165.language_school_manager.Entities.Lecture;
import PA165.language_school_manager.Entities.Lecturer;
import PA165.language_school_manager.Enums.Language;
import PA165.language_school_manager.service.LecturerService;
import PA165.language_school_manager.Facade.LecturerFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Peter Tirala
*/
@Service
public class LecturerFacadeImpl implements LecturerFacade {
private final static Logger log = LoggerFactory.getLogger(LecturerFacadeImpl.class);
@Autowired
private BeanMappingService beanMappingService;
@Autowired
private LecturerService lecturerService;
@Override
@Transactional
public LecturerDTO findLecturerById(Long id) {
Lecturer lecturer = lecturerService.findLecturerById(id);
return lecturer == null ? null : beanMappingService.mapTo(lecturer, LecturerDTO.class);
}
@Override
@Transactional
public List<LecturerDTO> findLecturerByFirstName(String firstName) {
List<Lecturer> lecturers = lecturerService.findLecturerByFirstName(firstName);
return beanMappingService.mapTo(lecturers, LecturerDTO.class);
}
@Override
@Transactional
public List<LecturerDTO> findLecturerByLastName(String lastName) {
List<Lecturer> lecturers = lecturerService.findLecturerByLastName(lastName);
return beanMappingService.mapTo(lecturers, LecturerDTO.class);
}
@Override
@Transactional
public LecturerDTO findLecturerByLecture(LectureDTO lectureDto) {
Lecture lecture = (lectureDto == null) ? null : beanMappingService.mapTo(lectureDto, Lecture.class);
Lecturer lecturer = lecturerService.findLecturerByLecture(lecture);
return lecturer == null ? null : beanMappingService.mapTo(lecturer, LecturerDTO.class);
}
@Override
@Transactional
public List<LecturerDTO> findLecturersByLanguage(Language language) {
List<Lecturer> lecturers = lecturerService.findLecturersByLanguage(language);
return beanMappingService.mapTo(lecturers, LecturerDTO.class);
}
@Override
@Transactional
public void assignNewLecture(Long lecturerId, LectureDTO lectureDto) {
Lecture lecture = (lectureDto == null) ? null : beanMappingService.mapTo(lectureDto, Lecture.class);
lecturerService.assignNewLecture(lecturerId, lecture);
}
@Override
@Transactional
public Long createLecturer(LecturerCreateDTO newLecturer) {
Lecturer lecturer = beanMappingService.mapTo(newLecturer,Lecturer.class);
lecturerService.createLecturer(lecturer);
return lecturer.getId();
}
@Override
@Transactional
public void deleteLecturer(Long id) {
lecturerService.deleteLecturer(id);
}
@Override
@Transactional
public List<LecturerDTO> findAllLecturers() {
List<Lecturer> lecturers = lecturerService.findAllLecturers();
return beanMappingService.mapTo(lecturers, LecturerDTO.class);
}
@Override
@Transactional
public void updateLecturer(LecturerDTO lecturer) {
Lecturer lecturer1 = lecturerService.findLecturerById(lecturer.getId());
lecturer1 = beanMappingService.mapTo(lecturer, Lecturer.class);
lecturerService.updateLecturer(lecturer1);
}
}
|
package com.trump.auction.order.enums;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 支付状态枚举
* Created by wangjian on 2017/12/20.
*/
public enum EnumPayStatus implements BaseEnum<Integer> {
ALL(-999, "全部"),
PAYING(0, "支付中"),
PAYSUC(2, "支付成功"),
PAYFAIL(1, "支付失败");
private Integer value;
private String text;
EnumPayStatus(Integer value, String text) {
this.value = value;
this.text = text;
}
@Override
public Integer getValue() {
return value;
}
@Override
public String getText() {
return text;
}
@Override
public String toString() {
return this.value.toString();
}
public static Map<Integer, String> getAllType() {
Map<Integer, String> ALL_EXPRESSION = new LinkedHashMap<Integer, String>();
for (EnumPayStatus enumOrderStatus : values()) {
ALL_EXPRESSION.put(enumOrderStatus.getValue(), enumOrderStatus.getText());
}
return ALL_EXPRESSION;
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.07.03 at 06:17:49 PM CST
//
package org.blogdemo.homeloan.model;
public class CustInfo {
protected String nationalID;
protected String firstName;
protected String lastName;
protected int age;
protected String occupation;
protected String infotype;
/**
* Gets the value of the nationalID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNationalID() {
return nationalID;
}
/**
* Sets the value of the nationalID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNationalID(String value) {
this.nationalID = value;
}
/**
* Gets the value of the firstName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFirstName() {
return firstName;
}
/**
* Sets the value of the firstName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFirstName(String value) {
this.firstName = value;
}
/**
* Gets the value of the lastName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLastName() {
return lastName;
}
/**
* Sets the value of the lastName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLastName(String value) {
this.lastName = value;
}
/**
* Gets the value of the age property.
*
*/
public int getAge() {
return age;
}
/**
* Sets the value of the age property.
*
*/
public void setAge(int value) {
this.age = value;
}
/**
* Gets the value of the occupation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOccupation() {
return occupation;
}
/**
* Sets the value of the occupation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOccupation(String value) {
this.occupation = value;
}
/**
* Gets the value of the infotype property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInfotype() {
return infotype;
}
/**
* Sets the value of the infotype property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInfotype(String value) {
this.infotype = value;
}
}
|
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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
*
* http://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.wso2.carbon.ml.model.spark.algorithms;
import org.apache.commons.math3.stat.regression.ModelSpecificationException;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.mllib.classification.LogisticRegressionModel;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.regression.LabeledPoint;
import org.apache.spark.mllib.stat.MultivariateStatisticalSummary;
import org.apache.spark.mllib.stat.Statistics;
import org.apache.spark.mllib.tree.model.DecisionTreeModel;
import org.wso2.carbon.ml.model.exceptions.AlgorithmNameException;
import org.wso2.carbon.ml.model.exceptions.DatabaseHandlerException;
import org.wso2.carbon.ml.model.exceptions.ModelServiceException;
import org.wso2.carbon.ml.model.internal.DatabaseHandler;
import org.wso2.carbon.ml.model.internal.MLModelUtils;
import org.wso2.carbon.ml.model.internal.dto.MLWorkflow;
import org.wso2.carbon.ml.model.spark.dto.ClassClassificationModelSummary;
import org.wso2.carbon.ml.model.spark.dto.ProbabilisticClassificationModelSummary;
import org.wso2.carbon.ml.model.spark.transformations.DiscardedRowsFilter;
import org.wso2.carbon.ml.model.spark.transformations.HeaderFilter;
import org.wso2.carbon.ml.model.spark.transformations.LineToTokens;
import org.wso2.carbon.ml.model.spark.transformations.MeanImputation;
import org.wso2.carbon.ml.model.spark.transformations.MissingValuesFilter;
import org.wso2.carbon.ml.model.spark.transformations.StringArrayToDoubleArray;
import org.wso2.carbon.ml.model.spark.transformations.TokensToLabeledPoints;
import org.wso2.carbon.ml.model.spark.transformations.TokensToVectors;
import scala.Tuple2;
import java.sql.Time;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.DISCARD;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.IMPURITY;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.ITERATIONS;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.LEARNING_RATE;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.MAX_BINS;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.MAX_DEPTH;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.MEAN_IMPUTATION;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.NUM_CLASSES;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.RANDOM_SEED;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.REGULARIZATION_PARAMETER;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.REGULARIZATION_TYPE;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.SGD_DATA_FRACTION;
import static org.wso2.carbon.ml.model.internal.constants.MLModelConstants.SUPERVISED_ALGORITHM;
public class SupervisedModel {
/**
* @param modelID Model ID
* @param workflow Workflow ID
* @param sparkConf Spark configuration
* @throws ModelServiceException
*/
public void buildModel(String modelID, MLWorkflow workflow, SparkConf sparkConf)
throws ModelServiceException {
try {
sparkConf.setAppName(modelID);
// create a new java spark context
JavaSparkContext sc = new JavaSparkContext(sparkConf);
// parse lines in the dataset
String datasetURL = workflow.getDatasetURL();
JavaRDD<String> lines = sc.textFile(datasetURL);
// get header line
String headerRow = lines.take(1).get(0);
// get column separator
String columnSeparator = MLModelUtils.getColumnSeparator(datasetURL);
// apply pre processing
JavaRDD<double[]> features = preProcess(sc, workflow, lines, headerRow,
columnSeparator);
// generate train and test datasets by converting tokens to labeled points
int responseIndex = MLModelUtils.getFeatureIndex(workflow.getResponseVariable(),
headerRow, columnSeparator);
TokensToLabeledPoints tokensToLabeledPoints = new TokensToLabeledPoints(responseIndex);
JavaRDD<LabeledPoint> labeledPoints = features.map(tokensToLabeledPoints);
JavaRDD<LabeledPoint> trainingData = labeledPoints.sample(false,
workflow.getTrainDataFraction(), RANDOM_SEED);
JavaRDD<LabeledPoint> testingData = labeledPoints.subtract(trainingData);
// build a machine learning model according to user selected algorithm
SUPERVISED_ALGORITHM supervisedAlgorithm = SUPERVISED_ALGORITHM.valueOf(
workflow.getAlgorithmName());
switch (supervisedAlgorithm) {
case LOGISTIC_REGRESSION:
buildLogisticRegressionModel(modelID, trainingData, testingData, workflow);
break;
case DECISION_TREE:
buildDecisionTreeModel(modelID, trainingData, testingData, workflow);
break;
default:
throw new AlgorithmNameException("Incorrect algorithm name");
}
// stop spark context
sc.stop();
} catch (ModelSpecificationException e) {
throw new ModelServiceException(
"An error occurred while building supervised machine learning model: " +
e.getMessage(), e);
}
}
/**
* @param sc JavaSparkContext
* @param workflow Machine learning workflow
* @param lines JavaRDD of strings
* @param headerRow HeaderFilter row
* @param columnSeparator Column separator
* @return Returns a JavaRDD of doubles
* @throws ModelServiceException
*/
private JavaRDD<double[]> preProcess(JavaSparkContext sc, MLWorkflow workflow, JavaRDD<String>
lines, String headerRow, String columnSeparator) throws ModelServiceException {
try {
HeaderFilter headerFilter = new HeaderFilter(headerRow);
JavaRDD<String> data = lines.filter(headerFilter);
Pattern pattern = Pattern.compile(columnSeparator);
LineToTokens lineToTokens = new LineToTokens(pattern);
JavaRDD<String[]> tokens = data.map(lineToTokens);
// get feature indices for discard imputation
DiscardedRowsFilter discardedRowsFilter = new DiscardedRowsFilter(
MLModelUtils.getImputeFeatureIndices(
workflow, DISCARD));
// Discard the row if any of the impute indices content have a missing or NA value
JavaRDD<String[]> tokensDiscardedRemoved = tokens.filter(discardedRowsFilter);
JavaRDD<double[]> features = null;
// get feature indices for mean imputation
List<Integer> meanImputeIndices = MLModelUtils.getImputeFeatureIndices(workflow,
MEAN_IMPUTATION);
if (meanImputeIndices.size() > 0) {
// calculate means for the whole dataset (sampleFraction = 1.0) or a sample
Map<Integer, Double> means = getMeans(sc, tokensDiscardedRemoved, meanImputeIndices,
0.01);
// Replace missing values in impute indices with the mean for that column
MeanImputation meanImputation = new MeanImputation(means);
features = tokensDiscardedRemoved.map(meanImputation);
} else {
/**
* Mean imputation mapper will convert string tokens to doubles as a part of the
* operation. If there is no mean imputation for any columns, tokens has to be
* converted into doubles.
*/
features = tokensDiscardedRemoved.map(new StringArrayToDoubleArray());
}
return features;
} catch (ModelServiceException e) {
throw new ModelServiceException("An error occured while preprocessing data: " +
e.getMessage(), e);
}
}
/**
* @param sc JavaSparkContext
* @param tokens JavaRDD of String[]
* @param meanImputeIndices Indices of columns to impute
* @param sampleFraction Sample fraction used to calculate mean
* @return Returns a map of impute indices and means
* @throws ModelServiceException
*/
private Map<Integer, Double> getMeans(JavaSparkContext sc, JavaRDD<String[]> tokens,
List<Integer> meanImputeIndices, double sampleFraction) throws ModelServiceException {
Map<Integer, Double> imputeMeans = new HashMap();
JavaRDD<String[]> missingValuesRemoved = tokens.filter(new MissingValuesFilter());
JavaRDD<Vector> features = null;
// calculate mean and populate mean imputation hashmap
TokensToVectors tokensToVectors = new TokensToVectors(meanImputeIndices);
if (sampleFraction < 1.0) {
features = tokens.sample(false, sampleFraction).map(tokensToVectors);
} else {
features = tokens.map(tokensToVectors);
}
MultivariateStatisticalSummary summary = Statistics.colStats(features.rdd());
double[] means = summary.mean().toArray();
for (int i = 0; i < means.length; i++) {
imputeMeans.put(meanImputeIndices.get(i), means[i]);
}
return imputeMeans;
}
/**
* This method builds a logistic regression model
*
* @param trainingData Training data
* @param testingData Testing data
* @param workflow Machine learning workflow
* @throws org.wso2.carbon.ml.model.exceptions.ModelServiceException
*/
private void buildLogisticRegressionModel(String modelID, JavaRDD<LabeledPoint> trainingData,
JavaRDD<LabeledPoint> testingData,
MLWorkflow workflow) throws ModelServiceException {
try {
DatabaseHandler databaseHandler = new DatabaseHandler();
databaseHandler.insertModel(modelID, workflow.getWorkflowID(),
new Time(System.currentTimeMillis()));
LogisticRegression logisticRegression = new LogisticRegression();
Map<String, String> hyperParameters = workflow.getHyperParameters();
LogisticRegressionModel model = logisticRegression.trainWithSGD(trainingData,
Double.parseDouble(hyperParameters.get(LEARNING_RATE)),
Integer.parseInt(hyperParameters.get(ITERATIONS)),
hyperParameters.get(REGULARIZATION_TYPE),
Double.parseDouble(hyperParameters.get(REGULARIZATION_PARAMETER)),
Double.parseDouble(hyperParameters.get(SGD_DATA_FRACTION)));
model.clearThreshold();
JavaRDD<Tuple2<Object, Object>> scoresAndLabels = logisticRegression.test(model,
testingData);
ProbabilisticClassificationModelSummary probabilisticClassificationModelSummary =
logisticRegression.getModelSummary(scoresAndLabels);
databaseHandler.updateModel(modelID, model, probabilisticClassificationModelSummary,
new Time(System.currentTimeMillis()));
} catch (DatabaseHandlerException e) {
throw new ModelServiceException("An error occured while building logistic regression " +
"model: " + e.getMessage(), e);
}
}
/**
* This method builds a decision tree model
*
* @param trainingData Training data
* @param testingData Testing data
* @param workflow Machine learning workflow
* @throws ModelServiceException
*/
private void buildDecisionTreeModel(String modelID, JavaRDD<LabeledPoint> trainingData,
JavaRDD<LabeledPoint> testingData, MLWorkflow workflow) throws ModelServiceException {
try {
DatabaseHandler databaseHandler = new DatabaseHandler();
databaseHandler.insertModel(modelID, workflow.getWorkflowID(),
new Time(System.currentTimeMillis()));
Map<String, String> hyperParameters = workflow.getHyperParameters();
DecisionTree decisionTree = new DecisionTree();
DecisionTreeModel decisionTreeModel = decisionTree.train(trainingData,
Integer.parseInt(hyperParameters.get(NUM_CLASSES)),
new HashMap<Integer, Integer>(), hyperParameters.get(IMPURITY),
Integer.parseInt(hyperParameters.get(MAX_DEPTH)),
Integer.parseInt(hyperParameters.get(MAX_BINS)));
JavaPairRDD<Double, Double> predictionsAnsLabels = decisionTree.test(decisionTreeModel,
trainingData);
ClassClassificationModelSummary classClassificationModelSummary = decisionTree
.getClassClassificationModelSummary(predictionsAnsLabels);
databaseHandler.updateModel(modelID, decisionTreeModel, classClassificationModelSummary,
new Time(System.currentTimeMillis()));
} catch (DatabaseHandlerException e) {
throw new ModelServiceException("An error occured while building decision tree model: "
+ e.getMessage(), e);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.