text
stringlengths 10
2.72M
|
|---|
package fr.ucbl.disp.vfos.util.configurator;
import java.util.ArrayList;
public class CPSConfiguration {
private String id;
private ArrayList<SensorConfiguration> sensorList = new ArrayList<SensorConfiguration>();
private ArrayList<ActuatorConfiguration> actuatorList = new ArrayList<ActuatorConfiguration>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ArrayList<SensorConfiguration> getSensorList() {
return sensorList;
}
public void setActuatorList(ArrayList<ActuatorConfiguration> actuatorList) {
this.actuatorList = actuatorList;
}
public ArrayList<ActuatorConfiguration> getActuatorList() {
return actuatorList;
}
public void setSensorList(ArrayList<SensorConfiguration> sensorList) {
this.sensorList = sensorList;
}
public void setID(String id) {
// TODO Auto-generated method stub
this.id=id;
}
public String getID() {
// TODO Auto-generated method stub
return this.id;
}
public void addSensor(SensorConfiguration sensor1) {
// TODO Auto-generated method stub
this.sensorList.add(sensor1);
}
public void addActuator(ActuatorConfiguration actuator) {
this.actuatorList.add(actuator);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bean;
/**
*
* @author Zhang Yanlin
*/
public class Loyalty {
private int Loyalty;
private int memberID;
public int getLoyalty(){
return this.Loyalty;
}
public void setLoyalty(int loyalty){
this.Loyalty=loyalty;
}
public int getMemberID(){
return this.memberID;
}
public void setMemberID(int memberID){
this.memberID=memberID;
}
}
|
package application;
import java.util.Random;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
public class MyController {
@FXML
private Label myMessage;
public void GenerateRadom(ActionEvent Event){
Random rand=new Random();
int myRand=rand.nextInt(50+1);
myMessage.setText(Integer.toString(myRand));
//System.out.println(Integer.toString(myRand));
}
}
|
package gromcode.main.lesson2;
public class SumAndDivision {
public static void main(String[] args) {
int s = 0, c1, c2;
boolean b;
for(int i = 1; i <= 1000; i++){
s += i;
}
c1 = s / 1234;
c2 = s % 1234;
b = c2 > c1;
System.out.println(b);
}
}
|
public class Column {
public int number;
public int numWhitePieces;
public int numBlackPieces;
public Column(){}
public Column(int num, int white, int black){
numWhitePieces=white;
numBlackPieces=black;
number=num;
}
}
|
package com.lenovohit.elh.base.model;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.lenovohit.core.model.BaseIdModel;
/**
*
* 定点医院
*/
@Entity
@Table(name="ELH_DESIGNATED_HOSPITAL")
public class DesignatedHos extends BaseIdModel {
/**
*
*/
private static final long serialVersionUID = -6796849509853964811L;
public String miId;//所属医社保
public String name;//名称
public String area;//所属地区
public String code;//编码
public String getMiId() {
return miId;
}
public void setMiId(String miId) {
this.miId = miId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
|
package stmt;
import expr.Expr;
import slp.PropagatingVisitor;
import slp.Visitor;
public class IfStmt extends Stmt {
public Expr expr;
public final Stmt s1;
public final Stmt s2;
public IfStmt(Expr expr,Stmt s1,Stmt s2, int line_num) {
super( line_num );
this.expr = expr;
this.s1 = s1;
this.s2 = s2;
}
public IfStmt(Expr expr,Stmt s1, int line_num) {
super( line_num );
this.expr = expr;
this.s1 = s1;
this.s2 = null;
}
/** Accepts a visitor object as part of the visitor pattern.
* @param visitor A visitor.
*/
@Override
public Object accept(Visitor visitor) {
return visitor.visit(this);
}
/** Accepts a propagating visitor parameterized by two types.
*
* @param <DownType> The type of the object holding the context.
* @param <UpType> The type of the result object.
* @param visitor A propagating visitor.
* @param context An object holding context information.
* @return The result of visiting this node.
*/
@Override
public <DownType, UpType> UpType accept(
PropagatingVisitor<DownType, UpType> visitor, DownType context) {
return visitor.visit(this, context);
}
}
|
// Result of most successfull run:
/*
Attempt 17905:
Max equal substring = 12
Max zero substring = 7
Least difference = 16
Total difference = 57784
Average difference = 24.568027210884352
Quality accepted!
long f[] = new long[49];
f[0] = 0x12C701D20654CL;
f[1] = 0x05B37B8EC22D5L;
f[2] = 0x0535941379CF2L;
f[3] = 0x003CCF778392AL;
f[4] = 0x13FE3CBB8CF94L;
f[5] = 0x11D543FBD4E56L;
f[6] = 0x172225A5C5814L;
f[7] = 0x1B89EF727CA59L;
f[8] = 0x124DD28F5983EL;
f[9] = 0x12671071D7D85L;
f[10] = 0x1D7F2B3EE3E77L;
f[11] = 0x0BBCEC18E1390L;
f[12] = 0x034809CBAB084L;
f[13] = 0x1E4FBF3423B81L;
f[14] = 0x1028856CDDBB8L;
f[15] = 0x19CAC89F484B6L;
f[16] = 0x04975CFE12118L;
f[17] = 0x0ABE08E5FE685L;
f[18] = 0x1C23DC6FBC49DL;
f[19] = 0x078A716385093L;
f[20] = 0x18DB680F271B4L;
f[21] = 0x0159E33CED46DL;
f[22] = 0x0E8B1E0F81239L;
f[23] = 0x068A150190706L;
f[24] = 0x1A7D4598560CDL;
f[25] = 0x066768F8701EBL;
f[26] = 0x0A3B826061391L;
f[27] = 0x1455D065FA669L;
f[28] = 0x1FD0F9F5A134EL;
f[29] = 0x00AE9C053C166L;
f[30] = 0x1E772D50C4380L;
f[31] = 0x083D7CC2385BDL;
f[32] = 0x05EE70E982EA8L;
f[33] = 0x1EB18631A8D1EL;
f[34] = 0x01691B9927F64L;
f[35] = 0x10B8C775BC150L;
f[36] = 0x0D0969C538A62L;
f[37] = 0x0A051B33E4187L;
f[38] = 0x18E6C30E61A0DL;
f[39] = 0x0C425C0A25E59L;
f[40] = 0x02C5A40B8B7FFL;
f[41] = 0x1B0F5352B93D1L;
f[42] = 0x160639929EF27L;
f[43] = 0x11D6C2E4CD986L;
f[44] = 0x1289317FDB589L;
f[45] = 0x068BE4529C9B0L;
f[46] = 0x04B2EC62E6A22L;
f[47] = 0x0647693535332L;
f[48] = 0x17CFFF7FD1703L;
*/
import java.util.Random;
import java.lang.String;
/**
* Creates a bijective mapping f: [0...2<SUP>49</SUP>[ -> [0...2<SUP>49</SUP>[ satisfying
* 1) f(x xor y) = f(x) xor f(y)<BR>
* 2) f(2<SUP>k</SUP>) is a more or less random 49 bit number, ie. its binary representation
* contains a "nice" distribution of zeroes and ones.
* <p>
* Idea:<BR>
* Choose f such that f(1b) = 1b, f(10b) = 11b, ..., f(100000b) = 111111b<BR>
* This f will satisfy 1).<BR>
* This f could also be defined as f(2<SUP>k</SUP>) = sum<SUB>i<=k</SUB> 2<SUP>i</SUP>
* <p>
* We have fixed the number of bits to 49, so let p be a permutation of {0, ..., 48}<BR>
* For each p we have f<SUB>p</SUB> satisfying 1) given as follows:<BR>
* f<SUB>p</SUB>(2<SUP>k</SUP>) = sum<SUB>p(i) <= p(k)</SUB> 2<SUP>i</SUP>
* <p>
* Note that given f<SUB>p</SUB> and f<SUB>p'</SUB> we can define a 3. function f<SUB>p'</SUB> o f<SUB>p</SUB> satisfying 1):<BR>
* f<SUB>p'</SUB>(f<SUB>p</SUB>(x xor y)) = f<SUB>p'</SUB>(f<SUB>p</SUB>(x) xor f<SUB>p</SUB>(y)) = f<SUB>p'</SUB>(f<SUB>p</SUB>(x)) xor f<SUB>p'</SUB>(f<SUB>p</SUB>(y))
* <p>
* Now it is the hope that 2) can be achieved by composing a small number of these functions. eg.<BR>
* f<SUB>q</SUB> = f<SUB>p'''''</SUB> o f<SUB>p''''</SUB> o f<SUB>p'''</SUB> o f<SUB>p''</SUB> o f<SUB>p'</SUB> o f<SUB>p</SUB><BR>
* Because of 1) f<SUB>q</SUB> is given on its values on the set {2<SUP>i</SUP>}
*
* @author Jesper Kristensen
*/
public class HashValueClass {
private void init49() {
f = new long[49];
f[0] = 1;
for (int i=1; i<49; i++)
f[i] = f[i-1] << 1;
// Debug:
rh = null;
int last_quality = -999;
for (int num=0; ; num++) {
// Set g = f_p o f
int[] p = getPermutation(49);
// This definition of g can be moved outside the for loop if
// the debug code is removed.
long[] g = new long[49];
/*
for (int i=0; i<49; i++)
System.out.print("(" + p[i] + ")");
System.out.println();
*/
// Define g according to the permutation p
for (int i=0; i<49; i++) {
g[i] = 0;
long b = 1;
for (int j=0; j<49; j++) {
if (p[j] <= p[i])
g[i] |= b;
b <<= 1;
}
}
// Debug:
rh = new ReverseHashing(rh, p, g);
// for (int i=0; i<49; i++) f[i] = g[i];
// Set f = g o f
for (int i=0; i<49; i++) {
long fi = f[i];
f[i] = 0;
// define f(2^i)
for (int j=0; j<49; j++) {
if (((int)fi & 1) != 0) {
f[i] ^= g[j];
}
fi >>= 1;
}
}
// estimate quality
int d_least = 49;
int d_sum = 0;
int max_equal_substring = 0;
int max_zero_substring = 0;
for (int i=0; i<49; i++) {
{
int mzs = 0;
long fi = f[i];
for (int j=0; j<49; j++) {
if (((int)fi & 1) == 0) {
++mzs;
} else {
if (mzs > max_zero_substring) {
max_zero_substring = mzs;
}
mzs = 0;
}
fi >>= 1;
}
}
for (int j=0; j<49; j++) if (i!=j) {
// higher value of difference, d, is better
int d = 0;
long a = f[i] ^ f[j];
int mes = 0;
for (int k=0; k<49; k++) {
if (((int)a & 1) == 1) {
++d;
++mes;
} else {
if (mes > max_equal_substring) {
max_equal_substring = mes;
}
mes = 0;
}
a >>= 1;
}
if (d < d_least) d_least = d;
d_sum += d;
}
}
int quality = d_least - max_equal_substring - max_zero_substring;
if (quality > last_quality) {
System.out.println("Attempt " + (num+1) + ":");
System.out.println(" Max equal substring = " + max_equal_substring);
System.out.println(" Max zero substring = " + max_zero_substring);
System.out.println(" Least difference = " + d_least);
System.out.println(" Total difference = " + d_sum);
System.out.println(" Average difference = " + d_sum/(49.0*48));
if (quality >= -5) {
System.out.println("Quality accepted!");
return;
}
last_quality = quality;
}
}
}
private void initExtended() {
F = new byte[num][num];
for (int i=0; i<num; i++)
for (int j=0; j<num; j++)
F[i][j] = 0;
for (int i=0; i<num; i++)
F[i][i] = 1;
// Debug:
erh = null;
int last_quality = -999999999;
for (int numIt=0; ; numIt++) {
// Set g = f_p o f
int[] p = getPermutation(num);
// This definition of g can be moved outside the for loop if
// the debug code is removed.
byte[][] G = new byte[num][num];
/*
for (int i=0; i<49; i++)
System.out.print("(" + p[i] + ")");
System.out.println();
*/
// Define g according to the permutation p
for (int i=0; i<num; i++) {
for (int j=0; j<num; j++)
G[i][j] = 0;
for (int j=0; j<num; j++) {
if (p[j] <= p[i]) {
G[i][j] = 1;
}
}
}
// Debug:
erh = new ExtendedReverseHashing(erh, p, G);
// for (int i=0; i<49; i++) f[i] = g[i];
// Set f = g o f
for (int i=0; i<num; i++) {
byte[] FI = new byte[num];
for (int j=0; j<num; j++) {
FI[j] = F[i][j];
F[i][j] = 0;
}
// define f(2^i)
for (int j=0; j<num; j++) {
if (FI[j] != 0) {
for (int k=0; k<num; k++)
F[i][k] ^= G[j][k];
}
}
}
// estimate quality
int d_least = 49;
int d_sum = 0;
int max_equal_substring = 0;
int max_zero_substring = 0;
for (int i=0; i<49; i++) {
{
int mzs = 0;
byte[] FI = new byte[num];
for (int j=0; j<num; j++)
FI[j] = F[i][j];
for (int j=0; j<num; j++) {
if (FI[j] != 0) {
++mzs;
} else {
if (mzs > max_zero_substring) {
max_zero_substring = mzs;
}
mzs = 0;
}
}
}
for (int j=0; j<num; j++) if (i!=j) {
// higher value of difference, d, is better
int d = 0;
int mes = 0;
for (int k=0; k<49; k++) {
if (F[i][k] != F[j][k]) {
++d;
++mes;
} else {
if (mes > max_equal_substring) {
max_equal_substring = mes;
}
mes = 0;
}
}
if (d < d_least) d_least = d;
d_sum += d;
}
}
int quality = d_least - max_equal_substring - max_zero_substring;
if (quality > last_quality) {
System.out.println("Attempt " + (numIt+1) + ":");
System.out.println(" Max equal substring = " + max_equal_substring);
System.out.println(" Max zero substring = " + max_zero_substring);
System.out.println(" Least difference = " + d_least);
System.out.println(" Total difference = " + d_sum);
System.out.println(" Average difference = " + d_sum/(49.0*48));
if (quality >= -7) { // -7
System.out.println("Quality accepted!");
return;
}
last_quality = quality;
}
}
}
/**
* This constructor constructs the bijective mapping f.
* It is an randomized algorithm, so the mapping produced will vary.<BR>
* Some status information will be written to <code>System.out</code>.
*/
public HashValueClass(boolean normalGame) {
useExtended = !normalGame;
if (normalGame) {
init49();
} else {
num = 80;
initExtended();
}
}
/**
* Writes a java definition of an array containing the values {f(2<SUP>0</SUP>), ..., f(2<SUP>48</SUP>)} to <code>System.out</code>.
* The function is represented as a 49 entry array of <code>long</code>s,
* such that <code>f[i]</code> gives the value of f(2^i).
*/
public void print() {
final byte C[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
if (!useExtended) {
System.out.println("long[] fKey = new long[49];");
for (int i=0; i<49; i++) {
long fi = f[i];
byte[] B = new byte[13];
for (int j=0; j<13; j++) {
B[12-j] = C[(int)fi & 0xF];
fi >>= 4;
}
System.out.println("fKey["+i+"] = 0x" + new String(B) + "L;");
}
System.out.println();
for (int i=0; i<49; i++) {
byte[] b = new byte[49];
for (int j=0; j<49; j++)
b[48 - j] = (byte)(48 + (i==j ? 1 : 0));
System.out.print("f(" + new String(b) + ") = ");
System.out.println(longToString(f[i]));
}
} else if (num == 80) {
System.out.println("int[] fIndex = new int[80];");
System.out.println("long[] fKey = new long[80];");
for (int i=0; i<80; i++) {
byte[] FI = F[i];
byte[] B_index = new byte[4];
byte[] B_key = new byte[16];
for (int j=0; j<16; j+=4)
B_index[3-j/4] = C[FI[j] + 2*FI[j+1] + 4*FI[j+2] + 8*FI[j+3]];
for (int j=16; j<80; j+=4)
B_key[19-j/4] = C[FI[j] + 2*FI[j+1] + 4*FI[j+2] + 8*FI[j+3]];
System.out.println("fIndex["+i+"] = 0x" + new String(B_index) + ";");
System.out.println("fKey["+i+"] = 0x" + new String(B_key) + "L;");
}
} else {
System.out.println("print num implemented for num != 80");
}
}
private String longToString(long fi) {
byte[] b = new byte[49];
for (int j=0; j<49; j++) {
b[48 - j] = (byte)(48 + (int)(fi & 1));
fi >>= 1;
}
return new String(b);
}
private String byteArrayToString(byte[] FI) {
byte[] b = new byte[num];
for (int j=0; j<num; j++)
b[num - 1 - j] = (byte)(48 + FI[j]);
return new String(b);
}
/**
* Applies the bijective mapping on an argument.
*
* @param h a value in [0..2<SUP>49</SUP>[
* @return the value f(h)
*/
public long hash(long h) throws RuntimeException {
if (useExtended)
throw new RuntimeException();
long r = 0;
for (int i=0; i<49; i++) {
if (((int)h & 1) != 0)
r ^= f[i];
h >>= 1;
}
return r;
}
/**
* Applies the bijective mapping on an argument.
*
* @param h a value in [0..2<SUP>49</SUP>[
* @return the value f(h)
*/
public byte[] hash(byte[] H) throws RuntimeException {
if (!useExtended || F[0].length != H.length)
throw new RuntimeException();
byte[] R = new byte[num];
for (int i=0; i<num; i++)
R[i] = 0;
for (int i=0; i<num; i++) {
if (H[i] != 0) {
for (int j=0; j<num; j++)
R[j] ^= F[i][j];
}
}
return R;
}
private int[] getPermutation(int num) {
Random r = new Random();
int[] A = new int[num];
for (int i=0; i<num; i++)
A[i] = i;
int[] B = new int[num];
for (int i=0; i<num; i++)
B[i] = r.nextInt();
// Bubble sort B and move A indexes correspondingly - making A an arbitrary
// permutation of {0, ..., 48}
for (int i=1; i<num; i++)
for (int j=0; j<i; j++)
if (B[j] > B[i]) {
// swap A[i] with A[j] and B[i] with B[j]
// A[i] ^= A[j] ^= A[i] ^= A[j];
// B[i] ^= B[j] ^= B[i] ^= B[j];
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
tmp = B[i];
B[i] = B[j];
B[j] = tmp;
}
return A;
}
/**
* Reverse hashing is only for debugging purposes - to demonstrate that it is really working.
* It is really slow. Some information is written to <code>System.out</code>.
*
* @return true if no errors were found.
*/
public boolean verifyHashing() {
System.out.println("Verifying reverse hashing:");
Random r = new Random();
for (int numIt=0; numIt<5; numIt++) {
if (numIt != 0)
System.out.println();
if (useExtended) {
//for (int i=0; i<num; i++) System.out.println(byteArrayToString(F[i]));
//System.out.println();
byte[] L = new byte[num];
for (int i=0; i<num; i++)
L[i] = (byte)r.nextInt(2);
byte[] H = hash(L);
byte[] H_inv = reverse_hash(H);
System.out.println(" f(" + byteArrayToString(L) + ") =");
System.out.println(" " + byteArrayToString(H) + " ?");
System.out.println("f^-1(" + byteArrayToString(H) + ") =");
System.out.println(" " + byteArrayToString(H_inv) + " ?");
for (int i=0; i<num; i++) {
if (L[i] != H_inv[i]) {
System.out.println("Verification failed!");
return false;
}
}
} else {
long l = (0x123456789654323L * r.nextInt()) & 0x1FFFFFFFFFFFFL;
long h = hash(l);
long h_inv = reverse_hash(h);
System.out.println("f(" + longToString(l ) + ") = " + longToString(h) + " ?");
System.out.println(" " + longToString(h_inv) + " = f^-1(" + longToString(h) + ") ?");
if (l != h_inv) {
System.out.println("Verification failed!");
return false;
}
l ^= 1<<(3*numIt);
h = hash(l);
h_inv = reverse_hash(h);
System.out.println("f(" + longToString(l ) + ") = " + longToString(h) + " ?");
System.out.println(" " + longToString(h_inv) + " = f^-1(" + longToString(h) + ") ?");
if (l != h_inv) {
System.out.println("Verification failed!");
return false;
}
}
}
System.out.println("Verification successfull!");
return true;
}
/**
* Applies the injerse bijective mapping f<SUP>-1</SUP> on an argument.
* This should rarely be used as it is utterly slow.
*
* @param h a value in [0..2<SUP>49</SUP>[
* @return the value f<SUP>-1</SUP>(h)
*/
public long reverse_hash(long h) {
return rh.reverse(h);
}
public byte[] reverse_hash(byte[] H) {
return erh.reverse(H);
}
private class ReverseHashing {
public ReverseHashing(ReverseHashing rh, int[] p, long[] f) {
this.rh = rh;
this.p = p;
this.f = f;
}
public long reverse(long h) {
long r = 0;
for (int i=48; i>=0; i--) {
long b = 1;
for (int j=0; j<49; j++) {
if (p[j]==i) {
if ((h & b) != 0) {
h ^= f[j];
r ^= b;
}
break;
}
b <<= 1;
}
}
if (rh != null) return rh.reverse(r);
return r;
}
ReverseHashing rh;
int[] p;
long[] f;
}
private class ExtendedReverseHashing {
public ExtendedReverseHashing(ExtendedReverseHashing erh, int[] p, byte[][] F) {
this.erh = erh;
this.p = p;
this.F = F;
}
public byte[] reverse(byte[] _H) {
byte[] R = new byte[num];
byte[] H = new byte[num];
for (int i=0; i<num; i++) {
R[i] = 0;
H[i] = _H[i];
}
for (int i=num-1; i>=0; i--) {
for (int j=0; j<num; j++) {
if (p[j]==i) {
if (H[j] != 0) {
for (int k=0; k<num; k++)
H[k] ^= F[j][k];
R[j] = 1;
}
break;
}
}
}
if (erh != null) return erh.reverse(R);
return R;
}
ExtendedReverseHashing erh;
int[] p;
byte[][] F;
}
private boolean useExtended;
private long[] f;
private ReverseHashing rh;
private int num;
private byte[][] F;
private ExtendedReverseHashing erh;
}
|
package edu.buffalo.cse.cse486586.groupmessenger1;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* GroupMessengerActivity is the main Activity for the assignment.
*
* @author stevko
*
*/
public class GroupMessengerActivity extends Activity {
//MyCode - from PA1
static final String TAG = GroupMessengerActivity.class.getSimpleName();
static final String REMOTE_PORT0 = "11108";
static final String REMOTE_PORT1 = "11112";
static final String REMOTE_PORT2 = "11116";
static final String REMOTE_PORT3 = "11120";
static final String REMOTE_PORT4 = "11124";
static final int SERVER_PORT = 10000;
static int msg_counter = -1;
//endCode
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_messenger);
/*
* TODO: Use the TextView to display your messages. Though there is no grading component
* on how you display the messages, if you implement it, it'll make your debugging easier.
*/
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setMovementMethod(new ScrollingMovementMethod());
// String tv_msg = tv.getText().toString();
// tv_msg
/*
* Registers OnPTestClickListener for "button1" in the layout, which is the "PTest" button.
* OnPTestClickListener demonstrates how to access a ContentProvider.
*/
findViewById(R.id.button1).setOnClickListener(
new OnPTestClickListener(tv, getContentResolver()));
/*
* TODO: You need to register and implement an OnClickListener for the "Send" button.
* In your implementation you need to get the message from the input box (EditText)
* and send it to other AVDs.
*/
/*
* Calculate the port number that this AVD listens on.
* It is just a hack that I came up with to get around the networking limitations of AVDs.
* The explanation is provided in the PA1 spec.
*/
TelephonyManager tel = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() - 4);
Log.d("Line Number", "onCreate:" + tel.getLine1Number());
final String myPort = String.valueOf((Integer.parseInt(portStr) * 2));
try {
/*
* Create a server socket as well as a thread (AsyncTask) that listens on the server
* port.
*
* AsyncTask is a simplified thread construct that Android provides. Please make sure
* you know how it works by reading
* http://developer.android.com/reference/android/os/AsyncTask.html
*/
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
new ServerTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serverSocket);
} catch (IOException e) {
/*
* Log is a good way to debug your code. LogCat prints out all the messages that
* Log class writes.
*
* Please read http://developer.android.com/tools/debugging/debugging-projects.html
* and http://developer.android.com/tools/debugging/debugging-log.html
* for more information on debugging.
*/
Log.e(TAG, "Can't create a ServerSocket");
return;
}
/*
* Retrieve a pointer to the input box (EditText) defined in the layout
* XML file (res/layout/main.xml).
*
* This is another example of R class variables. R.id.edit_text refers to the EditText UI
* element declared in res/layout/main.xml. The id of "edit_text" is given in that file by
* the use of "android:id="@+id/edit_text""
*/
final EditText editText = (EditText) findViewById(R.id.editText1);
findViewById(R.id.button4).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = editText.getText().toString() + "\n";
editText.setText("");
new ClientTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, msg, REMOTE_PORT0);
new ClientTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, msg, REMOTE_PORT1);
new ClientTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, msg, REMOTE_PORT2);
new ClientTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, msg, REMOTE_PORT3);
new ClientTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, msg, REMOTE_PORT4);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_group_messenger, menu);
return true;
}
//All code below this point from PA1
/***
* ServerTask is an AsyncTask that should handle incoming messages. It is created by
* ServerTask.executeOnExecutor() call in SimpleMessengerActivity.
*
* Please make sure you understand how AsyncTask works by reading
* http://developer.android.com/reference/android/os/AsyncTask.html
*
* @author stevko
*
*/
private class ServerTask extends AsyncTask<ServerSocket, String, Void> {
@Override
protected Void doInBackground(ServerSocket... sockets) {
ServerSocket serverSocket = sockets[0];
//Code
try {
// Loop to handle multiple messages
while (true) {
Socket clientSocket = serverSocket.accept();
// Code below referenced from
// https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
BufferedReader in =
new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String msgReceived = in.readLine();
// Null messages appear to be causing problems - publishing causes crash
// Temporary fix is to publish only if not null
if(msgReceived!=null){
msg_counter = msg_counter + 1;
//Referencing code for insertion:
// https://developer.android.com/guide/topics/providers/content-provider-basics.html#java
// And PA2 code snippet
ContentValues keyValueToInsert = new ContentValues();
// inserting <”key-to-insert”, “value-to-insert”>
keyValueToInsert.put("key", String.valueOf(msg_counter));
keyValueToInsert.put("value", msgReceived);
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.authority("edu.buffalo.cse.cse486586.groupmessenger1.provider");
uriBuilder.scheme("content");
final Uri contentProviderUri = uriBuilder.build();
Uri newUri = getContentResolver().insert(
contentProviderUri, // assume we already created a Uri object with our provider URI
keyValueToInsert
);
publishProgress(msgReceived);
}
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//codeEnd
return null;
}
protected void onProgressUpdate(String...strings) {
/*
* The following code displays what is received in doInBackground().
*/
String strReceived = strings[0].trim();
TextView localTextView = (TextView) findViewById(R.id.textView1);
localTextView.append(strReceived + "\t\n");
return;
}
}
/***
* ClientTask is an AsyncTask that should send a string over the network.
* It is created by ClientTask.executeOnExecutor() call whenever OnKeyListener.onKey() detects
* an enter key press event.
*
* @author stevko
*
*/
private class ClientTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... msgs) {
try {
String remotePort = msgs[1];
Log.d(TAG, "doInBackground: "+ msgs[0] + "\n" + msgs[1]);
Socket socket = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}),
Integer.parseInt(remotePort));
String msgToSend = msgs[0];
//Code
// Code below referenced from
// https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.write(msgToSend);
out.flush();
// Adding a sleep to handle inconsistency in two way communication
// Prevents message drops by keeping socket alive long enough to send out message
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.w(TAG, "ClientTask InterruptedException");
}
//endCode
socket.close();
} catch (UnknownHostException e) {
Log.e(TAG, "ClientTask UnknownHostException");
} catch (IOException e) {
Log.e(TAG, "ClientTask socket IOException");
}
return null;
}
}
}
|
package de.mq.phone.web.person;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import junit.framework.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.data.geo.Circle;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import de.mq.phone.domain.person.Address;
import de.mq.phone.domain.person.AddressStringAware;
import de.mq.phone.domain.person.Contact;
import de.mq.phone.domain.person.GeoCoordinates;
import de.mq.phone.domain.person.Person;
import de.mq.phone.domain.person.PersonService;
import de.mq.phone.domain.person.PersonStringAware;
import de.mq.phone.domain.person.support.DistanceCalculator;
import de.mq.phone.domain.person.support.Paging;
public class PersonSearchControllerTest {
private static final String COORDINATES = "48° 42′ N, 44° 29′ O";
private final Validator validator = Mockito.mock(Validator.class);
private PersonService personService = Mockito.mock(PersonService.class);
private DistanceCalculator distanceCalculator = Mockito.mock(DistanceCalculator.class);
private final PersonSearchController personSearchController = new PersonSearchControllerImpl(personService, distanceCalculator, validator);
private int PAGE_SIZE = 10;
private Paging paging = Mockito.mock(Paging.class);
@Test
public final void assign() {
final PersonSearchModel model = Mockito.mock(PersonSearchModel.class);
Mockito.when(model.getPaging()).thenReturn(paging);
final PersonStringAware person = Mockito.mock(PersonStringAware.class);
final Contact contact = Mockito.mock(Contact.class);
final AddressStringAware addressStringAware = Mockito.mock(AddressStringAware.class);
final Circle circle = Mockito.mock(Circle.class);
Mockito.when(model.getSearchCriteriaPerson()).thenReturn(person);
Mockito.when(model.getSearchCriteriaContact()).thenReturn(contact);
Mockito.when(model.getSearchCriteriaAddress()).thenReturn(addressStringAware);
Mockito.when(model.getSearchCriteriaDistance()).thenReturn(circle);
final List<Person> persons = new ArrayList<>();
persons.add(Mockito.mock(Person.class));
Mockito.when(personService.persons(person, addressStringAware, contact,circle, paging)).thenReturn(persons);
personSearchController.assignPersons(model, PAGE_SIZE);
Mockito.verify(model, Mockito.times(1)).setPersons(persons);
}
@Test
public final void assignGeoKoordinates() {
final PersonSearchModel model = Mockito.mock(PersonSearchModel.class);
final Person person = Mockito.mock(Person.class);
Mockito.when(person.hasGeoCoordinates()).thenReturn(true);
final Address address = Mockito.mock(Address.class);
final GeoCoordinates geoCoordinates = Mockito.mock(GeoCoordinates.class);
Mockito.when(address.coordinates()).thenReturn(geoCoordinates);
Mockito.when(person.address()).thenReturn(address);
Mockito.when(personService.defaultPerson()).thenReturn(person);
personSearchController.assignGeoKoordinates(model);
Mockito.verify(model, Mockito.times(1)).setGeoCoordinates(geoCoordinates);
}
@Test
public final void assignGeoKoordinatesNotAware() {
final PersonSearchModel model = Mockito.mock(PersonSearchModel.class);
final Person person = Mockito.mock(Person.class);
Mockito.when(person.hasGeoCoordinates()).thenReturn(false);
Mockito.when(personService.defaultPerson()).thenReturn(person);
personSearchController.assignGeoKoordinates(model);
Mockito.verify(model, Mockito.times(1)).setGeoCoordinates(null);
}
@Test
public final void validate() {
final Map<String,Object> map = new HashMap<>();
Mockito.when(validator.supports(map.getClass())).thenReturn(true);
BindingResult result = personSearchController.validate(map);
Assert.assertEquals(PersonSearchControllerImpl.BINDING_RESULT_NAME, result.getObjectName());
Mockito.verify(validator, Mockito.times(1)).validate(map, result);
}
@Test
public final void geoInfos() {
final GeoCoordinates geoCoordinates = Mockito.mock(GeoCoordinates.class);
final GeoCoordinates homeCoordinates = Mockito.mock(GeoCoordinates.class);
Mockito.when(geoCoordinates.location()).thenReturn(COORDINATES);
PersonSearchModel model = Mockito.mock(PersonSearchModel.class);
Mockito.when(model.hasGeoCoordinates()).thenReturn(true);
Mockito.when(model.getGeoCoordinates()).thenReturn(homeCoordinates);
Mockito.when(distanceCalculator.distance(homeCoordinates, geoCoordinates)).thenReturn(2216D);
Mockito.when(distanceCalculator.angle(homeCoordinates, geoCoordinates)).thenReturn(89D);
final List<String> results = new ArrayList<>();
results.addAll(personSearchController.geoInfos(geoCoordinates, model, Locale.GERMAN));
Assert.assertEquals(2, results.size());
Assert.assertEquals(COORDINATES, results.get(0));
Assert.assertEquals("2216,00 km, 89,00°", results.get(1));
results.clear();
Mockito.when(model.hasGeoCoordinates()).thenReturn(false);
results.addAll(personSearchController.geoInfos(geoCoordinates, model, Locale.GERMAN));
Assert.assertEquals(1, results.size());
Assert.assertEquals(COORDINATES, results.get(0));
Assert.assertTrue(personSearchController.geoInfos(null, model, Locale.GERMAN).isEmpty());
}
@Test
public final void incPaging() {
final PersonSearchModel model = Mockito.mock(PersonSearchModel.class);
personSearchController.incPaging(model);
Mockito.verify(model).incPaging();
Mockito.verify(personService, Mockito.times(1)).persons(model.getSearchCriteriaPerson(), model.getSearchCriteriaAddress(), model.getSearchCriteriaContact(), model.getSearchCriteriaDistance(), model.getPaging());
}
@Test
public final void decPaging() {
final PersonSearchModel model = Mockito.mock(PersonSearchModel.class);
personSearchController.decPaging(model);
Mockito.verify(model).decPaging();
Mockito.verify(personService, Mockito.times(1)).persons(model.getSearchCriteriaPerson(), model.getSearchCriteriaAddress(), model.getSearchCriteriaContact(), model.getSearchCriteriaDistance(), model.getPaging());
}
@Test
public final void endPaging() {
final PersonSearchModel model = Mockito.mock(PersonSearchModel.class);
personSearchController.endPaging(model);
Mockito.verify(model).endPaging();
Mockito.verify(personService, Mockito.times(1)).persons(model.getSearchCriteriaPerson(), model.getSearchCriteriaAddress(), model.getSearchCriteriaContact(), model.getSearchCriteriaDistance(), model.getPaging());
}
@Test
public final void beginPaging() {
final PersonSearchModel model = Mockito.mock(PersonSearchModel.class);
personSearchController.beginPaging(model);
Mockito.verify(model).beginPaging();
Mockito.verify(personService, Mockito.times(1)).persons(model.getSearchCriteriaPerson(), model.getSearchCriteriaAddress(), model.getSearchCriteriaContact(), model.getSearchCriteriaDistance(), model.getPaging());
}
}
|
package Models;
import java.awt.*;
import java.awt.print.*;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javafx.collections.ObservableList;
public class ObjetoDeImpresionFactura implements Printable{
private Factura factura;
private ObservableList<DetalleFactura> detalles;
private Cliente cliente;
public ObjetoDeImpresionFactura(Factura factura, ObservableList<DetalleFactura> detalles, Cliente cliente) {
this.factura = factura;
this.detalles = detalles;
this.cliente = cliente;
}
public Factura getFactura() {
return factura;
}
public void setFactura(Factura factura) {
this.factura = factura;
}
public ObservableList<DetalleFactura> getDetalles() {
return detalles;
}
public void setDetalles(ObservableList<DetalleFactura> detalles) {
this.detalles = detalles;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public int print(Graphics g, PageFormat f, int pageIndex){
if(pageIndex == 0){
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Font font = g.getFont();
g.setFont(new Font(font.getFontName(),font.getStyle(), 11));
g.drawString("El Mundo del Calzado II", 90, 18);
g.drawString("Santiago de Puriscal", 96, 36);
g.drawString("Telef: 2416-65-56", 18, 54);
if(this.factura.getTipoDeFactura() == 1){
g.drawString("Factura por Venta", 18, 72);
}else{
g.drawString("Factura por Apartado", 18, 72);
}
g.drawString("N° Factura: " + Integer.toString(this.factura.getCodigoFactura()), 18, 90);
if(this.factura.getIdTipoDePago() == 1){
g.drawString("Pago en Efectivo", 18, 108);
}else{
g.drawString("Pago por Tarjeta", 18, 108);
}
g.drawString("Fecha: " + df.format(this.factura.getFecha()), 18, 124);
int y = 142;
if(this.factura.getIdCliente() != 0){
if(!this.cliente.getNombre().equals("")){
g.drawString("Cliente: " + this.cliente.getNombre(), 18, y);
y+=18;
}
if(!this.cliente.getNumero().equals("")){
g.drawString("Telefono: " + this.cliente.getNumero(), 18, y);
y+=18;
}
}
g.setFont(new Font(font.getFontName(),font.getStyle(), 10));
g.drawString("Código", 18, y);
g.drawString("Artículo", 65, y);
g.drawString("Monto", 210, y);
y+=7;
g.drawString("____________________________________________", 15, y);
y+=15;
double descuento = 0;
double subTotal = 0;
for (int i = 0; i < this.detalles.size(); i++) {
int y2 = y;
ArrayList<String> codigo = Division(Integer.toString(this.detalles.get(i).getCodigoArticulo()),7);
ArrayList<String> articulo = Division(this.detalles.get(i).getNombre(),26);
ArrayList<String> monto = Division(String.valueOf(this.detalles.get(i).getPrecio()),12);
descuento += this.detalles.get(i).getDescuento();
subTotal += this.detalles.get(i).getPrecio();
int subY = codigo.size();
if(articulo.size() > subY){
subY = articulo.size();
}
if(monto.size() > subY){
subY = monto.size();
}
for(int j = 0; j < codigo.size(); j++){
g.drawString(codigo.get(j), 18, y2);
y2+=15;
}
y2 = y;
for(int j = 0; j < articulo.size(); j++){
g.drawString(articulo.get(j), 65, y2);
y2+=15;
}
y2 = y;
for(int j = 0; j < monto.size(); j++){
g.drawString(monto.get(j), 210, y2);
y2+=15;
}
y += subY*15;
}
y+=5;
g.drawString("____________________________________________", 15, y);
y+=15;
g.setFont(new Font(font.getFontName(),font.getStyle(), 11));
g.drawString("SubTotal: " + String.valueOf(subTotal), 18, y);
y+=18;
g.drawString("Descuento: " + String.valueOf(descuento), 18, y);
y+=18;
g.drawString("Total a Pagar: " + String.valueOf(this.factura.getMontoTotal()), 18, y);
y+=21;
if(this.factura.getTipoDeFactura() == 2){
g.drawString("Total Pagado: " + String.valueOf(this.factura.getMontoPagado()), 18, y);
y+=18;
g.drawString("Faltante: " + String.valueOf(this.factura.getMontoTotal()- this.factura.getMontoPagado()
), 18, y);
y+=18;
}
y+=5;
g.drawString("Para cambios 8 días con factura", 18, y);
y+=18;
g.drawString("Regimen simplificado según", 18, y);
y+=18;
g.drawString("DGTD Oficio #4641001009626 23-07-2013", 18, y);
return PAGE_EXISTS;
}else{
return NO_SUCH_PAGE;
}
}
private ArrayList<String> Division(String dato, int letras){
ArrayList<String> datos = new ArrayList<>();
if(dato.length() > letras){
String subDato = dato;
while(subDato.length() != 0){
int blanco = 0;
if(subDato.length() > letras){
blanco = Espacio(subDato.substring(0,letras));
}else{
blanco = Espacio(subDato);
}
if(blanco != 0){
datos.add(subDato.substring(0, blanco));
subDato = subDato.substring(blanco+1, subDato.length());
}else{
if(subDato.length() > letras){
datos.add(subDato.substring(0, letras) + "-");
subDato = subDato.substring(letras, subDato.length());
}else{
datos.add(subDato.substring(0, subDato.length()));
subDato = "";
}
}
}
}else{
datos.add(dato);
}
return datos;
}
private int Espacio(String dato){
for(int i = dato.length()-1; i >= 0; i--){
if(dato.charAt(i) == ' '){
return i;
}
}
return 0;
}
}
// Anterior impresion para hoja ancha
//
//public int print(Graphics g, PageFormat f, int pageIndex){
// if(pageIndex == 0){
// DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
// Font font = g.getFont();
// g.setFont(new Font(font.getFontName(),font.getStyle(), 18));
// g.drawString("Mundo del Calzado II", 30, 30);
// if(factura.getTipoDeFactura() == 1){
// g.drawString("Factura Venta", 425, 30);
// }else{
// g.drawString("Factura Apartado", 425, 30);
// }
// g.setFont(font);
// g.drawString("Puriscal, San Jose", 30, 50);
// g.drawString("Fecha: " + df.format(factura.getFecha()), 425, 50);
// g.drawString("Telef: 24166556", 30, 70);
// g.drawString("N° Factura: " + Integer.toString(factura.getCodigoFactura()), 425, 70);
// if(factura.getIdCliente() != 0){
// if(cliente.getNumero().equals("")){
// g.drawString("Cliente: " + cliente.getNombre(), 30, 90);
// }else{
// g.drawString("Cliente: " + cliente.getNombre() + " - " + cliente.getNumero(), 30, 90);
// }
// }
// if(factura.getIdTipoDePago() == 1){
// g.drawString("Pago en Efectivo", 425, 90);
// }else{
// g.drawString("Pago por Tarjeta", 425, 90);
// }
// g.drawRect( 50, 110, 47, 20);
// g.drawRect( 97, 110, 141, 20);
// g.drawRect( 238, 110, 94, 20);
// g.drawRect( 332, 110, 94, 20);
// g.drawRect( 426, 110, 104, 20);
// g.drawString("Codigo", 52, 125);
// g.drawString("Nombre", 147, 125);
// g.drawString("Precio", 255, 125);
// g.drawString("Descuento", 346, 125);
// g.drawString("Total", 444, 125);
// int y = 145;
// int largo = 0;
// for (int i = 0; i < detalles.size(); i++) {
// g.drawString(Integer.toString(detalles.get(i).getCodigoArticulo()), 55, y);
// g.drawString(detalles.get(i).getNombre(), 102, y);
// g.drawString(String.valueOf(detalles.get(i).getPrecio()), 257, y);
// g.drawString(String.valueOf(detalles.get(i).getDescuento()), 352, y);
// g.drawString(String.valueOf(detalles.get(i).getPrecio()-detalles.get(i).getDescuento()), 445, y);
// y += 15;
// largo += 15;
// }
// y += 5;
// g.drawString("Total:" + String.valueOf(factura.getMontoTotal()), 439, y);
// largo +=10;
// if(factura.getTipoDeFactura() == 2){
// y += 15;
// g.drawString("Pagado:" + String.valueOf(factura.getMontoPagado()), 433, y);
// largo += 15;
// y+= 15;
// g.drawString("Faltante:" + String.valueOf(factura.getMontoTotal() - factura.getMontoPagado()), 433, y);
// largo += 15;
// }
// y += 20;
// g.drawRect( 50, 130, 47, 20 + largo);
// g.drawRect( 97, 130, 141, 20 + largo);
// g.drawRect( 238, 130, 94, 20 + largo);
// g.drawRect( 332, 130, 94, 20 + largo);
// g.drawRect( 426, 130, 104, 20 + largo);
// g.drawString("Regimen simplificado segun DGTD Oficio #4641001009626 23-07-2013", 30, y);
// return PAGE_EXISTS;
// }else{
// return NO_SUCH_PAGE;
// }
// }
//
// if(pageIndex == 0){
//
// DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
// if(factura.getTipoDeFactura() == 1){
// g.drawString("Factura por venta", 50, 50);
// }else{
// g.drawString("Factura por Apartado", 50, 50);
// }
// g.drawString("Codigo de factura: " + Integer.toString(factura.getCodigoFactura()), 50, 70);
// g.drawString("Fecha: " + df.format(factura.getFecha()), 50, 90);
// if(factura.getIdTipoDePago() == 1){
// g.drawString("Pago en: Efectivo", 50, 110);
// }else{
// g.drawString("Pago por: Tarjeta", 50, 110);
// }
// g.drawString("Monto Total: ₡" + String.valueOf(factura.getMontoTotal()), 50, 130);
// if(factura.getTipoDeFactura() == 2){
// g.drawString("Monto Pagado: " + String.valueOf(factura.getMontoPagado()), 50, 150);
// g.drawString("Cliente: " + Integer.toString(factura.getIdCliente()), 50, 170);
// }
// g.drawString("Codigo Articulo", 80, 190);
// g.drawString("Nombre", 170, 190);
// g.drawString("Precio", 240, 190);
// g.drawString("Descuento", 310, 190);
// int y = 210;
// for (int i = 0; i < detalles.size(); i++) {
// g.drawString(Integer.toString(detalles.get(i).getCodigoArticulo()), 100, y);
// g.drawString(detalles.get(i).getNombre(), 170, y);
// g.drawString(String.valueOf(detalles.get(i).getPrecio()), 240, y);
// g.drawString(String.valueOf(detalles.get(i).getDescuento()), 310, y);
// y += 20;
// }
// return PAGE_EXISTS;
// }else{
// return NO_SUCH_PAGE;
// }
|
package com.techtest.mobilab.datamodel;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "Transaction")
public class TransactionDocument {
@Id
private String id;
private String date;
private String amountOfTransaction;
private String otherDetails;
private String creditorAccountNumber;
private String debtorAccountNumber;
private String currency;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAmountOfTransaction() {
return amountOfTransaction;
}
public void setAmountOfTransaction(String amountOfTransaction) {
this.amountOfTransaction = amountOfTransaction;
}
public String getOtherDetails() {
return otherDetails;
}
public void setOtherDetails(String otherDetails) {
this.otherDetails = otherDetails;
}
public String getCreditorAccountNumber() {
return creditorAccountNumber;
}
public void setCreditorAccountNumber(String creditorAccountNumber) {
this.creditorAccountNumber = creditorAccountNumber;
}
public String getDebtorAccountNumber() {
return debtorAccountNumber;
}
public void setDebtorAccountNumber(String debtorAccountNumber) {
this.debtorAccountNumber = debtorAccountNumber;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
|
package org.sparkle.jbind;
import java.nio.ByteBuffer;
import org.sparkle.jcfg.JCFG;
import org.sparkle.jcfg.Parser;
import org.sparkle.jcfg.Writer;
/**
*
* @author yew_mentzaki
*/
public class Part {
private String title;
private byte[] data;
Part(byte[] data) {
}
public Part(String title, byte[] data) {
this.title = title;
this.data = data;
}
public Part(String title, String data) {
this.title = title;
this.data = data.getBytes();
}
public Part(String title, JCFG data) {
this.title = title;
this.data = Writer.writeToString(data).getBytes();
}
public byte[] getDataAsByteArray() {
return data;
}
byte[] getPart() {
byte[] bytes = new byte[4 + title.getBytes().length + 4 + data.length];
int caret = 0;
byte[] titleLength = ByteBuffer.allocate(4).putInt(title.length()).array();
byte[] titleBytes = title.getBytes();
for (int i = 0; i < titleLength.length; i++) {
bytes[caret] = titleLength[i];
caret++;
}
for (int i = 0; i < titleBytes.length; i++) {
bytes[caret] = titleBytes[i];
caret++;
}
byte[] dataLength = ByteBuffer.allocate(4).putInt(data.length).array();
byte[] dataBytes = data;
for (int i = 0; i < dataLength.length; i++) {
bytes[caret] = dataLength[i];
caret++;
}
for (int i = 0; i < dataBytes.length; i++) {
bytes[caret] = dataBytes[i];
caret++;
}
return bytes;
}
public String getDataAsString() {
return new String(data);
}
public JCFG getDataAsJCFG() {
return Parser.parse(new String(data));
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
package sampleproject.sockets;
import java.io.*;
import java.net.UnknownHostException;
import sampleproject.db.*;
/**
* A DvdConnector is used in cases where the GUI client wants to make a
* network connection. In this case, that connection is a Socket connection.
*
* @author Denny's DVDs
* @version 2.0
*/
public class DvdConnector {
/**
* Since this is a utility class (it only exists for other classes to call
* it's static methods), lets stop users creating unneeded instances of this
* class by creating a private constructor.
*/
private DvdConnector() {
}
/**
* static method to create a connection to the database.
* The DBClient is a remote object.
*
* @param hostname The ip or ddress of the host machine.
* @param port the socket port the server is listening on.
* @return a connection to the database.
* @throws UnknownHostException when the host is unreachable or cannot be
* resloved
* @throws IOException if a communication error occurs trying to connect
* to the host.
*/
public static DBClient getRemote(String hostname, String port)
throws UnknownHostException, IOException {
return new DvdSocketClient(hostname, port);
}
}
|
package com.cskaoyan.bean.vo;
/**
* @Author:ZCH
* @Date:2019/6/6 21:58
*/
public class ImgPreVo extends Vo{
public ImgPreVo() {
}
public ImgPreVo(int status,Object data, String imgPre) {
this.setStatus(status);
this.setData(data);
this.setImgPre(imgPre);
}
@Override
public String getImgPre() {
return super.getImgPre();
}
@Override
public void setImgPre(String imgPre) {
super.setImgPre(imgPre);
}
@Override
public int getStatus() {
return super.getStatus();
}
@Override
public void setStatus(int status) {
super.setStatus(status);
}
@Override
public Object getData() {
return super.getData();
}
@Override
public void setData(Object data) {
super.setData(data);
}
}
|
/*
* 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 com.mmorg29.appointmentscheduler;
import com.mmorg29.dbtools.Customer;
import com.mmorg29.dbtools.CustomerBuilder;
import com.mmorg29.dbtools.DBManager;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.function.Predicate;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListView;
import javafx.scene.control.Tab;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Modality;
import javafx.stage.StageStyle;
/**
* FXML Controller class
*
* @author mmorg
*/
public class CustomerHistoryReportController implements Initializable {
@FXML
private ComboBox<String> customer_selector;
@FXML
private ListView<String> customer_history_list_view;
private Map<String, Customer> customers = new HashMap<>();
private Tab parentTab;
private final Predicate<String> NOT_EMPTY = (input) -> input != null && !input.isEmpty();
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
loadCustomers();
ObservableList<String> sortedCustomers = FXCollections.observableArrayList(customers.keySet()).sorted();
this.customer_selector.setItems(sortedCustomers);
this.customer_selector.getSelectionModel().select(0);
loadCustomerHistory();
}
@FXML
private void handleCustomerSelectorOnAction(ActionEvent event) {
loadCustomerHistory();
}
/**
* Creates a Customer object for each customer and adds it to a HashMap for later retrieval.
*/
private void loadCustomers() {
String sql = "SELECT * FROM " + DBManager.CUSTOMER_TABLE + " ORDER BY customerName ASC";
try (DBManager dbManager = new DBManager(); Statement statement = dbManager.getStatement(); ResultSet resultSet = statement.executeQuery(sql);) {
while (resultSet.next()) {
CustomerBuilder customerBuilder = new CustomerBuilder();
customerBuilder.setCustomerId(resultSet.getInt(1));
customerBuilder.setCustomerName(resultSet.getString(2));
customerBuilder.setAddress(resultSet.getInt(3));
customerBuilder.setStatus(resultSet.getBoolean(4));
customerBuilder.setCreateDate(resultSet.getTimestamp(5));
customerBuilder.setCreatedBy(resultSet.getString(6));
customerBuilder.setLastUpdate(resultSet.getTimestamp(7));
customerBuilder.setLastUpdatedBy(resultSet.getString(8));
Customer customer = customerBuilder.build();
this.customers.put(customer.getCustomerName(), customer);
}
} catch (SQLException sqlEx) {
Alert alert = new Alert(Alert.AlertType.ERROR, "There was an issue retrieving required data. Report will be closed.", ButtonType.OK);
alert.initStyle(StageStyle.UNDECORATED);
alert.initModality(Modality.APPLICATION_MODAL);
alert.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresent(response -> {
alert.close();
Platform.runLater(() -> {
if (parentTab != null) {
parentTab.getTabPane().getTabs().remove(parentTab);
}
});
});
}
}
/**
* mam
* Sets a reference to the tab that this report is displayed in
* @param tab the tab displaying this report
*/
public void setParentTab(Tab tab) {
this.parentTab = tab;
}
/**
* Creates the customer history report for all appointments the selected customer has ever had.
* Displays the appointment history for the customer in a ListView
*/
private void loadCustomerHistory() {
this.customer_history_list_view.getItems().clear();
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a");
Customer customer = this.customers.get(this.customer_selector.getValue());
String sql = "SELECT * FROM " + DBManager.APPOINTMENT_TABLE
+ " JOIN " + DBManager.USER_TABLE + " ON user.userId = CAST(appointment.createdBy AS UNSIGNED) WHERE appointment.customerId = "
+ customer.getId() + " ORDER BY appointment.start ASC";
try (DBManager dbManager = new DBManager();
Statement statement = dbManager.getStatement();
ResultSet resultSet = statement.executeQuery(sql);) {
while (resultSet.next()) {
LocalDateTime zonedStartDateTime = DateTimeConversion.ZONED_LOCAL_DATE_TIME.apply(resultSet.getTimestamp(8));
LocalDateTime zonedEndDateTime = DateTimeConversion.ZONED_LOCAL_DATE_TIME.apply(resultSet.getTimestamp(9));
StringBuilder customerAppointmentBuilder = new StringBuilder();
customerAppointmentBuilder.append(zonedStartDateTime.toLocalDate().format(dateFormatter));
customerAppointmentBuilder.append(" ").append(zonedStartDateTime.toLocalTime().format(timeFormatter)).append(" - ");
customerAppointmentBuilder.append(zonedEndDateTime.toLocalTime().format(timeFormatter));
customerAppointmentBuilder.append("\nType: ").append(resultSet.getString(3));
customerAppointmentBuilder.append("\nConsultant: ").append(resultSet.getString("user.userName"));
if (NOT_EMPTY.test(resultSet.getString(6))) {
customerAppointmentBuilder.append("\nContact: ").append(resultSet.getString(6));
}
customerAppointmentBuilder.append("\nLocation: ");
if (NOT_EMPTY.test(resultSet.getString(5))) {
customerAppointmentBuilder.append(resultSet.getString(5));
} else {
customerAppointmentBuilder.append(customer.ADDRESS.get().getPhoneNumber());
}
if (NOT_EMPTY.test(resultSet.getString(4))) {
customerAppointmentBuilder.append("\nDescription: ").append(resultSet.getString(4));
}
this.customer_history_list_view.getItems().add(customerAppointmentBuilder.toString());
}
} catch (SQLException sqlEx) {
Alert alert = new Alert(Alert.AlertType.ERROR, "There was an issue retrieving the customers history. Report will be closed.", ButtonType.OK);
alert.initStyle(StageStyle.UNDECORATED);
alert.initModality(Modality.APPLICATION_MODAL);
alert.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresent(response -> {
alert.close();
Platform.runLater(() -> {
if (parentTab != null) {
parentTab.getTabPane().getTabs().remove(parentTab);
}
});
});
}
}
}
|
package com.bot.currencies;
public class SimpleCurrency implements Comparable{
private String name;
private static final String format = "%s %.3f";
private float rate;
private String mark;
public SimpleCurrency(String name, float rate, String mark) {
this.name = name;
this.rate = rate;
this.mark = mark;
}
@Override
public String toString() {
return String.format(format, name, rate);
}
@Override
public int compareTo(Object o) {
return this.name.compareTo(((SimpleCurrency)o).getName());
}
private String getName() {
return name;
}
public String getMark() {
return mark;
}
public float getRate() {
return rate;
}
}
|
//designpatterns.factorymethod.FileLoggerFactory.java
package designpatterns.factorymethod;
//文件日志记录器工厂类,充当具体工厂角色
public class FileLoggerFactory implements LoggerFactory {
public Logger createLogger() {
//创建文件日志记录器对象
Logger logger = new FileLogger();
//创建文件,代码省略
return logger;
}
}
|
/**
* Card
*/
public class Card {
private String _identity;
private Character _suit;
private int _value;
public Card(String _identity, Character _suit) {
this._identity = _identity;
this._suit = _suit;
this._value = this._calcValue();
}
@Override
public String toString() {
return this._identity + this._suit;
}
public String getIdentity() {
return this._identity;
}
public Character getSuit() {
return this._suit;
}
public int getValue() {
return this._value;
}
private int _calcValue() {
int result;
switch (this._identity) {
case "A":
result = 11;
break;
case "K":
result = 4;
break;
case "Q":
result = 2;
break;
case "J":
result = 3;
break;
case "7":
result = 10;
break;
default:
result = 0;
break;
}
return result;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Card ) {
return this.toString().equals(((Card)obj).toString());
}
return false;
}
}
|
package action.com.team;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.ApplicationContext;
import pojo.businessObject.TeamBO;
import pojo.valueObject.domain.TeamVO;
import tool.BeanFactory;
import tool.JSONHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* 创建团队
* Created by GR on 2017/2/26.
*/
public class CreateTeamAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware {
//jsp获取
private String teamName;
private String description;
private Integer memberMax;
private HttpServletRequest request;
private HttpServletResponse response;
private Map<String, Object> session;
private JSONObject jsonObject;
@Override
public String execute() throws Exception {
TeamBO teamBO = BeanFactory.getApplicationContext().getBean("teamBO",TeamBO.class);
try {
jsonObject = teamBO.createTeam(teamName, description, memberMax, session);
JSONHandler.sendJSON(jsonObject,response);
System.out.println("创建团队");
System.out.println(jsonObject);
return "success";
}catch(Exception e){
e.printStackTrace();
jsonObject.put("result","SQLException");
JSONHandler.sendJSON(jsonObject, response);
return "fail";
}
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getMemberMax() {
return memberMax;
}
public void setMemberMax(Integer memberMax) {
this.memberMax = memberMax;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
try {
this.request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
this.response.setCharacterEncoding("UTF-8");
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public JSONObject getJsonObject() {
return jsonObject;
}
public void setJsonObject(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public Map<String, Object> getSession() {
return session;
}
}
|
package com.example.dto;
import lombok.Data;
/**
* Created by sunming on 2019/6/11.
*/
@Data
public class TbEmp {
private Integer id;
private String name;
private Integer age;
private String gender;
private String email;
}
|
package com.flyingh.moguard.receiver;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import com.flyingh.moguard.service.TaskManagerService;
public class TaskManagerWidgetProvider extends AppWidgetProvider {
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
context.startService(new Intent(context, TaskManagerService.class));
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
context.startService(new Intent(context, TaskManagerService.class));
}
}
|
package com.auro.scholr.home.presentation.view.adapter;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.auro.scholr.R;
import com.auro.scholr.core.common.AppConstant;
import com.auro.scholr.databinding.MonthWiseItemLayoutBinding;
import com.auro.scholr.home.data.model.MonthlyScholarShipModel;
import com.auro.scholr.home.presentation.view.viewholder.MonthlyWiseViewHolder;
import java.util.List;
public class MontlyWiseAdapter extends RecyclerView.Adapter {
List<MonthlyScholarShipModel> listmonthly;
public MontlyWiseAdapter(List<MonthlyScholarShipModel> listmonthly) {
this.listmonthly=listmonthly;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
switch (viewType) {
case AppConstant.FriendsLeaderBoard.TRANSACTIONS_ADAPTER:
MonthWiseItemLayoutBinding MonthWiseItemLayoutbinding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), R.layout.month_wise_item_layout, viewGroup, false);
return new MonthlyWiseViewHolder(MonthWiseItemLayoutbinding);
}
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
int viewType = listmonthly.get(position).getViewType();
switch (viewType) {
case AppConstant.FriendsLeaderBoard.TRANSACTIONS_ADAPTER:
((MonthlyWiseViewHolder) holder).bindUser(listmonthly.get(position), position);
break;
}
}
@Override
public int getItemViewType(int position) {
switch (listmonthly.get(position).getViewType()) {
case AppConstant.FriendsLeaderBoard.TRANSACTIONS_ADAPTER:
return AppConstant.FriendsLeaderBoard.TRANSACTIONS_ADAPTER;
default:
return -1;
}
}
@Override
public int getItemCount() {
return listmonthly.size();
}
}
|
package questionFactory;
import question.Question;
import question.concreteQuestion.BuildTowerAndCompareQuestion;
public class BuildTowerAndCompareFactory implements QuestionFactory {
BuildTowerAndCompareQuestion question;
@Override
public Question createQuestion() {
question = new BuildTowerAndCompareQuestion();
return question;
}
}
|
package com.vincent.algorithm.basic.btree;
/**
* leetcode 236
* 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
*
* 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
*
* 例如,给定如下二叉树: root =[3,5,1,6,2,0,8,null,null,7,4]
*
*
*
*
*
* 示例 1:
*
* 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
* 输出: 3
* 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
* 示例2:
*
* 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
* 输出: 5
* 解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
*
*
* 说明:
*
* 所有节点的值都是唯一的。
* p、q 为不同节点且均存在于给定的二叉树中。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class LowestCommonAncestorOfABinaryTree {
/**
视频讲解:见极客时间,覃超
最大公共子树定义:就是看两个节点,从它开始往根回溯过程中的两条路径中,最早相遇的点
解题思路:使用递归
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null|| root.equals(p) || root.equals(q)) return root;//如果输入的节点为空直接返回。如果要查找的节点任意一个等于根节点,那么最大公共子树就是根节点。因为根节点是所有子节点的共同节点。
TreeNode leftTreeNode = lowestCommonAncestor(root.left, p, q);//如果上述p或q不是根节点,那么递归去左子树中找
TreeNode rightTreeNode = lowestCommonAncestor(root.right, p, q);//如果上述p或q不是根节点,那么递归去右子树中找
if(leftTreeNode == null) {
//如果左子中找的结果为空,说明p和q 都不在左子树。所以直接使用右子树遍历的结果即可
return rightTreeNode;
}
if(rightTreeNode == null) {
//如果右子树查找的结果为空,说明p,q都不在右子树,而在左子树。 所以直接使用左子树搜索的结果即可
return leftTreeNode;
}
//如果左右搜索的结果都不为空,说明p和q,分别分布在左右子树中。那么当前的root显然就应该是他们的公共子节点
return root;
}
}
|
/*
* Created on Apr 23, 2007
*
*/
package com.citibank.ods.modules.client.erem.functionality;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.struts.action.ActionForm;
import com.citibank.ods.Globals;
import com.citibank.ods.common.functionality.ODSMovementDetailFnc;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
import com.citibank.ods.common.util.ODSConstraintDecoder;
import com.citibank.ods.entity.pl.TplCustomerPrvtEntity;
import com.citibank.ods.entity.pl.TplErEmEntity;
import com.citibank.ods.entity.pl.TplErEmHistEntity;
import com.citibank.ods.entity.pl.TplErEmMovEntity;
import com.citibank.ods.entity.pl.TplRoleCustEntity;
import com.citibank.ods.entity.pl.valueobject.TplErEmEntityVO;
import com.citibank.ods.entity.pl.valueobject.TplErEmMovEntityVO;
import com.citibank.ods.modules.client.erem.form.EREMMovementDetailForm;
import com.citibank.ods.modules.client.erem.functionality.valueobject.EREMMovementDetailFncVO;
import com.citibank.ods.persistence.pl.dao.BaseTplErEmDAO;
import com.citibank.ods.persistence.pl.dao.TplCustomerPrvtCmplDAO;
import com.citibank.ods.persistence.pl.dao.TplCustomerPrvtDAO;
import com.citibank.ods.persistence.pl.dao.TplErEmDAO;
import com.citibank.ods.persistence.pl.dao.TplErEmHistDAO;
import com.citibank.ods.persistence.pl.dao.TplErEmMovDAO;
import com.citibank.ods.persistence.pl.dao.TplRoleCustDAO;
import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory;
/**
* @author leonardo.nakada
*/
public class EREMMovementDetailFnc extends BaseEREMDetailFnc implements
ODSMovementDetailFnc
{
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.client.erem.functionality.BaseEREMDetailFnc#getDAO()
*/
protected BaseTplErEmDAO getDAO()
{
return null;
}
/**
* Realizar a atualização do reristro
*/
public void update( BaseFncVO fncVO_ )
{
TplErEmMovEntity erMovEntity;
TplErEmMovEntityVO erMovEntityVO;
this.validateUpdate( fncVO_ );
if ( !fncVO_.hasErrors() )
{
EREMMovementDetailFncVO erMovDetailFncVO = ( EREMMovementDetailFncVO ) fncVO_;
String erNbr = erMovDetailFncVO.getBaseTplErEmEntity().getData().getErNbr();
TplErEmMovDAO tplRelationErMovDAO = ODSDAOFactory.getInstance().getTplErEmMovDAO();
tplRelationErMovDAO.deleteRelations( erNbr );
for ( int j = 0; j < erMovDetailFncVO.getSelectedItemsInGrid().size(); j++ )
{
for ( int i = 0; i < erMovDetailFncVO.getBaseTplErEmEntities().size(); i++ )
{
if ( erMovDetailFncVO.getDeletedItems().get( j ).equals( "S" ) )
{
erMovDetailFncVO.getBaseTplErEmEntities().remove( i );
break;
}
}
}
ArrayList list = erMovDetailFncVO.getBaseTplErEmEntities();
for ( Iterator ite = list.iterator(); ite.hasNext(); )
{
erMovEntity = ( TplErEmMovEntity ) ite.next();
erMovEntityVO = ( TplErEmMovEntityVO ) erMovEntity.getData();
erMovEntityVO.setLastUpdDate( new Date() );
erMovEntityVO.setLastUpdUserId( fncVO_.getLoggedUser().getUserID() );
if ( erMovEntityVO.getOpernCode() == null )
{
erMovEntityVO.setOpernCode( TplErEmMovEntity.C_OPERN_CODE_INSERT );
}
tplRelationErMovDAO.insert( erMovEntity );
}
}
}
/**
* Realiza a aprovacao das associações EG x Relacionamentos
*/
public void approve( BaseFncVO fncVO_ )
{
TplErEmEntity tplErEmEntity;
TplErEmHistEntity TplErEmHistEntity;
this.validateApprove( fncVO_ );
if ( !fncVO_.hasErrors() )
{
EREMMovementDetailFncVO erMovDetailFncVO = ( EREMMovementDetailFncVO ) fncVO_;
String erNbr = erMovDetailFncVO.getBaseTplErEmEntity().getData().getErNbr();
TplErEmDAO tplRelationErDAO = ODSDAOFactory.getInstance().getTplErEmDAO();
TplErEmHistDAO tplRelationErHistDAO = ODSDAOFactory.getInstance().getTplErEmHistDAO();
// Inseri os dados da tabela de movimento
ArrayList approveList = erMovDetailFncVO.getBaseTplErEmEntities();
if ( approveList != null && !approveList.isEmpty() )
{
Date date = new Date();
TplErEmMovEntity tplErEmMovEntity;
TplErEmMovEntityVO tplErEmMovEntityVO;
Date approveDate = new Date();
String authUserId = fncVO_.getLoggedUser().getUserID();
List<String> listEmNbr = new ArrayList<String>();
for ( Iterator ite = approveList.iterator(); ite.hasNext(); )
{
tplErEmMovEntity = ( TplErEmMovEntity ) ite.next();
tplErEmMovEntityVO = ( TplErEmMovEntityVO ) tplErEmMovEntity.getData();
//Verifica se Em já passou pela atualizacao, pois qdo há mais de 1 cliente com o mesmo EM, vem 2 registros no 'approveList' com o mesmo ER x EM
if (!listEmNbr.contains(tplErEmMovEntityVO.getEmNbr())){
// Se existe associações na Current, copiar para histórico
if ( tplRelationErDAO.existsRelation( erNbr, tplErEmMovEntityVO.getEmNbr() ) )
{
ArrayList list = tplRelationErDAO.listAllByErEM(erNbr, tplErEmMovEntityVO.getEmNbr() );
if ( list != null && !list.isEmpty() )
{
if (list.iterator().hasNext()){
{
tplErEmEntity = ( TplErEmEntity ) list.iterator().next();
TplErEmHistEntity = new TplErEmHistEntity( tplErEmEntity, date );
tplRelationErHistDAO.insert( TplErEmHistEntity );
}
}
}
}
tplErEmEntity = new TplErEmEntity(
tplErEmMovEntity,
authUserId,
approveDate,
TplErEmEntity.C_REC_STAT_CODE_ACTIVE );
if ( TplErEmMovEntity.C_OPERN_CODE_DELETE.equals( tplErEmMovEntityVO.getOpernCode() ) )
{
( ( TplErEmEntityVO ) tplErEmEntity.getData() ).setRecStatCode( TplErEmEntity.C_REC_STAT_CODE_INACTIVE );
tplRelationErDAO.update( tplErEmEntity );
}
else
{
if ( tplRelationErDAO.existsRelation( erNbr,
tplErEmMovEntityVO.getEmNbr() ) )
{
// //Verifica se já existe associacao inativa, caso exista deve gravar na tabela de historico antes de atualizar o registro
// if (tplRelationErDAO.existsRelationInactive(erNbr, tplErEmMovEntityVO.getEmNbr() ) ){
// TplErEmHistEntity = new TplErEmHistEntity( tplErEmEntity, date );
// tplRelationErHistDAO.insert( TplErEmHistEntity );
// }
tplRelationErDAO.update( tplErEmEntity );
}
else
{
tplRelationErDAO.insert( tplErEmEntity );
}
}
listEmNbr.add(tplErEmMovEntityVO.getEmNbr());
TplErEmMovDAO tplRelationErMovDAO = ODSDAOFactory.getInstance().getTplErEmMovDAO();
tplRelationErMovDAO.deleteRelations( erNbr );
}
}
}
}
}
/**
* Realiza a reprovação das associações
*/
public void reprove( BaseFncVO fncVO_ )
{
this.validateReprove( fncVO_ );
if ( !fncVO_.hasErrors() )
{
EREMMovementDetailFncVO erMovDetailFncVO = ( EREMMovementDetailFncVO ) fncVO_;
String erNbr = erMovDetailFncVO.getBaseTplErEmEntity().getData().getErNbr();
TplErEmMovDAO tplRelationErMovDAO = ODSDAOFactory.getInstance().getTplErEmMovDAO();
tplRelationErMovDAO.deleteRelations( erNbr );
}
}
/**
* Realiza as validações de Update
*/
public void validateUpdate( BaseFncVO fncVO_ )
{
EREMMovementDetailFncVO erMovDetailFncVO = ( EREMMovementDetailFncVO ) fncVO_;
ArrayList list = erMovDetailFncVO.getBaseTplErEmEntities();
String lastUpdUserId = getLastUpdUserFromList( erMovDetailFncVO );
// testar usuário
if ( erMovDetailFncVO.getLoggedUser() == null
|| !erMovDetailFncVO.getLoggedUser().getUserID().equals( lastUpdUserId ) )
{
erMovDetailFncVO.addError( EREMMovementDetailFncVO.C_ERROR_APPROVAL_UPDATE_USER_NOT_AUTHORIZED );
}
}
/**
* Realiza as validações da aprovação
*/
public void validateApprove( BaseFncVO fncVO_ )
{
EREMMovementDetailFncVO erMovDetailFncVO = ( EREMMovementDetailFncVO ) fncVO_;
String lastUpdUserId = getLastUpdUserFromList( erMovDetailFncVO );
// testar usuário
if ( erMovDetailFncVO.getLoggedUser() == null
|| erMovDetailFncVO.getLoggedUser().getUserID().equals( lastUpdUserId ) )
{
erMovDetailFncVO.addError( EREMMovementDetailFncVO.C_ERROR_APPROVAL_USER_NOT_AUTHORIZED );
}
}
/*
* Recupera o usuário da última atualização dos reristros
*/
private String getLastUpdUserFromList(
EREMMovementDetailFncVO erMovDetailFncVO )
{
ArrayList list = erMovDetailFncVO.getBaseTplErEmEntities();
if ( list != null && list.size() > 0 )
{
TplErEmMovEntity tplErEmMovEntity = ( TplErEmMovEntity ) list.iterator().next();
return tplErEmMovEntity.getData().getLastUpdUserId();
}
return null;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.ODSMovementDetailFnc#validateReprove(com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void validateReprove( BaseFncVO fncVO_ )
{
//
}
/**
* Carreramentos iniciais para a atualização
*/
public void loadForUpdate( BaseFncVO fncVO_ )
{
EREMMovementDetailFncVO erMovDetailFncVO = ( EREMMovementDetailFncVO ) fncVO_;
super.loadDomains( erMovDetailFncVO );
if ( erMovDetailFncVO.isFromSearch() )
{
loadEmNbr( erMovDetailFncVO );
loadCustText( erMovDetailFncVO );
erMovDetailFncVO.setFromSearch( false );
}
else
{
String erNbr = erMovDetailFncVO.getBaseTplErEmEntity().getData().getErNbr();
TplErEmMovDAO tplRelationErMovDAO = ODSDAOFactory.getInstance().getTplErEmMovDAO();
ArrayList list = tplRelationErMovDAO.listByErNbr( erNbr );
if ( list != null && list.size() > 0 )
{
TplErEmMovEntity relationErMovEntity = ( TplErEmMovEntity ) list.iterator().next();
TplErEmMovEntityVO erMovEntityVO = ( TplErEmMovEntityVO ) relationErMovEntity.getData();
erMovDetailFncVO.setCurrentOpernCode( erMovEntityVO.getOpernCode() );
erMovDetailFncVO.setBaseTplErEmEntities( list );
}
erMovDetailFncVO.setCustFullNameText( null );
erMovDetailFncVO.getBaseTplErEmEntity().getData().setRoleCustCode( null );
erMovDetailFncVO.getBaseTplErEmEntity().getData().setEmNbr( null );
erMovDetailFncVO.setCustNbr( null );
}
}
/**
* Carreramentos iniciais para a aprovação
*/
public void loadForApprove( BaseFncVO fncVO_ )
{
EREMMovementDetailFncVO erMovDetailFncVO = ( EREMMovementDetailFncVO ) fncVO_;
String erNbr = erMovDetailFncVO.getBaseTplErEmEntity().getData().getErNbr();
TplErEmMovDAO tplRelationErMovDAO = ODSDAOFactory.getInstance().getTplErEmMovDAO();
ArrayList list = tplRelationErMovDAO.listByErNbr( erNbr );
if ( list != null )
{
erMovDetailFncVO.setBaseTplErEmEntities( list );
}
}
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.ODSMovementDetailFnc#loadForConsult(com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void loadForConsult( BaseFncVO fncVO_ )
{
//
}
/**
* Retorna uma instancia de um FncVO
*/
public BaseFncVO createFncVO()
{
return new EREMMovementDetailFncVO();
}
/**
* Atualiza as informações do Form com os valores vindos do FncVO
*/
public void updateFormFromFncVO( ActionForm form_, BaseFncVO fncVO_ )
{
TplErEmMovEntity erEntity;
TplErEmMovEntityVO erEntityVO;
super.updateFormFromFncVO( form_, fncVO_ );
EREMMovementDetailForm relationErDetailForm = ( EREMMovementDetailForm ) form_;
EREMMovementDetailFncVO relationErDetailFncVO = ( EREMMovementDetailFncVO ) fncVO_;
String[][] grid = new String[ relationErDetailFncVO.getBaseTplErEmEntities().size() ][ 7 ];
int indexLinha = 0;
for ( Iterator ite = relationErDetailFncVO.getBaseTplErEmEntities().iterator(); ite.hasNext(); indexLinha++ )
{
erEntity = ( TplErEmMovEntity ) ite.next();
erEntityVO = ( TplErEmMovEntityVO ) erEntity.getData();
String strErNbr = "";
if ( erEntityVO.getErNbr() != null )
{
strErNbr = erEntityVO.getErNbr();
}
grid[ indexLinha ][ EREMMovementDetailForm.COL_POS_ER_NBR ] = strErNbr;
String strEmNbr = "";
if ( erEntityVO.getEmNbr() != null )
{
strEmNbr = erEntityVO.getEmNbr();
}
grid[ indexLinha ][ EREMMovementDetailForm.COL_POS_EM_NBR ] = strEmNbr;
if ( erEntity.getRoleCustEntity() != null )
{
TplRoleCustEntity tplRoleCustEntity = null;
tplRoleCustEntity = erEntity.getRoleCustEntity();
if ( tplRoleCustEntity != null
&& tplRoleCustEntity.getData().getRoleCustText() != null )
{
grid[ indexLinha ][ EREMMovementDetailForm.COL_POS_ROLE_CUST_CODE ] = tplRoleCustEntity.getData().getRoleCustText();
}
else
{
grid[ indexLinha ][ EREMMovementDetailForm.COL_POS_ROLE_CUST_CODE ] = "";
}
}
String strCustFullName = "";
TplCustomerPrvtEntity tplCustomerPrvtEntity = erEntity.getCustomerPrvtEntity();
if ( tplCustomerPrvtEntity != null
&& tplCustomerPrvtEntity.getData().getCustFullNameText() != null )
{
strCustFullName = tplCustomerPrvtEntity.getData().getCustFullNameText();
}
grid[ indexLinha ][ EREMMovementDetailForm.COL_POS_CUST_FULL_NAME ] = strCustFullName;
String strLastUpdUserId = "";
if ( erEntityVO.getLastUpdUserId() != null )
{
strLastUpdUserId = erEntityVO.getLastUpdUserId();
}
grid[ indexLinha ][ EREMMovementDetailForm.COL_POS_LAST_UPD_USER_ID ] = strLastUpdUserId;
String strLastUpdDate = "";
if ( erEntityVO.getLastUpdDate() != null )
{
SimpleDateFormat sdf = new SimpleDateFormat(
Globals.FuncionalityFormatKeys.C_FORMAT_DATETIME_DDMMYYYY_HHMM );
strLastUpdDate = sdf.format( erEntityVO.getLastUpdDate() );
}
grid[ indexLinha ][ EREMMovementDetailForm.COL_POS_LAST_UPD_DATE ] = strLastUpdDate;
String strOpernCode = "";
if ( erEntityVO.getOpernCode() != null )
{
strOpernCode = ODSConstraintDecoder.decodeOpern( erEntityVO.getOpernCode() );
}
grid[ indexLinha ][ EREMMovementDetailForm.COL_POS_OPERN_CODE ] = strOpernCode;
relationErDetailForm.setLastUpdUserId( strLastUpdUserId );
}
relationErDetailForm.setErEmGrid( grid );
}
/*
* Insere o domínio no Grid
*/
public void insertDomain( BaseFncVO fncVO_ )
{
EREMMovementDetailFncVO detailFncVO = ( EREMMovementDetailFncVO ) fncVO_;
this.validateInsertDomain( detailFncVO );
if ( !detailFncVO.hasErrors() )
{
// Entity to Insert
TplErEmMovEntity tplErEmEntity = ( TplErEmMovEntity ) detailFncVO.getBaseTplErEmEntity();
// Cópia
TplErEmMovEntity cpTplErEmMovEntity = new TplErEmMovEntity();
cpTplErEmMovEntity.getData().setErNbr( tplErEmEntity.getData().getErNbr() );
cpTplErEmMovEntity.getData().setEmNbr( tplErEmEntity.getData().getEmNbr() );
cpTplErEmMovEntity.getData().setRoleCustCode(
tplErEmEntity.getData().getRoleCustCode() );
( ( TplErEmMovEntityVO ) cpTplErEmMovEntity.getData() ).setOpernCode( TplErEmMovEntity.C_OPERN_CODE_INSERT );
// Recuperando o Role Cust
TplRoleCustDAO roleCustDAO = ODSDAOFactory.getInstance().getTplRoleCustDAO();
TplRoleCustEntity tplRoleCustEntity = new TplRoleCustEntity();
tplRoleCustEntity.getData().setRoleCustCode(
tplErEmEntity.getData().getRoleCustCode() );
cpTplErEmMovEntity.setRoleCustEntity( ( TplRoleCustEntity ) roleCustDAO.find( tplRoleCustEntity ) );
TplCustomerPrvtDAO tplCustomerPrvtDAO = ODSDAOFactory.getInstance().getTplCustomerPrvtDAO();
TplCustomerPrvtEntity tplCustomerPrvtEntity = new TplCustomerPrvtEntity();
tplCustomerPrvtEntity.getData().setCustNbr( detailFncVO.getCustNbr() );
cpTplErEmMovEntity.setCustomerPrvtEntity( ( TplCustomerPrvtEntity ) tplCustomerPrvtDAO.find( tplCustomerPrvtEntity ) );
detailFncVO.getSelectedItemsInGrid().add( "S" );
detailFncVO.getDeletedItems().add( "N" );
detailFncVO.getBaseTplErEmEntities().add( cpTplErEmMovEntity );
}
}
/*
* Realiza as validações do insert domain
*/
private void validateInsertDomain( EREMMovementDetailFncVO detailFncVO_ )
{
EREMMovementDetailFncVO detailFncVO = ( EREMMovementDetailFncVO ) detailFncVO_;
TplErEmMovEntityVO erEmEntityVO = ( TplErEmMovEntityVO ) detailFncVO.getBaseTplErEmEntity().getData();
// Validação de campos obrigatórios
if ( erEmEntityVO.getErNbr() == null || erEmEntityVO.getErNbr().equals( "" ) )
{
detailFncVO.addError( EREMMovementDetailFncVO.C_ERROR_MANDATORY_FIELD,
EREMMovementDetailFncVO.C_ER_NBR_DESCRIPTION );
}
if ( erEmEntityVO.getEmNbr() == null || erEmEntityVO.getEmNbr().equals( "" ) )
{
detailFncVO.addError( EREMMovementDetailFncVO.C_ERROR_MANDATORY_FIELD,
EREMMovementDetailFncVO.C_EM_NBR_DESCRIPTION );
}
if ( erEmEntityVO.getRoleCustCode() == null
|| erEmEntityVO.getRoleCustCode().equals( "" ) )
{
detailFncVO.addError(
EREMMovementDetailFncVO.C_ERROR_MANDATORY_FIELD,
EREMMovementDetailFncVO.C_ROLE_CUST_CODE_DESCRIPTION );
}
if ( !detailFncVO.hasErrors() )
{
// Valida se o registro a ser inserido
// possui o mesmo ER dos outros
ArrayList list = detailFncVO.getBaseTplErEmEntities();
if ( !list.isEmpty() )
{
TplErEmMovEntity tplErEmEntity = ( TplErEmMovEntity ) list.iterator().next();
String firstErNbr = tplErEmEntity.getData().getErNbr();
if ( !erEmEntityVO.getErNbr().equals( firstErNbr ) )
{
detailFncVO.addError(
EREMMovementDetailFncVO.C_ERROR_DUPLICATE_REG_IN_GRID,
EREMMovementDetailFncVO.C_ER_NBR_DESCRIPTION );
}
}
// Verifica se já existe essa associação ER x EM no Grid
if ( detailFncVO.getBaseTplErEmEntities().contains(
detailFncVO.getBaseTplErEmEntity() ) )
{
detailFncVO.addError( EREMMovementDetailFncVO.C_ERROR_DUPLICATED_ELEMENT_IN_GRID );
}
}
if ( !detailFncVO.hasErrors() )
{
TplCustomerPrvtCmplDAO tplCustomerPrvtCmplDAO = ODSDAOFactory.getInstance().getTplCustomerPrvtCmplDAO();
if ( !tplCustomerPrvtCmplDAO.existsEmNbr( erEmEntityVO.getEmNbr() ) )
{
detailFncVO.addError( EREMMovementDetailFncVO.C_ERROR_REG_NOT_EXISTS,
EREMMovementDetailFncVO.C_EM_NBR_DESCRIPTION );
}
}
}
/*
* Remove o domínio do Grid
*/
public void deleteDomain( BaseFncVO fncVO_ )
{
EREMMovementDetailFncVO eremMovementDetailFncVO = ( EREMMovementDetailFncVO ) fncVO_;
ArrayList list = eremMovementDetailFncVO.getBaseTplErEmEntities();
TplErEmMovEntity tplEREMEntity = new TplErEmMovEntity();
tplEREMEntity.getData().setErNbr(
eremMovementDetailFncVO.getSelectedErNbrInGrid() );
tplEREMEntity.getData().setEmNbr(
eremMovementDetailFncVO.getSelectedEmNbrInGrid() );
list.remove( tplEREMEntity );
}
}
|
package com.datagraph.core;
/**
* Created by Denny Joseph on 4/24/16.
*/
public class ServiceManager {
}
|
package online.lahloba.www.lahloba.data.model;
import android.os.Parcel;
import android.os.Parcelable;
public class CityItem implements Parcelable {
private String id;
private String name;
double lat;
double lan;
String parent;
public CityItem() {
}
protected CityItem(Parcel in) {
id = in.readString();
name = in.readString();
lat = in.readDouble();
lan = in.readDouble();
parent = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(name);
dest.writeDouble(lat);
dest.writeDouble(lan);
dest.writeString(parent);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<CityItem> CREATOR = new Creator<CityItem>() {
@Override
public CityItem createFromParcel(Parcel in) {
return new CityItem(in);
}
@Override
public CityItem[] newArray(int size) {
return new CityItem[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLan() {
return lan;
}
public void setLan(double lan) {
this.lan = lan;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
}
|
package com.fanfte.concurrent.threads;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Created by tianen on 2019/3/18
*
* @author fanfte
* @date 2019/3/18
**/
public class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
Future<String> submit = executorService.submit(new MyCallable());
if (!submit.isDone()) {
System.out.println("task is not done, please wait " );
}
try {
System.out.println(submit.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
|
package io.raccoonconsultant.repositories;
import io.raccoonconsultant.entities.Exam;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ExamRepository extends JpaRepository<Exam, Long> {
}
|
package com.raymon.api.utils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class JsonTools {
/**
* 将json格式的字符串转换为map
* @param json
* @return
*/
public static Map<String, Object> jsonToMap(String json) {
Map<String, Object> map = new HashMap<String, Object>();
ObjectMapper mapper = new ObjectMapper();
try {
map = mapper.readValue(json, new TypeReference<HashMap<String, Object>>() {});
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static void main(String[] args) {
//String json = "{\"method\":\"\",\"params\":[{\"skuString\":\"1_31772\"},{\"skuString2\":\"1_3177222222\"}]}";
//List list = (List)JsonTools.jsonToMap(json).get("params");
//Map<String,String> s = (Map<String,String>)list.get(1);
}
}
|
public class Solution{
//this method takes O(n) time and O(logn) space;
public static TreeNode buildBST(int[] array){
return build(array,0,array.length-1);
}
private static TreeNode build(int[] array,int low,int high){
if(low>high){return null;}
int mid = low + (high-low)/2;
TreeNode node = new TreeNode(array[mid]);
node.left = build(array,low,mid-1);
node.right = build(array,mid+1,high);
return node;
}
}
|
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.sara.tablas.cajero.servicio;
import javax.persistence.Query;
import java.util.logging.Level;
import java.util.Collection;
import com.davivienda.sara.entitys.Transportadora;
import com.davivienda.sara.entitys.Ubicacion;
import com.davivienda.sara.entitys.TipoCajero;
import com.davivienda.sara.base.exception.EntityServicioExcepcion;
import com.davivienda.sara.entitys.Occa;
import javax.persistence.EntityManager;
import com.davivienda.sara.tablas.transportadora.servicio.TransportadoraServicio;
import com.davivienda.sara.tablas.ubicacion.servicio.UbicacionServicio;
import com.davivienda.sara.tablas.tipocajero.servicio.TipoCajeroServicio;
import com.davivienda.sara.tablas.occa.servicio.OccaServicio;
import com.davivienda.sara.entitys.Cajero;
import com.davivienda.sara.base.BaseEntityServicio;
public class CajeroServicio extends BaseEntityServicio<Cajero>
{
OccaServicio occaServicio;
TipoCajeroServicio tipoCajeroServicio;
UbicacionServicio ubicacionServicio;
TransportadoraServicio transportadoraServicio;
public CajeroServicio(final EntityManager em) {
super(em, Cajero.class);
this.occaServicio = new OccaServicio(em);
this.tipoCajeroServicio = new TipoCajeroServicio(em);
this.ubicacionServicio = new UbicacionServicio(em);
this.transportadoraServicio = new TransportadoraServicio(em);
}
@Override
public Cajero actualizar(final Cajero objeto) throws EntityServicioExcepcion {
Cajero objetoActual = super.buscar(objeto.getCodigoCajero());
final String accion = (objetoActual == null) ? "NUEVO" : "ACTUALIZAR";
if (accion.equals("NUEVO")) {
final Occa occa = this.occaServicio.buscar(objeto.getOcca().getCodigoOcca());
if (occa == null) {
throw new EntityServicioExcepcion("Debe asignar el c\u00f3digo de la occa");
}
final TipoCajero tipoCajero = this.tipoCajeroServicio.buscar(objeto.getTipoCajero().getCodigoTipoCajero());
if (tipoCajero == null) {
throw new EntityServicioExcepcion("Debe asignar el c\u00f3digo del Tipo de Cajero");
}
final Ubicacion ubicacion = this.ubicacionServicio.buscar(objeto.getUbicacion().getCodigoUbicacion());
if (ubicacion == null) {
throw new EntityServicioExcepcion("Debe asignar el c\u00f3digo de la Ubicacion");
}
final Transportadora transportadora = this.transportadoraServicio.buscar(objeto.getTransportadora().getIdTransportadora());
if (transportadora == null) {
throw new EntityServicioExcepcion("Debe asignar el c\u00f3digo de la Transportadora");
}
objeto.setUbicacion(ubicacion);
objeto.setTipoCajero(tipoCajero);
objeto.setOcca(occa);
objeto.setTransportadora(transportadora);
super.adicionar(objeto);
objetoActual = super.buscar(objeto.getCodigoCajero());
}
else {
final Occa occa = this.occaServicio.buscar(objeto.getOcca().getCodigoOcca());
if (occa == null) {
throw new EntityServicioExcepcion("c\u00f3digo de Occa no Valido");
}
final TipoCajero tipoCajero = this.tipoCajeroServicio.buscar(objeto.getTipoCajero().getCodigoTipoCajero());
if (tipoCajero == null) {
throw new EntityServicioExcepcion("c\u00f3digo del Tipo de Cajero no Valido");
}
final Ubicacion ubicacion = this.ubicacionServicio.buscar(objeto.getUbicacion().getCodigoUbicacion());
if (ubicacion == null) {
throw new EntityServicioExcepcion("c\u00f3digo de la Ubicacion no Valido");
}
final Transportadora transportadora = this.transportadoraServicio.buscar(objeto.getTransportadora().getIdTransportadora());
if (transportadora == null) {
throw new EntityServicioExcepcion("c\u00f3digo de la Transportadora no Valido");
}
objetoActual = objetoActual.actualizarEntity(objeto);
super.actualizar(objetoActual);
}
return objetoActual;
}
@Override
public void borrar(final Cajero entity) throws EntityServicioExcepcion {
Cajero confAccesoAplicacion = super.buscar(entity.getCodigoCajero());
super.borrar(confAccesoAplicacion);
confAccesoAplicacion = super.buscar(entity.getCodigoCajero());
}
public Collection<Cajero> getCajerosSnTransmitir(final Integer ciclo) throws EntityServicioExcepcion {
Collection<Cajero> items = null;
try {
Query query = null;
query = this.em.createNamedQuery("Cajero.NoTransmitidos");
query.setParameter("ciclo", (Object)ciclo);
items = (Collection<Cajero>)query.getResultList();
}
catch (IllegalStateException ex) {
CajeroServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (IllegalArgumentException ex2) {
CajeroServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2);
throw new EntityServicioExcepcion(ex2);
}
return items;
}
public Collection<Cajero> getCajerosMultiSnTransmitir(final Integer ciclo) throws EntityServicioExcepcion {
Collection<Cajero> items = null;
try {
Query query = null;
query = this.em.createNamedQuery("Cajero.MultiNoTrans");
query.setParameter("ciclo", (Object)ciclo);
items = (Collection<Cajero>)query.getResultList();
}
catch (IllegalStateException ex) {
CajeroServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (IllegalArgumentException ex2) {
CajeroServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2);
throw new EntityServicioExcepcion(ex2);
}
return items;
}
public Collection<Cajero> getCajerosActivos() throws EntityServicioExcepcion {
Collection<Cajero> items = null;
try {
Query query = null;
query = this.em.createNamedQuery("Cajero.AllActivos");
items = (Collection<Cajero>)query.getResultList();
}
catch (IllegalStateException ex) {
CajeroServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (IllegalArgumentException ex2) {
CajeroServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2);
throw new EntityServicioExcepcion(ex2);
}
return items;
}
public Collection<Cajero> getCajerosActivosMulti() {
Collection<Cajero> items = null;
try {
Query query = null;
query = this.em.createNamedQuery("Cajero.AllActivMulti");
items = (Collection<Cajero>)query.getResultList();
}
catch (IllegalStateException ex) {
CajeroServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex);
}
catch (IllegalArgumentException ex2) {
CajeroServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2);
}
return items;
}
}
|
package com.geniusgithub.lookaround.activity.set;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.geniusgithub.lookaround.R;
import com.geniusgithub.lookaround.activity.BaseActivity;
import com.geniusgithub.lookaround.util.CommonLog;
import com.geniusgithub.lookaround.util.CommonUtil;
import com.geniusgithub.lookaround.util.LogFactory;
import com.geniusgithub.lookaround.weibo.sdk.ShareCore;
import java.util.HashMap;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.sina.weibo.SinaWeibo;
import roboguice.inject.InjectView;
public class AdviseActivity extends BaseActivity implements Callback , TextWatcher,
OnClickListener, PlatformActionListener{
private static final CommonLog log = LogFactory.createLog();
private static final int MSG_TOAST = 1;
private static final int MSG_ACTION_CCALLBACK = 2;
private static final int MSG_CANCEL_NOTIFY = 3;
private static final int MAX_TEXT_LENGTH = 100;
@InjectView (R.id.btn_back) Button mBtnBack;
@InjectView (R.id.btn_right) Button mBtnShare;
@InjectView (R.id.et_content) EditText mETContent;
@InjectView (R.id.tv_target) TextView mTVTarget;
@InjectView (R.id.tv_live) TextView mTVLive;
private int notifyIcon;
private String notifyTitle;
private String sharePath;
private Platform mPlatform;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.advise_layout);
setupViews();
initData();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void setupViews(){
setNotification(R.drawable.logo_icon,"Look Around");
mBtnBack.setOnClickListener(this);
mBtnShare.setOnClickListener(this);
mETContent.addTextChangedListener(this);
}
private void initData(){
mPlatform = ShareSDK.getPlatform(this, SinaWeibo.NAME);
PlatformDb db = mPlatform.getDb();
String nickname = db.get("nickname");
if (nickname != null){
mTVTarget.setText(nickname);
}
updateTVLive();
}
/** 分享时Notification的图标和文字 */
public void setNotification(int icon, String title) {
notifyIcon = icon;
notifyTitle = title;
}
/** 执行分享 */
public void share() {
boolean started = false;
int relen = MAX_TEXT_LENGTH - mETContent.length();
if (relen == MAX_TEXT_LENGTH){
CommonUtil.showToast(R.string.toast_no_txtcount, this);
return ;
}
if (relen < 0){
CommonUtil.showToast(R.string.toast_too_txtcount, this);
return ;
}
int shareType = Platform.SHARE_TEXT;
HashMap<String, Object> reqMap = new HashMap<String, Object>();
reqMap.put("shareType", shareType);
String sendContent = getSendContent();
log.e("sendContent = " + sendContent);
reqMap.put("text", sendContent);
if (!started) {
started = true;
showNotification(2000, getString(R.string.sharing));
finish();
}
mPlatform.setPlatformActionListener(this);
ShareCore shareCore = new ShareCore();
shareCore.share(mPlatform, reqMap);
}
public String getSendContent(){
String value = mETContent.getText().toString();
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("@android火星人 ");
sBuffer.append("#意见与反馈#");
sBuffer.append("\n");
sBuffer.append(getMobileInfo());
sBuffer.append(value);
return sBuffer.toString();
}
public String getMobileInfo(){
String value = "(版本" + CommonUtil.getSoftVersion(this) +
",厂商" + CommonUtil.getDeviceManufacturer() +
", 型号" + CommonUtil.getDeviceModel() +
", 系统" + CommonUtil.getOSVersion() + ")";
return value;
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_back:
finish();
break;
case R.id.btn_right:
share();
break;
}
}
@Override
public boolean handleMessage(Message msg) {
switch(msg.what) {
case MSG_TOAST: {
String text = String.valueOf(msg.obj);
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
break;
case MSG_ACTION_CCALLBACK: {
switch (msg.arg1) {
case 1: { // 成功
showNotification(2000, getString(R.string.share_completed));
}
break;
case 2: { // 失败
showNotification(2000, getString(R.string.share_failed));
}
break;
case 3: { // 取消
showNotification(2000, getString(R.string.share_canceled));
}
break;
}
}
break;
case MSG_CANCEL_NOTIFY: {
NotificationManager nm = (NotificationManager) msg.obj;
if (nm != null) {
nm.cancel(msg.arg1);
}
}
break;
}
return false;
}
// 在状态栏提示分享操作
private void showNotification(long cancelTime, String text) {
try {
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
final int id = Integer.MAX_VALUE / 13 + 1;
nm.cancel(id);
long when = System.currentTimeMillis();
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(notifyIcon);
builder.setContentText(text);
builder.setWhen(when);
builder.setContentTitle(notifyTitle);
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(), 0);
builder.setContentIntent(pi);
builder.setAutoCancel(true);
nm.notify(id, builder.build());
if (cancelTime > 0) {
Message msg = new Message();
msg.what = MSG_CANCEL_NOTIFY;
msg.obj = nm;
msg.arg1 = id;
UIHandler.sendMessageDelayed(msg, cancelTime, this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onComplete(Platform platform, int action,
HashMap<String, Object> res) {
log.e("onComplete Platform = " + platform.getName() + ", action = " + action);
Message msg = new Message();
msg.what = MSG_ACTION_CCALLBACK;
msg.arg1 = 1;
msg.arg2 = action;
msg.obj = platform;
UIHandler.sendMessage(msg, this);
}
public void onError(Platform platform, int action, Throwable t) {
t.printStackTrace();
log.e("onError Platform = " + platform.getName() + ", action = " + action);
Message msg = new Message();
msg.what = MSG_ACTION_CCALLBACK;
msg.arg1 = 2;
msg.arg2 = action;
msg.obj = t;
UIHandler.sendMessage(msg, this);
// 分享失败的统计
ShareSDK.logDemoEvent(4, platform);
}
public void onCancel(Platform platform, int action) {
log.e("onCancel Platform = " + platform.getName() + ", action = " + action);
Message msg = new Message();
msg.what = MSG_ACTION_CCALLBACK;
msg.arg1 = 3;
msg.arg2 = action;
msg.obj = platform;
UIHandler.sendMessage(msg, this);
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
updateTVLive();
}
private void updateTVLive(){
int remain = MAX_TEXT_LENGTH - mETContent.length();
mTVLive.setText("您还可以输入" + String.valueOf(remain) + "字");
mTVLive.setTextColor(remain > 0 ? 0xffcfcfcf : 0xffff0000);
}
}
|
/**
* Copyright (C) 2014 android10.org. All rights reserved.
*
* @author Fernando Cejas (the android10 coder)
*/
package com.example.isvirin.storeclient.presentation.view.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import com.example.isvirin.storeclient.R;
import com.example.isvirin.storeclient.presentation.internal.di.HasComponent;
import com.example.isvirin.storeclient.presentation.internal.di.components.BrandComponent;
import com.example.isvirin.storeclient.presentation.internal.di.components.DaggerBrandComponent;
import com.example.isvirin.storeclient.presentation.internal.di.modules.BrandModule;
import com.example.isvirin.storeclient.presentation.model.BrandModel;
import com.example.isvirin.storeclient.presentation.view.fragment.BrandListFragment;
public class BrandsByCategoryActivity extends BaseActivity implements HasComponent<BrandComponent>,
BrandListFragment.BrandListListener {
private static final String INTENT_EXTRA_PARAM_CATEGORY_ID = "INTENT_PARAM_CATEGORY_ID";
private static final String INSTANCE_STATE_PARAM_CATEGORY_ID = "STATE_PARAM_CATEGORY_ID";
public static Intent getCallingIntent(Context context, int id) {
Intent intent = new Intent(context, BrandsByCategoryActivity.class);
intent.putExtra(INTENT_EXTRA_PARAM_CATEGORY_ID, id);
return intent;
}
private int id;
private BrandComponent brandComponent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_layout);
this.initializeInjector();
this.initializeActivity(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
if (outState != null) {
outState.putInt(INSTANCE_STATE_PARAM_CATEGORY_ID, this.id);
}
super.onSaveInstanceState(outState);
}
private void initializeActivity(Bundle savedInstanceState) {
if (savedInstanceState == null) {
this.id = getIntent().getIntExtra(INTENT_EXTRA_PARAM_CATEGORY_ID, -1);
addFragment(R.id.fragmentContainer, new BrandListFragment());
} else {
this.id = savedInstanceState.getInt(INSTANCE_STATE_PARAM_CATEGORY_ID);
}
}
private void initializeInjector() {
this.brandComponent = DaggerBrandComponent.builder()
.applicationComponent(getApplicationComponent())
.activityModule(getActivityModule())
.brandModule(new BrandModule(this.id))
.build();
}
@Override
public BrandComponent getComponent() {
return brandComponent;
}
public void onBrandClicked(BrandModel brandModel) {
this.navigator.navigateToProductList(this, brandModel.getId());
}
}
|
package com.fumei.bg.mapper;
import com.fumei.bg.domain.web.Partner;
import java.util.List;
/**
* @author zkh
*/
public interface PartnerMapper {
/**
* 查询合作人列表
* @param partner 条件
* @return 合作人列表
*/
List<Partner> selectPartnerList(Partner partner);
/**
* 保存合作人信息
* @param partner 合作人信息
* @return 执行结果 1成功 0失败
*/
int insert(Partner partner);
/**
* 修改合作人信息
* @param partner 合作人信息
* @return 执行结果 1成功 0失败
*/
int updateByPrimaryKey(Partner partner);
/**
* 删除合作人信息
* @param pId 合作人信息id
* @return 执行结果 1成功 0失败
*/
int deleteByPrimaryKey(Long pId);
}
|
package thuan.robin.fragment_send_target;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class FragmentTabTwo extends Fragment {
private ListView mListView;
private ArrayList<String> mListString;
private TextView mResult;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mListString = new ArrayList<>();
for (int i = 0; i < 10; i++) {
mListString.add(FragmentTabTwo.class.getSimpleName() + i);
}
mListView = view.findViewById(R.id.list_view);
mResult = view.findViewById(R.id.text_return);
mListView.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, mListString));
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
}
|
package com.example.group46;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class QuizMain extends AppCompatActivity {
//Best practice to use the package name as the key-values
public static final String FINAL_SCORE = "com.example.group2.FINAL_SCORE";
public static final String FINAL_INCORRECT = "com.example.group2.FINAL_INCORRECT";
private static final String TAG = "Quiz Main Screen";
//Initialising the widgets
private TextView textViewScore;
private TextView textViewQuestionCount;
private TextView textViewQuestion;
private RadioGroup radioGroup;
private RadioButton rb1;
private RadioButton rb2;
private RadioButton rb3;
private RadioButton rb4;
private Button submitBtn;
private ColorStateList textColorDefaultRb;
private List<Question> questionList;
private int questionCounter;
private int questionCountTotal;
private Question currentQuestion;
private int score;
private boolean answered;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_main);
Log.d(TAG, "Initialising the Quiz Layout");
//Assigning the widgets to its corresponding XML widget
textViewScore = findViewById(R.id.scoreText);
textViewQuestionCount = findViewById(R.id.countText);
textViewQuestion = findViewById(R.id.questionText);
radioGroup = findViewById(R.id.radioGroup);
rb1 = findViewById(R.id.radioButton1);
rb2 = findViewById(R.id.radioButton2);
rb3 = findViewById(R.id.radioButton3);
rb4 = findViewById(R.id.radioButton4);
submitBtn = findViewById(R.id.submitBtn);
textColorDefaultRb = rb1.getTextColors();
DBHelper dbHelper = new DBHelper(this);
questionList = dbHelper.getAllQuestions();
questionCountTotal = questionList.size();
//Getting questions in a random order
Collections.shuffle(questionList);
showNextQuestion();
submitBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if (!answered){ //if the question was not answered
if(rb1.isChecked() || rb2.isChecked() || rb3.isChecked() || rb4.isChecked()){
checkAnswer(); //if any of the radio buttons are selected, check the answer
} else {
Toast.makeText(QuizMain.this, "Please Select an Answer", Toast.LENGTH_SHORT).show();
}
} else {
showNextQuestion();
}
}
});
}
private void showNextQuestion(){
Log.d(TAG, "Deciding the Next Questions");
//Setting the radio buttons to a default colour before it will be changed
rb1.setTextColor(textColorDefaultRb);
rb2.setTextColor(textColorDefaultRb);
rb3.setTextColor(textColorDefaultRb);
rb4.setTextColor(textColorDefaultRb);
radioGroup.clearCheck(); //to unselect the radio buttons for each new question
//Testing to verify if there are any more questions left
if (questionCounter < questionCountTotal){
currentQuestion = questionList.get(questionCounter);
//Setting the XML text with our question bank
textViewQuestion.setText(currentQuestion.getQuestion());
//Setting the different answers for the options
rb1.setText(currentQuestion.getOption1());
rb2.setText(currentQuestion.getOption2());
rb3.setText(currentQuestion.getOption3());
rb4.setText(currentQuestion.getOption4());
questionCounter++;
//Setting the values for the current question and the total questions
textViewQuestionCount.setText("Question: " + questionCounter + "/" + questionCountTotal);
answered = false; //locking the question
} else {
finishQuiz();
}
}
private void checkAnswer(){
Log.d(TAG, "Checking Answer");
answered = true;
RadioButton radioButtonSelected = findViewById(radioGroup.getCheckedRadioButtonId());
int answerNo = radioGroup.indexOfChild(radioButtonSelected) + 1;
//If the answer selected is correct
if (answerNo == currentQuestion.getAnswerNo()){
score++; //increase score
textViewScore.setText("Score: " + score); //display the increased score
}
showSolution();
}
private void showSolution(){
Log.d(TAG, "Showing Solution to the User");
//Set the default colour of the radio button to red
rb1.setTextColor(Color.RED);
rb2.setTextColor(Color.RED);
rb3.setTextColor(Color.RED);
rb4.setTextColor(Color.RED);
//Change the correct answer's radio button to green
switch(currentQuestion.getAnswerNo()){
case 1:
rb1.setTextColor(Color.GREEN);
textViewQuestion.setText("Answer 1 is Correct!");
break;
case 2:
rb2.setTextColor(Color.GREEN);
textViewQuestion.setText("Answer 2 is Correct!");
break;
case 3:
rb3.setTextColor(Color.GREEN);
textViewQuestion.setText("Answer 3 is Correct!");
break;
case 4:
rb4.setTextColor(Color.GREEN);
textViewQuestion.setText("Answer 4 is Correct!");
break;
}
if(questionCounter < questionCountTotal){
submitBtn.setText("Next Question");
} else {
//if it is the last question, change the button to signify the quiz has finished
submitBtn.setText("Finish Quiz");
}
}
//Finish the quiz and sending the scores to the result activity
private void finishQuiz(){
int correct = score;
int incorrect = questionCountTotal - score;
Intent intent = new Intent(QuizMain.this, ResultMain.class);
intent.putExtra("Correct", correct);
intent.putExtra("Incorrect", incorrect);
startActivity(intent);
}
}
|
package com.moviee.moviee.fragments;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.annotation.IntegerRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.moviee.moviee.Interfaces.ServiceCallback;
import com.moviee.moviee.R;
import com.moviee.moviee.activities.FilmActivity;
import com.moviee.moviee.activities.MainActivity;
import com.moviee.moviee.adapters.base.MovieItemsAdapter;
import com.moviee.moviee.fragments.base.BaseTabFragment;
import com.moviee.moviee.models.Movie;
import com.moviee.moviee.services.FilmSharedIO;
import com.moviee.moviee.services.TheMovieDB;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* A simple {@link Fragment} subclass.
*/
public class SuggestFragment extends BaseTabFragment {
@BindView(R.id.SearchListView) ListView mSearchListView;
@BindView(R.id.CircularProgressBar) ProgressBar mSearchLoadingBar;
@BindView(R.id.ContentLinear) LinearLayout mContentLinear;
@BindView(R.id.MessageLinear) LinearLayout mMessageLinear;
@BindView(R.id.buttonSuggest) Button mButtonSuggest;
@BindView(R.id.refresh) SwipeRefreshLayout mRefresh;
List<Movie> moviesFound;
private View mRootView;
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mRootView = inflater.inflate(R.layout.fragment_suggest, container, false);
ButterKnife.bind(this, mRootView);
//performSearch(mSearch.getText().toString());
moviesFound = new FilmSharedIO(getContext()).loadListFromLiked();
if(moviesFound.size() < 3)
{
mButtonSuggest.setVisibility(View.GONE);
}
mSearchListView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition =
(mSearchListView == null || mSearchListView.getChildCount() == 0) ?
0 : mSearchListView.getChildAt(0).getTop();
mRefresh.setEnabled(firstVisibleItem == 0 && topRowVerticalPosition >= 0);
}
});
mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
performSearch();
}
});
mButtonSuggest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performSearch();
}
});
moviesFound = new FilmSharedIO(getContext()).loadListFromLiked();
if(moviesFound.size() < 3)
{
mButtonSuggest.setVisibility(View.GONE);
}
return mRootView;
}
private void performSearch()
{
if(mMessageLinear.getVisibility() == View.VISIBLE)
mSearchLoadingBar.setVisibility(View.VISIBLE);
mButtonSuggest.setVisibility(View.GONE);
mMessageLinear.setVisibility(View.GONE);
mContentLinear.setVisibility(View.VISIBLE);
moviesFound = new FilmSharedIO(getContext()).loadListFromLiked();
if(moviesFound.size() < 3)
{
mSearchLoadingBar.setVisibility(View.GONE);
return;
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
final List<Movie> movies = new ArrayList<>();
boolean doneWork = false;
final List<Movie> movieOne = new ArrayList<Movie>();
// this code uses just movies liked that has never been used for suggestions
do {
// it means refresh
if(movies.size() == 3)
movies.clear();
String elements = prefs.getString("doneReviewId", "");
for (int i = 0; i < moviesFound.size(); i++) {
if (!elements.contains(moviesFound.get(i).id + ",") && !movies.contains(moviesFound.get(i)))
movies.add(moviesFound.get(i));
}
if (movies.size() < 3)
{
doneWork = false;
for(int i = 0; i < movies.size(); i++) {
movieOne.add(movies.get(i));
movies.remove(i--);
}
prefs.edit().putString("doneReviewId", "").apply();
}
else
doneWork = true;
} while(!doneWork);
// in movies we have > 3 films, let's take 3 of those and add it to shared
int i = -1;
while(movieOne.size() < 3)
{
i++;
int casual = new Random().nextInt(movies.size());
movieOne.add(movies.get(casual));
prefs.edit().putString("doneReviewId", prefs.getString("doneReviewId", "") + movies.get(casual).id + ",").apply();
movies.remove(casual);
}
new TheMovieDB(new ServiceCallback() {
@Override
public void onResponse(final List list) {
new TheMovieDB(new ServiceCallback() {
@Override
public void onResponse(final List list1) {
new TheMovieDB(new ServiceCallback() {
@Override
public void onResponse(List FinalList) {
List<Movie> finalOfficial = new ArrayList<Movie>();
int position = 0;
int size = 0;
while(finalOfficial.size() != size || size == 0)
{
size = finalOfficial.size();
if(position + 1 < list.size())
finalOfficial.add((Movie)list.get(position));
if(position + 1 < list1.size())
finalOfficial.add((Movie)list1.get(position));
if(position + 1 < FinalList.size())
finalOfficial.add((Movie)FinalList.get(position));
position++;
}
performAdd(finalOfficial);
}
}, getContext()).getSimilarFilmsById(((Movie)movieOne.get(2)).id);
}
}, getContext()).getSimilarFilmsById(((Movie)movieOne.get(1)).id);
}
}, getContext()).getSimilarFilmsById(((Movie)movieOne.get(0)).id);
}
private void performAdd(final List<Movie> movies)
{
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// removing already liked
try
{
mRefresh.setRefreshing(false);
moviesFound = new FilmSharedIO(getContext()).loadListFromLiked(); // for security reason
for(int i = 0; i < movies.size(); i++)
{
String id = movies.get(i).id;
for(int j = 0; j < moviesFound.size(); j++)
{
if(id.equals(moviesFound.get(j).id))
{
movies.remove(i--);
j = moviesFound.size() + 60;
}
}
}
}
catch (Exception exd) {}
// different is needed here
try
{
for(int i = 0; i < movies.size(); i++)
{
String id = movies.get(i).id;
for(int j = i + 1; j < movies.size(); j++)
{
if(id.equals(movies.get(j).id))
{
movies.remove(i--);
j = movies.size() + 60; // + 60 to be sure :')
}
}
}
}
catch (Exception exd) {}
// reordering based on different factors
for(int i = 0; i < movies.size(); i++)
{
Movie movie = movies.get(i);
int score = 0;
if(movie.score > 6)
score += 4;
Calendar calendar = Calendar.getInstance();
if(calendar.get(Calendar.YEAR) - Integer.parseInt(movie.releaseDate.substring(0, movie.releaseDate.indexOf("-"))) < 12)
score += 2;
// for the info
if(movie.generalInfo.length() > 10)
score += 2;
else
score = 0;
movie.score = score;
movies.remove(i);
movies.add(i, movie);
}
Collections.sort(movies, new EmployeeComparator());
Collections.reverse(movies);
MovieItemsAdapter arrayAdapter = new MovieItemsAdapter(getContext(), movies, false, null, (MainActivity)getActivity(), false, -1, null, 0f);
mSearchListView.setAdapter(arrayAdapter);
mSearchLoadingBar.setVisibility(View.GONE);
}
});
}
@Override
public int getIconRes() {
return R.drawable.ic_subscriptions_black_24dp;
}
class EmployeeComparator implements Comparator<Movie> {
public int compare(Movie o1, Movie o2){
return (o1.score + "").compareTo(o2.score + "");
}
}
@Override
public int getActiveIconRes() {
return R.drawable.ic_subscriptions_black_24dp_active;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// Make sure that we are currently visible
if (this.isVisible()) {
// If we are becoming invisible, then...
List<Movie> ac = new FilmSharedIO(getContext()).loadListFromLiked();
if (!isVisibleToUser) {
// TODO stop audio playback
}
else if(mMessageLinear.getVisibility() != View.GONE && new FilmSharedIO(getContext()).loadListFromLiked().size() > 2)
{
mButtonSuggest.setVisibility(View.VISIBLE);
}
else if(mMessageLinear.getVisibility() == View.GONE && new FilmSharedIO(getContext()).loadListFromLiked().size() < 3)
{
mContentLinear.setVisibility(View.GONE);
mMessageLinear.setVisibility(View.VISIBLE);
mButtonSuggest.setVisibility(View.GONE);
}
}
}
}
|
package com.mpls.v2.service;
import com.mpls.v2.dto.GroupFullDTO;
import com.mpls.v2.dto.GroupShortDTO;
import com.mpls.v2.model.Group;
import java.util.List;
public interface GroupService {
Group save (Group group);
Group update(Group group);
Group update(GroupShortDTO groupShortDTO);
Group update(GroupFullDTO groupFullDTO);
List<Group> findAll();
Group findOne(Long id);
Boolean delete(Long id);
Group findByName(String name);
}
|
package expansion.neto.com.mx.jefeapp.fragment.fragmentDashboard;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Toast;
import com.eralp.circleprogressview.ProgressAnimationListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import expansion.neto.com.mx.jefeapp.R;
import expansion.neto.com.mx.jefeapp.cron.Cron;
import expansion.neto.com.mx.jefeapp.cron.CronJob;
import expansion.neto.com.mx.jefeapp.cron.ReminderUtilities;
import expansion.neto.com.mx.jefeapp.cron.ReminderUtilitiesJob;
import expansion.neto.com.mx.jefeapp.databinding.FragmentDashboardBinding;
import expansion.neto.com.mx.jefeapp.fragment.fragmentAgenda.FragmentInicioAgenda;
import expansion.neto.com.mx.jefeapp.fragment.fragmentAutorizadas.FragmentInicioAutorizadas;
import expansion.neto.com.mx.jefeapp.fragment.fragmentCreacion.FragmentInicioAutoriza;
import expansion.neto.com.mx.jefeapp.fragment.fragmentProceso.FragmentInicioProceso;
import expansion.neto.com.mx.jefeapp.fragment.fragmentRechazadas.FragmentInicioRechazadas;
import expansion.neto.com.mx.jefeapp.modelView.dashboardModel.Dashboard;
import expansion.neto.com.mx.jefeapp.modelView.loginModel.Permiso;
import expansion.neto.com.mx.jefeapp.modelView.loginModel.Usuario;
import expansion.neto.com.mx.jefeapp.modelView.loginModel.UsuarioLogin;
import expansion.neto.com.mx.jefeapp.provider.dashboardProvider.ProviderDatosDashboard;
import expansion.neto.com.mx.jefeapp.radios.ui.radios.ActivityRadios;
import expansion.neto.com.mx.jefeapp.ui.autoriza.ActivityAutorizar;
import expansion.neto.com.mx.jefeapp.utils.Util;
public class FragmentDashboard extends Fragment {
FragmentDashboardBinding binding;
String mes;
String semana;
UsuarioLogin.Perfil perfil = new UsuarioLogin.Perfil();
int anio = Calendar.getInstance().get(Calendar.YEAR);
String anioString;
int totalDaysInYear;
int totalWeeks;
int semanaRestaInt = 1;
String semanaResta;
int mesRestaInt = 0;
String mesResta;
private static final int MODULO_DASHBOARD = 7;
private static final int MODULO_CREAR_MD_ID = 1;
private static final int MODULO_POR_TERMINAR_ID = 2;
private static final int MODULO_EN_PROCESO_ID = 3;
private static final int MODULO_RECHAZADAS_ID = 4;
private static final int MODULO_AUTORIZADAS_ID = 5;
private static final int MODULO_AGENDA_ID = 6;
private static final int MODULO_RADIOS_ID = 12;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_dashboard, container, false);
View v = binding.getRoot();
Calendar mCalendar = new GregorianCalendar(TimeZone.getDefault());
mCalendar.setFirstDayOfWeek(Calendar.MONDAY);
mCalendar.set(anio, Calendar.DECEMBER, 31);
totalDaysInYear = mCalendar.get(Calendar.DAY_OF_YEAR);
totalWeeks = totalDaysInYear / 7;
Date hoy = Calendar.getInstance().getTime();
String upperString = Util.getFechaDay(hoy).substring(0, 1).toUpperCase() + Util.getFechaDay(hoy).substring(1);
binding.dia.setText("Hoy " + upperString + ", " + Util.getFechaFormat(hoy));
//centramos LinearLayout para vistas muy grandes
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
System.out.println( "ancho absoluto en pixels "+ width );
int height = metrics.heightPixels;
System.out.println( "alto absoluto en pixels " + height );
if (height >= 2000) {
binding.linearLayoutCentrar.setGravity( Gravity.CENTER );
}
getContext().getSharedPreferences("datosExpansion", Context.MODE_PRIVATE);
Calendar fecha = Calendar.getInstance();
final int meses = fecha.get(Calendar.MONTH) + 1;
getContext().getSharedPreferences("datosSuperficie", 0).edit().clear().apply();
SharedPreferences preferences = getContext().getSharedPreferences("datosExpansion", Context.MODE_PRIVATE);
final SharedPreferences.Editor editorExpansion = preferences.edit();
editorExpansion.putString("anioConsulta", String.valueOf(anio));
editorExpansion.putString("mesDasbord", String.valueOf(meses - 1));
editorExpansion.putString("mesTaco", String.valueOf(meses));
editorExpansion.putString("tipoSitio", "");
editorExpansion.apply();
binding.nombreJefe.setVisibility(View.INVISIBLE);
getDatos(String.valueOf(meses), "0");
getMesSemana();
String mese = getMes(meses);
binding.setSemana("Semana " + semana);
binding.setMes(mese);
binding.setAnioString(" " + anioString);
binding.derMes.setEnabled(false);
binding.derSemana.setEnabled(false);
binding.crearMD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getContext().getSharedPreferences("datosSuperficie", 0).edit().clear().apply();
SharedPreferences preferences = getContext().getSharedPreferences("datosExpansion", Context.MODE_PRIVATE);
SharedPreferences.Editor editorExpansion = preferences.edit();
editorExpansion.putString("mdIdterminar", "");
editorExpansion.apply();
Intent main = new Intent(getContext(), ActivityAutorizar.class);
startActivity(main);
}
});
binding.autorizar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent main = new Intent(getContext(), FragmentInicioAutoriza.class);
startActivity(main);
}
});
binding.proceso.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent main = new Intent(getContext(), FragmentInicioProceso.class);
startActivity(main);
}
});
binding.agenda.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent main = new Intent(getContext(), FragmentInicioAgenda.class);
startActivity(main);
}
});
binding.rechazadas.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent main = new Intent(getContext(), FragmentInicioRechazadas.class);
startActivity(main);
}
});
binding.autorizadas.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent main = new Intent(getContext(), FragmentInicioAutorizadas.class);
startActivity(main);
}
});
binding.izqSemana.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
binding.derSemana.setEnabled(true);
binding.derSemana.setAlpha(1.0f);
if (semanaRestaInt != 0) {
binding.izqSemana.setEnabled(true);
semanaRestaInt--;
semanaResta = String.valueOf(semanaRestaInt);
getDatos("0", semanaResta);
//binding.setSemana("Semana "+semanaResta);
} else {
binding.izqSemana.setEnabled(false);
}
}
});
binding.clradio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent main = new Intent(getContext(), ActivityRadios.class);
startActivity(main);
}
});
binding.derSemana.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
binding.izqSemana.setEnabled(true);
semanaRestaInt = (semanaRestaInt) + 1;
int semanaActual = Integer.parseInt(getMesSemana());
if (semanaRestaInt == semanaActual) {
getDatos("0", String.valueOf(semanaRestaInt));
//binding.setSemana("Semana "+String.valueOf(semanaRestaInt));
binding.derSemana.setAlpha(0.0f);
binding.derSemana.setEnabled(false);
} else {
getDatos("0", String.valueOf(semanaRestaInt));
//binding.setSemana("Semana "+String.valueOf(semanaRestaInt));
binding.derSemana.setAlpha(1.0f);
}
}
});
binding.izqMes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
binding.derMes.setEnabled(true);
binding.derMes.setAlpha(1.0f);
binding.izqMes.setEnabled(true);
mesRestaInt--;
mesResta = String.valueOf(mesRestaInt);
getDatos(mesResta, "0");
//String nombreMes = getMes(mesRestaInt);
//binding.setMes(nombreMes);
editorExpansion.putString("mesTaco", mesResta);
editorExpansion.apply();
}
});
binding.derMes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
binding.izqMes.setEnabled(true);
mesRestaInt = (mesRestaInt) + 1;
if (mesRestaInt == 13) {
mesRestaInt = 1;
anio++;
anioString = String.valueOf(anio);
binding.setAnioString(" " + anioString);
}
editorExpansion.putString("anioConsulta", String.valueOf(anio));
Calendar fecha = Calendar.getInstance();
int mesActual = fecha.get(Calendar.MONTH) + 1;
if (mesRestaInt == mesActual && anio == Calendar.getInstance().get(Calendar.YEAR)) {
getDatos(String.valueOf(mesRestaInt), "0");
String nombreMes = getMes(mesRestaInt);
binding.setMes(nombreMes);
binding.derMes.setAlpha(0.0f);
binding.derMes.setEnabled(false);
editorExpansion.putString("mesDasbord", String.valueOf(mesRestaInt));
editorExpansion.putString("mesTaco", String.valueOf(mesRestaInt));
editorExpansion.apply();
} else {
getDatos(String.valueOf(mesRestaInt), "0");
String mesNombre = getMes(mesRestaInt);
binding.setMes(mesNombre);
binding.derMes.setAlpha(1.0f);
binding.derMes.setEnabled(true);
editorExpansion.putString("mesDasbord", String.valueOf(mesRestaInt));
editorExpansion.putString("mesTaco", String.valueOf(mesRestaInt));
editorExpansion.apply();
}
}
});
ReminderUtilities.scheduleCronReminder(getContext());
//ReminderUtilitiesJob.scheduleCronReminder(getContext());
return v;
}
public String getMesSemana() {
Date date = new Date();
anioString = String.valueOf(anio);
mes = (String)
DateFormat.format("MMMM", date); // Jun
mes = mes.substring(0, 1).toUpperCase() + mes.substring(1).toLowerCase();
Calendar now = Calendar.getInstance();
now.setTime(date);
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
now.set(Calendar.YEAR, year);
now.set(Calendar.MONTH, month);
now.set(Calendar.DATE, day);
semana = String.valueOf(now.get(Calendar.WEEK_OF_YEAR));
return semana;
}
public String getMes(int mesNum) {
if (mesNum == 1) {
mes = "Enero";
}
if (mesNum == 2) {
mes = "Febrero";
}
if (mesNum == 3) {
mes = "Marzo";
}
if (mesNum == 4) {
mes = "Abril";
}
if (mesNum == 5) {
mes = "Mayo";
}
if (mesNum == 6) {
mes = "Junio";
}
if (mesNum == 7) {
mes = "Julio";
}
if (mesNum == 8) {
mes = "Agosto";
}
if (mesNum == 9) {
mes = "Septiembre";
}
if (mesNum == 10) {
mes = "Octubre";
}
if (mesNum == 11) {
mes = "Noviembre";
}
if (mesNum == 12) {
mes = "Diciembre";
}
return mes;
}
public void setTacometros(int planMes, int realMes, int planSemana, int realSemana) {
if (planSemana == 0 || planMes == 0) {
} else {
binding.tacometroMes.setTextEnabled(false);
binding.tacometroMes.setInterpolator(new AccelerateDecelerateInterpolator());
binding.tacometroMes.setStartAngle(270);
binding.tacometroMes.setProgressWithAnimation((100 / planMes * realMes), 2000);
binding.tacometroMes.addAnimationListener(new ProgressAnimationListener() {
@Override
public void onValueChanged(float value) {
}
@Override
public void onAnimationEnd() {
}
});
binding.tacometroSemana.setTextEnabled(false);
binding.tacometroSemana.setInterpolator(new AccelerateDecelerateInterpolator());
binding.tacometroSemana.setStartAngle(270);
binding.tacometroSemana.setProgressWithAnimation((100 / planSemana * realSemana), 2000);
binding.tacometroSemana.addAnimationListener(new ProgressAnimationListener() {
@Override
public void onValueChanged(float value) {
}
@Override
public void onAnimationEnd() {
}
});
}
}
public void getDatos(String buscaMes, String semanas) {
//bloqueo de señales hasta que halla respuesta
binding.izqMes.setEnabled(false);
binding.izqMes.setAlpha(0.0f);
binding.izqSemana.setEnabled(false);
binding.izqSemana.setAlpha(0.0f);
binding.derMes.setEnabled(false);
binding.derMes.setAlpha(0.0f);
binding.derSemana.setEnabled(false);
binding.derSemana.setAlpha(0.0f);
SharedPreferences preferences = getContext().getSharedPreferences("datosExpansion", Context.MODE_PRIVATE);
SharedPreferences.Editor editorExpansion = preferences.edit();
String usuarioId = preferences.getString("usuario", "");
String area = preferences.getString("areaxpuesto", "");
//blockUI();
Gson gson = new Gson();
String json = preferences.getString("permisos", null);
Type type = new TypeToken<ArrayList<Permiso>>() {
}.getType();
ArrayList<Permiso> permisos = gson.fromJson(json, type);
getPermisos(permisos, binding);
int semana = Integer.valueOf(semanas);
int mesSolicitud = Integer.valueOf(buscaMes);
if (mesSolicitud > 0) {
//buscaMes = String.valueOf(--mesSolicitud);
editorExpansion.putString("mesDasbord", String.valueOf(mesSolicitud));
} else if (semana > totalWeeks) {
semanas = "1";
anio++;
anioString = String.valueOf(anio);
binding.setAnioString(" " + anioString);
editorExpansion.putString("anioConsulta", String.valueOf(anio));
editorExpansion.putString("mesDasbord", "1");
} else if (semana == 0) {
anio--;
anioString = String.valueOf(anio);
binding.setAnioString(" " + anioString);
Calendar mCalendar = new GregorianCalendar(TimeZone.getDefault());
mCalendar.setFirstDayOfWeek(Calendar.MONDAY);
mCalendar.set(anio, Calendar.DECEMBER, 31);
totalDaysInYear = mCalendar.get(Calendar.DAY_OF_YEAR);
totalWeeks = totalDaysInYear / 7;
semanas = String.valueOf(totalWeeks);
editorExpansion.putString("anioConsulta", String.valueOf(anio));
editorExpansion.putString("mesDasbord", "12");
buscaMes="12";
}
editorExpansion.apply();
String anio2 = String.valueOf(anio);
Log.d("adolfo", anio2 + " buscaMes" + buscaMes);
ProviderDatosDashboard.getInstance(getContext()).obtenerDatosAutorizadas(semanas, buscaMes, anio2, usuarioId, area, new ProviderDatosDashboard.ConsultaDatosDashboard() {
@Override
public void resolve(Dashboard dashboard) {
if (dashboard != null) {
if (dashboard.getCodigo() == 200 && dashboard != null) {
for (int i = 0; i < dashboard.getTotales().size(); i++) {
binding.izqSemana.setEnabled(true);
binding.derMes.setEnabled(true);
binding.derSemana.setEnabled(true);
binding.izqMes.setEnabled(true);
if (dashboard.getTotales().get(i).getEstatusid() == 2) {
binding.totalProceso.setText(dashboard.getTotales().get(i).getTotal() + "");
}
if (dashboard.getTotales().get(i).getEstatusid() == 3) {
binding.totalRechazados.setText(dashboard.getTotales().get(i).getTotal() + "");
}
if (dashboard.getTotales().get(i).getEstatusid() == 1) {
binding.totalTerminar.setText(dashboard.getTotales().get(i).getTotal() + "");
}
if (dashboard.getTotales().get(i).getEstatusid() == 4) {
binding.totalAutorizadas.setText(dashboard.getTotales().get(i).getTotal() + "");
}
}
int planMes;
int realMes;
int planSem;
int realSem;
if (dashboard.getProductividad().get(0).getPlanMes() == null) {
planMes = 0;
} else {
planMes = dashboard.getProductividad().get(0).getPlanMes();
}
if (dashboard.getProductividad().get(0).getRealMes() == null) {
realMes = 0;
} else {
realMes = dashboard.getProductividad().get(0).getRealMes();
}
if (dashboard.getProductividad().get(0).getPlanSem() == null) {
planSem = 0;
} else {
planSem = dashboard.getProductividad().get(0).getPlanSem();
}
if (dashboard.getProductividad().get(0).getRealSem() == null) {
realSem = 0;
} else {
realSem = dashboard.getProductividad().get(0).getRealSem();
}
setTacometros(planMes,
realMes,
planSem,
realSem);
String mese = getMes(dashboard.getProductividad().get(0).getMes());
binding.setMes(mese);
binding.setSemana("Semana " + dashboard.getProductividad().get(0).getSemana());
semanaRestaInt = dashboard.getProductividad().get(0).getSemana();
mesRestaInt = dashboard.getProductividad().get(0).getMes();
binding.izqMes.setEnabled(true);
binding.izqMes.setAlpha(1.0f);
binding.izqSemana.setEnabled(true);
binding.izqSemana.setAlpha(1.0f);
Calendar fecha = Calendar.getInstance();
final int meses = fecha.get(Calendar.MONTH) + 1;
final int anioactual = fecha.get(Calendar.YEAR);
Log.d("adolfo", anio + " anio actual" + anioactual);
if (meses == mesRestaInt && anio >= anioactual) {
binding.derMes.setEnabled(false);
binding.derMes.setAlpha(0.0f);
} else {
binding.derMes.setEnabled(true);
binding.derMes.setAlpha(1.0f);
}
if (Integer.valueOf(getMesSemana()) == semanaRestaInt) {
binding.derSemana.setEnabled(false);
binding.derSemana.setAlpha(0.0f);
} else {
binding.derSemana.setEnabled(true);
binding.derSemana.setAlpha(1.0f);
}
perfil = Usuario.sharedGet(getContext());
perfil.setPlanMes(planMes);
perfil.setRealMes(realMes);
perfil.setPlanSemana(planSem);
perfil.setRealSemana(realSem);
binding.setPerfil(perfil);
binding.nombreJefe.setVisibility(View.VISIBLE);
SharedPreferences preferences = getContext().getSharedPreferences("datosExpansion", Context.MODE_PRIVATE);
final SharedPreferences.Editor editorExpansion = preferences.edit();
editorExpansion.putString("mesDasbord", String.valueOf(dashboard.getProductividad().get(0).getMes()));
editorExpansion.putString("mesTaco", String.valueOf(dashboard.getProductividad().get(0).getMes()));
editorExpansion.apply();
}
// unblockUI();
} else {
binding.izqMes.setEnabled(true);
binding.izqMes.setAlpha(1.0f);
binding.izqSemana.setEnabled(true);
binding.izqSemana.setAlpha(1.0f);
Toast.makeText(getContext(), "Error al cargar los datos", Toast.LENGTH_SHORT).show();
}
}
@Override
public void reject(Exception e) {
}
});
}
private void blockUI() {
Util.addProgressBar(getContext(), binding.container, binding.container.getChildCount() - 0);
}
private void unblockUI() {
binding.container.removeViewAt(binding.container.getChildCount() - 1);
}
ArrayList<Permiso> permisosJefe;
public void getPermisos(ArrayList<Permiso> permiso, FragmentDashboardBinding binding) {
permisosJefe = new ArrayList<>();
if (permiso != null && permiso.size() > 0) {
for (int i = 0; i < permiso.size(); i++) {
if (permiso.get(i).getFimoduloid() == MODULO_DASHBOARD) {
permisosJefe.add(permiso.get(i));
}
}
for (int j = 0; j < permisosJefe.size(); j++) {
int valor = permisosJefe.get(j).getFisubmodulo();
switch (valor) {
case MODULO_CREAR_MD_ID:
if (permisosJefe.get(j).getFiestatus() == 1) {
binding.crearMD.setVisibility(View.VISIBLE);
} else {
binding.crearMD.setVisibility(View.GONE);
}
break;
case MODULO_POR_TERMINAR_ID:
if (permisosJefe.get(j).getFiestatus() == 1) {
binding.autorizar.setVisibility(View.VISIBLE);
} else {
binding.autorizar.setVisibility(View.GONE);
}
break;
case MODULO_EN_PROCESO_ID:
if (permisosJefe.get(j).getFiestatus() == 1) {
binding.proceso.setVisibility(View.VISIBLE);
} else {
binding.proceso.setVisibility(View.GONE);
}
break;
case MODULO_RECHAZADAS_ID:
if (permisosJefe.get(j).getFiestatus() == 1) {
binding.rechazadas.setVisibility(View.VISIBLE);
} else {
binding.rechazadas.setVisibility(View.GONE);
}
break;
case MODULO_AUTORIZADAS_ID:
if (permisosJefe.get(j).getFiestatus() == 1) {
binding.autorizadas.setVisibility(View.VISIBLE);
} else {
binding.autorizadas.setVisibility(View.GONE);
}
break;
case MODULO_AGENDA_ID:
if (permisosJefe.get(j).getFiestatus() == 1) {
binding.agenda.setVisibility(View.VISIBLE);
} else {
binding.agenda.setVisibility(View.GONE);
}
break;
case MODULO_RADIOS_ID:
if (permisosJefe.get(j).getFiestatus() == 1) {
binding.clradio.setVisibility(View.VISIBLE);
} else {
binding.clradio.setVisibility(View.GONE);
}
break;
}
}
}
}
}
|
package lt.baltic.talents.projects.CalendarNoteReminder.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import lt.baltic.talents.projects.CalendarNoteReminder.models.User;
import lt.baltic.talents.projects.CalendarNoteReminder.services.UserService;
@Controller
public class LoginController {
@Autowired
private UserService userService;
//-----------------------------SIGN_UP_NEW_USER--------------------------------------------------
// @RequestMapping(value = "/signup", method = RequestMethod.GET)
// public String login(Model model) {
// return "login/signup";
// }
//
// @RequestMapping(value = "/signup", method = RequestMethod.POST)
// public String signup(Model model) {
// userService.create(new User());
//
// return "login/login";
// }
//-------------------------------------------------------------------------------------
// @RequestMapping(value = "testCreate", method = RequestMethod.GET)
// public String login(Model model) {
// userService.create(new User("OOOOO", "xzxzcxzcxzc".toCharArray()));
// return "login/failure";
// }
//-------------------------------------------------------------------------------------
//-------------------------------LOG_IN_USER-------------------------------------------
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model,
@RequestParam(value = "user", required = false) String userParam,
@RequestParam(value = "pwd", required = false) String pwd, RedirectAttributes redirectAttributes) {
if (userParam == null || pwd == null) {
return "login/login";
}
User user = userService.login(new User(userParam, pwd.toCharArray()));
if (user != null) {
redirectAttributes.addFlashAttribute("user", user);
return "redirect:/base";
}
return "login/failure";
}
}
|
public class mycalculation extends calculation
{
public void multiplication(int x,int y)
{
z=x*y;
System.out.println("the product"+z);
}
public static void main(String[]args)
{
int a=5,b=10;
mycalculation demo=new mycalculation();
demo.addition(a,b);
demo.subtract(a,b);
demo.multiplication(a,b);
}
}
|
package com.github.edwnmrtnz.betterpermissions;
import android.Manifest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.github.edwnmrtnz.betterpermission.BetterPermission;
import com.github.edwnmrtnz.betterpermission.PermissionCallback;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
BetterPermission betterPermission;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
betterPermission = new BetterPermission(this);
betterPermission.setPermissions(Manifest.permission.CALL_PHONE, Manifest.permission.SEND_SMS, Manifest.permission.READ_EXTERNAL_STORAGE)
.requestPermissions(new PermissionCallback() {
@Override
public void allPermissionsAreAlreadyGranted() {
Log.e(TAG, "All pemrissions are already granted");
}
@Override
public void onPermissionsGranted() {
Log.d(TAG, "onPermissionsGranted: ");
}
@Override
public void onIndividualPermissions(String[] grantedPermissions, String[] declinedPermissions) {
Log.d(TAG, "onIndividualPermissions: ");
Log.d(TAG, "\n*** Grated Permissions ***");
for(String permission : grantedPermissions){
Log.d(TAG, permission);
}
Log.d(TAG, "*** Denied Permissions ***");
for(String permission : declinedPermissions){
Log.d(TAG, permission);
}
}
@Override
public void onPermissionsDeclined() {
Log.d(TAG, "onPermissionsDeclined: ");
}
}).execute();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
betterPermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
|
package listeners;
import org.eclipse.swt.widgets.Shell;
import exceptions.NoEmptyPetsAllowedException;
import widgets.NewPetDialog;
import widgets.PetInfo;
/**
* Handles creating a new pet. New information will be saved in the database and
* available for viewing at any time.
*
* @author aggie
*
* @version $Revision: 1.0 $
*/
public class NewPetHandler {
private Shell shell;
private PetInfo pet;
private NewPetDialog dialog;
public NewPetHandler(Shell shell) throws NoEmptyPetsAllowedException {
this.shell = shell;
dialog = new NewPetDialog(shell);
pet = dialog.getPet();
if (!pet.equals(null))
savePet();
else
throw new NoEmptyPetsAllowedException();
}
private void savePet() {
// TODO get the pet info and save it in the database
//don't forget that a pet has an owner and need to check for that
//to save the pet to the right owner
}
}
|
package cn.itheima.naker.day_04;
public class Demo_02_Array_static_init {
//数组的静态初始化
public static void main(String[] args) {
double[] arr = {1.0, 2.0, 3.0}; //简化格式(推荐)
char[] arr2 = new char[]{'a', 'b', 'c'}; //完整格式
for (double d : arr) {
System.out.println(d);
}
System.out.println("-------------");
for (int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i]);
}
System.out.println("------------");
for (char ch : arr2) {
System.out.println(ch);
}
System.out.println("------------");
int[] arr3 = {23, 43, 16, 17, 28};
int max = arr3[0];
int min = arr3[0];
for (int a : arr3) {
if (a > max) {
max = a;
}
}
System.out.println("max:" + max);
System.out.println("------------");
for (int i = 1; i < arr3.length; i++) {
if (min > arr3[i]) {
min = arr3[i];
}
}
System.out.println("min:" + min);
}
}
|
import java.io.*;
/**
Incomplete version of supplementary class for phone books.
This version of the application declares a (fairly) large array to hold the directory.
When this class is instantiated, it reads in the contents of the data file
mydirectory.txt, each line of which contains one entry for the directory:
a subscriber's name, then a semicolon, then the subscriber's phone number - for example:
Father Christmas;252525
One Entry is added to the directory array for each line read in. Once the file
has been fully processed, the launch of application is finished, and the application
starts to interact with the user.
The methods for reading and processing, and for writing the data file need completing.
This code illustrates the use of an array which is not full of data.
The array is variable directory, and at any one time the entries in the array
are in consecutive locations starting at subscript 0. When a new entry is added,
it is placed in the next free location. The int variable next always holds the
subscript of the first free location, that is the next one that should be used.
Therefore, if directory can hold 10 entries, and it contains 4, then those
entries are at subscripts 0-3 and next holds 4.
@author Simon Jones (based on original code by Kenneth J. Turner)
@version 2/12/2015
*/
public class PhoneBook {
/** Phone book file name */
private String phoneBookFile = "mydirectory.txt";
/** Next entry to use */
private int next = 0;
/** Number of directory entries */
private final int size = 100;
/** Directory entry array */
private Entry directory[] = new Entry[size];
/**
* PhoneBook constructor: Initialize from data file
*/
public PhoneBook() {
readPhoneBookEntries();
}
/**
* This method opens and reads in the contents of the data file given by phoneBookFile.
* Each line of the file contains one entry for the directory:
* a subscriber's name, then a semicolon, then the subscriber's phone number.
* One Entry is added to the directory array for each line read in.
* If any exception occurs, then the file processing is halted,
* an on-screen alert is popped up for the user, and any
* directory entries already made are kept.
*/
private void readPhoneBookEntries() {
System.out.println("readPhoneBookEntries");
try{ // Prepare to catch IOExceptions
String infile;
BufferedReader infile;// Open a buffered reader for the file
infile = new BufferedReader (new FileReader(mydirectory));
String lines = 0;
//String lines = lines.readLine();
while ((line = mydirectory.readLine())!=Null){// Read and process each line in the file as follows:
lines++;
// Extract the subscriber's name and number into two string variables
// Use addEntry to add the new entry
// Close the file
// Note: Any IOException that occurs should be caught, an
// alert should be popped up to inform the user, and the method should be exited
// without further reading.
}}
catch (IOException e){
}
}
/**
* This method opens the data file given by phoneBookFile, and writes out the current
* directory contents to data file. This will overwrite the previous contents of the file.
* Each entry in the directory is output as a single line of text to the file,
* with the a subscriber's name, then a semicolon, then the subscriber's phone number.
* Therefore this file can be read in again at a later time by readPhoneBookEntries.
*/
public void writePhoneBookEntries() {
System.out.println("writePhoneBookEntries");
// Prepare to catch IOExceptions
// Open a buffered writer for the file
// Process each entry in the directory as follows:
// Obtain the subscriber's name and number into two string variables
// Write a formatted line of text to the file
// Close the file
// Note: Any IOException that occurs should be caught, an
// alert should be popped up to inform the user, and the method should be exited
// without further writing.
}
/**
Add a phone book entry to array <var>directory</var>, checking whether
there is space in the phone book for the new entry.
@param name new name
@param phone new phone number
@return true/false if entry added/not added
*/
public boolean addEntry(String name, String phone) {
if (next < size && // space in directory and ...
name.length() > 0 && // name is non-empty and ...
phone.length() > 0) { // phone is non-empty?
directory[next] = new Entry(name, phone); // make new directory entry
next++; // move to next free entry
return true; // report entry added
}
else // problems with entry
return false; // report entry not added
}
/**
Delete phone book entry from array <var>directory</var>, moving later
entries down one place and updating the next free entry index.
@param entry phone book entry index
*/
public void deleteEntry(int entry) {
for (int i = entry; i < next - 1; i++) // move later entries down
directory[i] = directory[i + 1]; // copy next entry
next--; // last entry now free
}
/**
Find a phone book entry in array <var>directory</var>. Accept a partial
match on name, irrespective of letter case. If there are several candidate
entries, the first is found.
@param person person name to find
@return index of matching entry, or -1 if not found
*/
public int findEntry(String person) {
int i = 0; // initialise counter
String dirName; // directory name
if (person.length() == 0) // name is empty?
return -1; // Yes, return "not found"
person = person.toLowerCase(); // convert name to lower case
while (i < next) { // not yet at directory end?
dirName = directory[i].getName(); // get directory name
dirName = dirName.toLowerCase(); // make it lower case
if (dirName.indexOf(person) != -1) // entry name matches?
return i; // return entry subscript
i++; // move to next entry
}
return -1; // return "not found"
}
/**
Get the name for a phone book entry in array <var>directory</var>.
@param entry phone book entry index
@return name for entry
*/
public String getName(int entry) {
return(directory[entry].getName()); // return directory name
}
/**
Get the number for a phone book entry in array <var>directory</var>.
@param entry phone book entry index
@return number for entry
*/
public String getNumber(int entry) {
return(directory[entry].getNumber()); // return directory number
}
}
|
package Udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpListener {
String ip;
public UdpListener(String ip) {
this.ip = ip;
}
public void start() {
try {
DatagramSocket ds = new DatagramSocket(11111, InetAddress.getByName(ip));
byte[] receiveData = new byte[16]; //adjust as you need
int num = 0;
System.out.println("UDP socket @" + ip + " listens...");
while(true) {
DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
ds.receive(packet);
String line = new String(packet.getData());
num++;
if (line.startsWith("ex")) break;
}
System.out.println(ip + "-> " + num);
ds.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.site.tools;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
*
* 工具类
*
*/
public class ImageUtil {
/**
* 压缩图片质量,返回图片名字
*
* @param activity
* @param uri
* @return author xuchun
*/
public static String compressBitmap(Activity activity, String path) {
File file = new File(path);
if (!file.exists()) {
return null;
}
if (file.length() / 1024 <= 200) {
return file.getName();
}
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
if (bitmap == null) { // 若获取图片失败就取消压缩
return file.getName();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// 压缩质量因数
// 越低代表图片质量越差,但图片质量会减小
// 为100时不减少图片质量
// 经测试,从60开始比较不错
int options = 60;
// 这里的200只是一个参考数
// 压缩后的图片质量在此值左右浮动,浮动值很小
while (baos.toByteArray().length / 1024 > 200) {
baos.reset();
options -= 1;
if (options == 1) {
break;
}
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
// 注意:
// 这里千万别用BitmapFactory.decodeStream(is)去生成Bitmap后再去保存
// 图片稍微大一点就会OOM
try {
// 压缩后的图片覆盖掉之前的图片
FileOutputStream fos = new FileOutputStream(path);
fos.write(baos.toByteArray());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file.getName();
}
}
|
package com.zp.integration.common.httpclient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
public class HttpClientDemo {
public static void main(String[] args) throws IOException {
myPost();
//myGet();
}
/**
* 以 post 方式请求网页
* @throws IOException
*/
public static void myPost() {
// 目标 URL
String url = "http://127.0.0.1:8080/***";
// 创建一个默认的 HttpClient
//HttpClient httpClient = new DefaultHttpClient();
// DefaultHttpClient 被弃用后的新的请求方法
//CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
//第一步:创建 httpClient 对象
httpClient = HttpClients.createDefault();
//第二步:创建 HttpPost 对象, 以 post 方式请求网页
HttpPost httpPost = new HttpPost(url);
// 添加 HTTP POST 参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//nvps.add(new BasicNameValuePair("username", "admin"));
//nvps.add(new BasicNameValuePair("password", "123456"));
nvps.add(new BasicNameValuePair("id", "1"));
//以表单的形式将参数传递过去
//httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
// 将 POST 参数以 UTF-8 编码并包装成表单实体对象
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
// 打印请求地址
System.out.println("executing request " + httpPost.getRequestLine().getUri());
// 创建响应处理器服务器相应内容
ResponseHandler<String> responseHandler = new BasicResponseHandler();
// 执行请求并获取结果
String responseBody = httpClient.execute(httpPost, responseHandler);
System.out.println(responseBody);
}catch (Exception e) {
e.printStackTrace();
}finally {
// 当不需要 HTTPClient 实例时,关闭连接管理器以确保释放所有占用的系统资源
//httpClient.getConnectionManager().shutdown();
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 以 get 方式请求网页
* @throws IOException
*/
public static void myGet() {
// 目标 URL
String url = "http://127.0.0.1:8080/***";
// 创建一个默认的 HttpClient
//HttpClient httpClient = new DefaultHttpClient();
// DefaultHttpClient 被弃用后的新的请求方法
//CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 以 get 方式请求网页
HttpGet httpGet = new HttpGet(url);
// 打印请求地址
System.out.println("executing request " + httpGet.getURI());
// 创建响应处理器服务器相应内容
ResponseHandler<String> responseHandler = new BasicResponseHandler();
// 执行请求并获取结果
String responseBody = httpClient.execute(httpGet, responseHandler);
System.out.println(responseBody);
}catch (Exception e) {
e.printStackTrace();
}finally {
// 当不需要 HTTPClient 实例时,关闭连接管理器以确保释放所有占用的系统资源
//httpClient.getConnectionManager().shutdown();
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 调用其他服务接口的方法一(POST 方式)
* @param params
* @return
*/
public static JSONObject doPost(JSONObject params) {
HttpClient client = HttpClients.createDefault();
// 要调用的接口方法
String url = "http://localhost:8080/***";
HttpPost post = new HttpPost(url);
JSONObject jsonObject = null;
try {
StringEntity stringEntity = new StringEntity(params.toString());
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);
post.addHeader("content-type", "te");
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String res = EntityUtils.toString(response.getEntity());// 返回 json 格式
jsonObject = JSONObject.parseObject(res);
}
}catch (Exception e) {
throw new RuntimeException(e);
}
return jsonObject;
}
// /**
// * Controller 层 调用例子(doPost)
// * @return
// * @throws ParseException
// */
// @RequestMapping("/doPostGetJson")
// public String doPostGetJson() throws ParseException {
// // 此处将要发送的数据转换为 json 格式字符串
// String jsonText = "{id:1}";
// JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonText);
// JSONObject res = this.doPost(jsonObject);
// System.out.println("返回参数:" + res);
// return sr.toString();
// }
}
|
package metier;
import exceptions.NumSecuException;
import java.math.BigInteger;
public class NumSecu {
private int nNumSecu;
private int sexe; // length 1
private int anneNaissance; // length 2
private int moisNaissance; // length 2
private int departement; // length 2, < 95
private int codeCommune; // length 3
private int ordre; // length 3 : ordre de Naissance
private int cle; // length 2 : cle=97 − (n%97)
public NumSecu(String numSecuAsString) throws NumSecuException {
setSexe(Integer.valueOf(numSecuAsString.substring(0, 1))); // 1 exclusive
setAnneNaissance(Integer.valueOf(numSecuAsString.substring(1, 3)));
setMoisNaissance(Integer.valueOf(numSecuAsString.substring(3, 5)));
setDepartement(Integer.valueOf(numSecuAsString.substring(5, 7)));
setCodeCommune(Integer.valueOf(numSecuAsString.substring(7, 10)));
setOrdre(Integer.valueOf(numSecuAsString.substring(10, 13)));
setCle(numSecuAsString, Integer.valueOf(numSecuAsString.substring(13, 15)));
}
public NumSecu(int nNumSecu, int sexe, int anneNaissance, int moisNaissance, int departement, int codeCommune, int ordre, int cle) {
this.nNumSecu = nNumSecu;
this.sexe = sexe;
this.anneNaissance = anneNaissance;
this.moisNaissance = moisNaissance;
this.departement = departement;
this.codeCommune = codeCommune;
this.ordre = ordre;
this.cle = cle;
}
public NumSecu(int sexe, int anneNaissance, int moisNaissance, int departement, int codeCommune, int ordre, int cle) throws NumSecuException {
this.setSexe(sexe);
this.anneNaissance = anneNaissance;
this.moisNaissance = moisNaissance;
this.departement = departement;
this.codeCommune = codeCommune;
this.ordre = ordre;
this.cle = cle;
}
public int getnNumSecu() {
return nNumSecu;
}
private void setSexe(int sexe) throws NumSecuException {
if (sexe == 1 || sexe == 2) {
this.sexe = sexe;
} else {
throw new NumSecuException("Premier chiffre, valeur : 1 ou 2");
}
}
private void setAnneNaissance(int anneNaissance) {
this.anneNaissance = anneNaissance;
}
private void setMoisNaissance(int moisNaissance) throws NumSecuException {
if (moisNaissance > 0 && moisNaissance < 12) {
this.moisNaissance = moisNaissance;
} else {
throw new NumSecuException("Chiffre 3 et 4 : mois de naissance (entre 0 et 12)");
}
}
private void setDepartement(int departement) throws NumSecuException {
if (this.departement <= 95) {
this.departement = departement;
} else {
throw new NumSecuException("Departement inférieur à 95");
}
}
private void setCodeCommune(int codeCommune) {
this.codeCommune = codeCommune;
}
private void setOrdre(int ordre) {
this.ordre = ordre;
}
private void setCle(String numSecu, int cle) throws NumSecuException {
// verification de la valeur
long n = Long.parseLong((numSecu.substring(0, 13)));
if (97 - (n % 97) == cle) {
this.cle = cle;
} else {
throw new NumSecuException("Clé Invalide");
}
}
public int getSexe() {
return sexe;
}
public int getAnneNaissance() {
return anneNaissance;
}
public int getMoisNaissance() {
return moisNaissance;
}
public int getDepartement() {
return departement;
}
public int getCodeCommune() {
return codeCommune;
}
public int getOrdre() {
return ordre;
}
public int getCle() {
return cle;
}
public static void main(String[] args) throws NumSecuException {
NumSecu s = new NumSecu(1, 98, 10, 24, 24, 22, 168);
System.out.println(s);
NumSecu numClaire = new NumSecu("267045918300767");
}
}
|
package by.htp.cratemynewpc.dao;
import by.htp.cratemynewpc.domain.DDRBean;
public interface DdrDAO extends CrudDAO<DDRBean> {
//add new
}
|
package FlowControlStatements;
/**
*
*/
/**
* @author guptaav
*
*/
public class Ifelse {
/**
* @param args
*/
public static void main(String[] args) {
int a=100;
int b=200;
if (true)
{
System.out.println("True body");
}
else
{
System.out.println("False body");
}
System.out.println("*******************************");
if (a<b) {
System.out.println("B is greater than A");
}
System.out.println("*******************************");
int x=10;
int y=20;
if(x==y)
{
System.out.println("X is Equlant to Y");
}
else
{
System.out.println("X is NotEqulant to Y");
}
System.out.println("*******************************");
int m =300;
int n=300;
if (m>n)
{
System.out.println("M is NotGreater N");
}
else if(m<n)
{
System.out.println("M is NotLess to N");
}
else if(m==n)
{
System.out.println("M is Equalnt to N");
}
else
{
System.out.println("Both above condiion are failed");
}
}
}
|
package net.liuzhenhua.shapedimageview;
import android.content.Context;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
/**
* Created by liuzhenhua on 2017/4/17.
*/
public class PathImageView extends BasePathImageView {
private Path mPath;
public PathImageView(Context context) {
super(context);
}
public PathImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PathImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setPath(Path mPath) {
this.mPath = mPath;
invalidate();
}
@Override
protected void buildPath(Path roundPath, RectF imageRectF) {
roundPath.addPath(mPath);
}
}
|
package com.zc.base.sys.modules.login;
import com.zc.base.sys.modules.user.entity.User;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class SessionAttributeListener
implements HttpSessionAttributeListener {
private static final Logger logger = LoggerFactory.getLogger(SessionAttributeListener.class);
public void attributeAdded(HttpSessionBindingEvent se) {
}
public void attributeRemoved(HttpSessionBindingEvent se) {
String name = se.getName();
if ("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY".equals(name)) {
SimplePrincipalCollection simplePrincipal = (SimplePrincipalCollection) se.getValue();
User user = (User) simplePrincipal.getPrimaryPrincipal();
logger.info("user:" + user.getAccount() + " authenticationInfo removed from session[" +
se.getSession().getId() + "]....");
}
}
public void attributeReplaced(HttpSessionBindingEvent se) {
}
}
|
package com.tandon.tanay.locationtracker.constants;
import com.google.android.gms.location.LocationRequest;
/**
* Created by tanaytandon on 18/09/17.
*/
public interface LocationRequestConfig {
int UPDATE_INTERVAL = 1 * 6000;
int FASTEST_INTERVAL = 1 * 6000;
int MAX_INTERVAL = 1 * 6000;
int PRIORITY = LocationRequest.PRIORITY_HIGH_ACCURACY;
}
|
/**
* Copyright 2014 Bill McDowell
*
* This file is part of theMess (https://github.com/forkunited/theMess)
*
* 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
*
* 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 ark.data.feature;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import ark.data.annotation.Datum;
import ark.util.Pair;
import ark.util.SerializationUtil;
/**
* Feature represents an abstract feature to be computed on data and
* used in a model.
*
* Implementations of particular features derive from the Feature class,
* and the Feature class is primarily responsible for providing the
* methods necessary for deserializing features from
* configuration files. The features are defined by strings in the
* configuration file of the form:
*
* feature(_[featureReferenceName](_ignored))=[featureGenericName]([parameterName1]=[parameterValue1],...)
*
* Where strings in parentheses are optional and strings in square brackets
* are replaced by feature specific information.
*
* A feature's computed values are generally vectors of real values.
* Each component of a feature's vector has a name, and the set of all names
* for components is the feature's 'vocabulary'.
*
* @author Bill McDowell
*
* @param <D> datum type
* @param <L> datum label type
*/
public abstract class Feature<D extends Datum<L>, L> {
// particular name by which the feature is referenced in configuration files
private String referenceName;
// indicator of whether to ignore the feature in data sets so that it
// isn't included in models
private boolean ignored;
/**
* @param dataSet
* @return true if the feature has been initialized for the dataSet
*/
public abstract boolean init(FeaturizedDataSet<D, L> dataSet);
/**
* @param datum
* @return a sparse mapping from vector indices to values of the feature
* for the given datum.
*/
public abstract Map<Integer, Double> computeVector(D datum);
/**
* @return the generic name of the feature in the configuration files. For
* feature class Feature[X], the generic name should usually be X.
*/
public abstract String getGenericName();
/**
* @return the length of the vector computed by this feature for each
* datum
*/
public abstract int getVocabularySize();
/**
*
* @param index
* @return the name of the component at the given index within vectors
* computed by this feature
*
*/
public abstract String getVocabularyTerm(int index);
/**
*
* @param index
* @param term
* @return true if the name of component at the given index has been set
* to the value of term. This is used when deserializing features that
* were previously computed and saved.
*
*/
protected abstract boolean setVocabularyTerm(int index, String term);
/**
* @return parameters of the feature that can be set through the experiment
* configuration file
*/
protected abstract String[] getParameterNames();
/**
* @param parameter
* @return the value of the given parameter
*/
protected abstract String getParameterValue(String parameter);
/**
*
* @param parameter
* @param parameterValue
* @param datumTools
* @return true if the parameter has been set to parameterValue. Some parameters are set to
* objects retrieved through datumTools that are named by parameterValue.
*/
protected abstract boolean setParameterValue(String parameter, String parameterValue, Datum.Tools<D, L> datumTools);
/**
* @return a generic instance of the feature. This is used when deserializing
* the parameters for the feature from a configuration file
*/
protected abstract Feature<D, L> makeInstance();
/**
* @return a name by which this particular feature is referenced by other
* features in experiment configuration files. This feature can be retrieved
* from a FeaturizedDataSet using this name.
*
*/
public String getReferenceName() {
return this.referenceName;
}
/**
* @return true if this feature should be ignored by models (it is only used for the
* computation of other features)
*/
public boolean isIgnored() {
return this.ignored;
}
public Map<Integer, String> getSpecificShortNamesForIndices(Iterable<Integer> indices) {
String prefix = getSpecificShortNamePrefix();
Map<Integer, String> specificShortNames = new HashMap<Integer, String>();
for (Integer index : indices) {
specificShortNames.put(index, prefix + getVocabularyTerm(index));
}
return specificShortNames;
}
public Map<Integer, String> getVocabularyForIndices(Iterable<Integer> indices) {
Map<Integer, String> vocabulary = new HashMap<Integer, String>();
for (Integer index : indices) {
vocabulary.put(index, getVocabularyTerm(index));
}
return vocabulary;
}
public List<String> getSpecificShortNames() {
String prefix = getSpecificShortNamePrefix();
int vocabularySize = getVocabularySize();
List<String> specificShortNames = new ArrayList<String>(vocabularySize);
for (int i = 0; i < vocabularySize; i++) {
String vocabularyTerm = getVocabularyTerm(i);
specificShortNames.add(prefix + ((vocabularyTerm == null) ? "" : vocabularyTerm));
}
return specificShortNames;
}
public Feature<D, L> clone(Datum.Tools<D, L> datumTools) {
return clone(datumTools, null);
}
public Feature<D, L> clone(Datum.Tools<D, L> datumTools, Map<String, String> environment) {
Feature<D, L> clone = makeInstance();
String[] parameterNames = getParameterNames();
for (int i = 0; i < parameterNames.length; i++) {
String parameterValue = getParameterValue(parameterNames[i]);
if (environment != null && parameterValue != null) {
for (Entry<String, String> entry : environment.entrySet())
parameterValue = parameterValue.replace("${" + entry.getKey() + "}", entry.getValue());
}
clone.setParameterValue(parameterNames[i], parameterValue, datumTools);
}
clone.referenceName = this.referenceName;
clone.ignored = this.ignored;
return clone;
}
public boolean deserialize(BufferedReader reader, boolean readGenericName, boolean readVocabulary, Datum.Tools<D, L> datumTools, String referenceName, boolean ignored) throws IOException {
if (readGenericName && SerializationUtil.deserializeGenericName(reader) == null)
return false;
Map<String, String> parameters = SerializationUtil.deserializeArguments(reader);
if (parameters != null)
for (Entry<String, String> entry : parameters.entrySet())
this.setParameterValue(entry.getKey(), entry.getValue(), datumTools);
if (readVocabulary) {
Map<String, String> vocabulary = SerializationUtil.deserializeArguments(reader);
if (vocabulary == null)
return true;
for (Entry<String, String> entry : vocabulary.entrySet()) {
if (!setVocabularyTerm(Integer.valueOf(entry.getValue()), entry.getKey()))
return false;
}
}
this.referenceName = referenceName;
this.ignored = ignored;
return true;
}
public boolean serialize(Writer writer) throws IOException {
int vocabularySize = getVocabularySize();
writer.write(toString(false));
writer.write("\t");
for (int i = 0; i < vocabularySize; i++) {
String vocabularyTerm = getVocabularyTerm(i);
if (vocabularyTerm == null)
continue;
Pair<String, Integer> v = new Pair<String, Integer>(vocabularyTerm, i);
if (!SerializationUtil.serializeAssignment(v, writer))
return false;
if (i != vocabularySize - 1)
writer.write(",");
}
return true;
}
public String toString(boolean withVocabulary) {
if (withVocabulary) {
StringWriter stringWriter = new StringWriter();
try {
if (serialize(stringWriter))
return stringWriter.toString();
else
return null;
} catch (IOException e) {
return null;
}
} else {
String genericName = getGenericName();
Map<String, String> parameters = new HashMap<String, String>();
String[] parameterNames = getParameterNames();
for (int i = 0; i < parameterNames.length; i++)
parameters.put(parameterNames[i], getParameterValue(parameterNames[i]));
StringWriter parametersWriter = new StringWriter();
try {
SerializationUtil.serializeArguments(parameters, parametersWriter);
} catch (IOException e) {
return null;
}
String parametersStr = parametersWriter.toString();
return genericName + "(" + parametersStr + ")";
}
}
public String toString() {
return toString(false);
}
public boolean fromString(String str, Datum.Tools<D, L> datumTools) {
try {
return deserialize(new BufferedReader(new StringReader(str)), true, true, datumTools, null, false);
} catch (IOException e) {
}
return true;
}
protected String getSpecificShortNamePrefix() {
if (this.referenceName != null)
return this.referenceName + "_";
StringBuilder shortNamePrefixBuilder = new StringBuilder();
String genericName = shortenName(getGenericName());
String[] parameterNames = getParameterNames();
shortNamePrefixBuilder = shortNamePrefixBuilder.append(genericName).append("_");
for (int i = 0; i < parameterNames.length; i++)
shortNamePrefixBuilder = shortNamePrefixBuilder.append(shortenName(parameterNames[i]))
.append("-")
.append(getParameterValue(parameterNames[i]))
.append("_");
return shortNamePrefixBuilder.toString();
}
private String shortenName(String name) {
if (name.length() == 0)
return name;
StringBuilder shortenedName = new StringBuilder();
shortenedName.append(name.charAt(0));
int curWordSize = 0;
for (int i = 1; i < name.length(); i++) {
if (Character.isUpperCase(name.charAt(i))) {
shortenedName.append(name.charAt(i));
curWordSize = 1;
} else if (curWordSize < 4) {
shortenedName.append(name.charAt(i));
curWordSize++;
}
}
return shortenedName.toString();
}
}
|
package Teste;
import Operacional.Cartao;
import Operacional.PagamentoCartao;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import org.junit.Before;
import org.junit.Test;
public class PagamentoCartaoTest {
private PagamentoCartao pc;
private Cartao c;
@Before
public void setUp() throws Exception {
String strValida = "";
for (int i=0; i<128;i++)
strValida += "1";
BigDecimal bd = new BigDecimal(3.00);
c = new Cartao (strValida, bd);
pc = new PagamentoCartao(c);
}
@Test
public void testPagamentoEmCartaoValorExato() {
BigDecimal bd = new BigDecimal(3.00);
assertTrue(pc.fazPagamento(bd));
System.out.println("Teste Valor Exato: " + "Valor do Ticket: 3.00 \n" + c.toString() );
}
@Test
public void testPagamentoEmCartaoFalta() {
BigDecimal bd = new BigDecimal(3.01);
assertFalse(pc.fazPagamento(bd));
System.out.println("Teste Saldo Insuficiente: " + "Valor do Ticket: 3.01 \n" + c.toString() );
}
@Test
public void testPagamentoEmCartaoValorMaior() {
BigDecimal bd = BigDecimal.valueOf(2.99);
assertTrue(pc.fazPagamento(bd));
System.out.println("Teste Falta Valor: " + "Valor do Ticket: 2.99 \n" + c.toString() );
}
}
|
package Entyties.Project.Development.BuildingWrapper.CalibrationData.ZcCalibrations.Bonus;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.annotation.Generated;
@Generated("com.robohorse.robopojogenerator")
public class BonusRow{
@JsonProperty("LevelBonus")
private int levelBonus;
@JsonProperty("ZoneCombinationId")
private int zoneCombinationId;
@JsonProperty("ParkingReductionBonus")
private int parkingReductionBonus;
@JsonProperty("OverlayTypologyId")
private Object overlayTypologyId;
@JsonProperty("BrownfieldRedevelopment")
private int brownfieldRedevelopment;
@JsonProperty("FLRBonus")
private int fLRBonus;
@JsonProperty("HeightBonus")
private int heightBonus;
public void setLevelBonus(int levelBonus){
this.levelBonus = levelBonus;
}
public int getLevelBonus(){
return levelBonus;
}
public void setZoneCombinationId(int zoneCombinationId){
this.zoneCombinationId = zoneCombinationId;
}
public int getZoneCombinationId(){
return zoneCombinationId;
}
public void setParkingReductionBonus(int parkingReductionBonus){
this.parkingReductionBonus = parkingReductionBonus;
}
public int getParkingReductionBonus(){
return parkingReductionBonus;
}
public void setOverlayTypologyId(Object overlayTypologyId){
this.overlayTypologyId = overlayTypologyId;
}
public Object getOverlayTypologyId(){
return overlayTypologyId;
}
public void setBrownfieldRedevelopment(int brownfieldRedevelopment){
this.brownfieldRedevelopment = brownfieldRedevelopment;
}
public int getBrownfieldRedevelopment(){
return brownfieldRedevelopment;
}
public void setFLRBonus(int fLRBonus){
this.fLRBonus = fLRBonus;
}
public int getFLRBonus(){
return fLRBonus;
}
public void setHeightBonus(int heightBonus){
this.heightBonus = heightBonus;
}
public int getHeightBonus(){
return heightBonus;
}
@Override
public String toString(){
return
"BonusRow{" +
"levelBonus = '" + levelBonus + '\'' +
",zoneCombinationId = '" + zoneCombinationId + '\'' +
",parkingReductionBonus = '" + parkingReductionBonus + '\'' +
",overlayTypologyId = '" + overlayTypologyId + '\'' +
",brownfieldRedevelopment = '" + brownfieldRedevelopment + '\'' +
",fLRBonus = '" + fLRBonus + '\'' +
",heightBonus = '" + heightBonus + '\'' +
"}";
}
}
|
package zookeeperTest.factory;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
/**
* zookeeper client factory
* Author: zirui liu
* Date: 2021/7/18
*/
public class ClientFactory {
/**
* create a simple connection
*
* @param connectionString zk address
* @return curator instance
*/
public static CuratorFramework createSimple(String connectionString) {
ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 3);
return CuratorFrameworkFactory.newClient(connectionString, retry);
}
/**
* create a connection with options
*
* @param connectionString address
* @param retryPolicy retry policy
* @param connectionTimeoutMs timeout
* @param sessionTimeoutMs session timeout
* @return curator framework instance
*/
public static CuratorFramework createWithOptions(String connectionString, RetryPolicy retryPolicy,
int connectionTimeoutMs, int sessionTimeoutMs) {
return CuratorFrameworkFactory
.builder()
.connectString(connectionString)
.retryPolicy(retryPolicy)
.connectionTimeoutMs(connectionTimeoutMs)
.sessionTimeoutMs(sessionTimeoutMs)
.build();
}
}
|
package servlets;
import dao.HeroDAO;
import dao.UserDAO;
import models.Hero;
import models.User;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
@WebServlet(name = "CreateHeroServlet")
@MultipartConfig
public class CreateHeroServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("cp1251");
response.setCharacterEncoding("cp1251");
response.setContentType("text/html;charset=cp1251");
HeroDAO dao = new HeroDAO();
String name = request.getParameter("heroname");
String desc = request.getParameter("desc");
Part p = request.getPart("photo");
String localdir = "uploads";
String pathDir = getServletContext().getRealPath("") + File.separator + localdir;
File dir = new File(pathDir);
if (!dir.exists()) {
dir.mkdir();
}
String[] filename_data = p.getSubmittedFileName().split("\\.");
String filename = Math.random() + "." + filename_data[filename_data.length - 1];
String fullpath = pathDir + File.separator + filename;
p.write(fullpath);
HttpSession session = request.getSession();
User user = (User) session.getAttribute("currentSessionUser");
long user_id = user.getId();
Hero hero = new Hero(1, user_id, name, localdir + "/" + filename, desc);
dao.save(hero);
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/myheroes");
dispatcher.forward(request, response);
/*Part part = request.getPart("photo");
if (part == null) {
response.sendRedirect("null.jsp");
} else {
InputStream is = part.getInputStream();
File uploads = new File("/home/alina");
File file = File.createTempFile("file-", ".png", uploads);
try (is) {
Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
String photo = file.getName();
HttpSession session = request.getSession();
User user = (User) session.getAttribute("currentSessionUser");
long user_id = user.getId();
Hero hero = new Hero(1, user_id, name, photo, desc);
dao.save(hero);
response.sendRedirect("my_heroes.jsp");
}*/
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.getAttribute("currentSessionUser") != null) {
RequestDispatcher dispatcher
= this.getServletContext().getRequestDispatcher("/createHero.jsp");
dispatcher.forward(request, response);
}
else {
RequestDispatcher dispatcher
= this.getServletContext().getRequestDispatcher("/login");
dispatcher.forward(request, response);
}
}
}
|
package com.simpletime.common;
public class Constant {
public static final String LOCAL = "http://localhost:8080/SimpleTime/";
}
|
public class XorSequenceEasy {
public int getmax(int[] A, int N) {
int zero = count(A, 0);
int result = zero;
long current = 1;
while(current < N) {
int newResult = count(A, (int)current);
if(zero < newResult) {
result += newResult - zero;
}
current *= 2;
}
return result;
}
private int count(int[] A, int B) {
int[] C = new int[A.length];
for(int i = 0; i < C.length; ++i) {
C[i] = A[i] ^ B;
}
int count = 0;
for(int i = 0; i < C.length; ++i) {
for(int j = i + 1; j < C.length; ++j) {
if(C[i] < C[j]) {
++count;
}
}
}
return count;
}
}
|
package com.ljh.dto;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
/**
* @Author laijinhan
* @date 2020/9/24 10:16 下午
*/
// Component 等价于 <bean id="user" class="com.ljh.dto.User"/>
@Component
public class User {
// 相当于在bean里面 注入属性值。
@Value("赖金寒")
public String name;
}
|
package com.empowerhack.family.memberservice.repository;
import java.util.List;
import com.empowerhack.family.memberservice.domain.Member;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.history.RevisionRepository;
import org.springframework.data.repository.query.Param;
public interface MemberRepository extends PagingAndSortingRepository<Member, Long>, RevisionRepository<Member, Long, Integer> {
@Query("SELECT m FROM Member m WHERE m.name LIKE %:name%")
List<Member> findByName(@Param("name") String name);
}
|
/*
* Created on 16-mei-2005
*/
package craterstudio.io;
import java.io.IOException;
public interface TransferListener
{
public void transferInitiated(int expectedBytes);
public void transfered(int bytes);
public void transferFinished(IOException potentialException);
}
|
package com.gxtc.huchuan.ui.news;
import com.gxtc.commlibrary.BasePresenter;
import com.gxtc.commlibrary.BaseUiView;
import com.gxtc.commlibrary.BaseUserView;
import com.gxtc.commlibrary.data.BaseRepository;
import com.gxtc.commlibrary.data.BaseSource;
import com.gxtc.huchuan.bean.NewNewsBean;
import com.gxtc.huchuan.bean.NewsBean;
import com.gxtc.huchuan.http.ApiCallBack;
import java.util.HashMap;
import java.util.List;
/**
* Created by sjr on 2017/2/15.
* 资讯首页
*/
public class NewsItemContract {
/**
* view层接口
* 如果涉及到用户相关的 那么这个接口应该继承
*
* @see BaseUserView 区别在于多了个token过期的回调方法
* <p>
* 如果没涉及到用户相关的操作 那么这个接口直接继承
* @see BaseUiView
*/
public interface View extends BaseUserView<NewsItemContract.Presenter> {
/**
* 展示数据
*
* @param datas
*/
void showData(List<NewNewsBean> datas);
/**
* 刷新结束
*
* @param datas
*/
void showRefreshFinish(List<NewNewsBean> datas);
/**
* 加载更多
*
* @param datas
*/
void showLoadMore(List<NewNewsBean> datas);
/**
* 没有更多数据
*/
void showNoMore();
void showShieldSuccess(String articleId, String targetUserCode);
void showShieldError(String articleId, String targetUserCode, String msg);
}
/**
* presenter层接口
*/
public interface Presenter extends BasePresenter {
/**
* @param isRefresh 是否刷新
*/
void getData(boolean isRefresh);
void loadMrore();
void shieldType(String newsId, String targetUserCode, int type, String shieldType);
}
/**
* model层接口 实现类还需要继承
*
* @see BaseRepository
*/
public interface Source extends BaseSource {
void getData(int start, String id, int flag, String userCode,String clickType, ApiCallBack<List<NewNewsBean>> callBack);
void shieldType(HashMap<String, String> map, ApiCallBack<Object> callBack);
}
}
|
package com.fumei.bg.controller;
import com.fumei.bg.common.AjaxResult;
import com.fumei.bg.common.BaseController;
import com.fumei.bg.domain.system.SysFile;
import com.fumei.bg.exception.FileException;
import com.fumei.bg.service.system.ISysFileService;
import com.fumei.bg.util.FileUploadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
*
* @author zkh
*/
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
@RestController
@RequestMapping("/api")
public class APIController extends BaseController {
private static final Logger log = LoggerFactory.getLogger(APIController.class);
private final ISysFileService fileService;
public APIController(ISysFileService fileService) {
this.fileService = fileService;
}
}
|
package user;
import browserUI.BrowserUI;
public class Browser extends User {
public Browser(String name,String password,String role){
super(name,password,role);
}
@Override
public void showMenu()
{
new BrowserUI(this,"ä¯ÀÀÕß²Ù×÷½çÃæ");
}
}
|
package inf1010.assignment;
public class Person {
private String email;
private String name;
private String userName;
Person(String email, String name, String userName) {
this.email = email;
this.name = name;
this.userName = userName;
}
public int compareTo(Person p) {
System.out.println("Does this work? " + p.getName());
return p.getName().compareTo(name);
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.console.menu;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.Collection;
import javax.swing.BorderFactory;
import javax.swing.border.TitledBorder;
import net.datacrow.console.ComponentFactory;
import net.datacrow.console.components.DcButton;
import net.datacrow.console.components.DcMenu;
import net.datacrow.console.components.DcTitledBorder;
import net.datacrow.core.DataCrow;
import net.datacrow.core.IconLibrary;
import net.datacrow.core.modules.DcModule;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.objects.DcTemplate;
import net.datacrow.core.objects.template.Templates;
import net.datacrow.core.plugin.Plugin;
import net.datacrow.core.plugin.PluginHelper;
import net.datacrow.core.plugin.Plugins;
import net.datacrow.core.resources.DcResources;
import net.datacrow.util.launcher.URLLauncher;
import org.apache.log4j.Logger;
public class MainFrameMenuBar extends net.datacrow.console.components.DcMenuBar {
private static Logger logger = Logger.getLogger(MainFrameMenuBar.class.getName());
public static final int _SEARCHPANEL = 0;
public static final int _INSERTPANEL = 1;
public static final int _NOTEPANEL = 2;
private final DcModule module;
public MainFrameMenuBar(DcModule module) {
this.module = module;
TitledBorder border = new DcTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 1), "");
this.setBorder(border);
build();
}
private void build() {
DcMenu menuAdministration = new AdministrationMenu(module);
DcMenu menuTools = ComponentFactory.getMenu(DcResources.getText("lblTools"));
DcMenu menuModules = ComponentFactory.getMenu(DcResources.getText("lblModules"));
DcMenu menuSettings = ComponentFactory.getMenu(DcResources.getText("lblSettings"));
DcMenu menuFile = ComponentFactory.getMenu(DcResources.getText("lblFile"));
DcMenu menuFilter = ComponentFactory.getMenu(DcResources.getText("lblFilter"));
DcMenu menuPlugins = ComponentFactory.getMenu(DcResources.getText("lblPlugins"));
DcMenu menuUser = ComponentFactory.getMenu(DcResources.getText("lblUser"));
DcMenu menuXp = ComponentFactory.getMenu(DcResources.getText("lblXpMode"));
DcMenu menuWebServer = ComponentFactory.getMenu(DcResources.getText("lblWebServer"));
DcMenu menuHelp = ComponentFactory.getMenu(DcResources.getText("lblHelp"));
// webserver menu
if (DataCrow.isWebModuleInstalled())
PluginHelper.add(menuWebServer, "WebServer");
// xp menu
PluginHelper.add(menuXp, "BeginnerMode");
PluginHelper.add(menuXp, "ExpertMode");
// view menu
DcMenu menuView = ComponentFactory.getMenu(DcResources.getText("lblView"));
for (int view : module.getSupportedViews())
PluginHelper.add(menuView, "ChangeView", null, null, null, view, -1, Plugin._VIEWTYPE_SEARCH);
menuView.addSeparator();
PluginHelper.add(menuView, "ToggleQuickFilterBar");
PluginHelper.add(menuView, "ToggleModuleList");
PluginHelper.add(menuView, "ToggleQuickView");
PluginHelper.add(menuView, "ToggleGroupingPane");
// PluginHelper.add(menuView, "ToggleToolbarLabels");
PluginHelper.add(menuView, "ToggleToolbar");
// modules menu
DcMenu subMenuModule = ComponentFactory.getMenu(DcResources.getText("lblActiveModule"));
for (DcModule module : DcModules.getModules()) {
if (module.isSelectableInUI())
PluginHelper.add(subMenuModule, "OpenModule", module.getIndex());
}
PluginHelper.add(menuModules, "CreateModuleWizard");
PluginHelper.add(menuModules, "CopyModuleWizard");
PluginHelper.add(menuModules, "AlterModuleWizard");
PluginHelper.add(menuModules, "RelateModuleWizard");
PluginHelper.add(menuModules, "DeleteModuleWizard");
menuModules.addSeparator();
PluginHelper.add(menuModules, "ExportModuleWizard");
PluginHelper.add(menuModules, "ImportModuleWizard");
menuModules.addSeparator();
menuModules.add(subMenuModule);
// help menu
PluginHelper.add(menuHelp, "Help");
PluginHelper.add(menuHelp, "TipOfTheDay");
menuHelp.addSeparator();
PluginHelper.add(menuHelp, "About");
PluginHelper.add(menuHelp, "Donate");
menuHelp.addSeparator();
PluginHelper.add(menuHelp, "ToolSelectWizard");
// filter menu
PluginHelper.add(menuFilter, "Filter");
PluginHelper.add(menuFilter, "ApplyFilter");
menuFilter.addSeparator();
PluginHelper.add(menuFilter, "UndoFilter");
// tools menu
if (module.getImporterClass() != null)
PluginHelper.add(menuTools, "FileImport");
if (module.deliversOnlineService()) {
menuTools.addSeparator();
if (module.getIndex() == DcModules._AUDIOCD)
PluginHelper.add(menuTools, "RetrieveAudioCDInformation");
PluginHelper.add(menuTools, "OnlineSearch");
menuTools.addSeparator();
}
if (module.getSynchronizer() != null) {
PluginHelper.add(menuTools, "MassUpdate");
menuTools.addSeparator();
}
// file menu
DcMenu menuCreateNew = ComponentFactory.getMenu(IconLibrary._icoAdd,
DcResources.getText("lblNewItem", module.getObjectName()));
boolean templatesPresent = false;
if (module.getTemplateModule() != null) {
Templates.refresh();
for (DcTemplate template : Templates.getTemplates(module.getTemplateModule().getIndex())) {
templatesPresent = true;
PluginHelper.add(menuCreateNew, "CreateNew", null, null, template, -1, module.getIndex(), Plugin._VIEWTYPE_SEARCH);
}
}
PluginHelper.add(menuFile, "NewItemWizard", module.getIndex(), Plugin._VIEWTYPE_SEARCH);
menuFile.addSeparator();
PluginHelper.add(menuFile, "FileLauncher", module.getIndex(), Plugin._VIEWTYPE_SEARCH);
menuFile.addSeparator();
if (templatesPresent)
menuFile.add(menuCreateNew);
PluginHelper.add(menuFile, "CreateNew", module.getIndex(), Plugin._VIEWTYPE_SEARCH);
PluginHelper.add(menuFile, "OpenItem", module.getIndex(), Plugin._VIEWTYPE_SEARCH);
PluginHelper.add(menuFile, "EditItem", module.getIndex(), Plugin._VIEWTYPE_SEARCH);
PluginHelper.add(menuFile, "SaveAll", module.getIndex(), Plugin._VIEWTYPE_SEARCH);
if (!module.isAbstract())
PluginHelper.add(menuFile, "Delete", module.getIndex(), Plugin._VIEWTYPE_SEARCH);
menuFile.addSeparator();
PluginHelper.add(menuFile, "Log");
PluginHelper.add(menuFile, "Exit");
// settings menu
PluginHelper.add(menuSettings, "Settings");
PluginHelper.add(menuSettings, "UserDirSettings");
PluginHelper.add(menuSettings, "FieldSettings", module.getIndex());
menuSettings.addSeparator();
if (!module.isAbstract())
PluginHelper.add(menuSettings, "QuickViewSettings");
PluginHelper.add(menuSettings, "ViewSettings");
if (!module.isAbstract()) {
if (DataCrow.isWebModuleInstalled())
PluginHelper.add(menuSettings, "WebFieldSettings");
}
PluginHelper.add(menuSettings, "ItemFormSettings", module.getIndex());
if (module.isParentModule())
PluginHelper.add(menuSettings, "ItemFormSettings", module.getChild().getIndex());
menuSettings.addSeparator();
PluginHelper.add(menuSettings, "ChangeLookAndFeel");
menuSettings.addSeparator();
PluginHelper.add(menuSettings, "ResourceEditor");
// tools menu
if (module.hasReports())
PluginHelper.add(menuTools, "Report");
PluginHelper.add(menuTools, "Charts");
menuTools.addSeparator();
PluginHelper.add(menuTools, "ItemExporterWizard");
PluginHelper.add(menuTools, "ItemImporterWizard");
if (DcModules.get(DcModules._LOAN).isEnabled())
PluginHelper.add(menuTools, "ICalendarExporter");
if (!module.isAbstract()) {
menuTools.addSeparator();
PluginHelper.add(menuTools, "NewItems");
menuTools.addSeparator();
PluginHelper.add(menuTools, "UpdateAll");
PluginHelper.add(menuTools, "FindReplace");
PluginHelper.add(menuTools, "AutoIncrementer");
if (module.getType() == DcModule._TYPE_ASSOCIATE_MODULE)
PluginHelper.add(menuTools, "AssociateNameRewriter");
else
PluginHelper.add(menuTools, "TitleRewriter");
}
Collection<Plugin> plugins = Plugins.getInstance().getUserPlugins(null, -1, module.getIndex(), Plugin._VIEWTYPE_SEARCH);
for (Plugin plugin : plugins) {
if (plugin.isShowInMenu())
menuPlugins.add(ComponentFactory.getMenuItem(plugin));
}
menuTools.addSeparator();
PluginHelper.add(menuTools, "BackupAndRestore");
menuTools.addSeparator();
PluginHelper.add(menuTools, "DatabaseEditor");
PluginHelper.add(menuTools, "DriveManager");
if (module.isFileBacked())
PluginHelper.add(menuTools, "FileRenamer", module.getIndex());
else if (module.getChild() != null && module.getChild().isFileBacked())
PluginHelper.add(menuTools, "FileRenamer",module.getChild().getIndex());
// item information menu
menuAdministration.addSeparator();
PluginHelper.add(menuAdministration, "LoanInformation");
// user menu
PluginHelper.add(menuUser, "ChangePassword");
menuWebServer.setEnabled(menuWebServer.getItemCount() > 0);
menuFile.setEnabled(menuFile.getItemCount() > 0);
menuModules.setEnabled(menuModules.getItemCount() > 0);
menuView.setEnabled(menuView.getItemCount() > 0);
menuFilter.setEnabled(menuFilter.getItemCount() > 0);
menuSettings.setEnabled(menuSettings.getItemCount() > 0);
menuTools.setEnabled(menuTools.getItemCount() > 0);
menuHelp.setEnabled(menuHelp.getItemCount() > 0);
if (menuFile.isEnabled())
this.add(menuFile);
if (menuAdministration.isEnabled())
this.add(menuAdministration);
this.add(menuXp);
if (menuModules.isEnabled())
this.add(menuModules);
if (menuView.isEnabled())
this.add(menuView);
if (menuFilter.isEnabled())
this.add(menuFilter);
if (menuSettings.isEnabled())
this.add(menuSettings);
if (menuUser.isEnabled())
this.add(menuUser);
if (menuTools.isEnabled())
this.add(menuTools);
if (plugins.size() > 0)
this.add(menuPlugins);
if (menuWebServer.isEnabled())
this.add(menuWebServer);
this.add(menuHelp);
DcButton btTwitter = ComponentFactory.getIconButton(IconLibrary._icoTwitter);
btTwitter.addActionListener(new TwitterActionListener());
this.add(btTwitter);
}
private class TwitterActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent ae) {
try {
URLLauncher launcher = new URLLauncher(new URL("http://twitter.com/data_crow"));
launcher.launch();
} catch (Exception e) {
logger.error(e, e);
}
}
}
}
|
package de.hdm.softwarepraktikum.server;
import java.util.logging.Logger;
import de.hdm.softwarepraktikum.shared.CommonSettings;
/**
* Klasse mit Eigenschaften und Diensten, die für alle Server-seitigen Klassen von
* Bedeutung sind.
* Durch diese Klasse wird eine Logging-Funktion unter Java unterstützt,
* indem ein zentraler Applikationslogger realisiert wird. Diese Funktion kann
* mit Hilfe von <code>ServerSideSettings.getLogger()</code> aufgerufen werden.
*
*/
public class ServersideSettings extends CommonSettings{
private static final String LOGGER_NAME = "Shoppinglisttool Server";
private static final Logger log = Logger.getLogger(LOGGER_NAME);
/**
* Auslesen des applikationsweiten zentralen Loggers.
* @return Server-Seitige Logger-Instanz
*/
public static Logger getLogger() {
return log;
}
}
|
package L6_ExerciciosComStrings;
import com.sun.jdi.Value;
import java.util.Scanner;
public class Exercicio_02_main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Digite seu nome");
String nomeUsuario = myScanner.nextLine();
StringBuilder nomeUBulder = new StringBuilder();
nomeUBulder.append(nomeUsuario).reverse();
String nomeURevers = String.valueOf(nomeUBulder);
System.out.print(String.valueOf(nomeUBulder));
}
}
|
package dao.impl;
import dao.CoffeeOrderItemDao;
import entities.CoffeeOrderItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
@Repository
public class CoffeeOrderItemDaoImpl extends AbstractDao implements CoffeeOrderItemDao {
private static Logger log = Logger.getLogger(CoffeeOrderItemDaoImpl.class);
private static final String SAVE_COFFEE_ORDER_ITEM_SQL =
"INSERT INTO CoffeeOrderItem (type_id, order_id, quantity) VALUES (?,?,?)";
private static final String GET_COFFEE_ORDER_ITEM_BY_ID_SQL =
"SELECT * FROM CoffeeOrderItem WHERE id=?";
private static final String GET_ALL_COFFEE_ORDER_ITEM_FOR_ORDER_ID_SQL =
"SELECT * FROM CoffeeOrderItem WHERE order_id=?";
private static final String UPDATE_COFFEE_ORDER_ITEM_BY_ID_SQL =
"UPDATE CoffeeOrderItem SET type_id=?, order_id=?, quantity=? WHERE id=?";
private static final String DELETE_COFFEE_ORDER_ITEM_BY_ID_SQL =
"DELETE FROM CoffeeOrderItem WHERE id=?";
private PreparedStatement psSave = null;
private PreparedStatement psGet = null;
private PreparedStatement psGetAllForOrderId = null;
private PreparedStatement psUpdate = null;
private PreparedStatement psDelete = null;
public CoffeeOrderItemDaoImpl() {}
/**
* Saves the entity type <CoffeeOrderItem> in the database
*
* @param coffeeOrderItem determine entity with type <CoffeeOrderItem>
* @return saved entity with not null id
* @throws SQLException if can't save entity
*/
@Override
public CoffeeOrderItem save(CoffeeOrderItem coffeeOrderItem) throws SQLException {
if (coffeeOrderItem == null) {
return null;
}
if (psSave == null) {
psSave = psSave = prepareStatement(SAVE_COFFEE_ORDER_ITEM_SQL, Statement.RETURN_GENERATED_KEYS);
}
psSave.setInt(1, coffeeOrderItem.getCoffeeTypeId());
psSave.setInt(2, coffeeOrderItem.getOrderId());
psSave.setInt(3, coffeeOrderItem.getQuantity());
psSave.executeUpdate();
try (ResultSet rs = psSave.getGeneratedKeys()) {
if (rs.next()) {
coffeeOrderItem.setId(rs.getInt(1));
}
} catch (SQLException e) {
String errorMessage = "Can't execute SQL: " + psSave + e.getMessage();
log.error(errorMessage);
throw new SQLException(errorMessage);
}
return coffeeOrderItem;
}
/**
* returns an entity with an id from the database
*
* @param id determine id of entity in database
* @return entity with type <CoffeeOrderItem> from the database,
* or null if such an entity was not found
* @throws SQLException if there is an error connecting to the database
*/
@Override
public CoffeeOrderItem get(Serializable id) throws SQLException {
if (psGet == null) {
psGet = prepareStatement(GET_COFFEE_ORDER_ITEM_BY_ID_SQL);
}
psGet.setInt(1, (int) id);
psGet.executeQuery();
try (ResultSet rs = psGet.getResultSet()) {
if (rs.next()) {
return populateEntity(rs);
}
} catch (SQLException e) {
String errorMessage = "Can't execute SQL: " + psGet + e.getMessage();
log.error(errorMessage);
throw new SQLException(errorMessage);
}
return null;
}
/**
* update an entity with an id = coffeeOrderItem.id in the database
*
* @param coffeeOrderItem determine a new entity to be updated
* in the database with id = coffeeOrderItem.id
* @throws SQLException if there is an error updating entity in the database
*/
@Override
public void update(CoffeeOrderItem coffeeOrderItem) throws SQLException {
if (coffeeOrderItem == null) {
return;
}
try {
if (psUpdate == null) {
psUpdate = prepareStatement(UPDATE_COFFEE_ORDER_ITEM_BY_ID_SQL);
}
psUpdate.setInt(4, coffeeOrderItem.getId());
psUpdate.setInt(1, coffeeOrderItem.getCoffeeTypeId());
psUpdate.setInt(2, coffeeOrderItem.getOrderId());
psUpdate.setInt(3, coffeeOrderItem.getQuantity());
psUpdate.executeUpdate();
} catch (SQLException e) {
String errorMessage = "Can't execute SQL: " + psUpdate + e.getMessage();
log.error(errorMessage);
throw new SQLException(errorMessage);
}
}
/**
* removes from the database an entity with type <CoffeeOrderItem> and id
*
* @param id determine id of entity in database
* @return returns the number of deleted rows from the database
* @throws SQLException if there is an error deleting entity from the database
*/
@Override
public int delete(Serializable id) throws SQLException {
try {
if (psDelete == null) {
psDelete = prepareStatement(DELETE_COFFEE_ORDER_ITEM_BY_ID_SQL);
}
psDelete.setInt(1, (int) id);
return psDelete.executeUpdate();
} catch (SQLException e) {
String errorMessage = "Can't execute SQL: " + psDelete + e.getMessage();
log.error(errorMessage);
throw new SQLException(errorMessage);
}
}
/**
* get all records of CoffeeOrderItem from DB for definite CoffeeOrder with id = orderId
*
* @param orderId determines id for CoffeeOrder
* @return a list of all records of CoffeeOrderItem from the database
* for definite CoffeeOrder with id = orderId or
* empty list if there are no entries
* @throws SQLException if there is an error connecting to the database
*/
@Override
public List<CoffeeOrderItem> getAllForOrderId(Serializable orderId) throws SQLException {
List<CoffeeOrderItem> list = new ArrayList<>();
try {
if (psGetAllForOrderId == null) {
psGetAllForOrderId = prepareStatement(GET_ALL_COFFEE_ORDER_ITEM_FOR_ORDER_ID_SQL);
}
psGetAllForOrderId.setInt(1, (int) orderId);
psGetAllForOrderId.execute();
try (ResultSet rs = psGetAllForOrderId.getResultSet()) {
while (rs.next()) {
list.add(populateEntity(rs));
}
} catch (SQLException e) {
String errorMessage = "Can't execute SQL: " + psGetAllForOrderId +
e.getMessage();
log.error(errorMessage);
throw new SQLException(errorMessage);
}
} catch (SQLException e) {
String errorMessage = "Can't execute SQL: " + psGetAllForOrderId +
e.getMessage();
log.error(errorMessage);
throw new SQLException(errorMessage);
}
return list;
}
private CoffeeOrderItem populateEntity(ResultSet rs) throws SQLException {
CoffeeOrderItem entity = new CoffeeOrderItem();
entity.setId(rs.getInt(1));
entity.setCoffeeTypeId(rs.getInt(2) );
entity.setOrderId(rs.getInt(3) );
entity.setQuantity(rs.getInt(4));
return entity;
}
}
|
package org.lf.event;
import java.util.EventListener;
/**
* @author liufu
*/
public interface MethodExecutionEventListener extends EventListener {
/**
* 处理方法开始执行的时候发布的MethodExecutionEvent事件 3
*/
void onMethodBegin(MethodExecutionEvent evt);
/**
* 处理方法执行将结束时候发布的MethodExecutionEvent事件 4
*/
void onMethodEnd(MethodExecutionEvent evt);
}
|
package com.xue.trainingclass.activity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import com.xue.trainingclass.adapter.ChildMenuAdapter;
import com.xue.trainingclass.bean.Class;
public class ChooseClassDialog extends Activity {
private TextView mTitle;
private GridView mClassGV;
ChildMenuAdapter mAdapter;
private ImageView mBack;
List<Class> mParentList = new ArrayList<Class>();
List<Class> mChildList = new ArrayList<Class>();
private boolean isParentClass=true;
private String mParentName;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_chooseclasstype);
mTitle=(TextView) findViewById(R.id.title);
mBack=(ImageView) findViewById(R.id.back);
mBack.setVisibility(View.INVISIBLE);
mBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!isParentClass){
isParentClass=true;
mBack.setVisibility(View.INVISIBLE);
if(mParentList.size()>0){
mAdapter = new ChildMenuAdapter(mParentList, ChooseClassDialog.this);
mClassGV.setAdapter(mAdapter);
mTitle.setText(getResources().getString(R.string.chooseParentClass));
}else {
queryClasses();
}
}
}
});
mClassGV=(GridView) findViewById(R.id.classType);
mClassGV.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
if(isParentClass ){
mParentName=mParentList.get(position).getClassname();
if( mParentList.get(position).getHaschild()){
//选择子分类
queryChildClassed(mParentList.get(position).getClassid());
isParentClass=false;
mBack.setVisibility(View.VISIBLE);
}else {
//没有子分类
Intent intent=new Intent(ChooseClassDialog.this,PublishActivity.class);
intent.putExtra("className", mParentName);
intent.putExtra("classId", mParentList.get(position).getClassid());
startActivity(intent);
finish();
}
}else{
Intent intent=new Intent(ChooseClassDialog.this,PublishActivity.class);
intent.putExtra("className", mParentName+"->"+mChildList.get(position).getClassname());
intent.putExtra("classId", mChildList.get(position).getClassid());
startActivity(intent);
finish();
}
}
});
queryClasses();
}
/**
* 查询主分类
*/
private void queryClasses() {
BmobQuery<Class> query = new BmobQuery<Class>();
query.addWhereEqualTo("type", "parent");
query.setLimit(50);
// 执行查询方法
query.findObjects(ChooseClassDialog.this, new FindListener<Class>() {
@Override
public void onSuccess(List<Class> object) {
// TODO Auto-generated method stub
mParentList = object;
// mMenuAdapter.notifyDataSetChanged();
mAdapter = new ChildMenuAdapter(mParentList, ChooseClassDialog.this);
mClassGV.setAdapter(mAdapter);
mTitle.setText(getResources().getString(R.string.chooseParentClass));
}
@Override
public void onError(int code, String msg) {
}
});
}
/**
* 查询子分类
*
* @param view
*/
private void queryChildClassed(String parentid) {
BmobQuery<Class> query = new BmobQuery<Class>();
query.addWhereEqualTo("type", "child");
query.addWhereEqualTo("parentid", parentid);
query.setLimit(50);
// 执行查询方法
query.findObjects(ChooseClassDialog.this, new FindListener<Class>() {
@Override
public void onSuccess(List<Class> object) {
// TODO Auto-generated method stub
mChildList = object;
mAdapter = new ChildMenuAdapter(mChildList, ChooseClassDialog.this);
mClassGV.setAdapter(mAdapter);
mTitle.setText(getResources().getString(R.string.chooseChildClass));
}
@Override
public void onError(int code, String msg) {
}
});
}
}
|
package com.tu.curd.elasticsearch;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
/**
* @Description
* @Classname EmployeeRepository
* @Date 2019/7/9 16:26
* @Created by tuyongjian
*/
@Component
public interface EmployeeRepository extends ElasticsearchRepository<Employee,String> {
}
|
package com.example.demo.controller;
import com.example.demo.model.AppImage;
import com.example.demo.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
public class GalleryAllImageControler {
private final ImageService imageService;
@Autowired
public GalleryAllImageControler(ImageService imageService) {
this.imageService = imageService;
}
// admin gallery returns images of all users
@GetMapping("/all_images")
String adminGallery(Model model) {
List<AppImage> images = imageService.getAllImages();
model.addAttribute("images", images);
return "admin-gallery";
}
@RequestMapping(value = "/deleteadm", method = RequestMethod.POST)
public String handleDeleteImageAdm(@RequestParam String id) {
Long idL = Long.valueOf(id);
imageService.removeImageById(idL);
return "redirect:/all_images";
}
}
|
package com.hunger.rpc.netty.client.handler;
import io.netty.channel.ChannelPipeline;
/**
* Created by 小排骨 on 2018/1/10.
*/
public interface RpcSendHandler {
/**
* 添加在channel上的handler
* @param pipeline
*/
void handle(ChannelPipeline pipeline);
}
|
/*
* 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.test.context.junit4.orm;
import jakarta.persistence.PersistenceException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.orm.domain.DriversLicense;
import org.springframework.test.context.junit4.orm.domain.Person;
import org.springframework.test.context.junit4.orm.service.PersonService;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.test.transaction.TransactionAssert.assertThatTransaction;
/**
* Transactional integration tests regarding <i>manual</i> session flushing with
* Hibernate.
*
* @author Sam Brannen
* @author Juergen Hoeller
* @author Vlad Mihalcea
* @since 3.0
* @see org.springframework.test.context.junit.jupiter.orm.JpaEntityListenerTests
*/
@ContextConfiguration
public class HibernateSessionFlushingTests extends AbstractTransactionalJUnit4SpringContextTests {
private static final String SAM = "Sam";
private static final String JUERGEN = "Juergen";
@Autowired
private PersonService personService;
@Autowired
private SessionFactory sessionFactory;
@Before
public void setup() {
assertThatTransaction().isActive();
assertThat(personService).as("PersonService should have been autowired.").isNotNull();
assertThat(sessionFactory).as("SessionFactory should have been autowired.").isNotNull();
}
@Test
public void findSam() {
Person sam = personService.findByName(SAM);
assertThat(sam).as("Should be able to find Sam").isNotNull();
DriversLicense driversLicense = sam.getDriversLicense();
assertThat(driversLicense).as("Sam's driver's license should not be null").isNotNull();
assertThat(driversLicense.getNumber()).as("Verifying Sam's driver's license number").isEqualTo(Long.valueOf(1234));
}
@Test // SPR-16956
@Transactional(readOnly = true)
public void findSamWithReadOnlySession() {
Person sam = personService.findByName(SAM);
sam.setName("Vlad");
// By setting setDefaultReadOnly(true), the user can no longer modify any entity...
Session session = sessionFactory.getCurrentSession();
session.flush();
session.refresh(sam);
assertThat(sam.getName()).isEqualTo("Sam");
}
@Test
public void saveJuergenWithDriversLicense() {
DriversLicense driversLicense = new DriversLicense(2L, 2222L);
Person juergen = new Person(JUERGEN, driversLicense);
int numRows = countRowsInTable("person");
personService.save(juergen);
assertThat(countRowsInTable("person")).as("Verifying number of rows in the 'person' table.").isEqualTo((numRows + 1));
assertThat(personService.findByName(JUERGEN)).as("Should be able to save and retrieve Juergen").isNotNull();
assertThat(juergen.getId()).as("Juergen's ID should have been set").isNotNull();
}
@Test
public void saveJuergenWithNullDriversLicense() {
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() ->
personService.save(new Person(JUERGEN)));
}
@Test
// no expected exception!
public void updateSamWithNullDriversLicenseWithoutSessionFlush() {
updateSamWithNullDriversLicense();
// False positive, since an exception will be thrown once the session is
// finally flushed (i.e., in production code)
}
@Test
public void updateSamWithNullDriversLicenseWithSessionFlush() throws Throwable {
updateSamWithNullDriversLicense();
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> {
// Manual flush is required to avoid false positive in test
try {
sessionFactory.getCurrentSession().flush();
}
catch (PersistenceException ex) {
// Wrapped in Hibernate 5.2, with the constraint violation as cause
throw ex.getCause();
}
});
}
private void updateSamWithNullDriversLicense() {
Person sam = personService.findByName(SAM);
assertThat(sam).as("Should be able to find Sam").isNotNull();
sam.setDriversLicense(null);
personService.save(sam);
}
}
|
package com.db.persistence.events.audit;
import com.db.persistence.events.ServerEvent;
import com.db.persistence.scheme.BaseObject;
import java.util.UUID;
@ServerEvent(id = 8)
public class ObjectModificationEvent implements AuditEvent {
private final BaseObject tip;
private final BaseObject item;
private final int nextRevision;
private final String userName;
public <T extends BaseObject> ObjectModificationEvent(T tip, T item, int nextRevision, String userName) {
this.tip = tip;
this.item = item;
this.nextRevision = nextRevision;
this.userName = userName;
}
public BaseObject getTip() {
return tip;
}
public BaseObject getItem() {
return item;
}
public int getNextRevision() {
return nextRevision;
}
@Override
public String getUserName() {
return userName;
}
@Override
public String toString() {
return "ObjectModificationEvent{" +
"tip=" + tip +
", item=" + item +
", nextRevision=" + nextRevision +
", userName=" + userName +
'}';
}
}
|
package com.auro.scholr.util.snippety.span;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.style.ReplacementSpan;
/**
* Creates a rounded background with specified cornerRadius.
*/
public class RoundedBackgroundSpan extends ReplacementSpan {
public static final int DEFAULT_CORNER_RADIUS = 16;
private int cornerRadius;
private int backgroundColor;
private int textColor;
public RoundedBackgroundSpan(int backgroundColor, int textColor, int cornerRadius) {
this.backgroundColor = backgroundColor;
this.textColor = textColor;
this.cornerRadius = cornerRadius;
}
public RoundedBackgroundSpan(int backgroundColor, int textColor) {
this(backgroundColor, textColor, DEFAULT_CORNER_RADIUS);
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
RectF rect = new RectF(x, top, x + paint.measureText(text, start, end) + cornerRadius, bottom);
paint.setColor(backgroundColor);
canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint);
paint.setColor(textColor);
canvas.drawText(text, start, end, x + cornerRadius / 2, y, paint);
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
return Math.round(paint.measureText(text, start, end));
}
}
|
public class EightRooks {
public String isCorrect(String[] board) {
int[] rowCount = new int[8];
int[] colCount = new int[8];
int count = 0;
for(int i = 0; i < board.length; ++i) {
for(int j = 0; j < board[i].length(); ++j) {
if(board[i].charAt(j) == 'R') {
++count;
if(rowCount[i] + colCount[j] != 0) {
return "Incorrect";
}
++rowCount[i];
++colCount[j];
}
}
}
if(count != 8) {
return "Incorrect";
}
return "Correct";
}
}
|
/**
* MIT License
* <p>
* Copyright (c) 2019-2022 nerve.network
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package network.nerve.converter.model.bo;
import io.nuls.core.crypto.AESEncrypt;
import io.nuls.core.crypto.EncryptedData;
import io.nuls.core.crypto.Sha256Hash;
import io.nuls.core.exception.CryptoException;
import io.nuls.core.exception.NulsException;
import io.nuls.core.model.FormatValidUtils;
import io.nuls.core.model.StringUtils;
import network.nerve.converter.constant.ConverterErrorCode;
import org.bouncycastle.crypto.params.KeyParameter;
import java.io.Serializable;
/**
* 异构链账户类
*
* @author: Mimi
* @date: 2020-02-26
*/
public abstract class HeterogeneousAccount implements Serializable {
private static final byte[] ZERO_BYTES = new byte[]{0};
private String address;
/**
* 账户公钥
*/
private byte[] pubKey;
/**
* 加密私钥
*/
private byte[] encryptedPriKey;
/**
* 明文私钥
*/
private byte[] priKey;
/**
* 账户是否被加密(是否设置过密码)
* Whether the account is encrypted (Whether the password is set)
*/
private boolean isEncrypted() {
return getEncryptedPriKey() != null && getEncryptedPriKey().length > 0;
}
private boolean isEmptyPriKey() {
return getPriKey() == null || getPriKey().length <= 1;
}
private boolean isEmptyEncryptedPriKey() {
return getEncryptedPriKey() == null || getEncryptedPriKey().length <= 1;
}
/**
* 验证账户密码是否正确
* Verify that the account password is correct
*/
public boolean validatePassword(String password) {
boolean result = FormatValidUtils.validPassword(password);
if (!result) {
return false;
}
byte[] unencryptedPrivateKey;
try {
unencryptedPrivateKey = AESEncrypt.decrypt(this.getEncryptedPriKey(), password);
} catch (CryptoException e) {
return false;
}
return validatePubKey(unencryptedPrivateKey, getPubKey());
}
/**
* 根据密码加密账户(给账户设置密码)
* Password-encrypted account (set password for account)
*/
public void encrypt(String password) {
if (isEmptyPriKey()) {
this.setPriKey(ZERO_BYTES);
this.setEncryptedPriKey(ZERO_BYTES);
return;
}
if (this.isEncrypted()) {
return;
}
EncryptedData encryptedPrivateKey = AESEncrypt.encrypt(this.priKey, EncryptedData.DEFAULT_IV, new KeyParameter(Sha256Hash.hash(password.getBytes())));
this.setPriKey(ZERO_BYTES);
this.setEncryptedPriKey(encryptedPrivateKey.getEncryptedBytes());
}
/**
* 根据解密账户, 包括生成账户明文私钥
* According to the decryption account, including generating the account plaintext private key
*/
public boolean decrypt(String password) throws NulsException {
try {
if (isEmptyEncryptedPriKey()) {
this.setPriKey(ZERO_BYTES);
this.setEncryptedPriKey(ZERO_BYTES);
return true;
}
byte[] unencryptedPrivateKey = AESEncrypt.decrypt(this.getEncryptedPriKey(), password);
// 解密后的明文生成公钥,与原公钥校验
if (!validatePubKey(unencryptedPrivateKey, getPubKey())) {
return false;
}
this.setPriKey(unencryptedPrivateKey);
} catch (Exception e) {
throw new NulsException(ConverterErrorCode.PASSWORD_IS_WRONG);
}
return true;
}
protected abstract boolean validatePubKey(byte[] newPriKey, byte[] orginPubKey);
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public byte[] getPubKey() {
return pubKey;
}
public void setPubKey(byte[] pubKey) {
this.pubKey = pubKey;
}
public byte[] getEncryptedPriKey() {
return encryptedPriKey;
}
public void setEncryptedPriKey(byte[] encryptedPriKey) {
this.encryptedPriKey = encryptedPriKey;
}
public byte[] getPriKey() {
return priKey;
}
public void setPriKey(byte[] priKey) {
this.priKey = priKey;
}
}
|
package com.zantong.mobilecttx.user.bean;
import com.zantong.mobilecttx.base.bean.BaseResult;
/**
* Created by zhengyingbing on 16/6/1.
* 消息类别返回实体列表
*/
public class MessageTypeResult extends BaseResult {
private MessageTypeBean data;
public void setData(MessageTypeBean data) {
this.data = data;
}
public MessageTypeBean getData() {
return data;
}
}
|
package com.zjf.myself.codebase.activity.FreeTimeProjectList;
import android.os.Bundle;
import com.zjf.myself.codebase.R;
import com.zjf.myself.codebase.activity.BaseAct;
/**
* <pre>
* author : ZouJianFeng
* e-mail : 1434690833@qq.com
* time : 2017/06/15
* desc :
* version: 1.0
* </pre>
*/
public class NewsCompatibleMainAct extends BaseAct{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_news_compatible_main);
}
}
|
/*
* 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 entidades;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
/**
*
* @author jaker
*/
@Entity
@Table(name = "inventario")
@NamedQueries({
@NamedQuery(name = "Inventario.findAll", query = "SELECT i FROM Inventario i"),
@NamedQuery(name = "Inventario.findByInventarioid", query = "SELECT i FROM Inventario i WHERE i.inventarioid = :inventarioid"),
@NamedQuery(name = "Inventario.findByExistencias", query = "SELECT i FROM Inventario i WHERE i.existencias = :existencias")})
public class Inventario implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "inventarioid")
private Long inventarioid;
@Basic(optional = false)
@NotNull
@Column(name = "existencias")
private int existencias;
@JoinColumn(name = "productoid", referencedColumnName = "productoid")
@ManyToOne(optional = false)
private Producto productoid;
public Inventario() {
}
public Inventario(Long inventarioid) {
this.inventarioid = inventarioid;
}
public Inventario(Long inventarioid, int existencias) {
this.inventarioid = inventarioid;
this.existencias = existencias;
}
public Long getInventarioid() {
return inventarioid;
}
public void setInventarioid(Long inventarioid) {
this.inventarioid = inventarioid;
}
public int getExistencias() {
return existencias;
}
public void setExistencias(int existencias) {
this.existencias = existencias;
}
public Producto getProductoid() {
return productoid;
}
public void setProductoid(Producto productoid) {
this.productoid = productoid;
}
@Override
public int hashCode() {
int hash = 0;
hash += (inventarioid != null ? inventarioid.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Inventario)) {
return false;
}
Inventario other = (Inventario) object;
if ((this.inventarioid == null && other.inventarioid != null) || (this.inventarioid != null && !this.inventarioid.equals(other.inventarioid))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidades.Inventario[ inventarioid=" + inventarioid + " ]";
}
}
|
package net.imagej.visad;
import net.imagej.Dataset;
import net.imagej.ImageJ;
import net.imglib2.RealRandomAccessible;
import net.imglib2.img.Img;
import net.imglib2.img.ImgView;
import net.imglib2.interpolation.randomaccess.NearestNeighborInterpolatorFactory;
import net.imglib2.realtransform.InverseRealTransform;
import net.imglib2.realtransform.RealTransformRandomAccessible;
import net.imglib2.realtransform.RealViews;
import net.imglib2.transform.InverseTransform;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.view.IntervalView;
import net.imglib2.view.Views;
import visad.Gridded2DDoubleSet;
import visad.MathType;
import visad.RealTupleType;
import visad.RealType;
public final class Main {
public static void main(final String... args) throws Exception {
ImageJ ij = new ImageJ();
final Dataset data = ij.scifio().datasetIO().open("/Users/curtis/Desktop/mitosis.tif");
final Img<UnsignedByteType> img = (Img) data.getImgPlus().getImg();
System.out.println(img);
final IntervalView<UnsignedByteType> t0 = Views.hyperSlice(img, 4, 0);
final IntervalView<UnsignedByteType> t0z0 = Views.hyperSlice(t0, 3, 0);
final IntervalView<UnsignedByteType> t0z0c0 = Views.hyperSlice(t0z0, 2, 0);
NearestNeighborInterpolatorFactory<UnsignedByteType> interpolatorFac = new NearestNeighborInterpolatorFactory<>();
final RealRandomAccessible<UnsignedByteType> rra = Views.interpolate(t0z0c0, interpolatorFac);
long w = t0z0c0.dimension(0), h = t0z0c0.dimension(1);
RealType xType = RealType.getRealType("x");
RealType yType = RealType.getRealType("y");
MathType type = new RealTupleType(xType, yType);
int gw = 4, gh = 3;
double[][] grid = { // 12 grid points
{.05*w, .40*w, .60*w, .95*w, .10*w, .30*w, .70*w, .90*w, .03*w, .25*w, .65*w, .85*w },
{.10*h, .20*h, .15*h, .25*h, .50*h, .45*h, .40*h, .55*h, .90*h, .85*h, .80*w, .75*h }
};
final Gridded2DDoubleSet set = new Gridded2DDoubleSet(type, grid, gw, gh);
final GriddedSetTransform transform = new GriddedSetTransform(set);
final RealTransformRandomAccessible<UnsignedByteType, InverseRealTransform> transformed =
RealViews.transform(rra, transform);
// reapply same bounds as before (we set up the grid for this to work OK)
final IntervalView<UnsignedByteType> transformedInterval = Views.interval(transformed, t0z0c0);
Img imgView = ImgView.wrap(transformedInterval, null);
System.out.println(imgView);
ij.ui().show("original", t0z0c0);
ij.ui().show("transformed", imgView);
// ij.getContext().dispose();
}
}
|
package com.riddit.Riddit.repository;
import com.riddit.Riddit.model.Text;
import org.springframework.data.repository.CrudRepository;
public interface TextRepository extends CrudRepository<Text, Long> {
}
|
/*
* Created by IntelliJ IDEA Ultimate, 2020
* User: Abhishek
* Date: 17-02-2020
* Time: 10:19 PM
*/
package contactList;
import contactADT.ContactADT;
public class ContactList<Person> implements ContactADT<Person> {
private Node<Person> head = null;
public int size = 0;
private Node<Person> getNode(int index) {
Node<Person> response = head;
for (int i = 0; i < index && response != null; i++) {
response = response.getNext();
}
return response;
}
private boolean addFirst(Person data) {
head = new Node<>(data, null);
size++;
return true;
}
private boolean addAfter(Person data, Node<Person> node) {
node.next = new Node<>(data, node.next);
size++;
return true;
}
private boolean add(Person data, int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(Integer.toString(index));
} else if (index == 0) {
return addFirst(data);
} else {
Node<Person> temp = getNode(index - 1);
return addAfter(data, temp);
}
}
@Override
public boolean add(Person data) {
return add(data, size);
}
public Person view(int index) {
if (index > size || index < 0) {
throw new IndexOutOfBoundsException(Integer.toString(index));
} else if (index == 0) {
Person data = this.getNode(0).getData();
return data;
} else {
Person data = this.getNode(index).getData();
return data;
}
}
@Override
public void view() {
System.out.println("---Here are all your contacts---");
for (int i = 1; i <= size; i++) {
Person data = this.getNode(i - 1).getData();
System.out.println(data);
}
}
private Person deleteFirst() {
Person response = null;
Node<Person> temp = head;
if (head != null) {
head = head.getNext();
}
if (temp != null) {
size--;
response = temp.getData();
}
return response;
}
private Person deleteAfter(Node<Person> node) {
Person response = null;
Node<Person> temp = node.getNext();
if (temp != null) {
node.next = temp.getNext();
size--;
response = temp.getData();
}
return response;
}
public Person delete(int index) {
Person response = null;
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(Integer.toString(index));
} else if (index == 0) {
deleteFirst();
} else {
Node<Person> temp = getNode(index - 1);
response = deleteAfter(temp);
}
return response;
}
@Override
public Person delete() {
return delete(size - 1);
}
private class Node<Person> {
private Person data;
private Node<Person> next;
public Node(Person data, Node<Person> next) {
this.data = data;
this.next = next;
}
public Person getData() {
return data;
}
private Node<Person> getNext() {
return next;
}
}
}
|
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LoginPage {
public WebDriver driver;
public LoginPage(WebDriver driver)
{
this.driver = driver;
}
By emailField = By.xpath("//*[@id='user_email']");
By passwordField = By.xpath("//*[@id='user_password']");
By loginButton = By.xpath("//input[@value='Log In']");
public WebElement getEmailField()
{
return driver.findElement(emailField);
}
public WebElement getPasswordField()
{
return driver.findElement(passwordField);
}
public WebElement getLoginButton()
{
return driver.findElement(loginButton);
}
}
|
package org.springframework.roo.addon.layers.repository.jpa.addon;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.roo.addon.layers.repository.jpa.annotations.RooJpaRepository;
import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder;
import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.metadata.MetadataIdentificationUtils;
import org.springframework.roo.model.DataType;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.model.SpringJavaType;
import org.springframework.roo.project.LogicalPath;
/**
* Metadata for {@link RooJpaRepository}.
*
* @author Stefan Schmidt
* @author Andrew Swan
* @since 1.2.0
*/
public class RepositoryJpaMetadata extends AbstractItdTypeDetailsProvidingMetadataItem {
private static final String PROVIDES_TYPE_STRING = RepositoryJpaMetadata.class.getName();
private static final String PROVIDES_TYPE = MetadataIdentificationUtils
.create(PROVIDES_TYPE_STRING);
private static final String SPRING_JPA_REPOSITORY =
"org.springframework.data.jpa.repository.JpaRepository";
public static String createIdentifier(final JavaType javaType, final LogicalPath path) {
return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path);
}
public static JavaType getJavaType(final String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING,
metadataIdentificationString);
}
public static String getMetadataIdentiferType() {
return PROVIDES_TYPE;
}
public static LogicalPath getPath(final String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING,
metadataIdentificationString);
}
public static boolean isValid(final String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING,
metadataIdentificationString);
}
/**
* Constructor
*
* @param identifier the identifier for this item of metadata (required)
* @param aspectName the Java type of the ITD (required)
* @param governorPhysicalTypeMetadata the governor, which is expected to
* contain a {@link ClassOrInterfaceTypeDetails} (required)
* @param annotationValues (required)
* @param identifierType the type of the entity's identifier field
* (required)
*/
public RepositoryJpaMetadata(final String identifier, final JavaType aspectName,
final PhysicalTypeMetadata governorPhysicalTypeMetadata,
final RepositoryJpaAnnotationValues annotationValues, final JavaType identifierType,
final boolean readOnly, final JavaType readOnlyRepository,
final List<JavaType> customRepositories) {
super(identifier, aspectName, governorPhysicalTypeMetadata);
Validate.notNull(annotationValues, "Annotation values required");
Validate.notNull(identifierType, "Id type required");
if (readOnly) {
// If readOnly, extends ReadOnlyRepository
ensureGovernorExtends(new JavaType(readOnlyRepository.getFullyQualifiedTypeName(), 0,
DataType.TYPE, null, Arrays.asList(annotationValues.getEntity(), identifierType)));
} else {
// Extends JpaRepository
ensureGovernorExtends(new JavaType(SPRING_JPA_REPOSITORY, 0, DataType.TYPE, null,
Arrays.asList(annotationValues.getEntity(), identifierType)));
}
// If has some RepositoryCustom associated, add extends
if (!customRepositories.isEmpty()) {
// Extends RepositoryCustom
for (JavaType repositoryCustom : customRepositories) {
ensureGovernorExtends(repositoryCustom);
}
}
// Always add @Repository annotation
ensureGovernorIsAnnotated(new AnnotationMetadataBuilder(SpringJavaType.REPOSITORY));
// All repositories are generated with @Transactional(readOnly = true)
AnnotationMetadataBuilder transactionalAnnotation =
new AnnotationMetadataBuilder(SpringJavaType.TRANSACTIONAL);
transactionalAnnotation.addBooleanAttribute("readOnly", true);
ensureGovernorIsAnnotated(transactionalAnnotation);
// Build the ITD
itdTypeDetails = builder.build();
}
@Override
public String toString() {
final ToStringBuilder builder = new ToStringBuilder(this);
builder.append("identifier", getId());
builder.append("valid", valid);
builder.append("aspectName", aspectName);
builder.append("destinationType", destination);
builder.append("governor", governorPhysicalTypeMetadata.getId());
builder.append("itdTypeDetails", itdTypeDetails);
return builder.toString();
}
}
|
package algorithms.search.symboltable.client;
import algorithms.search.ST;
import algorithms.search.symboltable.SequentialSearchST;
/**
* Created by Chen Li on 2017/7/9.
*/
public class SequenceSTTraceClientTest extends TraceSTClientTest {
@Override
protected ST<String, Integer> createST() {
return new SequentialSearchST<>();
}
}
|
package com.diablo.HibernateUtility;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtility {
public static SessionFactory getSessionFactory(){
Configuration config = new Configuration();
config.configure("hibernate.cfg.xml");
return config.buildSessionFactory();
}
}
|
package com.bupc.bupc_quiz.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bupc.bupc_quiz.R;
public class HelpFragment extends Fragment {
private final String TAG = HelpFragment.class.getSimpleName();
private View mView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_help, container, false);
return mView;
}
}
|
package generic.pecs;
public class Spring extends Session{
}
|
package com.tvm.dao;
public class Response {
}
|
package com.systemspecs.payrollfileinterface.itemProcessor;
import com.systemspecs.payrollfileinterface.model.Promotioninterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
public class PromotionItemProcessor implements ItemProcessor<Promotioninterface, Promotioninterface> {
private static final Logger log = LoggerFactory.getLogger(PromotionItemProcessor.class);
@Override
public Promotioninterface process(final Promotioninterface promotionInterface) throws Exception {
return promotionInterface;
}
}
|
package de.hofuniversity.ejbbean.bean;
import java.util.List;
import javax.ejb.Remote;
import de.hofuniversity.ejbbean.data.TeamGroupSummaryData;
/**
*
* @author Markus Exner
*
*/
@Remote
public interface TableListRemote {
public final String MAPPED_NAME = "ejb/TableList";
public List<TeamGroupSummaryData> getTableList();
}
|
package ch07;
public class AnonymousExam {
public static void main(String[]args){
Object iv=new Object() {
public void mm() {
System.out.println("아무도 모르게");
}
};
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.