blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
6fde158c395715923adea2f691855ec57853256f
7,825,430,425,272
b83041942d92ead939b8f56318a13e3d82f20e48
/src/com/wenyu/kaijiw/wxapi/WXEntryActivity.java
b56a98ecaee1da2c0f0b3d709c73db630846a8b7
[ "Apache-2.0" ]
permissive
xingfeng2010/kai-ji-wang
https://github.com/xingfeng2010/kai-ji-wang
cda7f9f032d09204cfe6d0deb9148154029999f4
c4d5156551c0cb42fe313e7dd82b6ac57607d1d6
refs/heads/master
2021-01-10T01:19:38.470000
2015-10-17T19:12:21
2015-10-17T19:12:21
44,230,645
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wenyu.kaijiw.wxapi;import com.umeng.socialize.weixin.view.WXCallbackActivity; public class WXEntryActivity extends WXCallbackActivity {}
UTF-8
Java
148
java
WXEntryActivity.java
Java
[]
null
[]
package com.wenyu.kaijiw.wxapi;import com.umeng.socialize.weixin.view.WXCallbackActivity; public class WXEntryActivity extends WXCallbackActivity {}
148
0.864865
0.864865
2
73.5
15.5
89
false
false
0
0
0
0
0
0
1
false
false
13
41a8abef4dc2f821eac7e47f57d98fae76f61cbb
19,095,424,626,988
e598b4c42832b50d5ec8c14ca6ebf91e141a7f6d
/GameTutorial/KeyHandler.java
ba658acb1715c05f2950ff7330d7046283d7a9ff
[]
no_license
MayeDay/First-Attempt-at-GameMaking
https://github.com/MayeDay/First-Attempt-at-GameMaking
2c5ed59cff1cac307e45dd90fcb0faa7e886fb02
7b846a3203a33a9d081f057927964b5376da3ec9
refs/heads/master
2020-04-27T11:20:49.587000
2019-03-07T07:57:16
2019-03-07T07:57:16
174,291,990
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class KeyHandler extends KeyAdapter{ private static final int Num_keys= 256; private static final boolean[] keys = new boolean[Num_keys]; private static final boolean[] lastKeys = new boolean[Num_keys]; public void keyPressed(KeyEvent e){ super.keyPressed(e); keys[e.getKeyCode()] = true; } public void keyReleased(KeyEvent e){ keys[e.getKeyCode()] = false; } public static void update(){ for(int i = 0; i< Num_keys;i++){ lastKeys[i] = keys[i]; } } public static boolean wasKeyPressed(int keyCode){ return isKeyDown(keyCode) && !lastKeys[keyCode]; } public static boolean isKeyDown(int keyCode){ return keys[keyCode]; } }
UTF-8
Java
734
java
KeyHandler.java
Java
[]
null
[]
import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class KeyHandler extends KeyAdapter{ private static final int Num_keys= 256; private static final boolean[] keys = new boolean[Num_keys]; private static final boolean[] lastKeys = new boolean[Num_keys]; public void keyPressed(KeyEvent e){ super.keyPressed(e); keys[e.getKeyCode()] = true; } public void keyReleased(KeyEvent e){ keys[e.getKeyCode()] = false; } public static void update(){ for(int i = 0; i< Num_keys;i++){ lastKeys[i] = keys[i]; } } public static boolean wasKeyPressed(int keyCode){ return isKeyDown(keyCode) && !lastKeys[keyCode]; } public static boolean isKeyDown(int keyCode){ return keys[keyCode]; } }
734
0.708447
0.702997
31
22.709677
20.621307
66
false
false
0
0
0
0
0
0
1.483871
false
false
13
91979013c033342ddd98e41b3ae40ec117a69e23
25,443,386,304,876
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/30/30_ab1bde12f342aa37a6c35c5ecf0d4884018bdd28/MaxwellianDistribution/30_ab1bde12f342aa37a6c35c5ecf0d4884018bdd28_MaxwellianDistribution_s.java
6f9b864be394fc35beb940a1812856375d588744
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package org.openpixi.pixi.physics; import java.util.List; import java.util.ArrayList; import java.util.Random; public class MaxwellianDistribution implements ParticleLoader { private Random rand; //Boltzmann constant private double k; /*Velocity normalization in x direction, temperature dependent */ private double vNormX; /*Velocity normalization in x direction, temperature dependent */ private double vNormY; private double rnd1; private double rnd2; private double rnd3; /** Generates a thermal VELOCITY distribution * TODO make this loader relativistic * TODO THINK ABOUT USEFUL UNITS FOR K AND T! cgs? * @param temperature */ public MaxwellianDistribution (long seed, double boltzmannk, double temperature) { rand = new Random(seed); k = boltzmannk; setNorms(temperature, temperature); } /** Generates a thermal VELOCITY distribution * TODO make this loader relativistic */ public MaxwellianDistribution (long seed, double boltzmannk, double temperatureX, double temperatureY) { rand = new Random(seed); k = boltzmannk; setNorms(temperatureX, temperatureY); } private void setNorms (double temperatureX, double temperatureY) { //0.5 is the mass of the electron that is used later //Factor of 2 comes from the denominator in the exponent of //the Maxwellian distribution. //NOTE: There are no further factors because we are inverting //the cumulative distribution hence the factors cancel vNormX = Math.sqrt(2 * k * temperatureX / 0.5); vNormY = Math.sqrt(2 * k * temperatureY / 0.5); } @Override public List<Particle> load (int numOfParticles, int numCellsX, int numCellsY, double simulationWidth, double simulationHeight, double radius) { int numOfElectrons= (numOfParticles / 2); int numOfIons = numOfParticles - (numOfParticles / 2); //WARNING: THIS CODE WILL VIOLATE THE ASSERT CONDITION IN MOST CASES int nX = (int) Math.sqrt((simulationWidth / simulationHeight) * numOfIons); int nY = (int) numOfParticles / nX; //2 added in the numerator because we do not want to place //the ions on the boundaries double deltaX = simulationWidth / (nX+2); double deltaY = simulationHeight / (nY+2); if (Debug.asserts) { assert nX*nY == numOfIons: nX*nY; } List<Particle> particles = new ArrayList<Particle>(); //Generates thermal electrons that are randomly distributed //across the simulation area for (int i = 0; i < numOfElectrons; i++) { Particle p = new Particle(); p.setX( simulationWidth * rand.nextDouble()); p.setY( simulationHeight * rand.nextDouble()); do { rnd1 = rand.nextDouble(); rnd2 = rand.nextDouble(); rnd3 = (rnd1*rnd1 + rnd2*rnd2); } while (rnd3 > 1); rnd3 = Math.sqrt( - Math.log(rnd3) / rnd3 ); p.setVx( vNormX * rnd1 * rnd3 ); p.setVy( vNormY * rnd2 * rnd3 ); p.setCharge(-1); p.setMass(0.5); p.setRadius(radius); particles.add(p); } //Generates a spatially uniform, cold and heavy ion background for (int i = 0; i < numOfIons; i++) { Particle p = new Particle(); p.setX( (i+1) * deltaX ); p.setY( (i+1) * deltaY ); p.setVx(0); p.setVy(0); p.setCharge(-1); p.setMass(2000); p.setRadius(radius); particles.add(p); } return particles; } }
UTF-8
Java
3,450
java
30_ab1bde12f342aa37a6c35c5ecf0d4884018bdd28_MaxwellianDistribution_s.java
Java
[]
null
[]
package org.openpixi.pixi.physics; import java.util.List; import java.util.ArrayList; import java.util.Random; public class MaxwellianDistribution implements ParticleLoader { private Random rand; //Boltzmann constant private double k; /*Velocity normalization in x direction, temperature dependent */ private double vNormX; /*Velocity normalization in x direction, temperature dependent */ private double vNormY; private double rnd1; private double rnd2; private double rnd3; /** Generates a thermal VELOCITY distribution * TODO make this loader relativistic * TODO THINK ABOUT USEFUL UNITS FOR K AND T! cgs? * @param temperature */ public MaxwellianDistribution (long seed, double boltzmannk, double temperature) { rand = new Random(seed); k = boltzmannk; setNorms(temperature, temperature); } /** Generates a thermal VELOCITY distribution * TODO make this loader relativistic */ public MaxwellianDistribution (long seed, double boltzmannk, double temperatureX, double temperatureY) { rand = new Random(seed); k = boltzmannk; setNorms(temperatureX, temperatureY); } private void setNorms (double temperatureX, double temperatureY) { //0.5 is the mass of the electron that is used later //Factor of 2 comes from the denominator in the exponent of //the Maxwellian distribution. //NOTE: There are no further factors because we are inverting //the cumulative distribution hence the factors cancel vNormX = Math.sqrt(2 * k * temperatureX / 0.5); vNormY = Math.sqrt(2 * k * temperatureY / 0.5); } @Override public List<Particle> load (int numOfParticles, int numCellsX, int numCellsY, double simulationWidth, double simulationHeight, double radius) { int numOfElectrons= (numOfParticles / 2); int numOfIons = numOfParticles - (numOfParticles / 2); //WARNING: THIS CODE WILL VIOLATE THE ASSERT CONDITION IN MOST CASES int nX = (int) Math.sqrt((simulationWidth / simulationHeight) * numOfIons); int nY = (int) numOfParticles / nX; //2 added in the numerator because we do not want to place //the ions on the boundaries double deltaX = simulationWidth / (nX+2); double deltaY = simulationHeight / (nY+2); if (Debug.asserts) { assert nX*nY == numOfIons: nX*nY; } List<Particle> particles = new ArrayList<Particle>(); //Generates thermal electrons that are randomly distributed //across the simulation area for (int i = 0; i < numOfElectrons; i++) { Particle p = new Particle(); p.setX( simulationWidth * rand.nextDouble()); p.setY( simulationHeight * rand.nextDouble()); do { rnd1 = rand.nextDouble(); rnd2 = rand.nextDouble(); rnd3 = (rnd1*rnd1 + rnd2*rnd2); } while (rnd3 > 1); rnd3 = Math.sqrt( - Math.log(rnd3) / rnd3 ); p.setVx( vNormX * rnd1 * rnd3 ); p.setVy( vNormY * rnd2 * rnd3 ); p.setCharge(-1); p.setMass(0.5); p.setRadius(radius); particles.add(p); } //Generates a spatially uniform, cold and heavy ion background for (int i = 0; i < numOfIons; i++) { Particle p = new Particle(); p.setX( (i+1) * deltaX ); p.setY( (i+1) * deltaY ); p.setVx(0); p.setVy(0); p.setCharge(-1); p.setMass(2000); p.setRadius(radius); particles.add(p); } return particles; } }
3,450
0.661159
0.647536
125
26.591999
22.392891
84
false
false
0
0
0
0
0
0
2.496
false
false
13
f255de31cfa29261ed6d84ce30bbc63306e85bf4
6,665,789,248,182
81ae03175fa4708a57fac059bdcc3669232a9021
/RedXXIEJB/ejbModule/net/ciespal/redxxi/ejb/persistence/entities/EspecialidadDTO.java
61e493d598b3b2dd116efa78b8064bc7b486dd7c
[]
no_license
Idonius/rsp
https://github.com/Idonius/rsp
0889965b83b0adaff0a9a0406ab60db9672500ee
bb7dbbcad047fd2cf1c2e4a07e3c1135f555534a
refs/heads/master
2020-04-25T12:21:30.005000
2015-08-22T00:43:11
2015-08-22T00:43:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.ciespal.redxxi.ejb.persistence.entities; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the ate_especialidad database table. * */ @Entity @Table(name="ate_especialidad") @NamedQuery(name="EspecialidadDTO.findAll", query="SELECT e FROM EspecialidadDTO e") public class EspecialidadDTO implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name="ATE_ESPECIALIDAD_ESPCODIGO_GENERATOR", sequenceName="ATE_ESPECIALIDAD_ESP_CODIGO_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ATE_ESPECIALIDAD_ESPCODIGO_GENERATOR") @Column(name="esp_codigo") private Integer espCodigo; @Column(name="esp_nombre") private String espNombre; //bi-directional many-to-one association to DoctorDTO @ManyToOne @JoinColumn(name="esp_doctor") private DoctorDTO ateDoctor; public EspecialidadDTO() { } public Integer getEspCodigo() { return this.espCodigo; } public void setEspCodigo(Integer espCodigo) { this.espCodigo = espCodigo; } public String getEspNombre() { return this.espNombre; } public void setEspNombre(String espNombre) { this.espNombre = espNombre; } public DoctorDTO getAteDoctor() { return this.ateDoctor; } public void setAteDoctor(DoctorDTO ateDoctor) { this.ateDoctor = ateDoctor; } }
UTF-8
Java
1,421
java
EspecialidadDTO.java
Java
[]
null
[]
package net.ciespal.redxxi.ejb.persistence.entities; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the ate_especialidad database table. * */ @Entity @Table(name="ate_especialidad") @NamedQuery(name="EspecialidadDTO.findAll", query="SELECT e FROM EspecialidadDTO e") public class EspecialidadDTO implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name="ATE_ESPECIALIDAD_ESPCODIGO_GENERATOR", sequenceName="ATE_ESPECIALIDAD_ESP_CODIGO_SEQ",allocationSize=1) @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ATE_ESPECIALIDAD_ESPCODIGO_GENERATOR") @Column(name="esp_codigo") private Integer espCodigo; @Column(name="esp_nombre") private String espNombre; //bi-directional many-to-one association to DoctorDTO @ManyToOne @JoinColumn(name="esp_doctor") private DoctorDTO ateDoctor; public EspecialidadDTO() { } public Integer getEspCodigo() { return this.espCodigo; } public void setEspCodigo(Integer espCodigo) { this.espCodigo = espCodigo; } public String getEspNombre() { return this.espNombre; } public void setEspNombre(String espNombre) { this.espNombre = espNombre; } public DoctorDTO getAteDoctor() { return this.ateDoctor; } public void setAteDoctor(DoctorDTO ateDoctor) { this.ateDoctor = ateDoctor; } }
1,421
0.734694
0.733286
58
22.534483
26.660196
129
false
false
0
0
0
0
0
0
0.948276
false
false
13
dd8a4dcf74e3e0e768e0761c63f89ec925fcee2d
9,861,244,955,910
ea47f10c9de6b96db485e4eebcb1393be6edee90
/hoscloudHadoopService/src/main/java/com/hoscloud/hadoop/service/tools/db/MysqlDBUtils.java
f101d9bf830027a10f9207bd033f1aa6d556de8e
[]
no_license
Moice/hoscloud
https://github.com/Moice/hoscloud
d6832da71dd8be3760fe489686a9e7332373db8d
368821f91421ade55e56be8f98dd7c4621b4c13f
refs/heads/master
2017-10-07T14:31:44.071000
2017-02-08T06:29:04
2017-02-08T06:29:04
81,211,544
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hoscloud.hadoop.service.tools.db; import com.hoscloud.hadoop.service.service.Utils; import com.hoscloud.hadoop.service.tools.ssh.common.PropertyBox; import com.hoscloud.hadoop.service.tools.ssh.common.PropertyDictory; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.MapListHandler; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by CC on 2016/7/25. */ public class MysqlDBUtils { // private static Map<String,MysqlDataSource> dataSources = new HashMap<String, MysqlDataSource>(); /** * 载入数据库中的配置参数 * @return */ public static Map<String ,String> initDBProperty(){ Map<String,String> result = new HashMap<String,String>(); String sql = PropertyBox.getVal(PropertyDictory.PROPERTY_INIT_MYSQL_PARAMETER_SQL, "select parameterkey as pkey,parameterval as pval from cluster_parameter"); //默认从websql 中取 List<Map<String , Object>> list = query(sql,getWebAppMysqlConnector(true)); if(null == list){ return result; } for(Map<String,Object> row : list){ Object key = row.get("pkey"); Object val = row.get("pval"); if (key==null) continue; if(val==null) result.put(key.toString(),""); else result.put(key.toString(),val.toString()); } return result; } /** * 这个方法会批量执行file文件中的sql语句 * 这里会剔除file中的select 语句,因为 返回结果不好返回 * @return */ public static int[] exeSQLFileInWebDB(String sqlFilePath){ QueryRunner runner = new QueryRunner(); int[] result=null; Connection connection=getWebAppMysqlConnector(false); try { //解析文件 List<String> sqls= Utils.loadSql(sqlFilePath); //这里是原始文件 result= new int[sqls.size()]; int count=0; for(String sql : sqls){ if (!sql.trim().toLowerCase().startsWith("select")) { result[count]=runner.update(connection,sql); }else{ result[count]=1; } } connection.commit(); } catch (SQLException e) { e.printStackTrace(); try { connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } catch (Exception e) { try { connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } return result; } /** * 查询 web 数据库 * @param sql * @return */ public static List<Map<String,Object>> queryWebDB(String sql ){ return queryWebDB(sql,true); } public static List<Map<String,Object>> queryWebDB(String sql ,boolean auto){ return query(sql,getWebAppMysqlConnector(auto)); } /** * 更新 web 数据库 * @param sql * @return */ public static int updateWebDB(String sql ){ return updateWebDB(sql,true); } public static int updateWebDB(String sql ,boolean auto){ return update(sql,getWebAppMysqlConnector(auto)); } /** * 查询hive数据库 * @param sql * @return */ public static List<Map<String,Object>> queryHiveDB(String sql){ return queryHiveDB(sql,true); } public static List<Map<String,Object>> queryHiveDB(String sql,boolean auto){ return query(sql, getHiveMysqlConnector(auto)); } /** * 更新 hive 数据库 * @param sql * @return */ public static int updateHiveDB(String sql){ return updateHiveDB(sql,true); } public static int updateHiveDB(String sql,boolean autocommit){ return update(sql,getHiveMysqlConnector(autocommit)); } /** * 批量在web执行语句 * @param sql * @param objects * @return */ public static int[] batchWebDB(String sql,Object[][] objects){ return batchWebDB(sql,objects,true); } public static int[] batchWebDB(String sql,Object[][] objects,boolean autocmmit){ return batch(sql,objects,getWebAppMysqlConnector(autocmmit)); } /** * 批量在hive执行语句 * @param sql * @param objects * @return */ public static int[] batchHiveDB(String sql,Object[][] objects){ return batchHiveDB(sql,objects,true); } public static int[] batchHiveDB(String sql,Object[][] objects,boolean autoCommit){ return batch(sql,objects,getHiveMysqlConnector(autoCommit)); } // private static boolean isSelect(String sql){ // return sql.trim().toLowerCase().startsWith("select"); // } // /** // * // * @param sql // * @param ds // * @return // */ // private static Object query_update(String sql,boolean isSelect,MysqlDataSource ds){ // //这里的判断比较简单,不知道是否考虑全面 //// sql = sql.trim(); //// sql.toLowerCase(); // if(isSelect) // return query(sql,ds); // else // return update(sql,ds); // } /** * 查询 * @param sql * @param ds mysql 元数据 * @return */ private static List<Map<String,Object>> query(String sql,MysqlDataSource ds){ QueryRunner runner = new QueryRunner(ds); List<Map<String , Object>> list = null; try { list= runner.query(sql,new MapListHandler()); } catch (SQLException e) { e.printStackTrace(); } return list; } public static void closeDBConnector(Connection connection){ if(connection!=null) try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * 使用connection 来查询 * @param sql * @param connection * @return */ private static List<Map<String,Object>> query(String sql,Connection connection){ QueryRunner runner = new QueryRunner(); List<Map<String , Object>> list = null; try { list= runner.query(connection,sql,new MapListHandler()); if(list!=null) System.out.println("MysqlDB query sql["+sql+"]: result["+list.size()+"]"); } catch (SQLException e) { e.printStackTrace(); }finally { closeDBConnector(connection); } return list; } /** * 执行非select 语句 * @param sql * @param ds * @return */ private static int update(String sql,MysqlDataSource ds){ QueryRunner runner = new QueryRunner(ds); try { return runner.update(sql); } catch (SQLException e) { e.printStackTrace(); } return -1; } private static int update(String sql,Connection connection){ QueryRunner runner = new QueryRunner(); try { return runner.update(connection,sql); } catch (SQLException e) { e.printStackTrace(); } finally { closeDBConnector(connection); } return -1; } private static int[] batch(String sql,Object[][] params,MysqlDataSource ds){ QueryRunner runner = new QueryRunner(ds); try { return runner.batch(sql,params); } catch (SQLException e) { e.printStackTrace(); } return null; } private static int[] batch(String sql,Object[][] params,Connection connection){ QueryRunner runner = new QueryRunner(); try { return runner.batch(connection,sql,params); } catch (SQLException e) { e.printStackTrace(); } finally { closeDBConnector(connection); } return null; } // /** // * 获取web 数据库信息 // * @return // */ // private static MysqlDataSource getWebAppMysqlDataSource(boolean autoCommit){ // DBproperty dBproperty=new DBproperty( PropertyBox.getVal(PropertyDictory.WEB_APP_DB_IP,"") // ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_USER,"") // ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_PW,"") // ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_DB,"") // ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_PORT,"3306")); // // return getDBSource(dBproperty,autoCommit); // } private static Connection getWebAppMysqlConnector(boolean autoCommit){ DBproperty dBproperty=new DBproperty( PropertyBox.getVal(PropertyDictory.WEB_APP_DB_IP,"") ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_USER,"") ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_PW,"") ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_DB,"") ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_PORT,"3306")); return getDBConnector(dBproperty,autoCommit); } // /** // * 获取HIVE 数据库信息 // * @return // */ // private static MysqlDataSource getHiveMysqlDataSource(boolean autoCommit){ // DBproperty dBproperty=new DBproperty( PropertyBox.getVal(PropertyDictory.HIVE_META_IP,"") // ,PropertyBox.getVal(PropertyDictory.HIVE_META_USER,"") // ,PropertyBox.getVal(PropertyDictory.HIVE_META_PW,"") // ,PropertyBox.getVal(PropertyDictory.HIVE_META_DB,"") // ,PropertyBox.getVal(PropertyDictory.HIVE_META_PORT,"3306")); // // return getDBSource(dBproperty,autoCommit); // } private static Connection getHiveMysqlConnector(boolean autoCommit){ DBproperty dBproperty=new DBproperty( PropertyBox.getVal(PropertyDictory.HIVE_META_IP,"") ,PropertyBox.getVal(PropertyDictory.HIVE_META_USER,"") ,PropertyBox.getVal(PropertyDictory.HIVE_META_PW,"") ,PropertyBox.getVal(PropertyDictory.HIVE_META_DB,"") ,PropertyBox.getVal(PropertyDictory.HIVE_META_PORT,"3306")); return getDBConnector(dBproperty, autoCommit); } // private static MysqlDataSource getDBSource(DBproperty dBproperty,boolean autoCommit){ // String key = dBproperty.getPropertyKey(); // MysqlDataSource ds=dataSources.get(key); // // if (ds == null) { // ds = new MysqlDataSource(); // ds.setServerName(dBproperty.getIp()); // ds.setUser(dBproperty.getUsername()); // ds.setPassword(dBproperty.getPassword()); // ds.setDatabaseName(dBproperty.getDbname()); // ds.setPort(Integer.parseInt(dBproperty.getProt())); // dataSources.put(key+"_"+autoCommit,ds); // } // return ds; // } private static Connection getDBConnector(DBproperty dBproperty,boolean autoCommit){ String url="jdbc:mysql://"+dBproperty.getIp()+":"+dBproperty.getProt()+"/"+dBproperty.getDbname(); Connection connection = null; try { connection = DriverManager.getConnection(url, dBproperty.getUsername(), dBproperty.getPassword()); connection.setAutoCommit(autoCommit); } catch (SQLException e) { e.printStackTrace(); } return connection; } public static class DBproperty{ String ip,username,password,dbname,prot; public DBproperty(String ip,String username,String password,String dbname,String prot){ this.ip=ip; this.username=username; this.password=password; this.dbname=dbname; this.prot =prot; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDbname() { return dbname; } public void setDbname(String dbname) { this.dbname = dbname; } public String getProt() { return prot; } public void setProt(String prot) { this.prot = prot; } public String getPropertyKey(){ return ip+":"+username+":"+password+":"+dbname+":"+prot; } } }
GB18030
Java
13,008
java
MysqlDBUtils.java
Java
[ { "context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by CC on 2016/7/25.\n */\npublic class MysqlDBUtils {\n// ", "end": 573, "score": 0.9870204925537109, "start": 571, "tag": "USERNAME", "value": "CC" }, { "context": "erty.getUsername());\n// ds.setPassword(dBproperty.getPassword());\n// ds.setDatabaseName(dBproperty.g", "end": 10676, "score": 0.8106799721717834, "start": 10654, "tag": "PASSWORD", "value": "dBproperty.getPassword" }, { "context": " this.ip=ip;\n this.username=username;\n this.password=password;\n ", "end": 11662, "score": 0.9984297156333923, "start": 11654, "tag": "USERNAME", "value": "username" }, { "context": "this.username=username;\n this.password=password;\n this.dbname=dbname;\n this", "end": 11698, "score": 0.9995788335800171, "start": 11690, "tag": "PASSWORD", "value": "password" }, { "context": " public String getUsername() {\n return username;\n }\n\n public void setUsername(Strin", "end": 11980, "score": 0.9591100811958313, "start": 11972, "tag": "USERNAME", "value": "username" }, { "context": "ame(String username) {\n this.username = username;\n }\n\n public String getPassword() {", "end": 12080, "score": 0.9879077672958374, "start": 12072, "tag": "USERNAME", "value": "username" }, { "context": " public String getPassword() {\n return password;\n }\n\n public void setPassword(Strin", "end": 12158, "score": 0.832827091217041, "start": 12150, "tag": "PASSWORD", "value": "password" }, { "context": "ord(String password) {\n this.password = password;\n }\n\n public String getDbname() {\n ", "end": 12258, "score": 0.973808228969574, "start": 12250, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.hoscloud.hadoop.service.tools.db; import com.hoscloud.hadoop.service.service.Utils; import com.hoscloud.hadoop.service.tools.ssh.common.PropertyBox; import com.hoscloud.hadoop.service.tools.ssh.common.PropertyDictory; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.MapListHandler; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by CC on 2016/7/25. */ public class MysqlDBUtils { // private static Map<String,MysqlDataSource> dataSources = new HashMap<String, MysqlDataSource>(); /** * 载入数据库中的配置参数 * @return */ public static Map<String ,String> initDBProperty(){ Map<String,String> result = new HashMap<String,String>(); String sql = PropertyBox.getVal(PropertyDictory.PROPERTY_INIT_MYSQL_PARAMETER_SQL, "select parameterkey as pkey,parameterval as pval from cluster_parameter"); //默认从websql 中取 List<Map<String , Object>> list = query(sql,getWebAppMysqlConnector(true)); if(null == list){ return result; } for(Map<String,Object> row : list){ Object key = row.get("pkey"); Object val = row.get("pval"); if (key==null) continue; if(val==null) result.put(key.toString(),""); else result.put(key.toString(),val.toString()); } return result; } /** * 这个方法会批量执行file文件中的sql语句 * 这里会剔除file中的select 语句,因为 返回结果不好返回 * @return */ public static int[] exeSQLFileInWebDB(String sqlFilePath){ QueryRunner runner = new QueryRunner(); int[] result=null; Connection connection=getWebAppMysqlConnector(false); try { //解析文件 List<String> sqls= Utils.loadSql(sqlFilePath); //这里是原始文件 result= new int[sqls.size()]; int count=0; for(String sql : sqls){ if (!sql.trim().toLowerCase().startsWith("select")) { result[count]=runner.update(connection,sql); }else{ result[count]=1; } } connection.commit(); } catch (SQLException e) { e.printStackTrace(); try { connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } catch (Exception e) { try { connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } return result; } /** * 查询 web 数据库 * @param sql * @return */ public static List<Map<String,Object>> queryWebDB(String sql ){ return queryWebDB(sql,true); } public static List<Map<String,Object>> queryWebDB(String sql ,boolean auto){ return query(sql,getWebAppMysqlConnector(auto)); } /** * 更新 web 数据库 * @param sql * @return */ public static int updateWebDB(String sql ){ return updateWebDB(sql,true); } public static int updateWebDB(String sql ,boolean auto){ return update(sql,getWebAppMysqlConnector(auto)); } /** * 查询hive数据库 * @param sql * @return */ public static List<Map<String,Object>> queryHiveDB(String sql){ return queryHiveDB(sql,true); } public static List<Map<String,Object>> queryHiveDB(String sql,boolean auto){ return query(sql, getHiveMysqlConnector(auto)); } /** * 更新 hive 数据库 * @param sql * @return */ public static int updateHiveDB(String sql){ return updateHiveDB(sql,true); } public static int updateHiveDB(String sql,boolean autocommit){ return update(sql,getHiveMysqlConnector(autocommit)); } /** * 批量在web执行语句 * @param sql * @param objects * @return */ public static int[] batchWebDB(String sql,Object[][] objects){ return batchWebDB(sql,objects,true); } public static int[] batchWebDB(String sql,Object[][] objects,boolean autocmmit){ return batch(sql,objects,getWebAppMysqlConnector(autocmmit)); } /** * 批量在hive执行语句 * @param sql * @param objects * @return */ public static int[] batchHiveDB(String sql,Object[][] objects){ return batchHiveDB(sql,objects,true); } public static int[] batchHiveDB(String sql,Object[][] objects,boolean autoCommit){ return batch(sql,objects,getHiveMysqlConnector(autoCommit)); } // private static boolean isSelect(String sql){ // return sql.trim().toLowerCase().startsWith("select"); // } // /** // * // * @param sql // * @param ds // * @return // */ // private static Object query_update(String sql,boolean isSelect,MysqlDataSource ds){ // //这里的判断比较简单,不知道是否考虑全面 //// sql = sql.trim(); //// sql.toLowerCase(); // if(isSelect) // return query(sql,ds); // else // return update(sql,ds); // } /** * 查询 * @param sql * @param ds mysql 元数据 * @return */ private static List<Map<String,Object>> query(String sql,MysqlDataSource ds){ QueryRunner runner = new QueryRunner(ds); List<Map<String , Object>> list = null; try { list= runner.query(sql,new MapListHandler()); } catch (SQLException e) { e.printStackTrace(); } return list; } public static void closeDBConnector(Connection connection){ if(connection!=null) try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * 使用connection 来查询 * @param sql * @param connection * @return */ private static List<Map<String,Object>> query(String sql,Connection connection){ QueryRunner runner = new QueryRunner(); List<Map<String , Object>> list = null; try { list= runner.query(connection,sql,new MapListHandler()); if(list!=null) System.out.println("MysqlDB query sql["+sql+"]: result["+list.size()+"]"); } catch (SQLException e) { e.printStackTrace(); }finally { closeDBConnector(connection); } return list; } /** * 执行非select 语句 * @param sql * @param ds * @return */ private static int update(String sql,MysqlDataSource ds){ QueryRunner runner = new QueryRunner(ds); try { return runner.update(sql); } catch (SQLException e) { e.printStackTrace(); } return -1; } private static int update(String sql,Connection connection){ QueryRunner runner = new QueryRunner(); try { return runner.update(connection,sql); } catch (SQLException e) { e.printStackTrace(); } finally { closeDBConnector(connection); } return -1; } private static int[] batch(String sql,Object[][] params,MysqlDataSource ds){ QueryRunner runner = new QueryRunner(ds); try { return runner.batch(sql,params); } catch (SQLException e) { e.printStackTrace(); } return null; } private static int[] batch(String sql,Object[][] params,Connection connection){ QueryRunner runner = new QueryRunner(); try { return runner.batch(connection,sql,params); } catch (SQLException e) { e.printStackTrace(); } finally { closeDBConnector(connection); } return null; } // /** // * 获取web 数据库信息 // * @return // */ // private static MysqlDataSource getWebAppMysqlDataSource(boolean autoCommit){ // DBproperty dBproperty=new DBproperty( PropertyBox.getVal(PropertyDictory.WEB_APP_DB_IP,"") // ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_USER,"") // ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_PW,"") // ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_DB,"") // ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_PORT,"3306")); // // return getDBSource(dBproperty,autoCommit); // } private static Connection getWebAppMysqlConnector(boolean autoCommit){ DBproperty dBproperty=new DBproperty( PropertyBox.getVal(PropertyDictory.WEB_APP_DB_IP,"") ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_USER,"") ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_PW,"") ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_DB,"") ,PropertyBox.getVal(PropertyDictory.WEB_APP_DB_PORT,"3306")); return getDBConnector(dBproperty,autoCommit); } // /** // * 获取HIVE 数据库信息 // * @return // */ // private static MysqlDataSource getHiveMysqlDataSource(boolean autoCommit){ // DBproperty dBproperty=new DBproperty( PropertyBox.getVal(PropertyDictory.HIVE_META_IP,"") // ,PropertyBox.getVal(PropertyDictory.HIVE_META_USER,"") // ,PropertyBox.getVal(PropertyDictory.HIVE_META_PW,"") // ,PropertyBox.getVal(PropertyDictory.HIVE_META_DB,"") // ,PropertyBox.getVal(PropertyDictory.HIVE_META_PORT,"3306")); // // return getDBSource(dBproperty,autoCommit); // } private static Connection getHiveMysqlConnector(boolean autoCommit){ DBproperty dBproperty=new DBproperty( PropertyBox.getVal(PropertyDictory.HIVE_META_IP,"") ,PropertyBox.getVal(PropertyDictory.HIVE_META_USER,"") ,PropertyBox.getVal(PropertyDictory.HIVE_META_PW,"") ,PropertyBox.getVal(PropertyDictory.HIVE_META_DB,"") ,PropertyBox.getVal(PropertyDictory.HIVE_META_PORT,"3306")); return getDBConnector(dBproperty, autoCommit); } // private static MysqlDataSource getDBSource(DBproperty dBproperty,boolean autoCommit){ // String key = dBproperty.getPropertyKey(); // MysqlDataSource ds=dataSources.get(key); // // if (ds == null) { // ds = new MysqlDataSource(); // ds.setServerName(dBproperty.getIp()); // ds.setUser(dBproperty.getUsername()); // ds.setPassword(<PASSWORD>()); // ds.setDatabaseName(dBproperty.getDbname()); // ds.setPort(Integer.parseInt(dBproperty.getProt())); // dataSources.put(key+"_"+autoCommit,ds); // } // return ds; // } private static Connection getDBConnector(DBproperty dBproperty,boolean autoCommit){ String url="jdbc:mysql://"+dBproperty.getIp()+":"+dBproperty.getProt()+"/"+dBproperty.getDbname(); Connection connection = null; try { connection = DriverManager.getConnection(url, dBproperty.getUsername(), dBproperty.getPassword()); connection.setAutoCommit(autoCommit); } catch (SQLException e) { e.printStackTrace(); } return connection; } public static class DBproperty{ String ip,username,password,dbname,prot; public DBproperty(String ip,String username,String password,String dbname,String prot){ this.ip=ip; this.username=username; this.password=<PASSWORD>; this.dbname=dbname; this.prot =prot; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return <PASSWORD>; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getDbname() { return dbname; } public void setDbname(String dbname) { this.dbname = dbname; } public String getProt() { return prot; } public void setProt(String prot) { this.prot = prot; } public String getPropertyKey(){ return ip+":"+username+":"+password+":"+dbname+":"+prot; } } }
13,002
0.579874
0.577358
423
29.070923
26.036066
110
false
false
0
0
0
0
0
0
0.586288
false
false
13
1309082fe66376b1d860a74a0c71bd2f650375e7
21,577,915,695,478
cb83189cc609ecb47befc7aa01c05b30ce8bca58
/src/Libraries/InitiatorTest.java
5e6369196961ef9f7e691fc5a7f31e1bf99dc417
[]
no_license
Suryakumarn/rakfw
https://github.com/Suryakumarn/rakfw
950b5f390f7e0c2a2c0cf3e902e9458256f509f8
d677775648e73be9c3b2e5f4a7983fd5b97fdc7b
refs/heads/master
2021-01-16T21:35:41.991000
2017-08-14T10:41:18
2017-08-14T10:41:18
100,240,230
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Libraries; //imports------------------------------------------------------------------------------------------------- import java.util.ArrayList; import org.apache.commons.io.FileUtils; import com.codoid.products.fillo.Connection; import com.codoid.products.fillo.Fillo; import com.codoid.products.fillo.Recordset; import java.io.*; import java.text.DateFormat; import java.text.SimpleDateFormat; //--------------------------------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------------------------------- * Class Name : Initiator * Use : Has functions related to TestNG * Designed By : AG * Last Modified Date : 25-Apr-2016 --------------------------------------------------------------------------------------------------------*/ public class InitiatorTest { private static String workingDir = System.getProperty("user.dir"); private static String basepth = workingDir.replace("/","\\"); public static String xmlpth = basepth+"\\src\\Libraries\\Driver.xml"; private static String DriverDBpthI = basepth+"/DataBase/DriverDB/DriverDB.xlsx"; /*--------------------------------------------------------------------------------------------------------- * Method Name : Main Function * Use : The Test Pack Execution starts from the main function * Designed By : AG * Last Modified Date : 25-Apr-2016 --------------------------------------------------------------------------------------------------------*/ public static void main(String argv[]) { try { //set parallel execution yes to run the batches in parallel, set no to run batches in sequence. String ParallelExecution = "yes"; Driver.workingDir.set(System.getProperty("user.dir")); Driver.basepth.set(Driver.workingDir.get().replace("\\","/")); Driver.Resultpath.set(Driver.basepth.get()+"/Results"); Driver.templatfold.set(Driver.basepth.get()+"/Templates"); DateFormat ExecutionStarttime; ExecutionStarttime = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); Driver.ExecutionStarttimestr.set(ExecutionStarttime.format(Driver.cal.getTime())); String[] totbatches = floadbatches(); createdynamicfiles(totbatches); if(ParallelExecution.equals("yes")) { if (totbatches != null) { ArrayList<RunnableDemo> bthArr = new ArrayList<RunnableDemo>(); for(int currbatch = 0 ; currbatch < totbatches.length ; currbatch++) { Result.fCreateReportFiles(totbatches[currbatch]); bthArr.add(new RunnableDemo(totbatches[currbatch],currbatch)); } for(RunnableDemo cbthArr: bthArr ) { cbthArr.start(); } } } else { if (totbatches != null) { for(int currbatch = 0 ; currbatch < totbatches.length ; currbatch++) { Driver.Drivermain(totbatches[currbatch], Integer.toString(currbatch)); } } } } catch (Exception e) { e.printStackTrace(); } } /*--------------------------------------------------------------------------------------------------------- * Method Name : floadbatches * Use : Reads all the batches with control 1 in the driver db and returns it in an array * Designed By : AG * Last Modified Date : 25-Apr-2016 --------------------------------------------------------------------------------------------------------*/ @SuppressWarnings("deprecation") static String[] floadbatches() { try { Fillo nfillo = new Fillo(); Connection connection=nfillo.getConnection(DriverDBpthI); String strQuery="Select * from Batches where Control = 1"; Recordset rs=connection.executeQuery(strQuery); rs.moveFirst(); String[] batches = new String[rs.getCount()]; for (int currs = 1 ; currs <= rs.getCount() ; currs++) { String BatchID = rs.getField(2).value(); batches[currs-1] = BatchID; if (rs.hasNext()) { rs.moveNext(); } } rs.close(); connection.close(); return batches; } catch(Exception ex) { System.err.print("Exception: "); System.err.println(ex.getMessage()); } return null; } /*--------------------------------------------------------------------------------------------------------- * Method Name : createdynamicfiles * Use : Creates dynamic testdata, Driverdb and object repository for each batch * Designed By : AG * Last Modified Date : 25-Apr-2016 --------------------------------------------------------------------------------------------------------*/ private static void createdynamicfiles(String[] batches) { try { String ORsrc = basepth+"/ObjectRepository/ObjectRepository.xlsx"; File cORsrc = new File(ORsrc); String DataDBsrc = basepth+"/DataBase"; File cDataDBsrc = new File(DataDBsrc); String tempfold = basepth+"/Temp"; for (String batchname : batches) { File batchdatafold = new File(tempfold + "/" + batchname); if ((!batchdatafold.exists())) try { batchdatafold.mkdir(); } catch (SecurityException se) { /* handle it */ } FileUtils.copyDirectory(cDataDBsrc, batchdatafold); FileUtils.copyFileToDirectory(cORsrc, batchdatafold); } } catch(Exception e) { e.printStackTrace(); } } } class RunnableDemo implements Runnable { private Thread t; private String threadName; private String batchcount; RunnableDemo(String name,int rbatchcount) { threadName = name; batchcount = Integer.toString(rbatchcount); System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { Driver.Drivermain(threadName, batchcount); } catch (Exception e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public void start () throws InterruptedException { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } //-----------------------------------------------------------------------------------------------------------------
UTF-8
Java
6,300
java
InitiatorTest.java
Java
[]
null
[]
package Libraries; //imports------------------------------------------------------------------------------------------------- import java.util.ArrayList; import org.apache.commons.io.FileUtils; import com.codoid.products.fillo.Connection; import com.codoid.products.fillo.Fillo; import com.codoid.products.fillo.Recordset; import java.io.*; import java.text.DateFormat; import java.text.SimpleDateFormat; //--------------------------------------------------------------------------------------------------------- /*--------------------------------------------------------------------------------------------------------- * Class Name : Initiator * Use : Has functions related to TestNG * Designed By : AG * Last Modified Date : 25-Apr-2016 --------------------------------------------------------------------------------------------------------*/ public class InitiatorTest { private static String workingDir = System.getProperty("user.dir"); private static String basepth = workingDir.replace("/","\\"); public static String xmlpth = basepth+"\\src\\Libraries\\Driver.xml"; private static String DriverDBpthI = basepth+"/DataBase/DriverDB/DriverDB.xlsx"; /*--------------------------------------------------------------------------------------------------------- * Method Name : Main Function * Use : The Test Pack Execution starts from the main function * Designed By : AG * Last Modified Date : 25-Apr-2016 --------------------------------------------------------------------------------------------------------*/ public static void main(String argv[]) { try { //set parallel execution yes to run the batches in parallel, set no to run batches in sequence. String ParallelExecution = "yes"; Driver.workingDir.set(System.getProperty("user.dir")); Driver.basepth.set(Driver.workingDir.get().replace("\\","/")); Driver.Resultpath.set(Driver.basepth.get()+"/Results"); Driver.templatfold.set(Driver.basepth.get()+"/Templates"); DateFormat ExecutionStarttime; ExecutionStarttime = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); Driver.ExecutionStarttimestr.set(ExecutionStarttime.format(Driver.cal.getTime())); String[] totbatches = floadbatches(); createdynamicfiles(totbatches); if(ParallelExecution.equals("yes")) { if (totbatches != null) { ArrayList<RunnableDemo> bthArr = new ArrayList<RunnableDemo>(); for(int currbatch = 0 ; currbatch < totbatches.length ; currbatch++) { Result.fCreateReportFiles(totbatches[currbatch]); bthArr.add(new RunnableDemo(totbatches[currbatch],currbatch)); } for(RunnableDemo cbthArr: bthArr ) { cbthArr.start(); } } } else { if (totbatches != null) { for(int currbatch = 0 ; currbatch < totbatches.length ; currbatch++) { Driver.Drivermain(totbatches[currbatch], Integer.toString(currbatch)); } } } } catch (Exception e) { e.printStackTrace(); } } /*--------------------------------------------------------------------------------------------------------- * Method Name : floadbatches * Use : Reads all the batches with control 1 in the driver db and returns it in an array * Designed By : AG * Last Modified Date : 25-Apr-2016 --------------------------------------------------------------------------------------------------------*/ @SuppressWarnings("deprecation") static String[] floadbatches() { try { Fillo nfillo = new Fillo(); Connection connection=nfillo.getConnection(DriverDBpthI); String strQuery="Select * from Batches where Control = 1"; Recordset rs=connection.executeQuery(strQuery); rs.moveFirst(); String[] batches = new String[rs.getCount()]; for (int currs = 1 ; currs <= rs.getCount() ; currs++) { String BatchID = rs.getField(2).value(); batches[currs-1] = BatchID; if (rs.hasNext()) { rs.moveNext(); } } rs.close(); connection.close(); return batches; } catch(Exception ex) { System.err.print("Exception: "); System.err.println(ex.getMessage()); } return null; } /*--------------------------------------------------------------------------------------------------------- * Method Name : createdynamicfiles * Use : Creates dynamic testdata, Driverdb and object repository for each batch * Designed By : AG * Last Modified Date : 25-Apr-2016 --------------------------------------------------------------------------------------------------------*/ private static void createdynamicfiles(String[] batches) { try { String ORsrc = basepth+"/ObjectRepository/ObjectRepository.xlsx"; File cORsrc = new File(ORsrc); String DataDBsrc = basepth+"/DataBase"; File cDataDBsrc = new File(DataDBsrc); String tempfold = basepth+"/Temp"; for (String batchname : batches) { File batchdatafold = new File(tempfold + "/" + batchname); if ((!batchdatafold.exists())) try { batchdatafold.mkdir(); } catch (SecurityException se) { /* handle it */ } FileUtils.copyDirectory(cDataDBsrc, batchdatafold); FileUtils.copyFileToDirectory(cORsrc, batchdatafold); } } catch(Exception e) { e.printStackTrace(); } } } class RunnableDemo implements Runnable { private Thread t; private String threadName; private String batchcount; RunnableDemo(String name,int rbatchcount) { threadName = name; batchcount = Integer.toString(rbatchcount); System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { Driver.Drivermain(threadName, batchcount); } catch (Exception e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public void start () throws InterruptedException { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } //-----------------------------------------------------------------------------------------------------------------
6,300
0.530159
0.525238
180
34.005554
29.78301
115
false
false
0
0
0
0
0
0
2.983333
false
false
13
933f7c910f491c5ff550fa158b31d4681ebdbdf1
21,577,915,697,964
a950525e8af6849929626a48109b1dc04da778c8
/app/src/main/java/cz/com/dosomething/adapter/RecyclerAdapter.java
580e2854584b11b9c5bb26f5d753ea0be7cd0f02
[]
no_license
notOnly20k/DoSomething
https://github.com/notOnly20k/DoSomething
a95e8e2617b85b567ab2732f1b386f98688e9c9c
1dfcae8943855d90c9a1f06ef1be6b5460f67103
refs/heads/master
2020-12-30T10:37:52.865000
2017-08-04T08:39:33
2017-08-04T08:39:33
96,960,750
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.com.dosomething.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import cz.com.dosomething.R; import cz.com.dosomething.bean.TaskInfo; /** * Created by cz on 2017/6/28. */ public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{ private Context context; private List<TaskInfo> list; private OnItemClickListener mOnItemClickListener; private OnItemLongClickListener mOnItemLongClickListener; public RecyclerAdapter(Context context, List<TaskInfo> list) { this.context = context; this.list = list; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(final MyViewHolder holder, int position) { TaskInfo taskInfo=list.get(position); if (taskInfo.ischecked()){ holder.check.isChecked(); } holder.itemTitle.setText(taskInfo.getTitle()); holder.content.setText(taskInfo.getContent()); if (TextUtils.isEmpty(taskInfo.getTitle())){ holder.itemTitle.setVisibility(View.GONE); } if (TextUtils.isEmpty(taskInfo.getContent())){ holder.content.setVisibility(View.GONE); } if (taskInfo.getTime()!=null){ holder.time.setText((CharSequence) taskInfo.getTime()); }else { holder.time.setVisibility(View.GONE); } if(mOnItemClickListener != null){ //为ItemView设置监听器 holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = holder.getLayoutPosition(); // 1 mOnItemClickListener.onItemClick(holder.itemView,position,list.get(position).getId()); // 2 } }); } if(mOnItemLongClickListener != null){ holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int position = holder.getLayoutPosition(); mOnItemLongClickListener.onItemLongClick(holder.itemView,position,list.get(position).getId()); //返回true 表示消耗了事件 事件不会继续传递 return true; } }); } } @Override public int getItemCount() { return list.size(); } class MyViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.check) CheckBox check; @BindView(R.id.item_title) TextView itemTitle; @BindView(R.id.content) TextView content; @BindView(R.id.time) TextView time; public MyViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } public void setOnItemClickListener(OnItemClickListener mOnItemClickListener){ this.mOnItemClickListener = mOnItemClickListener; } public void setOnItemLongClickListener(OnItemLongClickListener mOnItemLongClickListener) { this.mOnItemLongClickListener = mOnItemLongClickListener; } public interface OnItemClickListener{ void onItemClick(View view, int position, Long id); } public interface OnItemLongClickListener{ void onItemLongClick(View view, int position, Long id); } public void notifyAdapter(List<TaskInfo> myLiveList,boolean isAdd){ if (!isAdd){ this.list=myLiveList; }else { this.list.addAll(myLiveList); } notifyDataSetChanged(); } }
UTF-8
Java
4,167
java
RecyclerAdapter.java
Java
[ { "context": ".com.dosomething.bean.TaskInfo;\n\n/**\n * Created by cz on 2017/6/28.\n */\n\npublic class RecyclerAdapter e", "end": 481, "score": 0.9967954754829407, "start": 479, "tag": "USERNAME", "value": "cz" } ]
null
[]
package cz.com.dosomething.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import cz.com.dosomething.R; import cz.com.dosomething.bean.TaskInfo; /** * Created by cz on 2017/6/28. */ public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{ private Context context; private List<TaskInfo> list; private OnItemClickListener mOnItemClickListener; private OnItemLongClickListener mOnItemLongClickListener; public RecyclerAdapter(Context context, List<TaskInfo> list) { this.context = context; this.list = list; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(final MyViewHolder holder, int position) { TaskInfo taskInfo=list.get(position); if (taskInfo.ischecked()){ holder.check.isChecked(); } holder.itemTitle.setText(taskInfo.getTitle()); holder.content.setText(taskInfo.getContent()); if (TextUtils.isEmpty(taskInfo.getTitle())){ holder.itemTitle.setVisibility(View.GONE); } if (TextUtils.isEmpty(taskInfo.getContent())){ holder.content.setVisibility(View.GONE); } if (taskInfo.getTime()!=null){ holder.time.setText((CharSequence) taskInfo.getTime()); }else { holder.time.setVisibility(View.GONE); } if(mOnItemClickListener != null){ //为ItemView设置监听器 holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = holder.getLayoutPosition(); // 1 mOnItemClickListener.onItemClick(holder.itemView,position,list.get(position).getId()); // 2 } }); } if(mOnItemLongClickListener != null){ holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int position = holder.getLayoutPosition(); mOnItemLongClickListener.onItemLongClick(holder.itemView,position,list.get(position).getId()); //返回true 表示消耗了事件 事件不会继续传递 return true; } }); } } @Override public int getItemCount() { return list.size(); } class MyViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.check) CheckBox check; @BindView(R.id.item_title) TextView itemTitle; @BindView(R.id.content) TextView content; @BindView(R.id.time) TextView time; public MyViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } public void setOnItemClickListener(OnItemClickListener mOnItemClickListener){ this.mOnItemClickListener = mOnItemClickListener; } public void setOnItemLongClickListener(OnItemLongClickListener mOnItemLongClickListener) { this.mOnItemLongClickListener = mOnItemLongClickListener; } public interface OnItemClickListener{ void onItemClick(View view, int position, Long id); } public interface OnItemLongClickListener{ void onItemLongClick(View view, int position, Long id); } public void notifyAdapter(List<TaskInfo> myLiveList,boolean isAdd){ if (!isAdd){ this.list=myLiveList; }else { this.list.addAll(myLiveList); } notifyDataSetChanged(); } }
4,167
0.643776
0.641349
127
31.448818
25.869968
114
false
false
0
0
0
0
0
0
0.519685
false
false
13
5ebd8faf0fe1b3e6db2bb1ae7cd13ac7a362359a
2,216,203,178,916
4a283914cd85ce37ad189033e0beacaf9393acf6
/app/src/main/java/com/emproducciones/listapreciosalgunlugar/viewModel/vMProducto.java
57e92e2079b5b84550aa77d7121225357a1581bf
[]
no_license
emproducciones2257/listaDePreciosApp
https://github.com/emproducciones2257/listaDePreciosApp
dafc29558e6963a62a493b002fd19aca61374c1c
deaf9469a62e4ac36fb0fd686134f0f81d8857eb
refs/heads/master
2022-12-04T02:10:23.642000
2020-08-22T12:05:47
2020-08-22T12:05:47
263,620,642
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.emproducciones.listapreciosalgunlugar.viewModel; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.emproducciones.listapreciosalgunlugar.Repositorio.consultaRepository; import com.emproducciones.listapreciosalgunlugar.Repositorio.ModeloClases.precio; import com.emproducciones.listapreciosalgunlugar.Repositorio.ModeloClases.producto; public class vMProducto extends ViewModel { public static int porcentaje=0; private consultaRepository cRepo; public void vMProducto(){ obtenerPorcentaje(); } private void obtenerPorcentaje(){ cRepo.obtenerPorcentaje().observe(null, por -> porcentaje=por); } public vMProducto(){ cRepo = new consultaRepository(); } public MutableLiveData<producto> getProducto(String codMar, String codProdu, String categoria){return cRepo.obtenerProducto(codMar,codProdu,categoria);} public MutableLiveData<precio> getPrecioProducto(producto producto, int porcentaje, String categoria){return cRepo.obtenerPrecioProducto(producto,porcentaje,categoria);} public MutableLiveData<Integer> getPorcentaje() {return cRepo.obtenerPorcentaje();} }
UTF-8
Java
1,193
java
vMProducto.java
Java
[]
null
[]
package com.emproducciones.listapreciosalgunlugar.viewModel; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.emproducciones.listapreciosalgunlugar.Repositorio.consultaRepository; import com.emproducciones.listapreciosalgunlugar.Repositorio.ModeloClases.precio; import com.emproducciones.listapreciosalgunlugar.Repositorio.ModeloClases.producto; public class vMProducto extends ViewModel { public static int porcentaje=0; private consultaRepository cRepo; public void vMProducto(){ obtenerPorcentaje(); } private void obtenerPorcentaje(){ cRepo.obtenerPorcentaje().observe(null, por -> porcentaje=por); } public vMProducto(){ cRepo = new consultaRepository(); } public MutableLiveData<producto> getProducto(String codMar, String codProdu, String categoria){return cRepo.obtenerProducto(codMar,codProdu,categoria);} public MutableLiveData<precio> getPrecioProducto(producto producto, int porcentaje, String categoria){return cRepo.obtenerPrecioProducto(producto,porcentaje,categoria);} public MutableLiveData<Integer> getPorcentaje() {return cRepo.obtenerPorcentaje();} }
1,193
0.791282
0.790444
34
34.088234
43.266186
173
false
false
0
0
0
0
0
0
0.676471
false
false
13
cdadda41b6f2b6e1c7236eb73df892201e7bcfd4
12,987,981,116,245
d4d036eb0873f743ad2df59238bf7854b692c231
/projects/stage-0/user-platform/user-injectors/src/main/java/org/geektimes/context/core/Context.java
3043963efd5bf290b0b411d9f20b4b9e431f97d5
[ "Apache-2.0" ]
permissive
young1lin/gk-homework
https://github.com/young1lin/gk-homework
e0f9417e0f49f3d5cc206eb56c37b4903404cef1
93ffb0c40ef13c96d5a71875b4ce2d53dde14f77
refs/heads/main
2023-05-30T21:56:01.418000
2021-04-13T14:33:22
2021-04-13T14:33:22
344,124,833
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.geektimes.context.core; /** * @author <a href="mailto:young1lin0108@gmail.com">young1lin</a> * @date 2021/3/16 下午11:00 * @version 1.0 */ public interface Context extends LifeCycle { /** * get component object with component's name * * @param name component's name * @see org.geektimes.context.core.support.AbstractCustomContext#getComponent(String) * @return component object or null */ Object getComponent(String name); }
UTF-8
Java
460
java
Context.java
Java
[ { "context": "mes.context.core;\n\n/**\n * @author <a href=\"mailto:young1lin0108@gmail.com\">young1lin</a>\n * @date 2021/3/16 下午11:00\n * @ver", "end": 91, "score": 0.9999285340309143, "start": 68, "tag": "EMAIL", "value": "young1lin0108@gmail.com" }, { "context": " @author <a href=\"mailto:young1lin0108@gmail.com\">young1lin</a>\n * @date 2021/3/16 下午11:00\n * @version 1.0\n *", "end": 102, "score": 0.999702513217926, "start": 93, "tag": "USERNAME", "value": "young1lin" } ]
null
[]
package org.geektimes.context.core; /** * @author <a href="mailto:<EMAIL>">young1lin</a> * @date 2021/3/16 下午11:00 * @version 1.0 */ public interface Context extends LifeCycle { /** * get component object with component's name * * @param name component's name * @see org.geektimes.context.core.support.AbstractCustomContext#getComponent(String) * @return component object or null */ Object getComponent(String name); }
444
0.719298
0.677632
19
23
24.369955
86
false
false
0
0
0
0
0
0
0.526316
false
false
13
ca066b11abe705417b5bee20d0ed25077243cb86
12,987,981,116,177
c35c4fb597471e5cf2b53e2910ea9ecc03b4b0ee
/src/test/java/ru/ybogdanov/bbparser/service/BbParserServiceImplTest.java
c60584064d76e2afc7be528e91bcfec4757b7296
[]
no_license
Wonderkot/bbParser
https://github.com/Wonderkot/bbParser
11699aca63dbcda96399afcfd1b581133cbba269
7acb940cc203d00132337145c01984cab3f3741f
refs/heads/master
2023-07-03T09:44:37.559000
2021-08-07T07:54:50
2021-08-07T07:54:50
378,941,510
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.ybogdanov.bbparser.service; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import ru.ybogdanov.bbparser.interfaces.ParserService; import ru.ybogdanov.bbparser.repository.MoneyDataRepository; import ru.ybogdanov.bbparser.service.parser.CbParserServiceImpl; @SpringBootTest class BbParserServiceImplTest { @Qualifier("bbParserServiceImpl") @Autowired private ParserService parserService; @Autowired private MoneyDataRepository moneyDataRepository; @BeforeEach void setUp() { } @Test void bBParse() { parserService.parse(); } @Test void cBParse() { parserService = new CbParserServiceImpl(moneyDataRepository); parserService.parse(); } }
UTF-8
Java
948
java
BbParserServiceImplTest.java
Java
[]
null
[]
package ru.ybogdanov.bbparser.service; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import ru.ybogdanov.bbparser.interfaces.ParserService; import ru.ybogdanov.bbparser.repository.MoneyDataRepository; import ru.ybogdanov.bbparser.service.parser.CbParserServiceImpl; @SpringBootTest class BbParserServiceImplTest { @Qualifier("bbParserServiceImpl") @Autowired private ParserService parserService; @Autowired private MoneyDataRepository moneyDataRepository; @BeforeEach void setUp() { } @Test void bBParse() { parserService.parse(); } @Test void cBParse() { parserService = new CbParserServiceImpl(moneyDataRepository); parserService.parse(); } }
948
0.761603
0.761603
36
25.361111
22.573524
69
false
false
0
0
0
0
0
0
0.388889
false
false
13
add299767cdc2e0196eee0191d30744594e722dc
27,831,388,137,361
b8d00be638a6a1d0f30c8a033de5b92545cab541
/spring-boot-2-rest-service-basic/src/main/java/com/in28minutes/springboot/rest/example/student/StudentNotFoundException.java
b83242f0c1269305804e3b0a004ef868d24e7fcb
[]
no_license
pradip030/springboot-rest-h2db
https://github.com/pradip030/springboot-rest-h2db
2fac99c22d8eb7243a3aa7f2e05e3e3ea4e90bc6
f320a321080357226bae543d91b43f40f8a2c352
refs/heads/master
2020-04-26T03:12:37.134000
2019-03-08T07:07:04
2019-03-08T07:07:04
173,259,647
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.in28minutes.springboot.rest.example.student; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus public class StudentNotFoundException extends RuntimeException{ private String id; public StudentNotFoundException(String id) { super(String.format(" not found : '%s'",id)); this.id=id; } public String getId() { return this.id; } }
UTF-8
Java
374
java
StudentNotFoundException.java
Java
[]
null
[]
package com.in28minutes.springboot.rest.example.student; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus public class StudentNotFoundException extends RuntimeException{ private String id; public StudentNotFoundException(String id) { super(String.format(" not found : '%s'",id)); this.id=id; } public String getId() { return this.id; } }
374
0.786096
0.780749
20
17.75
22.400614
63
false
false
0
0
0
0
0
0
0.35
false
false
13
254e9da9deb06af5a907d68c73b37e6ff8027902
23,184,233,479,012
b1cba0397b8d77bc234df1372252b545aa8ba61d
/src/main/java/library/dataAccess/adapters/jdbc/entities/BookAuthorAdapter.java
886833bf7c9bb992ca11039e7f5b1fcedb3a8a15
[]
no_license
cha63506/library-564
https://github.com/cha63506/library-564
4d1209299784ed26b4601e3c2ae5063eef09f681
590997e24c5dddd26d37b3c03b2270e364846b56
refs/heads/master
2017-05-23T14:58:29.248000
2016-03-26T05:55:13
2016-03-26T05:55:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package library.dataAccess.adapters.jdbc.entities; import library.dataAccess.connectors.jdbc.entities.BookAuthor; public class BookAuthorAdapter { private BookAuthor entity; public BookAuthorAdapter() { this.entity = new BookAuthor(); } public BookAuthorAdapter(BookAuthor entity) { this.entity = entity; } public int getId() { return entity.getId(); } public void setId(int id) { entity.setId(id); } public int getBookId() { return entity.getBookId(); } public void setBookId(int bookId) { entity.setBookId(bookId); } public int getAuthorId() { return entity.getAuthorId(); } public void setAuthorId(int authorId) { entity.setAuthorId(authorId); } @Override public String toString() { return entity.toString(); } }
UTF-8
Java
874
java
BookAuthorAdapter.java
Java
[]
null
[]
package library.dataAccess.adapters.jdbc.entities; import library.dataAccess.connectors.jdbc.entities.BookAuthor; public class BookAuthorAdapter { private BookAuthor entity; public BookAuthorAdapter() { this.entity = new BookAuthor(); } public BookAuthorAdapter(BookAuthor entity) { this.entity = entity; } public int getId() { return entity.getId(); } public void setId(int id) { entity.setId(id); } public int getBookId() { return entity.getBookId(); } public void setBookId(int bookId) { entity.setBookId(bookId); } public int getAuthorId() { return entity.getAuthorId(); } public void setAuthorId(int authorId) { entity.setAuthorId(authorId); } @Override public String toString() { return entity.toString(); } }
874
0.630435
0.630435
39
21.410257
17.236988
62
false
false
0
0
0
0
0
0
0.307692
false
false
13
dc30956de7b43c12950028ef94dd0d4f2bead3f2
1,692,217,175,546
0a812b75bd375534f17c452f2e31666d83c2dd08
/camposSrc/campos/util/Random.java
9cb5cd678a1b664e25af016a6b661cf0d0bd9111
[]
no_license
Camposm97/SCCCHackathonSpring2019
https://github.com/Camposm97/SCCCHackathonSpring2019
1e282701b7a406451ef80d608e6d2a07e89fc18c
bda3f32a4c740e2b76a6186d663fd8751850378d
refs/heads/master
2020-05-15T20:36:37.475000
2019-10-09T21:14:44
2019-10-09T21:14:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package campos.util; import campos.models.Major; import javafx.scene.image.Image; public class Random { public static double emitGpa() { final double GPA = 4.0; return (Math.random() * GPA) + 1; } public static String emitPassword() { final int length = 8; String str = ""; do { str = emitCharacters(length); } while (!PasswordUtil.isValid(str)); return str; } public static String emitCharacters(int n) { // String alphabet = "AaBcCcDdEeFfGgHhIiJjKkMmNnOoPpQqRrSsTtUuVvWwXxYyZz !\"#$%&'()*+,-./:;<=>?@[]^_`{|}~"; String alphabet = "AaBcCcDdEeFfGgHhIiJjKkMmNnOoPpQqRrSsTtUuVvWwXxYyZz~!@#$%^&*()-_=+"; String str = ""; for (int i = 0; i < n; i++) str += alphabet.charAt(emitNumber(alphabet.length(), 0)); return str; } public static int emitNumber(int max, int min) { return (int) ((Math.random() * max) + min); } public static Major emitMajor() { return Major.values()[(int) (Math.random() * Major.values().length)]; } public static String emitAvatarUrl() { int n = emitNumber(ImgUtil.NUM_OF_AVATARS, 0); String url = "resources/images/avatar/" + String.valueOf(n) + ".jpg"; return url; } public static Image emitAvatar() { int n = emitNumber(ImgUtil.NUM_OF_AVATARS, 0); Image image = ImgUtil.loadImg("resources/images/avatars/" + String.valueOf(n) + ".jpg"); return image; } }
UTF-8
Java
1,347
java
Random.java
Java
[]
null
[]
package campos.util; import campos.models.Major; import javafx.scene.image.Image; public class Random { public static double emitGpa() { final double GPA = 4.0; return (Math.random() * GPA) + 1; } public static String emitPassword() { final int length = 8; String str = ""; do { str = emitCharacters(length); } while (!PasswordUtil.isValid(str)); return str; } public static String emitCharacters(int n) { // String alphabet = "AaBcCcDdEeFfGgHhIiJjKkMmNnOoPpQqRrSsTtUuVvWwXxYyZz !\"#$%&'()*+,-./:;<=>?@[]^_`{|}~"; String alphabet = "AaBcCcDdEeFfGgHhIiJjKkMmNnOoPpQqRrSsTtUuVvWwXxYyZz~!@#$%^&*()-_=+"; String str = ""; for (int i = 0; i < n; i++) str += alphabet.charAt(emitNumber(alphabet.length(), 0)); return str; } public static int emitNumber(int max, int min) { return (int) ((Math.random() * max) + min); } public static Major emitMajor() { return Major.values()[(int) (Math.random() * Major.values().length)]; } public static String emitAvatarUrl() { int n = emitNumber(ImgUtil.NUM_OF_AVATARS, 0); String url = "resources/images/avatar/" + String.valueOf(n) + ".jpg"; return url; } public static Image emitAvatar() { int n = emitNumber(ImgUtil.NUM_OF_AVATARS, 0); Image image = ImgUtil.loadImg("resources/images/avatars/" + String.valueOf(n) + ".jpg"); return image; } }
1,347
0.657758
0.651819
49
26.489796
26.382681
108
false
false
0
0
0
0
0
0
1.918367
false
false
13
084cf88063851fb6214f76b5e83b2e6f29e321ec
1,692,217,171,558
74a06299a51b7a917b26729523dc0d2d9d08a152
/app/src/main/java/org/icddrb/enap/KMC_DataExt.java
7a1c8d5440f8eecc4b435134f40d6c5998a4def4
[]
no_license
akmtanvirhossain/ENAPProject
https://github.com/akmtanvirhossain/ENAPProject
625906fd617450f27233bef70a2839f3e1053ba7
8c427bbaa86b93a3c0e89645a7da51d021c13d6d
refs/heads/master
2021-01-20T05:37:46.654000
2019-08-19T10:41:56
2019-08-19T10:41:56
83,386,856
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.icddrb.enap; //Android Manifest Code //<activity android:name=".KMC_DataExt" android:label="KMC_DataExt" /> import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import android.app.*; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.provider.Settings; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.MotionEvent; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.BaseAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.graphics.Color; import Utility.*; import Common.*; public class KMC_DataExt extends Activity { boolean networkAvailable=false; Location currentLocation; double currentLatitude,currentLongitude; //Disabled Back/Home key //-------------------------------------------------------------------------------------------------- @Override public boolean onKeyDown(int iKeyCode, KeyEvent event) { if(iKeyCode == KeyEvent.KEYCODE_BACK || iKeyCode == KeyEvent.KEYCODE_HOME) { return false; } else { return true; } } String VariableID; private int hour; private int minute; private int mDay; private int mMonth; private int mYear; static final int DATE_DIALOG = 1; static final int TIME_DIALOG = 2; Connection C; Global g; SimpleAdapter dataAdapter; ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>(); LinearLayout secstatus; RadioGroup rdogrpstatus; RadioButton rdostatus1; RadioButton rdostatus2; RadioButton rdostatus3; LinearLayout secreason; RadioGroup rdogrpreason; RadioButton rdoreason1; RadioButton rdoreason2; RadioButton rdoreason3; RadioButton rdoreason4; LinearLayout secreasmention; EditText txtreasmention; LinearLayout secrefdelivdatenot; RadioGroup rdogrprefdelivdatenot; RadioButton rdorefdelivdatenot1; RadioButton rdorefdelivdatenot2; LinearLayout secrefdelivtimenot; RadioGroup rdogrprefdelivtimenot; RadioButton rdorefdelivtimenot1; RadioButton rdorefdelivtimenot2; LinearLayout secrefdoadmkmcnot; RadioGroup rdogrprefdoadmkmcnot; RadioButton rdorefdoadmkmcnot1; RadioButton rdorefdoadmkmcnot2; LinearLayout secreftoadmkmcnot; RadioGroup rdogrpreftoadmkmcnot; RadioButton rdoreftoadmkmcnot1; RadioButton rdoreftoadmkmcnot2; LinearLayout secrefdodkmcnot; RadioGroup rdogrprefdodkmcnot; RadioButton rdorefdodkmcnot1; RadioButton rdorefdodkmcnot2; TextView lblHeading; LinearLayout seclbl01; View linelbl01; LinearLayout secCountryCode; View lineCountryCode; TextView VlblCountryCode; EditText txtCountryCode; LinearLayout secFaciCode; View lineFaciCode; TextView VlblFaciCode; EditText txtFaciCode; LinearLayout secDataID; View lineDataID; TextView VlblDataID; EditText txtDataID; LinearLayout secrefdoe; View linerefdoe; TextView Vlblrefdoe; EditText dtprefdoe; LinearLayout secrefabskmc; View linerefabskmc; TextView Vlblrefabskmc; RadioGroup rdogrprefabskmc; RadioButton rdorefabskmc1; RadioButton rdorefabskmc2; RadioButton rdorefabskmc3; LinearLayout secrefabskmcOth; View linerefabskmcOth; TextView VlblrefabskmcOth; EditText txtrefabskmcOth; LinearLayout secrefmatname; View linerefmatname; TextView Vlblrefmatname; EditText txtrefmatname; LinearLayout secrefmatage; View linerefmatage; TextView Vlblrefmatage; EditText txtrefmatage; LinearLayout secrefmatid; View linerefmatid; TextView Vlblrefmatid; EditText txtrefmatid; LinearLayout secrefbname; View linerefbname; TextView Vlblrefbname; EditText txtrefbname; LinearLayout secrefbid; View linerefbid; TextView Vlblrefbid; EditText txtrefbid; LinearLayout secrefbsex; View linerefbsex; TextView Vlblrefbsex; RadioGroup rdogrprefbsex; RadioButton rdorefbsex1; RadioButton rdorefbsex2; RadioButton rdorefbsex3; RadioButton rdorefbsex4; RadioButton rdorefbsex5; LinearLayout secrefdelivdate; View linerefdelivdate; TextView Vlblrefdelivdate; EditText dtprefdelivdate; LinearLayout secrefbwgt; View linerefbwgt; TextView Vlblrefbwgt; EditText txtrefbwgt; LinearLayout secrefbwgtnot; View linerefbwgtnot; TextView Vlblrefbwgtnot; RadioGroup rdogrprefbwgtnot; RadioButton rdorefbwgtnot1; RadioButton rdorefbwgtnot2; LinearLayout secrefgakmc; View linerefgakmc; TextView Vlblrefgakmc; EditText txtrefgakmc; LinearLayout secrefgakmcnot; View linerefgakmcnot; TextView Vlblrefgakmcnot; RadioGroup rdogrprefgakmcnot; RadioButton rdorefgakmcnot1; RadioButton rdorefgakmcnot2; LinearLayout secrefbbornloc; View linerefbbornloc; TextView Vlblrefbbornloc; RadioGroup rdogrprefbbornloc; RadioButton rdorefbbornloc1; RadioButton rdorefbbornloc2; RadioButton rdorefbbornloc3; RadioButton rdorefbbornloc4; RadioButton rdorefbbornloc5; RadioButton rdorefbbornloc6; LinearLayout secrefbbornOth; View linerefbbornOth; TextView VlblrefbbornOth; EditText txtrefbbornOth; LinearLayout secrefdelivtime; View linerefdelivtime; TextView Vlblrefdelivtime; EditText txtrefdelivtime; LinearLayout secrefdoadmkmc; View linerefdoadmkmc; TextView Vlblrefdoadmkmc; EditText dtprefdoadmkmc; LinearLayout secreftoadmkmc; View linereftoadmkmc; TextView Vlblreftoadmkmc; EditText txtreftoadmkmc; LinearLayout secrefadwgtkmc; View linerefadwgtkmc; TextView Vlblrefadwgtkmc; EditText txtrefadwgtkmc; LinearLayout secrefadwgtkmcnot; View linerefadwgtkmcnot; TextView Vlblrefadwgtkmcnot; RadioGroup rdogrprefadwgtkmcnot; RadioButton rdorefadwgtkmcnot1; RadioButton rdorefadwgtkmcnot2; LinearLayout seclblrefbfsup; View linelblrefbfsup; LinearLayout secrefbfsupA; View linerefbfsupA; TextView VlblrefbfsupA; CheckBox chkrefbfsupA; LinearLayout secrefbfsupB; View linerefbfsupB; TextView VlblrefbfsupB; CheckBox chkrefbfsupB; LinearLayout secrefbfsupC; View linerefbfsupC; TextView VlblrefbfsupC; CheckBox chkrefbfsupC; LinearLayout secrefbfsupD; View linerefbfsupD; TextView VlblrefbfsupD; CheckBox chkrefbfsupD; LinearLayout secrefbfsupE; View linerefbfsupE; TextView VlblrefbfsupE; CheckBox chkrefbfsupE; LinearLayout secrefbfsupF; View linerefbfsupF; TextView VlblrefbfsupF; CheckBox chkrefbfsupF; LinearLayout secrefbfsupFOth; View linerefbfsupFOth; TextView VlblrefbfsupFOth; EditText txtrefbfsupFOth; LinearLayout secrefdisoutkmc; View linerefdisoutkmc; TextView Vlblrefdisoutkmc; RadioGroup rdogrprefdisoutkmc; RadioButton rdorefdisoutkmc1; RadioButton rdorefdisoutkmc2; RadioButton rdorefdisoutkmc3; RadioButton rdorefdisoutkmc4; RadioButton rdorefdisoutkmc5; RadioButton rdorefdisoutkmc6; RadioButton rdorefdisoutkmc7; LinearLayout secreftransPlace; View linereftransPlace; TextView VlblreftransPlace; EditText txtreftransPlace; LinearLayout secrefdodkmc; View linerefdodkmc; TextView Vlblrefdodkmc; EditText dtprefdodkmc; LinearLayout secrefdiswgtkmc; View linerefdiswgtkmc; TextView Vlblrefdiswgtkmc; EditText txtrefdiswgtkmc; LinearLayout secregdiswgtkmcnot; View lineregdiswgtkmcnot; TextView Vlblregdiswgtkmcnot; RadioGroup rdogrpregdiswgtkmcnot; RadioButton rdoregdiswgtkmcnot1; RadioButton rdoregdiswgtkmcnot2; static String TableName; static String STARTTIME = ""; static String DEVICEID = ""; static String ENTRYUSER = ""; MySharedPreferences sp; Bundle IDbundle; static String COUNTRYCODE = ""; static String FACICODE = ""; static String DATAID = ""; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.kmc_dataext); C = new Connection(this); g = Global.getInstance(); STARTTIME = g.CurrentTime24(); DEVICEID = sp.getValue(this, "deviceid"); ENTRYUSER = sp.getValue(this, "userid"); IDbundle = getIntent().getExtras(); COUNTRYCODE = IDbundle.getString("CountryCode"); FACICODE = IDbundle.getString("FaciCode"); DATAID = IDbundle.getString("DataID"); TableName = "KMC_DataExt"; //turnGPSOn(); //GPS Location //FindLocation(); // Double.toString(currentLatitude); // Double.toString(currentLongitude); lblHeading = (TextView)findViewById(R.id.lblHeading); ImageButton cmdBack = (ImageButton) findViewById(R.id.cmdBack); cmdBack.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { AlertDialog.Builder adb = new AlertDialog.Builder(KMC_DataExt.this); adb.setTitle("Close"); adb.setMessage("Do you want to close this form[Yes/No]?"); adb.setNegativeButton("No", null); adb.setPositiveButton("Yes", new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); }}); adb.show(); }}); secstatus=(LinearLayout)findViewById(R.id.secstatus) ; rdogrpstatus=(RadioGroup)findViewById(R.id.rdogrpstatus) ; rdostatus1=(RadioButton)findViewById(R.id.rdostatus1) ; rdostatus2=(RadioButton)findViewById(R.id.rdostatus2) ; rdostatus3=(RadioButton)findViewById(R.id.rdostatus3) ; secreason=(LinearLayout)findViewById(R.id.secreason) ; rdogrpreason=(RadioGroup)findViewById(R.id.rdogrpreason) ; rdoreason1=(RadioButton)findViewById(R.id.rdoreason1) ; rdoreason2=(RadioButton)findViewById(R.id.rdoreason2) ; rdoreason3=(RadioButton)findViewById(R.id.rdoreason3) ; rdoreason4=(RadioButton)findViewById(R.id.rdoreason4) ; secreasmention=(LinearLayout)findViewById(R.id.secreasmention) ; txtreasmention=(EditText)findViewById(R.id.txtreasmention) ; secrefdelivdatenot=(LinearLayout)findViewById(R.id.secrefdelivdatenot) ; rdogrprefdelivdatenot=(RadioGroup)findViewById(R.id.rdogrprefdelivdatenot) ; rdorefdelivdatenot1=(RadioButton)findViewById(R.id.rdorefdelivdatenot1) ; rdorefdelivdatenot2=(RadioButton)findViewById(R.id.rdorefdelivdatenot2) ; secrefdelivtimenot=(LinearLayout)findViewById(R.id.secrefdelivtimenot) ; rdogrprefdelivtimenot=(RadioGroup)findViewById(R.id.rdogrprefdelivtimenot) ; rdorefdelivtimenot1=(RadioButton)findViewById(R.id.rdorefdelivtimenot1) ; rdorefdelivtimenot2=(RadioButton)findViewById(R.id.rdorefdelivtimenot2) ; secrefdoadmkmcnot=(LinearLayout)findViewById(R.id.secrefdoadmkmcnot) ; rdogrprefdoadmkmcnot=(RadioGroup)findViewById(R.id.rdogrprefdoadmkmcnot) ; rdorefdoadmkmcnot1=(RadioButton)findViewById(R.id.rdorefdoadmkmcnot1) ; rdorefdoadmkmcnot2=(RadioButton)findViewById(R.id.rdorefdoadmkmcnot2) ; secreftoadmkmcnot=(LinearLayout)findViewById(R.id.secreftoadmkmcnot) ; rdogrpreftoadmkmcnot=(RadioGroup)findViewById(R.id.rdogrpreftoadmkmcnot) ; rdoreftoadmkmcnot1=(RadioButton)findViewById(R.id.rdoreftoadmkmcnot1) ; rdoreftoadmkmcnot2=(RadioButton)findViewById(R.id.rdoreftoadmkmcnot2) ; secrefdodkmcnot=(LinearLayout)findViewById(R.id.secrefdodkmcnot) ; rdogrprefdodkmcnot=(RadioGroup)findViewById(R.id.rdogrprefdodkmcnot) ; rdorefdodkmcnot1=(RadioButton)findViewById(R.id.rdorefdodkmcnot1) ; rdorefdodkmcnot2=(RadioButton)findViewById(R.id.rdorefdodkmcnot2) ; seclbl01=(LinearLayout)findViewById(R.id.seclbl01); linelbl01=(View)findViewById(R.id.linelbl01); secCountryCode=(LinearLayout)findViewById(R.id.secCountryCode); lineCountryCode=(View)findViewById(R.id.lineCountryCode); VlblCountryCode=(TextView) findViewById(R.id.VlblCountryCode); txtCountryCode=(EditText) findViewById(R.id.txtCountryCode); txtCountryCode.setText(COUNTRYCODE); secFaciCode=(LinearLayout)findViewById(R.id.secFaciCode); lineFaciCode=(View)findViewById(R.id.lineFaciCode); VlblFaciCode=(TextView) findViewById(R.id.VlblFaciCode); txtFaciCode=(EditText) findViewById(R.id.txtFaciCode); txtFaciCode.setText(FACICODE); secDataID=(LinearLayout)findViewById(R.id.secDataID); lineDataID=(View)findViewById(R.id.lineDataID); VlblDataID=(TextView) findViewById(R.id.VlblDataID); txtDataID=(EditText) findViewById(R.id.txtDataID); txtDataID.setText(DATAID); secrefdoe=(LinearLayout)findViewById(R.id.secrefdoe); linerefdoe=(View)findViewById(R.id.linerefdoe); Vlblrefdoe=(TextView) findViewById(R.id.Vlblrefdoe); dtprefdoe=(EditText) findViewById(R.id.dtprefdoe); dtprefdoe.setText(Global.DateNowDMY()); secrefabskmc=(LinearLayout)findViewById(R.id.secrefabskmc); linerefabskmc=(View)findViewById(R.id.linerefabskmc); Vlblrefabskmc = (TextView) findViewById(R.id.Vlblrefabskmc); rdogrprefabskmc = (RadioGroup) findViewById(R.id.rdogrprefabskmc); rdorefabskmc1 = (RadioButton) findViewById(R.id.rdorefabskmc1); rdorefabskmc2 = (RadioButton) findViewById(R.id.rdorefabskmc2); rdorefabskmc3 = (RadioButton) findViewById(R.id.rdorefabskmc3); rdogrprefabskmc.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup radioGroup,int radioButtonID) { String rbData = ""; RadioButton rb; String[] d_rdogrprefabskmc = new String[] {"1","2","3"}; for (int i = 0; i < rdogrprefabskmc.getChildCount(); i++) { rb = (RadioButton)rdogrprefabskmc.getChildAt(i); if (rb.isChecked()) rbData = d_rdogrprefabskmc[i]; } if(rbData.equalsIgnoreCase("1")) { secrefabskmcOth.setVisibility(View.GONE); linerefabskmcOth.setVisibility(View.GONE); txtrefabskmcOth.setText(""); } else if(rbData.equalsIgnoreCase("2")) { secrefabskmcOth.setVisibility(View.GONE); linerefabskmcOth.setVisibility(View.GONE); txtrefabskmcOth.setText(""); } else if(rbData.equalsIgnoreCase("3")) { secrefabskmcOth.setVisibility(View.VISIBLE); linerefabskmcOth.setVisibility(View.VISIBLE); } else { //sec.setVisibility(View.VISIBLE); //line.setVisibility(View.VISIBLE); } } public void onNothingSelected(AdapterView<?> adapterView) { return; } }); secrefabskmcOth=(LinearLayout)findViewById(R.id.secrefabskmcOth); linerefabskmcOth=(View)findViewById(R.id.linerefabskmcOth); VlblrefabskmcOth=(TextView) findViewById(R.id.VlblrefabskmcOth); txtrefabskmcOth=(EditText) findViewById(R.id.txtrefabskmcOth); secrefmatname=(LinearLayout)findViewById(R.id.secrefmatname); linerefmatname=(View)findViewById(R.id.linerefmatname); Vlblrefmatname=(TextView) findViewById(R.id.Vlblrefmatname); txtrefmatname=(EditText) findViewById(R.id.txtrefmatname); secrefmatage=(LinearLayout)findViewById(R.id.secrefmatage); linerefmatage=(View)findViewById(R.id.linerefmatage); Vlblrefmatage=(TextView) findViewById(R.id.Vlblrefmatage); txtrefmatage=(EditText) findViewById(R.id.txtrefmatage); secrefmatid=(LinearLayout)findViewById(R.id.secrefmatid); linerefmatid=(View)findViewById(R.id.linerefmatid); Vlblrefmatid=(TextView) findViewById(R.id.Vlblrefmatid); txtrefmatid=(EditText) findViewById(R.id.txtrefmatid); secrefbname=(LinearLayout)findViewById(R.id.secrefbname); linerefbname=(View)findViewById(R.id.linerefbname); Vlblrefbname=(TextView) findViewById(R.id.Vlblrefbname); txtrefbname=(EditText) findViewById(R.id.txtrefbname); secrefbid=(LinearLayout)findViewById(R.id.secrefbid); linerefbid=(View)findViewById(R.id.linerefbid); Vlblrefbid=(TextView) findViewById(R.id.Vlblrefbid); txtrefbid=(EditText) findViewById(R.id.txtrefbid); secrefbsex=(LinearLayout)findViewById(R.id.secrefbsex); linerefbsex=(View)findViewById(R.id.linerefbsex); Vlblrefbsex = (TextView) findViewById(R.id.Vlblrefbsex); rdogrprefbsex = (RadioGroup) findViewById(R.id.rdogrprefbsex); rdorefbsex1 = (RadioButton) findViewById(R.id.rdorefbsex1); rdorefbsex2 = (RadioButton) findViewById(R.id.rdorefbsex2); rdorefbsex3 = (RadioButton) findViewById(R.id.rdorefbsex3); rdorefbsex4 = (RadioButton) findViewById(R.id.rdorefbsex4); rdorefbsex5 = (RadioButton) findViewById(R.id.rdorefbsex5); secrefdelivdate=(LinearLayout)findViewById(R.id.secrefdelivdate); linerefdelivdate=(View)findViewById(R.id.linerefdelivdate); Vlblrefdelivdate=(TextView) findViewById(R.id.Vlblrefdelivdate); dtprefdelivdate=(EditText) findViewById(R.id.dtprefdelivdate); secrefbwgt=(LinearLayout)findViewById(R.id.secrefbwgt); linerefbwgt=(View)findViewById(R.id.linerefbwgt); Vlblrefbwgt=(TextView) findViewById(R.id.Vlblrefbwgt); txtrefbwgt=(EditText) findViewById(R.id.txtrefbwgt); secrefbwgtnot=(LinearLayout)findViewById(R.id.secrefbwgtnot); linerefbwgtnot=(View)findViewById(R.id.linerefbwgtnot); Vlblrefbwgtnot = (TextView) findViewById(R.id.Vlblrefbwgtnot); rdogrprefbwgtnot = (RadioGroup) findViewById(R.id.rdogrprefbwgtnot); rdorefbwgtnot1 = (RadioButton) findViewById(R.id.rdorefbwgtnot1); rdorefbwgtnot2 = (RadioButton) findViewById(R.id.rdorefbwgtnot2); secrefgakmc=(LinearLayout)findViewById(R.id.secrefgakmc); linerefgakmc=(View)findViewById(R.id.linerefgakmc); Vlblrefgakmc=(TextView) findViewById(R.id.Vlblrefgakmc); txtrefgakmc=(EditText) findViewById(R.id.txtrefgakmc); secrefgakmcnot=(LinearLayout)findViewById(R.id.secrefgakmcnot); linerefgakmcnot=(View)findViewById(R.id.linerefgakmcnot); Vlblrefgakmcnot = (TextView) findViewById(R.id.Vlblrefgakmcnot); rdogrprefgakmcnot = (RadioGroup) findViewById(R.id.rdogrprefgakmcnot); rdorefgakmcnot1 = (RadioButton) findViewById(R.id.rdorefgakmcnot1); rdorefgakmcnot2 = (RadioButton) findViewById(R.id.rdorefgakmcnot2); secrefbbornloc=(LinearLayout)findViewById(R.id.secrefbbornloc); linerefbbornloc=(View)findViewById(R.id.linerefbbornloc); Vlblrefbbornloc = (TextView) findViewById(R.id.Vlblrefbbornloc); rdogrprefbbornloc = (RadioGroup) findViewById(R.id.rdogrprefbbornloc); rdorefbbornloc1 = (RadioButton) findViewById(R.id.rdorefbbornloc1); rdorefbbornloc2 = (RadioButton) findViewById(R.id.rdorefbbornloc2); rdorefbbornloc3 = (RadioButton) findViewById(R.id.rdorefbbornloc3); rdorefbbornloc4 = (RadioButton) findViewById(R.id.rdorefbbornloc4); rdorefbbornloc5 = (RadioButton) findViewById(R.id.rdorefbbornloc5); rdorefbbornloc6 = (RadioButton) findViewById(R.id.rdorefbbornloc6); rdogrprefbbornloc.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup radioGroup,int radioButtonID) { String rbData = ""; RadioButton rb; String[] d_rdogrprefbbornloc = new String[] {"1","2","3","4","6","9"}; for (int i = 0; i < rdogrprefbbornloc.getChildCount(); i++) { rb = (RadioButton)rdogrprefbbornloc.getChildAt(i); if (rb.isChecked()) rbData = d_rdogrprefbbornloc[i]; } if(rbData.equalsIgnoreCase("1")) { secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); txtrefbbornOth.setText(""); } else if(rbData.equalsIgnoreCase("2")) { secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); txtrefbbornOth.setText(""); } else if(rbData.equalsIgnoreCase("3")) { secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); txtrefbbornOth.setText(""); } else if(rbData.equalsIgnoreCase("6")) { secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); txtrefbbornOth.setText(""); } else if(rbData.equalsIgnoreCase("9")) { secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); txtrefbbornOth.setText(""); } else { secrefbbornOth.setVisibility(View.VISIBLE); linerefbbornOth.setVisibility(View.VISIBLE); } } public void onNothingSelected(AdapterView<?> adapterView) { return; } }); secrefbbornOth=(LinearLayout)findViewById(R.id.secrefbbornOth); linerefbbornOth=(View)findViewById(R.id.linerefbbornOth); VlblrefbbornOth=(TextView) findViewById(R.id.VlblrefbbornOth); txtrefbbornOth=(EditText) findViewById(R.id.txtrefbbornOth); secrefdelivtime=(LinearLayout)findViewById(R.id.secrefdelivtime); linerefdelivtime=(View)findViewById(R.id.linerefdelivtime); Vlblrefdelivtime=(TextView) findViewById(R.id.Vlblrefdelivtime); txtrefdelivtime=(EditText) findViewById(R.id.txtrefdelivtime); secrefdoadmkmc=(LinearLayout)findViewById(R.id.secrefdoadmkmc); linerefdoadmkmc=(View)findViewById(R.id.linerefdoadmkmc); Vlblrefdoadmkmc=(TextView) findViewById(R.id.Vlblrefdoadmkmc); dtprefdoadmkmc=(EditText) findViewById(R.id.dtprefdoadmkmc); secreftoadmkmc=(LinearLayout)findViewById(R.id.secreftoadmkmc); linereftoadmkmc=(View)findViewById(R.id.linereftoadmkmc); Vlblreftoadmkmc=(TextView) findViewById(R.id.Vlblreftoadmkmc); txtreftoadmkmc=(EditText) findViewById(R.id.txtreftoadmkmc); secrefadwgtkmc=(LinearLayout)findViewById(R.id.secrefadwgtkmc); linerefadwgtkmc=(View)findViewById(R.id.linerefadwgtkmc); Vlblrefadwgtkmc=(TextView) findViewById(R.id.Vlblrefadwgtkmc); txtrefadwgtkmc=(EditText) findViewById(R.id.txtrefadwgtkmc); secrefadwgtkmcnot=(LinearLayout)findViewById(R.id.secrefadwgtkmcnot); linerefadwgtkmcnot=(View)findViewById(R.id.linerefadwgtkmcnot); Vlblrefadwgtkmcnot = (TextView) findViewById(R.id.Vlblrefadwgtkmcnot); rdogrprefadwgtkmcnot = (RadioGroup) findViewById(R.id.rdogrprefadwgtkmcnot); rdorefadwgtkmcnot1 = (RadioButton) findViewById(R.id.rdorefadwgtkmcnot1); rdorefadwgtkmcnot2 = (RadioButton) findViewById(R.id.rdorefadwgtkmcnot2); seclblrefbfsup=(LinearLayout)findViewById(R.id.seclblrefbfsup); linelblrefbfsup=(View)findViewById(R.id.linelblrefbfsup); secrefbfsupA=(LinearLayout)findViewById(R.id.secrefbfsupA); linerefbfsupA=(View)findViewById(R.id.linerefbfsupA); VlblrefbfsupA=(TextView) findViewById(R.id.VlblrefbfsupA); chkrefbfsupA=(CheckBox) findViewById(R.id.chkrefbfsupA); secrefbfsupB=(LinearLayout)findViewById(R.id.secrefbfsupB); linerefbfsupB=(View)findViewById(R.id.linerefbfsupB); VlblrefbfsupB=(TextView) findViewById(R.id.VlblrefbfsupB); chkrefbfsupB=(CheckBox) findViewById(R.id.chkrefbfsupB); secrefbfsupC=(LinearLayout)findViewById(R.id.secrefbfsupC); linerefbfsupC=(View)findViewById(R.id.linerefbfsupC); VlblrefbfsupC=(TextView) findViewById(R.id.VlblrefbfsupC); chkrefbfsupC=(CheckBox) findViewById(R.id.chkrefbfsupC); secrefbfsupD=(LinearLayout)findViewById(R.id.secrefbfsupD); linerefbfsupD=(View)findViewById(R.id.linerefbfsupD); VlblrefbfsupD=(TextView) findViewById(R.id.VlblrefbfsupD); chkrefbfsupD=(CheckBox) findViewById(R.id.chkrefbfsupD); secrefbfsupE=(LinearLayout)findViewById(R.id.secrefbfsupE); linerefbfsupE=(View)findViewById(R.id.linerefbfsupE); VlblrefbfsupE=(TextView) findViewById(R.id.VlblrefbfsupE); chkrefbfsupE=(CheckBox) findViewById(R.id.chkrefbfsupE); secrefbfsupF=(LinearLayout)findViewById(R.id.secrefbfsupF); linerefbfsupF=(View)findViewById(R.id.linerefbfsupF); VlblrefbfsupF=(TextView) findViewById(R.id.VlblrefbfsupF); chkrefbfsupF=(CheckBox) findViewById(R.id.chkrefbfsupF); chkrefbfsupF.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!isChecked) { secrefbfsupFOth.setVisibility(View.GONE); linerefbfsupFOth.setVisibility(View.GONE); txtrefbfsupFOth.setText(""); } else { secrefbfsupFOth.setVisibility(View.VISIBLE); linerefbfsupFOth.setVisibility(View.VISIBLE); } } }); secrefbfsupFOth=(LinearLayout)findViewById(R.id.secrefbfsupFOth); linerefbfsupFOth=(View)findViewById(R.id.linerefbfsupFOth); VlblrefbfsupFOth=(TextView) findViewById(R.id.VlblrefbfsupFOth); txtrefbfsupFOth=(EditText) findViewById(R.id.txtrefbfsupFOth); secrefdisoutkmc=(LinearLayout)findViewById(R.id.secrefdisoutkmc); linerefdisoutkmc=(View)findViewById(R.id.linerefdisoutkmc); Vlblrefdisoutkmc = (TextView) findViewById(R.id.Vlblrefdisoutkmc); rdogrprefdisoutkmc = (RadioGroup) findViewById(R.id.rdogrprefdisoutkmc); rdorefdisoutkmc1 = (RadioButton) findViewById(R.id.rdorefdisoutkmc1); rdorefdisoutkmc2 = (RadioButton) findViewById(R.id.rdorefdisoutkmc2); rdorefdisoutkmc3 = (RadioButton) findViewById(R.id.rdorefdisoutkmc3); rdorefdisoutkmc4 = (RadioButton) findViewById(R.id.rdorefdisoutkmc4); rdorefdisoutkmc5 = (RadioButton) findViewById(R.id.rdorefdisoutkmc5); rdorefdisoutkmc6 = (RadioButton) findViewById(R.id.rdorefdisoutkmc6); rdorefdisoutkmc7 = (RadioButton) findViewById(R.id.rdorefdisoutkmc7); rdogrprefdisoutkmc.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup radioGroup,int radioButtonID) { String rbData = ""; RadioButton rb; String[] d_rdogrprefdisoutkmc = new String[] {"1","2","3","4","5","8","9"}; for (int i = 0; i < rdogrprefdisoutkmc.getChildCount(); i++) { rb = (RadioButton)rdogrprefdisoutkmc.getChildAt(i); if (rb.isChecked()) rbData = d_rdogrprefdisoutkmc[i]; } if(rbData.equalsIgnoreCase("1")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else if(rbData.equalsIgnoreCase("2")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else if(rbData.equalsIgnoreCase("3")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else if(rbData.equalsIgnoreCase("5")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else if(rbData.equalsIgnoreCase("8")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else if(rbData.equalsIgnoreCase("9")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else { secreftransPlace.setVisibility(View.VISIBLE); linereftransPlace.setVisibility(View.VISIBLE); } } public void onNothingSelected(AdapterView<?> adapterView) { return; } }); secreftransPlace=(LinearLayout)findViewById(R.id.secreftransPlace); linereftransPlace=(View)findViewById(R.id.linereftransPlace); VlblreftransPlace=(TextView) findViewById(R.id.VlblreftransPlace); txtreftransPlace=(EditText) findViewById(R.id.txtreftransPlace); secrefdodkmc=(LinearLayout)findViewById(R.id.secrefdodkmc); linerefdodkmc=(View)findViewById(R.id.linerefdodkmc); Vlblrefdodkmc=(TextView) findViewById(R.id.Vlblrefdodkmc); dtprefdodkmc=(EditText) findViewById(R.id.dtprefdodkmc); secrefdiswgtkmc=(LinearLayout)findViewById(R.id.secrefdiswgtkmc); linerefdiswgtkmc=(View)findViewById(R.id.linerefdiswgtkmc); Vlblrefdiswgtkmc=(TextView) findViewById(R.id.Vlblrefdiswgtkmc); txtrefdiswgtkmc=(EditText) findViewById(R.id.txtrefdiswgtkmc); secregdiswgtkmcnot=(LinearLayout)findViewById(R.id.secregdiswgtkmcnot); lineregdiswgtkmcnot=(View)findViewById(R.id.lineregdiswgtkmcnot); Vlblregdiswgtkmcnot = (TextView) findViewById(R.id.Vlblregdiswgtkmcnot); rdogrpregdiswgtkmcnot = (RadioGroup) findViewById(R.id.rdogrpregdiswgtkmcnot); rdoregdiswgtkmcnot1 = (RadioButton) findViewById(R.id.rdoregdiswgtkmcnot1); rdoregdiswgtkmcnot2 = (RadioButton) findViewById(R.id.rdoregdiswgtkmcnot2); dtprefdoe.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (dtprefdoe.getRight() - dtprefdoe.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnrefdoe"; showDialog(DATE_DIALOG); return true; } } return false; } }); dtprefdelivdate.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (dtprefdelivdate.getRight() - dtprefdelivdate.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnrefdelivdate"; showDialog(DATE_DIALOG); return true; } } return false; } }); dtprefdoadmkmc.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (dtprefdoadmkmc.getRight() - dtprefdoadmkmc.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnrefdoadmkmc"; showDialog(DATE_DIALOG); return true; } } return false; } }); dtprefdodkmc.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (dtprefdodkmc.getRight() - dtprefdodkmc.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnrefdodkmc"; showDialog(DATE_DIALOG); return true; } } return false; } }); txtrefdelivtime.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (txtrefdelivtime.getRight() - txtrefdelivtime.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnrefdelivtime"; showDialog(TIME_DIALOG); return true; } } return false; } }); txtreftoadmkmc.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (txtreftoadmkmc.getRight() - txtreftoadmkmc.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnreftoadmkmc"; showDialog(TIME_DIALOG); return true; } } return false; } }); txtrefbwgt.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtrefbwgt.getText().toString().length()>0) rdogrprefbwgtnot.clearCheck(); } }); rdogrprefbwgtnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefbwgtnot1.isChecked() | rdorefbwgtnot2.isChecked()) txtrefbwgt.setText(""); } }); txtrefgakmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtrefgakmc.getText().toString().length()>0) rdogrprefgakmcnot.clearCheck(); } }); rdogrprefgakmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefgakmcnot1.isChecked() | rdorefgakmcnot2.isChecked()) txtrefgakmc.setText(""); } }); txtrefadwgtkmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtrefadwgtkmc.getText().toString().length()>0) rdogrprefadwgtkmcnot.clearCheck(); } }); rdogrprefadwgtkmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefadwgtkmcnot1.isChecked()|rdorefadwgtkmcnot2.isChecked()) txtrefadwgtkmc.setText(""); } }); txtrefdiswgtkmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtrefdiswgtkmc.getText().toString().length()>0) rdogrpregdiswgtkmcnot.clearCheck(); } }); rdogrpregdiswgtkmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdoregdiswgtkmcnot1.isChecked() | rdoregdiswgtkmcnot2.isChecked()) txtrefdiswgtkmc.setText(""); } }); dtprefdelivdate.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(dtprefdelivdate.getText().toString().length()>0) rdogrprefdelivdatenot.clearCheck(); } }); rdogrprefdelivdatenot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefdelivdatenot1.isChecked() | rdorefdelivdatenot2.isChecked()) dtprefdelivdate.setText(""); } }); //--- txtrefdelivtime.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtrefdelivtime.getText().toString().length()>0) rdogrprefdelivtimenot.clearCheck(); } }); rdogrprefdelivtimenot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefdelivtimenot1.isChecked() | rdorefdelivtimenot2.isChecked()) txtrefdelivtime.setText(""); } }); //---- dtprefdoadmkmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(dtprefdoadmkmc.getText().toString().length()>0) rdogrprefdoadmkmcnot.clearCheck(); } }); rdogrprefdoadmkmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefdoadmkmcnot1.isChecked() | rdorefdoadmkmcnot2.isChecked()) dtprefdoadmkmc.setText(""); } }); //---- txtreftoadmkmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtreftoadmkmc.getText().toString().length()>0) rdogrpreftoadmkmcnot.clearCheck(); } }); rdogrpreftoadmkmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdoreftoadmkmcnot1.isChecked() | rdoreftoadmkmcnot2.isChecked()) txtreftoadmkmc.setText(""); } }); //---- dtprefdodkmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(dtprefdodkmc.getText().toString().length()>0) rdogrprefdodkmcnot.clearCheck(); } }); rdogrprefdodkmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefdodkmcnot1.isChecked() | rdorefdodkmcnot2.isChecked()) dtprefdodkmc.setText(""); } }); rdogrpstatus.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdostatus1.isChecked()){ secreason.setVisibility(View.GONE); rdogrpreason.clearCheck(); secreasmention.setVisibility(View.GONE); txtreasmention.setText(""); }else{ secreason.setVisibility(View.VISIBLE); secreasmention.setVisibility(View.VISIBLE); } } }); //Hide all skip variables secreason.setVisibility(View.GONE); secreasmention.setVisibility(View.GONE); secrefabskmcOth.setVisibility(View.GONE); linerefabskmcOth.setVisibility(View.GONE); secrefabskmcOth.setVisibility(View.GONE); linerefabskmcOth.setVisibility(View.GONE); //sec.setVisibility(View.GONE); //line.setVisibility(View.GONE); secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); secrefbfsupFOth.setVisibility(View.GONE); linerefbfsupFOth.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); DataSearch(COUNTRYCODE,FACICODE,DATAID); Button cmdSave = (Button) findViewById(R.id.cmdSave); cmdSave.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DataSave(); }}); } catch(Exception e) { Connection.MessageBox(KMC_DataExt.this, e.getMessage()); return; } } private void DataSave() { try { String DV=""; if(txtCountryCode.getText().toString().length()==0 & secCountryCode.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: CountryCode."); txtCountryCode.requestFocus(); return; } else if(Integer.valueOf(txtCountryCode.getText().toString().length()==0 ? "1" : txtCountryCode.getText().toString()) < 1 || Integer.valueOf(txtCountryCode.getText().toString().length()==0 ? "3" : txtCountryCode.getText().toString()) > 3) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 1 and 3(CountryCode)."); txtCountryCode.requestFocus(); return; } else if(txtFaciCode.getText().toString().length()==0 & secFaciCode.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Facility."); txtFaciCode.requestFocus(); return; } else if(Integer.valueOf(txtFaciCode.getText().toString().length()==0 ? "1" : txtFaciCode.getText().toString()) < 1 || Integer.valueOf(txtFaciCode.getText().toString().length()==0 ? "9" : txtFaciCode.getText().toString()) > 9) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 1 and 9(Facility)."); txtFaciCode.requestFocus(); return; } else if(txtDataID.getText().toString().length()==0 & secDataID.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Data ID."); txtDataID.requestFocus(); return; } DV = Global.DateValidate(dtprefdoe.getText().toString()); if(DV.length()!=0 & secrefdoe.isShown()) { Connection.MessageBox(KMC_DataExt.this, DV); dtprefdoe.requestFocus(); return; } else if(!rdorefabskmc1.isChecked() & !rdorefabskmc2.isChecked() & !rdorefabskmc3.isChecked() & secrefabskmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from (Source of Record)."); rdorefabskmc1.requestFocus(); return; } else if(txtrefabskmcOth.getText().toString().length()==0 & secrefabskmcOth.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Other Specify."); txtrefabskmcOth.requestFocus(); return; } else if(txtrefmatname.getText().toString().length()==0 & secrefmatname.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Mother’s name."); txtrefmatname.requestFocus(); return; } else if(txtrefmatage.getText().toString().length()==0 & secrefmatage.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Mother’s age (years)."); txtrefmatage.requestFocus(); return; } else if(Integer.valueOf(txtrefmatage.getText().toString().length()==0 ? "12" : txtrefmatage.getText().toString()) < 12 || Integer.valueOf(txtrefmatage.getText().toString().length()==0 ? "99" : txtrefmatage.getText().toString()) > 99) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 12 and 99(Mother’s age (years))."); txtrefmatage.requestFocus(); return; } else if(txtrefmatid.getText().toString().length()==0 & secrefmatid.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Mother’s ID."); txtrefmatid.requestFocus(); return; } /*else if(txtrefbname.getText().toString().length()==0 & secrefbname.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Child’s name, if available."); txtrefbname.requestFocus(); return; } else if(txtrefbid.getText().toString().length()==0 & secrefbid.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Child’s ID."); txtrefbid.requestFocus(); return; }*/ else if(!rdorefbsex1.isChecked() & !rdorefbsex2.isChecked() & !rdorefbsex3.isChecked() & !rdorefbsex4.isChecked() & !rdorefbsex5.isChecked() & secrefbsex.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from (Sex of Child)."); rdorefbsex1.requestFocus(); return; } DV = Global.DateValidate(dtprefdelivdate.getText().toString()); if(!rdorefdelivdatenot1.isChecked() & !rdorefdelivdatenot2.isChecked() & DV.length()!=0 & secrefdelivdate.isShown()) { Connection.MessageBox(KMC_DataExt.this, "This is not a valid date of delivery."); dtprefdelivdate.requestFocus(); return; } else if(!rdorefbwgtnot1.isChecked() & !rdorefbwgtnot2.isChecked() & txtrefbwgt.getText().toString().length()==0 & secrefbwgt.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Birth weight (grams)."); txtrefbwgt.requestFocus(); return; } else if(!rdorefbwgtnot1.isChecked() & !rdorefbwgtnot2.isChecked() & (Integer.valueOf(txtrefbwgt.getText().toString().length()==0 ? "400" : txtrefbwgt.getText().toString()) < 400 || Integer.valueOf(txtrefbwgt.getText().toString().length()==0 ? "9999" : txtrefbwgt.getText().toString()) > 9999)) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 400 and 9999(Birth weight (grams))."); txtrefbwgt.requestFocus(); return; } /*else if(!rdorefbwgtnot1.isChecked() & !rdorefbwgtnot2.isChecked() & secrefbwgtnot.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from ()."); rdorefbwgtnot1.requestFocus(); return; }*/ else if(!rdorefgakmcnot1.isChecked() & !rdorefgakmcnot2.isChecked() & txtrefgakmc.getText().toString().length()==0 & secrefgakmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Gestational age (completed weeks + days)."); txtrefgakmc.requestFocus(); return; } else if(!rdorefgakmcnot1.isChecked() & !rdorefgakmcnot2.isChecked() & (Integer.valueOf(txtrefgakmc.getText().toString().length()==0 ? "1" : txtrefgakmc.getText().toString()) < 1 || Integer.valueOf(txtrefgakmc.getText().toString().length()==0 ? "99" : txtrefgakmc.getText().toString()) > 99)) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 1 and 99(Gestational age (completed weeks + days))."); txtrefgakmc.requestFocus(); return; } /*else if(!rdorefgakmcnot1.isChecked() & !rdorefgakmcnot2.isChecked() & secrefgakmcnot.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from ()."); rdorefgakmcnot1.requestFocus(); return; }*/ else if(!rdorefbbornloc1.isChecked() & !rdorefbbornloc2.isChecked() & !rdorefbbornloc3.isChecked() & !rdorefbbornloc4.isChecked() & !rdorefbbornloc5.isChecked() & !rdorefbbornloc6.isChecked() & secrefbbornloc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from (Where the child was born?)."); rdorefbbornloc1.requestFocus(); return; } else if(txtrefbbornOth.getText().toString().length()==0 & secrefbbornOth.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Referred from."); txtrefbbornOth.requestFocus(); return; } else if(!rdorefdelivtimenot1.isChecked() & !rdorefdelivtimenot2.isChecked() & txtrefdelivtime.getText().length()==0 & secrefdelivtime.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Time of Delivery."); txtrefdelivtime.requestFocus(); return; } DV = Global.DateValidate(dtprefdoadmkmc.getText().toString()); if(!rdorefdoadmkmcnot1.isChecked() & !rdorefdoadmkmcnot2.isChecked() & DV.length()!=0 & secrefdoadmkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "11. This is not a valid Date of Admission to KMC"); dtprefdoadmkmc.requestFocus(); return; } else if(!rdoreftoadmkmcnot1.isChecked() & !rdoreftoadmkmcnot2.isChecked() & txtreftoadmkmc.getText().length()==0 & secreftoadmkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Time of Admission to KMC."); txtreftoadmkmc.requestFocus(); return; } else if(!rdorefadwgtkmcnot1.isChecked() & !rdorefadwgtkmcnot2.isChecked() & txtrefadwgtkmc.getText().toString().length()==0 & secrefadwgtkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Weight at admission to KMC (grams)."); txtrefadwgtkmc.requestFocus(); return; } else if(!rdorefadwgtkmcnot1.isChecked() & !rdorefadwgtkmcnot2.isChecked() & (Integer.valueOf(txtrefadwgtkmc.getText().toString().length()==0 ? "400" : txtrefadwgtkmc.getText().toString()) < 400 || Integer.valueOf(txtrefadwgtkmc.getText().toString().length()==0 ? "9999" : txtrefadwgtkmc.getText().toString()) > 9999)) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 400 and 9999(Weight at admission to KMC (grams))."); txtrefadwgtkmc.requestFocus(); return; } /*else if(!rdorefadwgtkmcnot1.isChecked() & !rdorefadwgtkmcnot2.isChecked() & secrefadwgtkmcnot.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from ()."); rdorefadwgtkmcnot1.requestFocus(); return; }*/ else if(txtrefbfsupFOth.getText().toString().length()==0 & secrefbfsupFOth.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Other Specify."); txtrefbfsupFOth.requestFocus(); return; } else if(!rdorefdisoutkmc1.isChecked() & !rdorefdisoutkmc2.isChecked() & !rdorefdisoutkmc3.isChecked() & !rdorefdisoutkmc4.isChecked() & !rdorefdisoutkmc5.isChecked() & !rdorefdisoutkmc6.isChecked() & !rdorefdisoutkmc7.isChecked() & secrefdisoutkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from (Outcome at discharge)."); rdorefdisoutkmc1.requestFocus(); return; } else if(txtreftransPlace.getText().toString().length()==0 & secreftransPlace.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Transferred alive where."); txtreftransPlace.requestFocus(); return; } DV = Global.DateValidate(dtprefdodkmc.getText().toString()); if(!rdorefdodkmcnot1.isChecked() & !rdorefdodkmcnot2.isChecked() & DV.length()!=0 & secrefdodkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "16.This is not a valid Date of discharge from KMC."); dtprefdodkmc.requestFocus(); return; } else if(!rdoregdiswgtkmcnot1.isChecked() & !rdoregdiswgtkmcnot2.isChecked() & txtrefdiswgtkmc.getText().toString().length()==0 & secrefdiswgtkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: If alive, weight at discharge/transfer from KMC (grams)."); txtrefdiswgtkmc.requestFocus(); return; } else if(!rdoregdiswgtkmcnot1.isChecked() & !rdoregdiswgtkmcnot2.isChecked() & (Integer.valueOf(txtrefdiswgtkmc.getText().toString().length()==0 ? "400" : txtrefdiswgtkmc.getText().toString()) < 400 || Integer.valueOf(txtrefdiswgtkmc.getText().toString().length()==0 ? "9999" : txtrefdiswgtkmc.getText().toString()) > 9999)) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 400 and 9999(If alive, weight at discharge/transfer from KMC (grams))."); txtrefdiswgtkmc.requestFocus(); return; } else if(!rdostatus1.isChecked() & !rdostatus2.isChecked() & !rdostatus3.isChecked() & secstatus.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: 18. What is the final status of the Recall Survey for this patient"); rdostatus1.requestFocus(); return; } else if(!rdoreason1.isChecked() & !rdoreason2.isChecked() & !rdoreason3.isChecked() & !rdoreason4.isChecked() & secreason.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: 19. Why partially incomplete or totally incomplete?"); rdoreason1.requestFocus(); return; } /*else if(!rdoregdiswgtkmcnot1.isChecked() & !rdoregdiswgtkmcnot2.isChecked() & secregdiswgtkmcnot.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from ()."); rdoregdiswgtkmcnot1.requestFocus(); return; }*/ String SQL = ""; RadioButton rb; KMC_DataExt_DataModel objSave = new KMC_DataExt_DataModel(); objSave.setCountryCode(txtCountryCode.getText().toString()); objSave.setFaciCode(txtFaciCode.getText().toString()); objSave.setDataID(txtDataID.getText().toString()); objSave.setrefdoe(dtprefdoe.getText().toString().length() > 0 ? Global.DateConvertYMD(dtprefdoe.getText().toString()) : dtprefdoe.getText().toString()); String[] d_rdogrprefabskmc = new String[] {"1","2","3"}; objSave.setrefabskmc(""); for (int i = 0; i < rdogrprefabskmc.getChildCount(); i++) { rb = (RadioButton)rdogrprefabskmc.getChildAt(i); if (rb.isChecked()) objSave.setrefabskmc(d_rdogrprefabskmc[i]); } objSave.setrefabskmcOth(txtrefabskmcOth.getText().toString()); objSave.setrefmatname(txtrefmatname.getText().toString()); objSave.setrefmatage(txtrefmatage.getText().toString()); objSave.setrefmatid(txtrefmatid.getText().toString()); objSave.setrefbname(txtrefbname.getText().toString()); objSave.setrefbid(txtrefbid.getText().toString()); String[] d_rdogrprefbsex = new String[] {"1","2","3","8","9"}; objSave.setrefbsex(""); for (int i = 0; i < rdogrprefbsex.getChildCount(); i++) { rb = (RadioButton)rdogrprefbsex.getChildAt(i); if (rb.isChecked()) objSave.setrefbsex(d_rdogrprefbsex[i]); } objSave.setrefdelivdate(dtprefdelivdate.getText().toString().length() > 0 ? Global.DateConvertYMD(dtprefdelivdate.getText().toString()) : dtprefdelivdate.getText().toString()); if(rdorefdelivdatenot1.isChecked()) objSave.setrefdelivdatenot("1"); else if(rdorefdelivdatenot2.isChecked()) objSave.setrefdelivdatenot("2"); else objSave.setrefdelivdatenot(""); objSave.setrefbwgt(txtrefbwgt.getText().toString()); String[] d_rdogrprefbwgtnot = new String[] {"1","2"}; objSave.setrefbwgtnot(""); for (int i = 0; i < rdogrprefbwgtnot.getChildCount(); i++) { rb = (RadioButton)rdogrprefbwgtnot.getChildAt(i); if (rb.isChecked()) objSave.setrefbwgtnot(d_rdogrprefbwgtnot[i]); } objSave.setrefgakmc(txtrefgakmc.getText().toString()); String[] d_rdogrprefgakmcnot = new String[] {"1","2"}; objSave.setrefgakmcnot(""); for (int i = 0; i < rdogrprefgakmcnot.getChildCount(); i++) { rb = (RadioButton)rdogrprefgakmcnot.getChildAt(i); if (rb.isChecked()) objSave.setrefgakmcnot(d_rdogrprefgakmcnot[i]); } String[] d_rdogrprefbbornloc = new String[] {"1","2","3","4","6","9"}; objSave.setrefbbornloc(""); for (int i = 0; i < rdogrprefbbornloc.getChildCount(); i++) { rb = (RadioButton)rdogrprefbbornloc.getChildAt(i); if (rb.isChecked()) objSave.setrefbbornloc(d_rdogrprefbbornloc[i]); } objSave.setrefbbornOth(txtrefbbornOth.getText().toString()); objSave.setrefdelivtime(txtrefdelivtime.getText().toString()); if(rdorefdelivtimenot1.isChecked()) objSave.setrefdelivtimenot("1"); else if(rdorefdelivtimenot2.isChecked()) objSave.setrefdelivtimenot("2"); else objSave.setrefdelivtimenot(""); objSave.setrefdoadmkmc(dtprefdoadmkmc.getText().toString().length() > 0 ? Global.DateConvertYMD(dtprefdoadmkmc.getText().toString()) : dtprefdoadmkmc.getText().toString()); if(rdorefdoadmkmcnot1.isChecked()) objSave.setrefdoadmkmcnot("1"); else if(rdorefdoadmkmcnot2.isChecked()) objSave.setrefdoadmkmcnot("2"); else objSave.setrefdoadmkmcnot(""); objSave.setreftoadmkmc(txtreftoadmkmc.getText().toString()); if(rdoreftoadmkmcnot1.isChecked()) objSave.setreftoadmkmcnot("1"); else if(rdoreftoadmkmcnot2.isChecked()) objSave.setreftoadmkmcnot("2"); else objSave.setreftoadmkmcnot(""); objSave.setrefadwgtkmc(txtrefadwgtkmc.getText().toString()); String[] d_rdogrprefadwgtkmcnot = new String[] {"1","2"}; objSave.setrefadwgtkmcnot(""); for (int i = 0; i < rdogrprefadwgtkmcnot.getChildCount(); i++) { rb = (RadioButton)rdogrprefadwgtkmcnot.getChildAt(i); if (rb.isChecked()) objSave.setrefadwgtkmcnot(d_rdogrprefadwgtkmcnot[i]); } objSave.setrefbfsupA((chkrefbfsupA.isChecked()?"1":(secrefbfsupA.isShown()?"2":""))); objSave.setrefbfsupB((chkrefbfsupB.isChecked()?"1":(secrefbfsupB.isShown()?"2":""))); objSave.setrefbfsupC((chkrefbfsupC.isChecked()?"1":(secrefbfsupC.isShown()?"2":""))); objSave.setrefbfsupD((chkrefbfsupD.isChecked()?"1":(secrefbfsupD.isShown()?"2":""))); objSave.setrefbfsupE((chkrefbfsupE.isChecked()?"1":(secrefbfsupE.isShown()?"2":""))); objSave.setrefbfsupF((chkrefbfsupF.isChecked()?"1":(secrefbfsupF.isShown()?"2":""))); objSave.setrefbfsupFOth(txtrefbfsupFOth.getText().toString()); String[] d_rdogrprefdisoutkmc = new String[] {"1","2","3","4","5","8","9"}; objSave.setrefdisoutkmc(""); for (int i = 0; i < rdogrprefdisoutkmc.getChildCount(); i++) { rb = (RadioButton)rdogrprefdisoutkmc.getChildAt(i); if (rb.isChecked()) objSave.setrefdisoutkmc(d_rdogrprefdisoutkmc[i]); } objSave.setreftransPlace(txtreftransPlace.getText().toString()); objSave.setrefdodkmc(dtprefdodkmc.getText().toString().length() > 0 ? Global.DateConvertYMD(dtprefdodkmc.getText().toString()) : dtprefdodkmc.getText().toString()); if(rdorefdodkmcnot1.isChecked()) objSave.setrefdodkmcnot("1"); else if(rdorefdodkmcnot2.isChecked()) objSave.setrefdodkmcnot("2"); else objSave.setrefdodkmcnot(""); objSave.setrefdiswgtkmc(txtrefdiswgtkmc.getText().toString()); String[] d_rdogrpregdiswgtkmcnot = new String[] {"1","2"}; objSave.setregdiswgtkmcnot(""); for (int i = 0; i < rdogrpregdiswgtkmcnot.getChildCount(); i++) { rb = (RadioButton)rdogrpregdiswgtkmcnot.getChildAt(i); if (rb.isChecked()) objSave.setregdiswgtkmcnot(d_rdogrpregdiswgtkmcnot[i]); } //Status String[] d_rdogrpstatus = new String[] {"1","2","3"}; objSave.setStatus(""); for (int i = 0; i < rdogrpstatus.getChildCount(); i++) { rb = (RadioButton)rdogrpstatus.getChildAt(i); if (rb.isChecked()) objSave.setStatus(d_rdogrpstatus[i]); } String[] d_rdogrpreason = new String[] {"1","2","3","4"}; objSave.setReason(""); for (int i = 0; i < rdogrpreason.getChildCount(); i++) { rb = (RadioButton)rdogrpreason.getChildAt(i); if (rb.isChecked()) objSave.setReason(d_rdogrpreason[i]); } objSave.setReasmention(txtreasmention.getText().toString()); objSave.setEnDt(Global.DateTimeNowYMDHMS()); objSave.setStartTime(STARTTIME); objSave.setEndTime(g.CurrentTime24()); objSave.setDeviceID(DEVICEID); objSave.setEntryUser(ENTRYUSER); //from data entry user list objSave.setmodifyDate(Global.DateTimeNowYMDHMS()); //objSave.setLat(Double.toString(currentLatitude)); //objSave.setLon(Double.toString(currentLongitude)); String status = objSave.SaveUpdateData(this); if(status.length()==0) { C.SaveDT("Update Registration set StatusDE='1',Upload='2',modifyDate='"+ Global.DateTimeNowYMDHMS() +"' where CountryCode='" + COUNTRYCODE + "' and FaciCode='" + FACICODE + "' and DataId='" + DATAID + "'"); Intent returnIntent = new Intent(); returnIntent.putExtra("res", ""); setResult(Activity.RESULT_OK, returnIntent); Connection.MessageBox(KMC_DataExt.this, "Saved Successfully"); } else{ Connection.MessageBox(KMC_DataExt.this, status); return; } } catch(Exception e) { Connection.MessageBox(KMC_DataExt.this, e.getMessage()); return; } } private void DataSearch(String CountryCode, String FaciCode, String DataID) { try { RadioButton rb; KMC_DataExt_DataModel d = new KMC_DataExt_DataModel(); String SQL = "Select * from "+ TableName +" Where CountryCode='"+ CountryCode +"' and FaciCode='"+ FaciCode +"' and DataID='"+ DataID +"'"; List<KMC_DataExt_DataModel> data = d.SelectAll(this, SQL); for(KMC_DataExt_DataModel item : data){ txtCountryCode.setText(item.getCountryCode()); txtFaciCode.setText(item.getFaciCode()); txtDataID.setText(item.getDataID()); dtprefdoe.setText(item.getrefdoe().toString().length()==0 ? "" : Global.DateConvertDMY(item.getrefdoe())); String[] d_rdogrprefabskmc = new String[] {"1","2","3"}; for (int i = 0; i < d_rdogrprefabskmc.length; i++) { if (item.getrefabskmc().equals(String.valueOf(d_rdogrprefabskmc[i]))) { rb = (RadioButton)rdogrprefabskmc.getChildAt(i); rb.setChecked(true); } } txtrefabskmcOth.setText(item.getrefabskmcOth()); txtrefmatname.setText(item.getrefmatname()); txtrefmatage.setText(item.getrefmatage()); txtrefmatid.setText(item.getrefmatid()); txtrefbname.setText(item.getrefbname()); txtrefbid.setText(item.getrefbid()); String[] d_rdogrprefbsex = new String[] {"1","2","3","8","9"}; for (int i = 0; i < d_rdogrprefbsex.length; i++) { if (item.getrefbsex().equals(String.valueOf(d_rdogrprefbsex[i]))) { rb = (RadioButton)rdogrprefbsex.getChildAt(i); rb.setChecked(true); } } dtprefdelivdate.setText(item.getrefdelivdate().toString().length()==0 ? "" : Global.DateConvertDMY(item.getrefdelivdate())); if(item.getrefdelivdatenot().equals("1")) rdorefdelivdatenot1.setChecked(true); else if(item.getrefdelivdatenot().equals("2")) rdorefdelivdatenot2.setChecked(true); txtrefbwgt.setText(item.getrefbwgt()); String[] d_rdogrprefbwgtnot = new String[] {"1","2"}; for (int i = 0; i < d_rdogrprefbwgtnot.length; i++) { if (item.getrefbwgtnot().equals(String.valueOf(d_rdogrprefbwgtnot[i]))) { rb = (RadioButton)rdogrprefbwgtnot.getChildAt(i); rb.setChecked(true); } } txtrefgakmc.setText(item.getrefgakmc()); String[] d_rdogrprefgakmcnot = new String[] {"1","2"}; for (int i = 0; i < d_rdogrprefgakmcnot.length; i++) { if (item.getrefgakmcnot().equals(String.valueOf(d_rdogrprefgakmcnot[i]))) { rb = (RadioButton)rdogrprefgakmcnot.getChildAt(i); rb.setChecked(true); } } String[] d_rdogrprefbbornloc = new String[] {"1","2","3","4","6","9"}; for (int i = 0; i < d_rdogrprefbbornloc.length; i++) { if (item.getrefbbornloc().equals(String.valueOf(d_rdogrprefbbornloc[i]))) { rb = (RadioButton)rdogrprefbbornloc.getChildAt(i); rb.setChecked(true); } } txtrefbbornOth.setText(item.getrefbbornOth()); txtrefdelivtime.setText(item.getrefdelivtime()); if(item.getrefdelivtimenot().equals("1")) rdorefdelivtimenot1.setChecked(true); else if(item.getrefdelivtimenot().equals("2")) rdorefdelivtimenot2.setChecked(true); dtprefdoadmkmc.setText(item.getrefdoadmkmc().toString().length()==0 ? "" : Global.DateConvertDMY(item.getrefdoadmkmc())); if(item.getrefdoadmkmcnot().equals("1")) rdorefdoadmkmcnot1.setChecked(true); else if(item.getrefdoadmkmcnot().equals("2")) rdorefdoadmkmcnot2.setChecked(true); txtreftoadmkmc.setText(item.getreftoadmkmc()); if(item.getreftoadmkmcnot().equals("1")) rdoreftoadmkmcnot1.setChecked(true); else if(item.getreftoadmkmcnot().equals("2")) rdoreftoadmkmcnot2.setChecked(true); txtrefadwgtkmc.setText(item.getrefadwgtkmc()); String[] d_rdogrprefadwgtkmcnot = new String[] {"1","2"}; for (int i = 0; i < d_rdogrprefadwgtkmcnot.length; i++) { if (item.getrefadwgtkmcnot().equals(String.valueOf(d_rdogrprefadwgtkmcnot[i]))) { rb = (RadioButton)rdogrprefadwgtkmcnot.getChildAt(i); rb.setChecked(true); } } if(item.getrefbfsupA().equals("1")) { chkrefbfsupA.setChecked(true); } else if(item.getrefbfsupA().equals("2")) { chkrefbfsupA.setChecked(false); } if(item.getrefbfsupB().equals("1")) { chkrefbfsupB.setChecked(true); } else if(item.getrefbfsupB().equals("2")) { chkrefbfsupB.setChecked(false); } if(item.getrefbfsupC().equals("1")) { chkrefbfsupC.setChecked(true); } else if(item.getrefbfsupC().equals("2")) { chkrefbfsupC.setChecked(false); } if(item.getrefbfsupD().equals("1")) { chkrefbfsupD.setChecked(true); } else if(item.getrefbfsupD().equals("2")) { chkrefbfsupD.setChecked(false); } if(item.getrefbfsupE().equals("1")) { chkrefbfsupE.setChecked(true); } else if(item.getrefbfsupE().equals("2")) { chkrefbfsupE.setChecked(false); } if(item.getrefbfsupF().equals("1")) { chkrefbfsupF.setChecked(true); } else if(item.getrefbfsupF().equals("2")) { chkrefbfsupF.setChecked(false); } txtrefbfsupFOth.setText(item.getrefbfsupFOth()); String[] d_rdogrprefdisoutkmc = new String[] {"1","2","3","4","5","8","9"}; for (int i = 0; i < d_rdogrprefdisoutkmc.length; i++) { if (item.getrefdisoutkmc().equals(String.valueOf(d_rdogrprefdisoutkmc[i]))) { rb = (RadioButton)rdogrprefdisoutkmc.getChildAt(i); rb.setChecked(true); } } txtreftransPlace.setText(item.getreftransPlace()); dtprefdodkmc.setText(item.getrefdodkmc().toString().length()==0 ? "" : Global.DateConvertDMY(item.getrefdodkmc())); if(item.getrefdodkmcnot().equals("1")) rdorefdodkmcnot1.setChecked(true); else if(item.getrefdodkmcnot().equals("2")) rdorefdodkmcnot2.setChecked(true); txtrefdiswgtkmc.setText(item.getrefdiswgtkmc()); String[] d_rdogrpregdiswgtkmcnot = new String[] {"1","2"}; for (int i = 0; i < d_rdogrpregdiswgtkmcnot.length; i++) { if (item.getregdiswgtkmcnot().equals(String.valueOf(d_rdogrpregdiswgtkmcnot[i]))) { rb = (RadioButton)rdogrpregdiswgtkmcnot.getChildAt(i); rb.setChecked(true); } } //Status String[] d_rdogrpstatus = new String[] {"1","2","3"}; for (int i = 0; i < d_rdogrpstatus.length; i++) { if (item.getStatus().equals(String.valueOf(d_rdogrpstatus[i]))) { rb = (RadioButton)rdogrpstatus.getChildAt(i); rb.setChecked(true); } } String[] d_rdogrpreason = new String[] {"1","2","3","4"}; for (int i = 0; i < d_rdogrpreason.length; i++) { if (item.getReason().equals(String.valueOf(d_rdogrpreason[i]))) { rb = (RadioButton)rdogrpreason.getChildAt(i); rb.setChecked(true); } } txtreasmention.setText(item.getReasmention()); } } catch(Exception e) { Connection.MessageBox(KMC_DataExt.this, e.getMessage()); return; } } protected Dialog onCreateDialog(int id) { final Calendar c = Calendar.getInstance(); hour = c.get(Calendar.HOUR_OF_DAY); minute = c.get(Calendar.MINUTE); switch (id) { case DATE_DIALOG: return new DatePickerDialog(this, mDateSetListener,g.mYear,g.mMonth-1,g.mDay); case TIME_DIALOG: return new TimePickerDialog(this, timePickerListener, hour, minute,false); } return null; } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear+1; mDay = dayOfMonth; EditText dtpDate; dtpDate = (EditText)findViewById(R.id.dtprefdoe); if (VariableID.equals("btnrefdoe")) { dtpDate = (EditText)findViewById(R.id.dtprefdoe); } else if (VariableID.equals("btnrefdelivdate")) { dtpDate = (EditText)findViewById(R.id.dtprefdelivdate); } else if (VariableID.equals("btnrefdoadmkmc")) { dtpDate = (EditText)findViewById(R.id.dtprefdoadmkmc); } else if (VariableID.equals("btnrefdodkmc")) { dtpDate = (EditText)findViewById(R.id.dtprefdodkmc); } dtpDate.setText(new StringBuilder() .append(Global.Right("00"+mDay,2)).append("/") .append(Global.Right("00"+mMonth,2)).append("/") .append(mYear)); } }; private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) { hour = selectedHour; minute = selectedMinute; EditText tpTime; tpTime = (EditText)findViewById(R.id.txtrefdelivtime); if (VariableID.equals("btnrefdelivtime")) { tpTime = (EditText)findViewById(R.id.txtrefdelivtime); } else if (VariableID.equals("btnreftoadmkmc")) { tpTime = (EditText)findViewById(R.id.txtreftoadmkmc); } tpTime.setText(new StringBuilder().append(Global.Right("00"+hour,2)).append(":").append(Global.Right("00"+minute,2))); } }; //GPS Reading //..................................................................................................... public void FindLocation() { LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { updateLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } void updateLocation(Location location) { currentLocation = location; currentLatitude = currentLocation.getLatitude(); currentLongitude = currentLocation.getLongitude(); } // Method to turn on GPS public void turnGPSOn(){ try { String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(!provider.contains("gps")){ //if gps is disabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); } } catch (Exception e) { } } // Method to turn off the GPS public void turnGPSOff(){ String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(provider.contains("gps")){ //if gps is enabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); } } // turning off the GPS if its in on state. to avoid the battery drain. @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); turnGPSOff(); } }
UTF-8
Java
83,675
java
KMC_DataExt.java
Java
[]
null
[]
package org.icddrb.enap; //Android Manifest Code //<activity android:name=".KMC_DataExt" android:label="KMC_DataExt" /> import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import android.app.*; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.provider.Settings; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.MotionEvent; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.BaseAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.graphics.Color; import Utility.*; import Common.*; public class KMC_DataExt extends Activity { boolean networkAvailable=false; Location currentLocation; double currentLatitude,currentLongitude; //Disabled Back/Home key //-------------------------------------------------------------------------------------------------- @Override public boolean onKeyDown(int iKeyCode, KeyEvent event) { if(iKeyCode == KeyEvent.KEYCODE_BACK || iKeyCode == KeyEvent.KEYCODE_HOME) { return false; } else { return true; } } String VariableID; private int hour; private int minute; private int mDay; private int mMonth; private int mYear; static final int DATE_DIALOG = 1; static final int TIME_DIALOG = 2; Connection C; Global g; SimpleAdapter dataAdapter; ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>(); LinearLayout secstatus; RadioGroup rdogrpstatus; RadioButton rdostatus1; RadioButton rdostatus2; RadioButton rdostatus3; LinearLayout secreason; RadioGroup rdogrpreason; RadioButton rdoreason1; RadioButton rdoreason2; RadioButton rdoreason3; RadioButton rdoreason4; LinearLayout secreasmention; EditText txtreasmention; LinearLayout secrefdelivdatenot; RadioGroup rdogrprefdelivdatenot; RadioButton rdorefdelivdatenot1; RadioButton rdorefdelivdatenot2; LinearLayout secrefdelivtimenot; RadioGroup rdogrprefdelivtimenot; RadioButton rdorefdelivtimenot1; RadioButton rdorefdelivtimenot2; LinearLayout secrefdoadmkmcnot; RadioGroup rdogrprefdoadmkmcnot; RadioButton rdorefdoadmkmcnot1; RadioButton rdorefdoadmkmcnot2; LinearLayout secreftoadmkmcnot; RadioGroup rdogrpreftoadmkmcnot; RadioButton rdoreftoadmkmcnot1; RadioButton rdoreftoadmkmcnot2; LinearLayout secrefdodkmcnot; RadioGroup rdogrprefdodkmcnot; RadioButton rdorefdodkmcnot1; RadioButton rdorefdodkmcnot2; TextView lblHeading; LinearLayout seclbl01; View linelbl01; LinearLayout secCountryCode; View lineCountryCode; TextView VlblCountryCode; EditText txtCountryCode; LinearLayout secFaciCode; View lineFaciCode; TextView VlblFaciCode; EditText txtFaciCode; LinearLayout secDataID; View lineDataID; TextView VlblDataID; EditText txtDataID; LinearLayout secrefdoe; View linerefdoe; TextView Vlblrefdoe; EditText dtprefdoe; LinearLayout secrefabskmc; View linerefabskmc; TextView Vlblrefabskmc; RadioGroup rdogrprefabskmc; RadioButton rdorefabskmc1; RadioButton rdorefabskmc2; RadioButton rdorefabskmc3; LinearLayout secrefabskmcOth; View linerefabskmcOth; TextView VlblrefabskmcOth; EditText txtrefabskmcOth; LinearLayout secrefmatname; View linerefmatname; TextView Vlblrefmatname; EditText txtrefmatname; LinearLayout secrefmatage; View linerefmatage; TextView Vlblrefmatage; EditText txtrefmatage; LinearLayout secrefmatid; View linerefmatid; TextView Vlblrefmatid; EditText txtrefmatid; LinearLayout secrefbname; View linerefbname; TextView Vlblrefbname; EditText txtrefbname; LinearLayout secrefbid; View linerefbid; TextView Vlblrefbid; EditText txtrefbid; LinearLayout secrefbsex; View linerefbsex; TextView Vlblrefbsex; RadioGroup rdogrprefbsex; RadioButton rdorefbsex1; RadioButton rdorefbsex2; RadioButton rdorefbsex3; RadioButton rdorefbsex4; RadioButton rdorefbsex5; LinearLayout secrefdelivdate; View linerefdelivdate; TextView Vlblrefdelivdate; EditText dtprefdelivdate; LinearLayout secrefbwgt; View linerefbwgt; TextView Vlblrefbwgt; EditText txtrefbwgt; LinearLayout secrefbwgtnot; View linerefbwgtnot; TextView Vlblrefbwgtnot; RadioGroup rdogrprefbwgtnot; RadioButton rdorefbwgtnot1; RadioButton rdorefbwgtnot2; LinearLayout secrefgakmc; View linerefgakmc; TextView Vlblrefgakmc; EditText txtrefgakmc; LinearLayout secrefgakmcnot; View linerefgakmcnot; TextView Vlblrefgakmcnot; RadioGroup rdogrprefgakmcnot; RadioButton rdorefgakmcnot1; RadioButton rdorefgakmcnot2; LinearLayout secrefbbornloc; View linerefbbornloc; TextView Vlblrefbbornloc; RadioGroup rdogrprefbbornloc; RadioButton rdorefbbornloc1; RadioButton rdorefbbornloc2; RadioButton rdorefbbornloc3; RadioButton rdorefbbornloc4; RadioButton rdorefbbornloc5; RadioButton rdorefbbornloc6; LinearLayout secrefbbornOth; View linerefbbornOth; TextView VlblrefbbornOth; EditText txtrefbbornOth; LinearLayout secrefdelivtime; View linerefdelivtime; TextView Vlblrefdelivtime; EditText txtrefdelivtime; LinearLayout secrefdoadmkmc; View linerefdoadmkmc; TextView Vlblrefdoadmkmc; EditText dtprefdoadmkmc; LinearLayout secreftoadmkmc; View linereftoadmkmc; TextView Vlblreftoadmkmc; EditText txtreftoadmkmc; LinearLayout secrefadwgtkmc; View linerefadwgtkmc; TextView Vlblrefadwgtkmc; EditText txtrefadwgtkmc; LinearLayout secrefadwgtkmcnot; View linerefadwgtkmcnot; TextView Vlblrefadwgtkmcnot; RadioGroup rdogrprefadwgtkmcnot; RadioButton rdorefadwgtkmcnot1; RadioButton rdorefadwgtkmcnot2; LinearLayout seclblrefbfsup; View linelblrefbfsup; LinearLayout secrefbfsupA; View linerefbfsupA; TextView VlblrefbfsupA; CheckBox chkrefbfsupA; LinearLayout secrefbfsupB; View linerefbfsupB; TextView VlblrefbfsupB; CheckBox chkrefbfsupB; LinearLayout secrefbfsupC; View linerefbfsupC; TextView VlblrefbfsupC; CheckBox chkrefbfsupC; LinearLayout secrefbfsupD; View linerefbfsupD; TextView VlblrefbfsupD; CheckBox chkrefbfsupD; LinearLayout secrefbfsupE; View linerefbfsupE; TextView VlblrefbfsupE; CheckBox chkrefbfsupE; LinearLayout secrefbfsupF; View linerefbfsupF; TextView VlblrefbfsupF; CheckBox chkrefbfsupF; LinearLayout secrefbfsupFOth; View linerefbfsupFOth; TextView VlblrefbfsupFOth; EditText txtrefbfsupFOth; LinearLayout secrefdisoutkmc; View linerefdisoutkmc; TextView Vlblrefdisoutkmc; RadioGroup rdogrprefdisoutkmc; RadioButton rdorefdisoutkmc1; RadioButton rdorefdisoutkmc2; RadioButton rdorefdisoutkmc3; RadioButton rdorefdisoutkmc4; RadioButton rdorefdisoutkmc5; RadioButton rdorefdisoutkmc6; RadioButton rdorefdisoutkmc7; LinearLayout secreftransPlace; View linereftransPlace; TextView VlblreftransPlace; EditText txtreftransPlace; LinearLayout secrefdodkmc; View linerefdodkmc; TextView Vlblrefdodkmc; EditText dtprefdodkmc; LinearLayout secrefdiswgtkmc; View linerefdiswgtkmc; TextView Vlblrefdiswgtkmc; EditText txtrefdiswgtkmc; LinearLayout secregdiswgtkmcnot; View lineregdiswgtkmcnot; TextView Vlblregdiswgtkmcnot; RadioGroup rdogrpregdiswgtkmcnot; RadioButton rdoregdiswgtkmcnot1; RadioButton rdoregdiswgtkmcnot2; static String TableName; static String STARTTIME = ""; static String DEVICEID = ""; static String ENTRYUSER = ""; MySharedPreferences sp; Bundle IDbundle; static String COUNTRYCODE = ""; static String FACICODE = ""; static String DATAID = ""; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.kmc_dataext); C = new Connection(this); g = Global.getInstance(); STARTTIME = g.CurrentTime24(); DEVICEID = sp.getValue(this, "deviceid"); ENTRYUSER = sp.getValue(this, "userid"); IDbundle = getIntent().getExtras(); COUNTRYCODE = IDbundle.getString("CountryCode"); FACICODE = IDbundle.getString("FaciCode"); DATAID = IDbundle.getString("DataID"); TableName = "KMC_DataExt"; //turnGPSOn(); //GPS Location //FindLocation(); // Double.toString(currentLatitude); // Double.toString(currentLongitude); lblHeading = (TextView)findViewById(R.id.lblHeading); ImageButton cmdBack = (ImageButton) findViewById(R.id.cmdBack); cmdBack.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { AlertDialog.Builder adb = new AlertDialog.Builder(KMC_DataExt.this); adb.setTitle("Close"); adb.setMessage("Do you want to close this form[Yes/No]?"); adb.setNegativeButton("No", null); adb.setPositiveButton("Yes", new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); }}); adb.show(); }}); secstatus=(LinearLayout)findViewById(R.id.secstatus) ; rdogrpstatus=(RadioGroup)findViewById(R.id.rdogrpstatus) ; rdostatus1=(RadioButton)findViewById(R.id.rdostatus1) ; rdostatus2=(RadioButton)findViewById(R.id.rdostatus2) ; rdostatus3=(RadioButton)findViewById(R.id.rdostatus3) ; secreason=(LinearLayout)findViewById(R.id.secreason) ; rdogrpreason=(RadioGroup)findViewById(R.id.rdogrpreason) ; rdoreason1=(RadioButton)findViewById(R.id.rdoreason1) ; rdoreason2=(RadioButton)findViewById(R.id.rdoreason2) ; rdoreason3=(RadioButton)findViewById(R.id.rdoreason3) ; rdoreason4=(RadioButton)findViewById(R.id.rdoreason4) ; secreasmention=(LinearLayout)findViewById(R.id.secreasmention) ; txtreasmention=(EditText)findViewById(R.id.txtreasmention) ; secrefdelivdatenot=(LinearLayout)findViewById(R.id.secrefdelivdatenot) ; rdogrprefdelivdatenot=(RadioGroup)findViewById(R.id.rdogrprefdelivdatenot) ; rdorefdelivdatenot1=(RadioButton)findViewById(R.id.rdorefdelivdatenot1) ; rdorefdelivdatenot2=(RadioButton)findViewById(R.id.rdorefdelivdatenot2) ; secrefdelivtimenot=(LinearLayout)findViewById(R.id.secrefdelivtimenot) ; rdogrprefdelivtimenot=(RadioGroup)findViewById(R.id.rdogrprefdelivtimenot) ; rdorefdelivtimenot1=(RadioButton)findViewById(R.id.rdorefdelivtimenot1) ; rdorefdelivtimenot2=(RadioButton)findViewById(R.id.rdorefdelivtimenot2) ; secrefdoadmkmcnot=(LinearLayout)findViewById(R.id.secrefdoadmkmcnot) ; rdogrprefdoadmkmcnot=(RadioGroup)findViewById(R.id.rdogrprefdoadmkmcnot) ; rdorefdoadmkmcnot1=(RadioButton)findViewById(R.id.rdorefdoadmkmcnot1) ; rdorefdoadmkmcnot2=(RadioButton)findViewById(R.id.rdorefdoadmkmcnot2) ; secreftoadmkmcnot=(LinearLayout)findViewById(R.id.secreftoadmkmcnot) ; rdogrpreftoadmkmcnot=(RadioGroup)findViewById(R.id.rdogrpreftoadmkmcnot) ; rdoreftoadmkmcnot1=(RadioButton)findViewById(R.id.rdoreftoadmkmcnot1) ; rdoreftoadmkmcnot2=(RadioButton)findViewById(R.id.rdoreftoadmkmcnot2) ; secrefdodkmcnot=(LinearLayout)findViewById(R.id.secrefdodkmcnot) ; rdogrprefdodkmcnot=(RadioGroup)findViewById(R.id.rdogrprefdodkmcnot) ; rdorefdodkmcnot1=(RadioButton)findViewById(R.id.rdorefdodkmcnot1) ; rdorefdodkmcnot2=(RadioButton)findViewById(R.id.rdorefdodkmcnot2) ; seclbl01=(LinearLayout)findViewById(R.id.seclbl01); linelbl01=(View)findViewById(R.id.linelbl01); secCountryCode=(LinearLayout)findViewById(R.id.secCountryCode); lineCountryCode=(View)findViewById(R.id.lineCountryCode); VlblCountryCode=(TextView) findViewById(R.id.VlblCountryCode); txtCountryCode=(EditText) findViewById(R.id.txtCountryCode); txtCountryCode.setText(COUNTRYCODE); secFaciCode=(LinearLayout)findViewById(R.id.secFaciCode); lineFaciCode=(View)findViewById(R.id.lineFaciCode); VlblFaciCode=(TextView) findViewById(R.id.VlblFaciCode); txtFaciCode=(EditText) findViewById(R.id.txtFaciCode); txtFaciCode.setText(FACICODE); secDataID=(LinearLayout)findViewById(R.id.secDataID); lineDataID=(View)findViewById(R.id.lineDataID); VlblDataID=(TextView) findViewById(R.id.VlblDataID); txtDataID=(EditText) findViewById(R.id.txtDataID); txtDataID.setText(DATAID); secrefdoe=(LinearLayout)findViewById(R.id.secrefdoe); linerefdoe=(View)findViewById(R.id.linerefdoe); Vlblrefdoe=(TextView) findViewById(R.id.Vlblrefdoe); dtprefdoe=(EditText) findViewById(R.id.dtprefdoe); dtprefdoe.setText(Global.DateNowDMY()); secrefabskmc=(LinearLayout)findViewById(R.id.secrefabskmc); linerefabskmc=(View)findViewById(R.id.linerefabskmc); Vlblrefabskmc = (TextView) findViewById(R.id.Vlblrefabskmc); rdogrprefabskmc = (RadioGroup) findViewById(R.id.rdogrprefabskmc); rdorefabskmc1 = (RadioButton) findViewById(R.id.rdorefabskmc1); rdorefabskmc2 = (RadioButton) findViewById(R.id.rdorefabskmc2); rdorefabskmc3 = (RadioButton) findViewById(R.id.rdorefabskmc3); rdogrprefabskmc.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup radioGroup,int radioButtonID) { String rbData = ""; RadioButton rb; String[] d_rdogrprefabskmc = new String[] {"1","2","3"}; for (int i = 0; i < rdogrprefabskmc.getChildCount(); i++) { rb = (RadioButton)rdogrprefabskmc.getChildAt(i); if (rb.isChecked()) rbData = d_rdogrprefabskmc[i]; } if(rbData.equalsIgnoreCase("1")) { secrefabskmcOth.setVisibility(View.GONE); linerefabskmcOth.setVisibility(View.GONE); txtrefabskmcOth.setText(""); } else if(rbData.equalsIgnoreCase("2")) { secrefabskmcOth.setVisibility(View.GONE); linerefabskmcOth.setVisibility(View.GONE); txtrefabskmcOth.setText(""); } else if(rbData.equalsIgnoreCase("3")) { secrefabskmcOth.setVisibility(View.VISIBLE); linerefabskmcOth.setVisibility(View.VISIBLE); } else { //sec.setVisibility(View.VISIBLE); //line.setVisibility(View.VISIBLE); } } public void onNothingSelected(AdapterView<?> adapterView) { return; } }); secrefabskmcOth=(LinearLayout)findViewById(R.id.secrefabskmcOth); linerefabskmcOth=(View)findViewById(R.id.linerefabskmcOth); VlblrefabskmcOth=(TextView) findViewById(R.id.VlblrefabskmcOth); txtrefabskmcOth=(EditText) findViewById(R.id.txtrefabskmcOth); secrefmatname=(LinearLayout)findViewById(R.id.secrefmatname); linerefmatname=(View)findViewById(R.id.linerefmatname); Vlblrefmatname=(TextView) findViewById(R.id.Vlblrefmatname); txtrefmatname=(EditText) findViewById(R.id.txtrefmatname); secrefmatage=(LinearLayout)findViewById(R.id.secrefmatage); linerefmatage=(View)findViewById(R.id.linerefmatage); Vlblrefmatage=(TextView) findViewById(R.id.Vlblrefmatage); txtrefmatage=(EditText) findViewById(R.id.txtrefmatage); secrefmatid=(LinearLayout)findViewById(R.id.secrefmatid); linerefmatid=(View)findViewById(R.id.linerefmatid); Vlblrefmatid=(TextView) findViewById(R.id.Vlblrefmatid); txtrefmatid=(EditText) findViewById(R.id.txtrefmatid); secrefbname=(LinearLayout)findViewById(R.id.secrefbname); linerefbname=(View)findViewById(R.id.linerefbname); Vlblrefbname=(TextView) findViewById(R.id.Vlblrefbname); txtrefbname=(EditText) findViewById(R.id.txtrefbname); secrefbid=(LinearLayout)findViewById(R.id.secrefbid); linerefbid=(View)findViewById(R.id.linerefbid); Vlblrefbid=(TextView) findViewById(R.id.Vlblrefbid); txtrefbid=(EditText) findViewById(R.id.txtrefbid); secrefbsex=(LinearLayout)findViewById(R.id.secrefbsex); linerefbsex=(View)findViewById(R.id.linerefbsex); Vlblrefbsex = (TextView) findViewById(R.id.Vlblrefbsex); rdogrprefbsex = (RadioGroup) findViewById(R.id.rdogrprefbsex); rdorefbsex1 = (RadioButton) findViewById(R.id.rdorefbsex1); rdorefbsex2 = (RadioButton) findViewById(R.id.rdorefbsex2); rdorefbsex3 = (RadioButton) findViewById(R.id.rdorefbsex3); rdorefbsex4 = (RadioButton) findViewById(R.id.rdorefbsex4); rdorefbsex5 = (RadioButton) findViewById(R.id.rdorefbsex5); secrefdelivdate=(LinearLayout)findViewById(R.id.secrefdelivdate); linerefdelivdate=(View)findViewById(R.id.linerefdelivdate); Vlblrefdelivdate=(TextView) findViewById(R.id.Vlblrefdelivdate); dtprefdelivdate=(EditText) findViewById(R.id.dtprefdelivdate); secrefbwgt=(LinearLayout)findViewById(R.id.secrefbwgt); linerefbwgt=(View)findViewById(R.id.linerefbwgt); Vlblrefbwgt=(TextView) findViewById(R.id.Vlblrefbwgt); txtrefbwgt=(EditText) findViewById(R.id.txtrefbwgt); secrefbwgtnot=(LinearLayout)findViewById(R.id.secrefbwgtnot); linerefbwgtnot=(View)findViewById(R.id.linerefbwgtnot); Vlblrefbwgtnot = (TextView) findViewById(R.id.Vlblrefbwgtnot); rdogrprefbwgtnot = (RadioGroup) findViewById(R.id.rdogrprefbwgtnot); rdorefbwgtnot1 = (RadioButton) findViewById(R.id.rdorefbwgtnot1); rdorefbwgtnot2 = (RadioButton) findViewById(R.id.rdorefbwgtnot2); secrefgakmc=(LinearLayout)findViewById(R.id.secrefgakmc); linerefgakmc=(View)findViewById(R.id.linerefgakmc); Vlblrefgakmc=(TextView) findViewById(R.id.Vlblrefgakmc); txtrefgakmc=(EditText) findViewById(R.id.txtrefgakmc); secrefgakmcnot=(LinearLayout)findViewById(R.id.secrefgakmcnot); linerefgakmcnot=(View)findViewById(R.id.linerefgakmcnot); Vlblrefgakmcnot = (TextView) findViewById(R.id.Vlblrefgakmcnot); rdogrprefgakmcnot = (RadioGroup) findViewById(R.id.rdogrprefgakmcnot); rdorefgakmcnot1 = (RadioButton) findViewById(R.id.rdorefgakmcnot1); rdorefgakmcnot2 = (RadioButton) findViewById(R.id.rdorefgakmcnot2); secrefbbornloc=(LinearLayout)findViewById(R.id.secrefbbornloc); linerefbbornloc=(View)findViewById(R.id.linerefbbornloc); Vlblrefbbornloc = (TextView) findViewById(R.id.Vlblrefbbornloc); rdogrprefbbornloc = (RadioGroup) findViewById(R.id.rdogrprefbbornloc); rdorefbbornloc1 = (RadioButton) findViewById(R.id.rdorefbbornloc1); rdorefbbornloc2 = (RadioButton) findViewById(R.id.rdorefbbornloc2); rdorefbbornloc3 = (RadioButton) findViewById(R.id.rdorefbbornloc3); rdorefbbornloc4 = (RadioButton) findViewById(R.id.rdorefbbornloc4); rdorefbbornloc5 = (RadioButton) findViewById(R.id.rdorefbbornloc5); rdorefbbornloc6 = (RadioButton) findViewById(R.id.rdorefbbornloc6); rdogrprefbbornloc.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup radioGroup,int radioButtonID) { String rbData = ""; RadioButton rb; String[] d_rdogrprefbbornloc = new String[] {"1","2","3","4","6","9"}; for (int i = 0; i < rdogrprefbbornloc.getChildCount(); i++) { rb = (RadioButton)rdogrprefbbornloc.getChildAt(i); if (rb.isChecked()) rbData = d_rdogrprefbbornloc[i]; } if(rbData.equalsIgnoreCase("1")) { secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); txtrefbbornOth.setText(""); } else if(rbData.equalsIgnoreCase("2")) { secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); txtrefbbornOth.setText(""); } else if(rbData.equalsIgnoreCase("3")) { secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); txtrefbbornOth.setText(""); } else if(rbData.equalsIgnoreCase("6")) { secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); txtrefbbornOth.setText(""); } else if(rbData.equalsIgnoreCase("9")) { secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); txtrefbbornOth.setText(""); } else { secrefbbornOth.setVisibility(View.VISIBLE); linerefbbornOth.setVisibility(View.VISIBLE); } } public void onNothingSelected(AdapterView<?> adapterView) { return; } }); secrefbbornOth=(LinearLayout)findViewById(R.id.secrefbbornOth); linerefbbornOth=(View)findViewById(R.id.linerefbbornOth); VlblrefbbornOth=(TextView) findViewById(R.id.VlblrefbbornOth); txtrefbbornOth=(EditText) findViewById(R.id.txtrefbbornOth); secrefdelivtime=(LinearLayout)findViewById(R.id.secrefdelivtime); linerefdelivtime=(View)findViewById(R.id.linerefdelivtime); Vlblrefdelivtime=(TextView) findViewById(R.id.Vlblrefdelivtime); txtrefdelivtime=(EditText) findViewById(R.id.txtrefdelivtime); secrefdoadmkmc=(LinearLayout)findViewById(R.id.secrefdoadmkmc); linerefdoadmkmc=(View)findViewById(R.id.linerefdoadmkmc); Vlblrefdoadmkmc=(TextView) findViewById(R.id.Vlblrefdoadmkmc); dtprefdoadmkmc=(EditText) findViewById(R.id.dtprefdoadmkmc); secreftoadmkmc=(LinearLayout)findViewById(R.id.secreftoadmkmc); linereftoadmkmc=(View)findViewById(R.id.linereftoadmkmc); Vlblreftoadmkmc=(TextView) findViewById(R.id.Vlblreftoadmkmc); txtreftoadmkmc=(EditText) findViewById(R.id.txtreftoadmkmc); secrefadwgtkmc=(LinearLayout)findViewById(R.id.secrefadwgtkmc); linerefadwgtkmc=(View)findViewById(R.id.linerefadwgtkmc); Vlblrefadwgtkmc=(TextView) findViewById(R.id.Vlblrefadwgtkmc); txtrefadwgtkmc=(EditText) findViewById(R.id.txtrefadwgtkmc); secrefadwgtkmcnot=(LinearLayout)findViewById(R.id.secrefadwgtkmcnot); linerefadwgtkmcnot=(View)findViewById(R.id.linerefadwgtkmcnot); Vlblrefadwgtkmcnot = (TextView) findViewById(R.id.Vlblrefadwgtkmcnot); rdogrprefadwgtkmcnot = (RadioGroup) findViewById(R.id.rdogrprefadwgtkmcnot); rdorefadwgtkmcnot1 = (RadioButton) findViewById(R.id.rdorefadwgtkmcnot1); rdorefadwgtkmcnot2 = (RadioButton) findViewById(R.id.rdorefadwgtkmcnot2); seclblrefbfsup=(LinearLayout)findViewById(R.id.seclblrefbfsup); linelblrefbfsup=(View)findViewById(R.id.linelblrefbfsup); secrefbfsupA=(LinearLayout)findViewById(R.id.secrefbfsupA); linerefbfsupA=(View)findViewById(R.id.linerefbfsupA); VlblrefbfsupA=(TextView) findViewById(R.id.VlblrefbfsupA); chkrefbfsupA=(CheckBox) findViewById(R.id.chkrefbfsupA); secrefbfsupB=(LinearLayout)findViewById(R.id.secrefbfsupB); linerefbfsupB=(View)findViewById(R.id.linerefbfsupB); VlblrefbfsupB=(TextView) findViewById(R.id.VlblrefbfsupB); chkrefbfsupB=(CheckBox) findViewById(R.id.chkrefbfsupB); secrefbfsupC=(LinearLayout)findViewById(R.id.secrefbfsupC); linerefbfsupC=(View)findViewById(R.id.linerefbfsupC); VlblrefbfsupC=(TextView) findViewById(R.id.VlblrefbfsupC); chkrefbfsupC=(CheckBox) findViewById(R.id.chkrefbfsupC); secrefbfsupD=(LinearLayout)findViewById(R.id.secrefbfsupD); linerefbfsupD=(View)findViewById(R.id.linerefbfsupD); VlblrefbfsupD=(TextView) findViewById(R.id.VlblrefbfsupD); chkrefbfsupD=(CheckBox) findViewById(R.id.chkrefbfsupD); secrefbfsupE=(LinearLayout)findViewById(R.id.secrefbfsupE); linerefbfsupE=(View)findViewById(R.id.linerefbfsupE); VlblrefbfsupE=(TextView) findViewById(R.id.VlblrefbfsupE); chkrefbfsupE=(CheckBox) findViewById(R.id.chkrefbfsupE); secrefbfsupF=(LinearLayout)findViewById(R.id.secrefbfsupF); linerefbfsupF=(View)findViewById(R.id.linerefbfsupF); VlblrefbfsupF=(TextView) findViewById(R.id.VlblrefbfsupF); chkrefbfsupF=(CheckBox) findViewById(R.id.chkrefbfsupF); chkrefbfsupF.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!isChecked) { secrefbfsupFOth.setVisibility(View.GONE); linerefbfsupFOth.setVisibility(View.GONE); txtrefbfsupFOth.setText(""); } else { secrefbfsupFOth.setVisibility(View.VISIBLE); linerefbfsupFOth.setVisibility(View.VISIBLE); } } }); secrefbfsupFOth=(LinearLayout)findViewById(R.id.secrefbfsupFOth); linerefbfsupFOth=(View)findViewById(R.id.linerefbfsupFOth); VlblrefbfsupFOth=(TextView) findViewById(R.id.VlblrefbfsupFOth); txtrefbfsupFOth=(EditText) findViewById(R.id.txtrefbfsupFOth); secrefdisoutkmc=(LinearLayout)findViewById(R.id.secrefdisoutkmc); linerefdisoutkmc=(View)findViewById(R.id.linerefdisoutkmc); Vlblrefdisoutkmc = (TextView) findViewById(R.id.Vlblrefdisoutkmc); rdogrprefdisoutkmc = (RadioGroup) findViewById(R.id.rdogrprefdisoutkmc); rdorefdisoutkmc1 = (RadioButton) findViewById(R.id.rdorefdisoutkmc1); rdorefdisoutkmc2 = (RadioButton) findViewById(R.id.rdorefdisoutkmc2); rdorefdisoutkmc3 = (RadioButton) findViewById(R.id.rdorefdisoutkmc3); rdorefdisoutkmc4 = (RadioButton) findViewById(R.id.rdorefdisoutkmc4); rdorefdisoutkmc5 = (RadioButton) findViewById(R.id.rdorefdisoutkmc5); rdorefdisoutkmc6 = (RadioButton) findViewById(R.id.rdorefdisoutkmc6); rdorefdisoutkmc7 = (RadioButton) findViewById(R.id.rdorefdisoutkmc7); rdogrprefdisoutkmc.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup radioGroup,int radioButtonID) { String rbData = ""; RadioButton rb; String[] d_rdogrprefdisoutkmc = new String[] {"1","2","3","4","5","8","9"}; for (int i = 0; i < rdogrprefdisoutkmc.getChildCount(); i++) { rb = (RadioButton)rdogrprefdisoutkmc.getChildAt(i); if (rb.isChecked()) rbData = d_rdogrprefdisoutkmc[i]; } if(rbData.equalsIgnoreCase("1")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else if(rbData.equalsIgnoreCase("2")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else if(rbData.equalsIgnoreCase("3")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else if(rbData.equalsIgnoreCase("5")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else if(rbData.equalsIgnoreCase("8")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else if(rbData.equalsIgnoreCase("9")) { secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); txtreftransPlace.setText(""); } else { secreftransPlace.setVisibility(View.VISIBLE); linereftransPlace.setVisibility(View.VISIBLE); } } public void onNothingSelected(AdapterView<?> adapterView) { return; } }); secreftransPlace=(LinearLayout)findViewById(R.id.secreftransPlace); linereftransPlace=(View)findViewById(R.id.linereftransPlace); VlblreftransPlace=(TextView) findViewById(R.id.VlblreftransPlace); txtreftransPlace=(EditText) findViewById(R.id.txtreftransPlace); secrefdodkmc=(LinearLayout)findViewById(R.id.secrefdodkmc); linerefdodkmc=(View)findViewById(R.id.linerefdodkmc); Vlblrefdodkmc=(TextView) findViewById(R.id.Vlblrefdodkmc); dtprefdodkmc=(EditText) findViewById(R.id.dtprefdodkmc); secrefdiswgtkmc=(LinearLayout)findViewById(R.id.secrefdiswgtkmc); linerefdiswgtkmc=(View)findViewById(R.id.linerefdiswgtkmc); Vlblrefdiswgtkmc=(TextView) findViewById(R.id.Vlblrefdiswgtkmc); txtrefdiswgtkmc=(EditText) findViewById(R.id.txtrefdiswgtkmc); secregdiswgtkmcnot=(LinearLayout)findViewById(R.id.secregdiswgtkmcnot); lineregdiswgtkmcnot=(View)findViewById(R.id.lineregdiswgtkmcnot); Vlblregdiswgtkmcnot = (TextView) findViewById(R.id.Vlblregdiswgtkmcnot); rdogrpregdiswgtkmcnot = (RadioGroup) findViewById(R.id.rdogrpregdiswgtkmcnot); rdoregdiswgtkmcnot1 = (RadioButton) findViewById(R.id.rdoregdiswgtkmcnot1); rdoregdiswgtkmcnot2 = (RadioButton) findViewById(R.id.rdoregdiswgtkmcnot2); dtprefdoe.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (dtprefdoe.getRight() - dtprefdoe.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnrefdoe"; showDialog(DATE_DIALOG); return true; } } return false; } }); dtprefdelivdate.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (dtprefdelivdate.getRight() - dtprefdelivdate.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnrefdelivdate"; showDialog(DATE_DIALOG); return true; } } return false; } }); dtprefdoadmkmc.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (dtprefdoadmkmc.getRight() - dtprefdoadmkmc.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnrefdoadmkmc"; showDialog(DATE_DIALOG); return true; } } return false; } }); dtprefdodkmc.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (dtprefdodkmc.getRight() - dtprefdodkmc.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnrefdodkmc"; showDialog(DATE_DIALOG); return true; } } return false; } }); txtrefdelivtime.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (txtrefdelivtime.getRight() - txtrefdelivtime.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnrefdelivtime"; showDialog(TIME_DIALOG); return true; } } return false; } }); txtreftoadmkmc.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_RIGHT = 2; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (txtreftoadmkmc.getRight() - txtreftoadmkmc.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { VariableID = "btnreftoadmkmc"; showDialog(TIME_DIALOG); return true; } } return false; } }); txtrefbwgt.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtrefbwgt.getText().toString().length()>0) rdogrprefbwgtnot.clearCheck(); } }); rdogrprefbwgtnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefbwgtnot1.isChecked() | rdorefbwgtnot2.isChecked()) txtrefbwgt.setText(""); } }); txtrefgakmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtrefgakmc.getText().toString().length()>0) rdogrprefgakmcnot.clearCheck(); } }); rdogrprefgakmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefgakmcnot1.isChecked() | rdorefgakmcnot2.isChecked()) txtrefgakmc.setText(""); } }); txtrefadwgtkmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtrefadwgtkmc.getText().toString().length()>0) rdogrprefadwgtkmcnot.clearCheck(); } }); rdogrprefadwgtkmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefadwgtkmcnot1.isChecked()|rdorefadwgtkmcnot2.isChecked()) txtrefadwgtkmc.setText(""); } }); txtrefdiswgtkmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtrefdiswgtkmc.getText().toString().length()>0) rdogrpregdiswgtkmcnot.clearCheck(); } }); rdogrpregdiswgtkmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdoregdiswgtkmcnot1.isChecked() | rdoregdiswgtkmcnot2.isChecked()) txtrefdiswgtkmc.setText(""); } }); dtprefdelivdate.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(dtprefdelivdate.getText().toString().length()>0) rdogrprefdelivdatenot.clearCheck(); } }); rdogrprefdelivdatenot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefdelivdatenot1.isChecked() | rdorefdelivdatenot2.isChecked()) dtprefdelivdate.setText(""); } }); //--- txtrefdelivtime.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtrefdelivtime.getText().toString().length()>0) rdogrprefdelivtimenot.clearCheck(); } }); rdogrprefdelivtimenot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefdelivtimenot1.isChecked() | rdorefdelivtimenot2.isChecked()) txtrefdelivtime.setText(""); } }); //---- dtprefdoadmkmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(dtprefdoadmkmc.getText().toString().length()>0) rdogrprefdoadmkmcnot.clearCheck(); } }); rdogrprefdoadmkmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefdoadmkmcnot1.isChecked() | rdorefdoadmkmcnot2.isChecked()) dtprefdoadmkmc.setText(""); } }); //---- txtreftoadmkmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(txtreftoadmkmc.getText().toString().length()>0) rdogrpreftoadmkmcnot.clearCheck(); } }); rdogrpreftoadmkmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdoreftoadmkmcnot1.isChecked() | rdoreftoadmkmcnot2.isChecked()) txtreftoadmkmc.setText(""); } }); //---- dtprefdodkmc.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before,int count) { } public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void afterTextChanged(Editable s) { if(dtprefdodkmc.getText().toString().length()>0) rdogrprefdodkmcnot.clearCheck(); } }); rdogrprefdodkmcnot.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdorefdodkmcnot1.isChecked() | rdorefdodkmcnot2.isChecked()) dtprefdodkmc.setText(""); } }); rdogrpstatus.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(rdostatus1.isChecked()){ secreason.setVisibility(View.GONE); rdogrpreason.clearCheck(); secreasmention.setVisibility(View.GONE); txtreasmention.setText(""); }else{ secreason.setVisibility(View.VISIBLE); secreasmention.setVisibility(View.VISIBLE); } } }); //Hide all skip variables secreason.setVisibility(View.GONE); secreasmention.setVisibility(View.GONE); secrefabskmcOth.setVisibility(View.GONE); linerefabskmcOth.setVisibility(View.GONE); secrefabskmcOth.setVisibility(View.GONE); linerefabskmcOth.setVisibility(View.GONE); //sec.setVisibility(View.GONE); //line.setVisibility(View.GONE); secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); secrefbbornOth.setVisibility(View.GONE); linerefbbornOth.setVisibility(View.GONE); secrefbfsupFOth.setVisibility(View.GONE); linerefbfsupFOth.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); secreftransPlace.setVisibility(View.GONE); linereftransPlace.setVisibility(View.GONE); DataSearch(COUNTRYCODE,FACICODE,DATAID); Button cmdSave = (Button) findViewById(R.id.cmdSave); cmdSave.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DataSave(); }}); } catch(Exception e) { Connection.MessageBox(KMC_DataExt.this, e.getMessage()); return; } } private void DataSave() { try { String DV=""; if(txtCountryCode.getText().toString().length()==0 & secCountryCode.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: CountryCode."); txtCountryCode.requestFocus(); return; } else if(Integer.valueOf(txtCountryCode.getText().toString().length()==0 ? "1" : txtCountryCode.getText().toString()) < 1 || Integer.valueOf(txtCountryCode.getText().toString().length()==0 ? "3" : txtCountryCode.getText().toString()) > 3) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 1 and 3(CountryCode)."); txtCountryCode.requestFocus(); return; } else if(txtFaciCode.getText().toString().length()==0 & secFaciCode.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Facility."); txtFaciCode.requestFocus(); return; } else if(Integer.valueOf(txtFaciCode.getText().toString().length()==0 ? "1" : txtFaciCode.getText().toString()) < 1 || Integer.valueOf(txtFaciCode.getText().toString().length()==0 ? "9" : txtFaciCode.getText().toString()) > 9) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 1 and 9(Facility)."); txtFaciCode.requestFocus(); return; } else if(txtDataID.getText().toString().length()==0 & secDataID.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Data ID."); txtDataID.requestFocus(); return; } DV = Global.DateValidate(dtprefdoe.getText().toString()); if(DV.length()!=0 & secrefdoe.isShown()) { Connection.MessageBox(KMC_DataExt.this, DV); dtprefdoe.requestFocus(); return; } else if(!rdorefabskmc1.isChecked() & !rdorefabskmc2.isChecked() & !rdorefabskmc3.isChecked() & secrefabskmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from (Source of Record)."); rdorefabskmc1.requestFocus(); return; } else if(txtrefabskmcOth.getText().toString().length()==0 & secrefabskmcOth.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Other Specify."); txtrefabskmcOth.requestFocus(); return; } else if(txtrefmatname.getText().toString().length()==0 & secrefmatname.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Mother’s name."); txtrefmatname.requestFocus(); return; } else if(txtrefmatage.getText().toString().length()==0 & secrefmatage.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Mother’s age (years)."); txtrefmatage.requestFocus(); return; } else if(Integer.valueOf(txtrefmatage.getText().toString().length()==0 ? "12" : txtrefmatage.getText().toString()) < 12 || Integer.valueOf(txtrefmatage.getText().toString().length()==0 ? "99" : txtrefmatage.getText().toString()) > 99) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 12 and 99(Mother’s age (years))."); txtrefmatage.requestFocus(); return; } else if(txtrefmatid.getText().toString().length()==0 & secrefmatid.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Mother’s ID."); txtrefmatid.requestFocus(); return; } /*else if(txtrefbname.getText().toString().length()==0 & secrefbname.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Child’s name, if available."); txtrefbname.requestFocus(); return; } else if(txtrefbid.getText().toString().length()==0 & secrefbid.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Child’s ID."); txtrefbid.requestFocus(); return; }*/ else if(!rdorefbsex1.isChecked() & !rdorefbsex2.isChecked() & !rdorefbsex3.isChecked() & !rdorefbsex4.isChecked() & !rdorefbsex5.isChecked() & secrefbsex.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from (Sex of Child)."); rdorefbsex1.requestFocus(); return; } DV = Global.DateValidate(dtprefdelivdate.getText().toString()); if(!rdorefdelivdatenot1.isChecked() & !rdorefdelivdatenot2.isChecked() & DV.length()!=0 & secrefdelivdate.isShown()) { Connection.MessageBox(KMC_DataExt.this, "This is not a valid date of delivery."); dtprefdelivdate.requestFocus(); return; } else if(!rdorefbwgtnot1.isChecked() & !rdorefbwgtnot2.isChecked() & txtrefbwgt.getText().toString().length()==0 & secrefbwgt.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Birth weight (grams)."); txtrefbwgt.requestFocus(); return; } else if(!rdorefbwgtnot1.isChecked() & !rdorefbwgtnot2.isChecked() & (Integer.valueOf(txtrefbwgt.getText().toString().length()==0 ? "400" : txtrefbwgt.getText().toString()) < 400 || Integer.valueOf(txtrefbwgt.getText().toString().length()==0 ? "9999" : txtrefbwgt.getText().toString()) > 9999)) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 400 and 9999(Birth weight (grams))."); txtrefbwgt.requestFocus(); return; } /*else if(!rdorefbwgtnot1.isChecked() & !rdorefbwgtnot2.isChecked() & secrefbwgtnot.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from ()."); rdorefbwgtnot1.requestFocus(); return; }*/ else if(!rdorefgakmcnot1.isChecked() & !rdorefgakmcnot2.isChecked() & txtrefgakmc.getText().toString().length()==0 & secrefgakmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Gestational age (completed weeks + days)."); txtrefgakmc.requestFocus(); return; } else if(!rdorefgakmcnot1.isChecked() & !rdorefgakmcnot2.isChecked() & (Integer.valueOf(txtrefgakmc.getText().toString().length()==0 ? "1" : txtrefgakmc.getText().toString()) < 1 || Integer.valueOf(txtrefgakmc.getText().toString().length()==0 ? "99" : txtrefgakmc.getText().toString()) > 99)) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 1 and 99(Gestational age (completed weeks + days))."); txtrefgakmc.requestFocus(); return; } /*else if(!rdorefgakmcnot1.isChecked() & !rdorefgakmcnot2.isChecked() & secrefgakmcnot.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from ()."); rdorefgakmcnot1.requestFocus(); return; }*/ else if(!rdorefbbornloc1.isChecked() & !rdorefbbornloc2.isChecked() & !rdorefbbornloc3.isChecked() & !rdorefbbornloc4.isChecked() & !rdorefbbornloc5.isChecked() & !rdorefbbornloc6.isChecked() & secrefbbornloc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from (Where the child was born?)."); rdorefbbornloc1.requestFocus(); return; } else if(txtrefbbornOth.getText().toString().length()==0 & secrefbbornOth.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Referred from."); txtrefbbornOth.requestFocus(); return; } else if(!rdorefdelivtimenot1.isChecked() & !rdorefdelivtimenot2.isChecked() & txtrefdelivtime.getText().length()==0 & secrefdelivtime.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Time of Delivery."); txtrefdelivtime.requestFocus(); return; } DV = Global.DateValidate(dtprefdoadmkmc.getText().toString()); if(!rdorefdoadmkmcnot1.isChecked() & !rdorefdoadmkmcnot2.isChecked() & DV.length()!=0 & secrefdoadmkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "11. This is not a valid Date of Admission to KMC"); dtprefdoadmkmc.requestFocus(); return; } else if(!rdoreftoadmkmcnot1.isChecked() & !rdoreftoadmkmcnot2.isChecked() & txtreftoadmkmc.getText().length()==0 & secreftoadmkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Time of Admission to KMC."); txtreftoadmkmc.requestFocus(); return; } else if(!rdorefadwgtkmcnot1.isChecked() & !rdorefadwgtkmcnot2.isChecked() & txtrefadwgtkmc.getText().toString().length()==0 & secrefadwgtkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Weight at admission to KMC (grams)."); txtrefadwgtkmc.requestFocus(); return; } else if(!rdorefadwgtkmcnot1.isChecked() & !rdorefadwgtkmcnot2.isChecked() & (Integer.valueOf(txtrefadwgtkmc.getText().toString().length()==0 ? "400" : txtrefadwgtkmc.getText().toString()) < 400 || Integer.valueOf(txtrefadwgtkmc.getText().toString().length()==0 ? "9999" : txtrefadwgtkmc.getText().toString()) > 9999)) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 400 and 9999(Weight at admission to KMC (grams))."); txtrefadwgtkmc.requestFocus(); return; } /*else if(!rdorefadwgtkmcnot1.isChecked() & !rdorefadwgtkmcnot2.isChecked() & secrefadwgtkmcnot.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from ()."); rdorefadwgtkmcnot1.requestFocus(); return; }*/ else if(txtrefbfsupFOth.getText().toString().length()==0 & secrefbfsupFOth.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Other Specify."); txtrefbfsupFOth.requestFocus(); return; } else if(!rdorefdisoutkmc1.isChecked() & !rdorefdisoutkmc2.isChecked() & !rdorefdisoutkmc3.isChecked() & !rdorefdisoutkmc4.isChecked() & !rdorefdisoutkmc5.isChecked() & !rdorefdisoutkmc6.isChecked() & !rdorefdisoutkmc7.isChecked() & secrefdisoutkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from (Outcome at discharge)."); rdorefdisoutkmc1.requestFocus(); return; } else if(txtreftransPlace.getText().toString().length()==0 & secreftransPlace.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: Transferred alive where."); txtreftransPlace.requestFocus(); return; } DV = Global.DateValidate(dtprefdodkmc.getText().toString()); if(!rdorefdodkmcnot1.isChecked() & !rdorefdodkmcnot2.isChecked() & DV.length()!=0 & secrefdodkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "16.This is not a valid Date of discharge from KMC."); dtprefdodkmc.requestFocus(); return; } else if(!rdoregdiswgtkmcnot1.isChecked() & !rdoregdiswgtkmcnot2.isChecked() & txtrefdiswgtkmc.getText().toString().length()==0 & secrefdiswgtkmc.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: If alive, weight at discharge/transfer from KMC (grams)."); txtrefdiswgtkmc.requestFocus(); return; } else if(!rdoregdiswgtkmcnot1.isChecked() & !rdoregdiswgtkmcnot2.isChecked() & (Integer.valueOf(txtrefdiswgtkmc.getText().toString().length()==0 ? "400" : txtrefdiswgtkmc.getText().toString()) < 400 || Integer.valueOf(txtrefdiswgtkmc.getText().toString().length()==0 ? "9999" : txtrefdiswgtkmc.getText().toString()) > 9999)) { Connection.MessageBox(KMC_DataExt.this, "Value should be between 400 and 9999(If alive, weight at discharge/transfer from KMC (grams))."); txtrefdiswgtkmc.requestFocus(); return; } else if(!rdostatus1.isChecked() & !rdostatus2.isChecked() & !rdostatus3.isChecked() & secstatus.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: 18. What is the final status of the Recall Survey for this patient"); rdostatus1.requestFocus(); return; } else if(!rdoreason1.isChecked() & !rdoreason2.isChecked() & !rdoreason3.isChecked() & !rdoreason4.isChecked() & secreason.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Required field: 19. Why partially incomplete or totally incomplete?"); rdoreason1.requestFocus(); return; } /*else if(!rdoregdiswgtkmcnot1.isChecked() & !rdoregdiswgtkmcnot2.isChecked() & secregdiswgtkmcnot.isShown()) { Connection.MessageBox(KMC_DataExt.this, "Select anyone options from ()."); rdoregdiswgtkmcnot1.requestFocus(); return; }*/ String SQL = ""; RadioButton rb; KMC_DataExt_DataModel objSave = new KMC_DataExt_DataModel(); objSave.setCountryCode(txtCountryCode.getText().toString()); objSave.setFaciCode(txtFaciCode.getText().toString()); objSave.setDataID(txtDataID.getText().toString()); objSave.setrefdoe(dtprefdoe.getText().toString().length() > 0 ? Global.DateConvertYMD(dtprefdoe.getText().toString()) : dtprefdoe.getText().toString()); String[] d_rdogrprefabskmc = new String[] {"1","2","3"}; objSave.setrefabskmc(""); for (int i = 0; i < rdogrprefabskmc.getChildCount(); i++) { rb = (RadioButton)rdogrprefabskmc.getChildAt(i); if (rb.isChecked()) objSave.setrefabskmc(d_rdogrprefabskmc[i]); } objSave.setrefabskmcOth(txtrefabskmcOth.getText().toString()); objSave.setrefmatname(txtrefmatname.getText().toString()); objSave.setrefmatage(txtrefmatage.getText().toString()); objSave.setrefmatid(txtrefmatid.getText().toString()); objSave.setrefbname(txtrefbname.getText().toString()); objSave.setrefbid(txtrefbid.getText().toString()); String[] d_rdogrprefbsex = new String[] {"1","2","3","8","9"}; objSave.setrefbsex(""); for (int i = 0; i < rdogrprefbsex.getChildCount(); i++) { rb = (RadioButton)rdogrprefbsex.getChildAt(i); if (rb.isChecked()) objSave.setrefbsex(d_rdogrprefbsex[i]); } objSave.setrefdelivdate(dtprefdelivdate.getText().toString().length() > 0 ? Global.DateConvertYMD(dtprefdelivdate.getText().toString()) : dtprefdelivdate.getText().toString()); if(rdorefdelivdatenot1.isChecked()) objSave.setrefdelivdatenot("1"); else if(rdorefdelivdatenot2.isChecked()) objSave.setrefdelivdatenot("2"); else objSave.setrefdelivdatenot(""); objSave.setrefbwgt(txtrefbwgt.getText().toString()); String[] d_rdogrprefbwgtnot = new String[] {"1","2"}; objSave.setrefbwgtnot(""); for (int i = 0; i < rdogrprefbwgtnot.getChildCount(); i++) { rb = (RadioButton)rdogrprefbwgtnot.getChildAt(i); if (rb.isChecked()) objSave.setrefbwgtnot(d_rdogrprefbwgtnot[i]); } objSave.setrefgakmc(txtrefgakmc.getText().toString()); String[] d_rdogrprefgakmcnot = new String[] {"1","2"}; objSave.setrefgakmcnot(""); for (int i = 0; i < rdogrprefgakmcnot.getChildCount(); i++) { rb = (RadioButton)rdogrprefgakmcnot.getChildAt(i); if (rb.isChecked()) objSave.setrefgakmcnot(d_rdogrprefgakmcnot[i]); } String[] d_rdogrprefbbornloc = new String[] {"1","2","3","4","6","9"}; objSave.setrefbbornloc(""); for (int i = 0; i < rdogrprefbbornloc.getChildCount(); i++) { rb = (RadioButton)rdogrprefbbornloc.getChildAt(i); if (rb.isChecked()) objSave.setrefbbornloc(d_rdogrprefbbornloc[i]); } objSave.setrefbbornOth(txtrefbbornOth.getText().toString()); objSave.setrefdelivtime(txtrefdelivtime.getText().toString()); if(rdorefdelivtimenot1.isChecked()) objSave.setrefdelivtimenot("1"); else if(rdorefdelivtimenot2.isChecked()) objSave.setrefdelivtimenot("2"); else objSave.setrefdelivtimenot(""); objSave.setrefdoadmkmc(dtprefdoadmkmc.getText().toString().length() > 0 ? Global.DateConvertYMD(dtprefdoadmkmc.getText().toString()) : dtprefdoadmkmc.getText().toString()); if(rdorefdoadmkmcnot1.isChecked()) objSave.setrefdoadmkmcnot("1"); else if(rdorefdoadmkmcnot2.isChecked()) objSave.setrefdoadmkmcnot("2"); else objSave.setrefdoadmkmcnot(""); objSave.setreftoadmkmc(txtreftoadmkmc.getText().toString()); if(rdoreftoadmkmcnot1.isChecked()) objSave.setreftoadmkmcnot("1"); else if(rdoreftoadmkmcnot2.isChecked()) objSave.setreftoadmkmcnot("2"); else objSave.setreftoadmkmcnot(""); objSave.setrefadwgtkmc(txtrefadwgtkmc.getText().toString()); String[] d_rdogrprefadwgtkmcnot = new String[] {"1","2"}; objSave.setrefadwgtkmcnot(""); for (int i = 0; i < rdogrprefadwgtkmcnot.getChildCount(); i++) { rb = (RadioButton)rdogrprefadwgtkmcnot.getChildAt(i); if (rb.isChecked()) objSave.setrefadwgtkmcnot(d_rdogrprefadwgtkmcnot[i]); } objSave.setrefbfsupA((chkrefbfsupA.isChecked()?"1":(secrefbfsupA.isShown()?"2":""))); objSave.setrefbfsupB((chkrefbfsupB.isChecked()?"1":(secrefbfsupB.isShown()?"2":""))); objSave.setrefbfsupC((chkrefbfsupC.isChecked()?"1":(secrefbfsupC.isShown()?"2":""))); objSave.setrefbfsupD((chkrefbfsupD.isChecked()?"1":(secrefbfsupD.isShown()?"2":""))); objSave.setrefbfsupE((chkrefbfsupE.isChecked()?"1":(secrefbfsupE.isShown()?"2":""))); objSave.setrefbfsupF((chkrefbfsupF.isChecked()?"1":(secrefbfsupF.isShown()?"2":""))); objSave.setrefbfsupFOth(txtrefbfsupFOth.getText().toString()); String[] d_rdogrprefdisoutkmc = new String[] {"1","2","3","4","5","8","9"}; objSave.setrefdisoutkmc(""); for (int i = 0; i < rdogrprefdisoutkmc.getChildCount(); i++) { rb = (RadioButton)rdogrprefdisoutkmc.getChildAt(i); if (rb.isChecked()) objSave.setrefdisoutkmc(d_rdogrprefdisoutkmc[i]); } objSave.setreftransPlace(txtreftransPlace.getText().toString()); objSave.setrefdodkmc(dtprefdodkmc.getText().toString().length() > 0 ? Global.DateConvertYMD(dtprefdodkmc.getText().toString()) : dtprefdodkmc.getText().toString()); if(rdorefdodkmcnot1.isChecked()) objSave.setrefdodkmcnot("1"); else if(rdorefdodkmcnot2.isChecked()) objSave.setrefdodkmcnot("2"); else objSave.setrefdodkmcnot(""); objSave.setrefdiswgtkmc(txtrefdiswgtkmc.getText().toString()); String[] d_rdogrpregdiswgtkmcnot = new String[] {"1","2"}; objSave.setregdiswgtkmcnot(""); for (int i = 0; i < rdogrpregdiswgtkmcnot.getChildCount(); i++) { rb = (RadioButton)rdogrpregdiswgtkmcnot.getChildAt(i); if (rb.isChecked()) objSave.setregdiswgtkmcnot(d_rdogrpregdiswgtkmcnot[i]); } //Status String[] d_rdogrpstatus = new String[] {"1","2","3"}; objSave.setStatus(""); for (int i = 0; i < rdogrpstatus.getChildCount(); i++) { rb = (RadioButton)rdogrpstatus.getChildAt(i); if (rb.isChecked()) objSave.setStatus(d_rdogrpstatus[i]); } String[] d_rdogrpreason = new String[] {"1","2","3","4"}; objSave.setReason(""); for (int i = 0; i < rdogrpreason.getChildCount(); i++) { rb = (RadioButton)rdogrpreason.getChildAt(i); if (rb.isChecked()) objSave.setReason(d_rdogrpreason[i]); } objSave.setReasmention(txtreasmention.getText().toString()); objSave.setEnDt(Global.DateTimeNowYMDHMS()); objSave.setStartTime(STARTTIME); objSave.setEndTime(g.CurrentTime24()); objSave.setDeviceID(DEVICEID); objSave.setEntryUser(ENTRYUSER); //from data entry user list objSave.setmodifyDate(Global.DateTimeNowYMDHMS()); //objSave.setLat(Double.toString(currentLatitude)); //objSave.setLon(Double.toString(currentLongitude)); String status = objSave.SaveUpdateData(this); if(status.length()==0) { C.SaveDT("Update Registration set StatusDE='1',Upload='2',modifyDate='"+ Global.DateTimeNowYMDHMS() +"' where CountryCode='" + COUNTRYCODE + "' and FaciCode='" + FACICODE + "' and DataId='" + DATAID + "'"); Intent returnIntent = new Intent(); returnIntent.putExtra("res", ""); setResult(Activity.RESULT_OK, returnIntent); Connection.MessageBox(KMC_DataExt.this, "Saved Successfully"); } else{ Connection.MessageBox(KMC_DataExt.this, status); return; } } catch(Exception e) { Connection.MessageBox(KMC_DataExt.this, e.getMessage()); return; } } private void DataSearch(String CountryCode, String FaciCode, String DataID) { try { RadioButton rb; KMC_DataExt_DataModel d = new KMC_DataExt_DataModel(); String SQL = "Select * from "+ TableName +" Where CountryCode='"+ CountryCode +"' and FaciCode='"+ FaciCode +"' and DataID='"+ DataID +"'"; List<KMC_DataExt_DataModel> data = d.SelectAll(this, SQL); for(KMC_DataExt_DataModel item : data){ txtCountryCode.setText(item.getCountryCode()); txtFaciCode.setText(item.getFaciCode()); txtDataID.setText(item.getDataID()); dtprefdoe.setText(item.getrefdoe().toString().length()==0 ? "" : Global.DateConvertDMY(item.getrefdoe())); String[] d_rdogrprefabskmc = new String[] {"1","2","3"}; for (int i = 0; i < d_rdogrprefabskmc.length; i++) { if (item.getrefabskmc().equals(String.valueOf(d_rdogrprefabskmc[i]))) { rb = (RadioButton)rdogrprefabskmc.getChildAt(i); rb.setChecked(true); } } txtrefabskmcOth.setText(item.getrefabskmcOth()); txtrefmatname.setText(item.getrefmatname()); txtrefmatage.setText(item.getrefmatage()); txtrefmatid.setText(item.getrefmatid()); txtrefbname.setText(item.getrefbname()); txtrefbid.setText(item.getrefbid()); String[] d_rdogrprefbsex = new String[] {"1","2","3","8","9"}; for (int i = 0; i < d_rdogrprefbsex.length; i++) { if (item.getrefbsex().equals(String.valueOf(d_rdogrprefbsex[i]))) { rb = (RadioButton)rdogrprefbsex.getChildAt(i); rb.setChecked(true); } } dtprefdelivdate.setText(item.getrefdelivdate().toString().length()==0 ? "" : Global.DateConvertDMY(item.getrefdelivdate())); if(item.getrefdelivdatenot().equals("1")) rdorefdelivdatenot1.setChecked(true); else if(item.getrefdelivdatenot().equals("2")) rdorefdelivdatenot2.setChecked(true); txtrefbwgt.setText(item.getrefbwgt()); String[] d_rdogrprefbwgtnot = new String[] {"1","2"}; for (int i = 0; i < d_rdogrprefbwgtnot.length; i++) { if (item.getrefbwgtnot().equals(String.valueOf(d_rdogrprefbwgtnot[i]))) { rb = (RadioButton)rdogrprefbwgtnot.getChildAt(i); rb.setChecked(true); } } txtrefgakmc.setText(item.getrefgakmc()); String[] d_rdogrprefgakmcnot = new String[] {"1","2"}; for (int i = 0; i < d_rdogrprefgakmcnot.length; i++) { if (item.getrefgakmcnot().equals(String.valueOf(d_rdogrprefgakmcnot[i]))) { rb = (RadioButton)rdogrprefgakmcnot.getChildAt(i); rb.setChecked(true); } } String[] d_rdogrprefbbornloc = new String[] {"1","2","3","4","6","9"}; for (int i = 0; i < d_rdogrprefbbornloc.length; i++) { if (item.getrefbbornloc().equals(String.valueOf(d_rdogrprefbbornloc[i]))) { rb = (RadioButton)rdogrprefbbornloc.getChildAt(i); rb.setChecked(true); } } txtrefbbornOth.setText(item.getrefbbornOth()); txtrefdelivtime.setText(item.getrefdelivtime()); if(item.getrefdelivtimenot().equals("1")) rdorefdelivtimenot1.setChecked(true); else if(item.getrefdelivtimenot().equals("2")) rdorefdelivtimenot2.setChecked(true); dtprefdoadmkmc.setText(item.getrefdoadmkmc().toString().length()==0 ? "" : Global.DateConvertDMY(item.getrefdoadmkmc())); if(item.getrefdoadmkmcnot().equals("1")) rdorefdoadmkmcnot1.setChecked(true); else if(item.getrefdoadmkmcnot().equals("2")) rdorefdoadmkmcnot2.setChecked(true); txtreftoadmkmc.setText(item.getreftoadmkmc()); if(item.getreftoadmkmcnot().equals("1")) rdoreftoadmkmcnot1.setChecked(true); else if(item.getreftoadmkmcnot().equals("2")) rdoreftoadmkmcnot2.setChecked(true); txtrefadwgtkmc.setText(item.getrefadwgtkmc()); String[] d_rdogrprefadwgtkmcnot = new String[] {"1","2"}; for (int i = 0; i < d_rdogrprefadwgtkmcnot.length; i++) { if (item.getrefadwgtkmcnot().equals(String.valueOf(d_rdogrprefadwgtkmcnot[i]))) { rb = (RadioButton)rdogrprefadwgtkmcnot.getChildAt(i); rb.setChecked(true); } } if(item.getrefbfsupA().equals("1")) { chkrefbfsupA.setChecked(true); } else if(item.getrefbfsupA().equals("2")) { chkrefbfsupA.setChecked(false); } if(item.getrefbfsupB().equals("1")) { chkrefbfsupB.setChecked(true); } else if(item.getrefbfsupB().equals("2")) { chkrefbfsupB.setChecked(false); } if(item.getrefbfsupC().equals("1")) { chkrefbfsupC.setChecked(true); } else if(item.getrefbfsupC().equals("2")) { chkrefbfsupC.setChecked(false); } if(item.getrefbfsupD().equals("1")) { chkrefbfsupD.setChecked(true); } else if(item.getrefbfsupD().equals("2")) { chkrefbfsupD.setChecked(false); } if(item.getrefbfsupE().equals("1")) { chkrefbfsupE.setChecked(true); } else if(item.getrefbfsupE().equals("2")) { chkrefbfsupE.setChecked(false); } if(item.getrefbfsupF().equals("1")) { chkrefbfsupF.setChecked(true); } else if(item.getrefbfsupF().equals("2")) { chkrefbfsupF.setChecked(false); } txtrefbfsupFOth.setText(item.getrefbfsupFOth()); String[] d_rdogrprefdisoutkmc = new String[] {"1","2","3","4","5","8","9"}; for (int i = 0; i < d_rdogrprefdisoutkmc.length; i++) { if (item.getrefdisoutkmc().equals(String.valueOf(d_rdogrprefdisoutkmc[i]))) { rb = (RadioButton)rdogrprefdisoutkmc.getChildAt(i); rb.setChecked(true); } } txtreftransPlace.setText(item.getreftransPlace()); dtprefdodkmc.setText(item.getrefdodkmc().toString().length()==0 ? "" : Global.DateConvertDMY(item.getrefdodkmc())); if(item.getrefdodkmcnot().equals("1")) rdorefdodkmcnot1.setChecked(true); else if(item.getrefdodkmcnot().equals("2")) rdorefdodkmcnot2.setChecked(true); txtrefdiswgtkmc.setText(item.getrefdiswgtkmc()); String[] d_rdogrpregdiswgtkmcnot = new String[] {"1","2"}; for (int i = 0; i < d_rdogrpregdiswgtkmcnot.length; i++) { if (item.getregdiswgtkmcnot().equals(String.valueOf(d_rdogrpregdiswgtkmcnot[i]))) { rb = (RadioButton)rdogrpregdiswgtkmcnot.getChildAt(i); rb.setChecked(true); } } //Status String[] d_rdogrpstatus = new String[] {"1","2","3"}; for (int i = 0; i < d_rdogrpstatus.length; i++) { if (item.getStatus().equals(String.valueOf(d_rdogrpstatus[i]))) { rb = (RadioButton)rdogrpstatus.getChildAt(i); rb.setChecked(true); } } String[] d_rdogrpreason = new String[] {"1","2","3","4"}; for (int i = 0; i < d_rdogrpreason.length; i++) { if (item.getReason().equals(String.valueOf(d_rdogrpreason[i]))) { rb = (RadioButton)rdogrpreason.getChildAt(i); rb.setChecked(true); } } txtreasmention.setText(item.getReasmention()); } } catch(Exception e) { Connection.MessageBox(KMC_DataExt.this, e.getMessage()); return; } } protected Dialog onCreateDialog(int id) { final Calendar c = Calendar.getInstance(); hour = c.get(Calendar.HOUR_OF_DAY); minute = c.get(Calendar.MINUTE); switch (id) { case DATE_DIALOG: return new DatePickerDialog(this, mDateSetListener,g.mYear,g.mMonth-1,g.mDay); case TIME_DIALOG: return new TimePickerDialog(this, timePickerListener, hour, minute,false); } return null; } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear+1; mDay = dayOfMonth; EditText dtpDate; dtpDate = (EditText)findViewById(R.id.dtprefdoe); if (VariableID.equals("btnrefdoe")) { dtpDate = (EditText)findViewById(R.id.dtprefdoe); } else if (VariableID.equals("btnrefdelivdate")) { dtpDate = (EditText)findViewById(R.id.dtprefdelivdate); } else if (VariableID.equals("btnrefdoadmkmc")) { dtpDate = (EditText)findViewById(R.id.dtprefdoadmkmc); } else if (VariableID.equals("btnrefdodkmc")) { dtpDate = (EditText)findViewById(R.id.dtprefdodkmc); } dtpDate.setText(new StringBuilder() .append(Global.Right("00"+mDay,2)).append("/") .append(Global.Right("00"+mMonth,2)).append("/") .append(mYear)); } }; private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) { hour = selectedHour; minute = selectedMinute; EditText tpTime; tpTime = (EditText)findViewById(R.id.txtrefdelivtime); if (VariableID.equals("btnrefdelivtime")) { tpTime = (EditText)findViewById(R.id.txtrefdelivtime); } else if (VariableID.equals("btnreftoadmkmc")) { tpTime = (EditText)findViewById(R.id.txtreftoadmkmc); } tpTime.setText(new StringBuilder().append(Global.Right("00"+hour,2)).append(":").append(Global.Right("00"+minute,2))); } }; //GPS Reading //..................................................................................................... public void FindLocation() { LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { updateLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } void updateLocation(Location location) { currentLocation = location; currentLatitude = currentLocation.getLatitude(); currentLongitude = currentLocation.getLongitude(); } // Method to turn on GPS public void turnGPSOn(){ try { String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(!provider.contains("gps")){ //if gps is disabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); } } catch (Exception e) { } } // Method to turn off the GPS public void turnGPSOff(){ String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(provider.contains("gps")){ //if gps is enabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); } } // turning off the GPS if its in on state. to avoid the battery drain. @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); turnGPSOff(); } }
83,675
0.61211
0.6047
1,837
44.542732
35.610226
332
false
false
0
0
0
0
0
0
0.765378
false
false
13
a8b0a7f3503c6f29df9ce9d73f14bc0218122550
4,054,449,131,043
9120661eb2043eaf48054e441e8d2a1ea0ce985a
/smbcustsrv/src/main/java/businesslogic/login/LoginLogicController.java
b9c967a8a397dea24d34310f2019e911c0752d31
[]
no_license
mieru/smbapp
https://github.com/mieru/smbapp
582d18f8cc8c7c1a48837897d70c75fd2964f245
5a9359f9bcf7507d28b0a0be9ae38a622e14c9b0
refs/heads/master
2021-01-12T16:25:38.395000
2016-12-30T20:04:16
2016-12-30T20:04:16
69,270,970
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package businesslogic.login; import java.util.Base64; import java.util.List; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import org.json.JSONException; import org.json.JSONObject; import dbmenager.user.UserDAO; import dbmodel.Users; import restapi.login.LoginRestData; import utils.Status; @Stateless @LocalBean public class LoginLogicController { private final String LOGIN_RESULT = "login_result"; private final String NOT_ACTIVE = "not_active"; private final String ID_USER = "id_user"; @EJB UserDAO userDAO; public String checkLoginData(LoginRestData loginRestData) throws JSONException{ JSONObject jsonObject = new JSONObject(); Users user = new Users(); user.setLogin(loginRestData.username); user.setPassword(new String(Base64.getEncoder().encode(loginRestData.password.getBytes()))); List<Users> userList = userDAO.findEntity(user); if (userList.size() == 1 && userList.iterator().next().getRole().contains(Status.USER_ROLE.CUSTOMER)) { user = userList.iterator().next(); if (user.getState().equals(Status.USER_STATE.ACTIVE)) { jsonObject.put(LOGIN_RESULT, Boolean.TRUE); jsonObject.put(ID_USER, user.getId()); } else { jsonObject.put(LOGIN_RESULT, NOT_ACTIVE); } } else { jsonObject.put(LOGIN_RESULT, Boolean.FALSE); } return jsonObject.toString(); } }
UTF-8
Java
1,437
java
LoginLogicController.java
Java
[]
null
[]
package businesslogic.login; import java.util.Base64; import java.util.List; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import org.json.JSONException; import org.json.JSONObject; import dbmenager.user.UserDAO; import dbmodel.Users; import restapi.login.LoginRestData; import utils.Status; @Stateless @LocalBean public class LoginLogicController { private final String LOGIN_RESULT = "login_result"; private final String NOT_ACTIVE = "not_active"; private final String ID_USER = "id_user"; @EJB UserDAO userDAO; public String checkLoginData(LoginRestData loginRestData) throws JSONException{ JSONObject jsonObject = new JSONObject(); Users user = new Users(); user.setLogin(loginRestData.username); user.setPassword(new String(Base64.getEncoder().encode(loginRestData.password.getBytes()))); List<Users> userList = userDAO.findEntity(user); if (userList.size() == 1 && userList.iterator().next().getRole().contains(Status.USER_ROLE.CUSTOMER)) { user = userList.iterator().next(); if (user.getState().equals(Status.USER_STATE.ACTIVE)) { jsonObject.put(LOGIN_RESULT, Boolean.TRUE); jsonObject.put(ID_USER, user.getId()); } else { jsonObject.put(LOGIN_RESULT, NOT_ACTIVE); } } else { jsonObject.put(LOGIN_RESULT, Boolean.FALSE); } return jsonObject.toString(); } }
1,437
0.700765
0.697286
51
26.17647
24.424919
106
false
false
0
0
0
0
0
0
2.156863
false
false
13
fbd3120481d2518c688fc72adda43dbf1dd0ef07
17,660,905,544,293
d8a58be9ec6cd06641598021353b58054851636e
/src/com/fourteen/outersource/bean/UserSkillBean.java
4680fd577205d2be9744a2f5db5c428c60afe5d8
[]
no_license
lyxwll/OuterSource
https://github.com/lyxwll/OuterSource
bfafd89814536691e176728d266a1d04797f4941
c4bd745c0a2ca0dc985816c7b268985a649e4f42
refs/heads/master
2020-05-27T19:38:44.185000
2015-08-16T14:04:24
2015-08-16T14:04:24
40,820,195
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fourteen.outersource.bean; import java.io.Serializable; public class UserSkillBean implements Serializable{ /** * */ private static final long serialVersionUID = 1L; public int user_id; public String user_name; public int category_id; public String category_name; public String addtime; public String exam_time; public int exam_score; }
UTF-8
Java
369
java
UserSkillBean.java
Java
[]
null
[]
package com.fourteen.outersource.bean; import java.io.Serializable; public class UserSkillBean implements Serializable{ /** * */ private static final long serialVersionUID = 1L; public int user_id; public String user_name; public int category_id; public String category_name; public String addtime; public String exam_time; public int exam_score; }
369
0.753388
0.750678
20
17.450001
16.301764
51
false
false
0
0
0
0
0
0
1.1
false
false
13
76f94283fa75fe049669b120a944325c0556997f
33,526,514,714,738
934962f2151593c2faa4c10606277511edefc19f
/app/controllers/Application.java
7c6da70fdcc5930697d7f30d64d4f70945385f57
[ "Apache-2.0" ]
permissive
HusseinSalami/SCM-Project
https://github.com/HusseinSalami/SCM-Project
f75e80b6ea0064b44f13787ec2169fb1eaec224f
e2ccf70bfbc00f880d0101812bf47e90dbc4bf6c
refs/heads/master
2021-01-10T17:55:47.075000
2016-03-17T22:11:37
2016-03-17T22:11:37
54,153,889
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controllers; import play.*; import play.mvc.*; import play.db.jpa.*; import views.html.*; import models.Person; import models.Version; import models.ChangeList; import models.MetricTest; import models.MetricDef; import models.TestDef; import models.TestRun; import models.MetricValue; import models.User; import play.data.Form; import java.util.List; import java.util.*; import java.util.ArrayList; import static play.libs.Json.*; import play.data.DynamicForm; import play.data.Form; import play.mvc.Http; import play.mvc.Http.Session; public class Application extends Controller { public Result index() { return ok(index.render()); } public Result getLoginPage() { return ok(signUp.render()); } public Result getIndex2Page() { return ok(index2.render()); } public Result getTestPage() { return ok(tester.render()); } @Transactional(readOnly = true) public Result getAllChangeLists() { List<ChangeList> ListchangeList = (List<ChangeList>) JPA.em().createQuery("select p from ChangeList p order by p.versionId").getResultList(); return ok(toJson(ListchangeList)); } @Transactional public Result addVersion() { Session session = Http.Context.current().session(); String email=session.get("username"); Version version = Form.form(Version.class).bindFromRequest().get(); JPA.em().persist(version); ChangeList change=new ChangeList(); String id_version1; version= (Version) JPA.em().createQuery("SELECT p from Version p where p.name =:name").setParameter("name",version.name).getSingleResult(); id_version1=version.id; change.setversionId(id_version1); change.description = "Base" + version.id; change.user=email; JPA.em().persist(change); change=(ChangeList) JPA.em().createQuery("SELECT p from ChangeList p WHERE p.versionId =:versionid").setParameter("versionid",id_version1).getSingleResult(); String id_change=(String) change.id; Version version_base=(Version) JPA.em().find(Version.class,id_version1); version_base.setheadId(""+id_change); version_base.setbaseId(""+id_change); JPA.em().merge(version_base); return redirect(routes.Application.index()); //return redirect(routes.Application.getTestPage()); } @Transactional public Result addVersion3(String id,String versionName) { Version version=new Version(); version.setheadId(id); version.setbaseId(id); version.name=(String)versionName; JPA.em().persist(version); return redirect(routes.Application.index()); } @Transactional public Result createmetric() { MetricDef metric=new MetricDef(); DynamicForm dynamicForm = Form.form().bindFromRequest(); String name= dynamicForm.get("name"); String description=dynamicForm.get("description"); String tolerance=dynamicForm.get("tolerance"); metric.name=name; metric.description=description; metric.tolerance=tolerance; JPA.em().persist(metric); return redirect(routes.Application.getIndex2()); } //ajouter les contraintes qui vont empecher a lutilisateur de creer des versions de meme nom, et des testdef aussi. @Transactional public Result createTest(String tags) { String[] array = tags.split(","); TestDef test=new TestDef(); DynamicForm dynamicForm = Form.form().bindFromRequest(); String name= dynamicForm.get("name"); String description=dynamicForm.get("description"); test.name=name; test.description=description; JPA.em().persist(test); TestDef test_modifier=(TestDef) JPA.em().createQuery("select DISTINCT p from TestDef p where p.name=:name1 and p.description=:name2").setParameter("name1",name).setParameter("name2",description).getSingleResult(); String test_id=test_modifier.idTestDef; for(int i=0;i<array.length;++i) { MetricTest metric=new MetricTest(); metric.idTestDef=test_id; metric.idMetricDef=array[i]; JPA.em().persist(metric); } return redirect(routes.Application.getIndex2()); } ///parler du workaroundd @Transactional public Result addMetricValue( ) { DynamicForm dynamicForm = Form.form().bindFromRequest(); List<List <MetricDef>> liste_metri=new ArrayList<>(); List<TestRun> list_testRun=(List<TestRun>)JPA.em().createQuery("select distinct p from TestRun p, MetricValue v where p.idTestRun=v.idTestRun and v.value=:valeur").setParameter("valeur","null").getResultList(); for(int i=0;i<list_testRun.size();++i) { String test=list_testRun.get(i).idTestDef; List<MetricDef> testdef=(List<MetricDef>)JPA.em().createQuery("select distinct s from MetricTest p, TestDef t, MetricDef s where p.idMetricDef=s.idMetricDef AND p.idTestDef=t.idTestDef AND t.idTestDef=:value").setParameter("value",test).getResultList(); liste_metri.add(i,testdef); for(int j=0;j<testdef.size();++j) { String metric_id=testdef.get(j).idMetricDef; String test_id= list_testRun.get(i).idTestRun; MetricValue metric_value=(MetricValue) JPA.em().createQuery("select p from MetricValue p where p.idTestRun=:test_id and p.idMetricDef=:metric_id").setParameter("test_id",test_id).setParameter("metric_id",metric_id).getSingleResult(); String value=dynamicForm.get(testdef.get(j).idMetricDef+test_id); if(value.equals("")) { ; } else{ metric_value.value=value; JPA.em().merge(metric_value); } } } return redirect(routes.Application.getIndex2Page()); } @Transactional(readOnly = true) public Result getTestDefOrder() { List<TestRun> list_testRun=(List<TestRun>)JPA.em().createQuery("select distinct p from TestRun p, MetricValue v where p.idTestRun=v.idTestRun and v.value=:valeur").setParameter("valeur","null").getResultList(); List<TestDef> list_testDef=new ArrayList<>(); for(int i=0;i<list_testRun.size();++i) { // String valeur=list_testRun.get(i).idTestDef; TestDef td=(TestDef)JPA.em().createQuery("select td from TestDef td where td.idTestDef=:value").setParameter("value",list_testRun.get(i).idTestDef).getSingleResult(); list_testDef.add(i,td); } return ok(toJson(list_testDef)); } @Transactional(readOnly = true) public Result getMetricValue() { List<MetricValue> metricValue = (List<MetricValue>) JPA.em().createQuery("select p from MetricValue p order by p.idMetricValue").getResultList(); return ok(toJson(metricValue)); } @Transactional(readOnly = true) public Result getTestmetrique() { List<MetricTest> metricTest = (List<MetricTest>) JPA.em().createQuery("select p from MetricTest p").getResultList(); return ok(toJson(metricTest)); } @Transactional(readOnly = true) public Result getTest() { List<TestDef> list_test = (List<TestDef>) JPA.em().createQuery("select p from TestDef p").getResultList(); return ok(toJson(list_test)); } @Transactional(readOnly = true) public Result getTesteurNeedsTest() { List<TestRun> list_testRun=(List<TestRun>)JPA.em().createQuery("select distinct p from TestRun p, MetricValue v where p.idTestRun=v.idTestRun and v.value=:valeur").setParameter("valeur","null").getResultList(); return ok(toJson(list_testRun)); } @Transactional(readOnly = true) public Result getTesteurNeedsMetric() { List<List <MetricDef>> liste_metri=new ArrayList<>(); List<TestRun> list_testRun=(List<TestRun>)JPA.em().createQuery("select distinct p from TestRun p, MetricValue v where p.idTestRun=v.idTestRun and v.value=:valeur").setParameter("valeur","null").getResultList(); for(int i=0;i<list_testRun.size();++i) { String test=list_testRun.get(i).idTestDef; List<MetricDef> testdef=(List<MetricDef>)JPA.em().createQuery("select distinct s from MetricTest p, TestDef t, MetricDef s where p.idMetricDef=s.idMetricDef AND p.idTestDef=t.idTestDef AND t.idTestDef=:value").setParameter("value",test).getResultList(); liste_metri.add(i,testdef); } return ok(toJson(liste_metri)); } // @Transactional(readOnly = true) public Result getTestRunCreate(String id) { List<TestDef> list_test = (List<TestDef>) JPA.em().createQuery("select p from TestDef p").getResultList(); return ok(toJson(list_test)); } @Transactional(readOnly = true) public Result getTesteurWork() { return ok(index2.render()); } @Transactional public Result getTestRunDexideCreate(String id_test_def,String id_changeList) { // TestRun t=new TestRun(); String count=(String) JPA.em().createQuery("select count(x) from TestRun x where x.idTestDef=:name1 and x.idChangeList=:name2").setParameter("name1",id_test_def).setParameter("name2",id_changeList).getSingleResult().toString(); if(count.equals("0")) { TestRun t=new TestRun(); t.idTestDef=id_test_def; t.idChangeList=id_changeList; JPA.em().persist(t); String id_testRun=(String) JPA.em().createQuery("SELECT x.id FROM TestRun x WHERE x.idTestDef=:id1 and x.idChangeList=:id2").setParameter("id1",id_test_def).setParameter("id2",id_changeList).getSingleResult(); List<MetricDef> testdef=(List<MetricDef>)JPA.em().createQuery("select s from MetricTest p, TestDef t, MetricDef s where p.idMetricDef=s.idMetricDef AND p.idTestDef=t.idTestDef AND t.idTestDef=:value").setParameter("value",id_test_def).getResultList(); for(int i=0;i<testdef.size();++i) { MetricValue m=new MetricValue(); m.idTestRun=id_testRun; m.idMetricDef=testdef.get(i).idMetricDef; m.value="null"; JPA.em().persist(m); } } else { TestRun t= (TestRun) JPA.em().createQuery("select distinct t from TestRun t where t.idTestDef=:value1 and t.idChangeList=:value2").setParameter("value1",id_test_def).setParameter("value2",id_changeList).getSingleResult(); String id_test_run = t.idTestRun; List<MetricValue> m_value= (List<MetricValue>) JPA.em().createQuery("select m from MetricValue m where m.idTestRun=:value").setParameter("value",id_test_run).getResultList(); for(int i=0;i<m_value.size();++i) { m_value.get(i).value="null"; JPA.em().merge(m_value.get(i)); } //je met ;les valeurs du testRun a null } return redirect(routes.Application.index()); } @Transactional(readOnly = true) public Result getTestRunAll() { List <TestRun> list_test_run=(List<TestRun>) JPA.em().createQuery("select p from TestRun p").getResultList(); return ok(toJson(list_test_run)); } @Transactional(readOnly = true) public Result getmetric() { List<MetricDef> metrics = (List<MetricDef>) JPA.em().createQuery("select p from MetricDef p").getResultList(); return ok(toJson(metrics)); } @Transactional(readOnly = true) public Result getVersions() { List<Version> versions = (List<Version>) JPA.em().createQuery("select p from Version p order by p.id").getResultList(); return ok(toJson(versions)); } @Transactional public Result addChangeList() { ChangeList changeList = Form.form(ChangeList.class).bindFromRequest().get(); JPA.em().persist(changeList); return redirect(routes.Application.index()); } @Transactional public Result addChangeList2(String id,String description) { Session session = Http.Context.current().session(); ChangeList changeList=new ChangeList(); changeList.description=description; changeList.versionId=id; changeList.user=session.get("username"); Version version=(Version) JPA.em().find(Version.class,id); JPA.em().persist(changeList); String change=(String) JPA.em().createQuery("SELECT MAX(c.id) FROM ChangeList c,Version v WHERE (c.versionId=v.id or c.id=v.baseId) and c.versionId=:id1").setParameter("id1",id).getSingleResult(); version.setheadId(change); JPA.em().merge(version); return redirect(routes.Application.index()); } @Transactional(readOnly = true) public Result getChangeLists() { List<ChangeList> changeLists = (List<ChangeList>) JPA.em().createQuery("select p from ChangeList p").getResultList(); return ok(toJson(changeLists)); } @Transactional(readOnly = true) public Result getTestDef() { List<TestDef> liste_test_def=(List<TestDef>)JPA.em().createQuery("select p from TestDef p").getResultList(); return ok(toJson(liste_test_def)); } //comparaison entre changeList @Transactional(readOnly = true) public Result getComparePage(String value) { List<Version> list_version_chercher=(List<Version>) JPA.em().createQuery("select distinct v from Version v, ChangeList c,TestRun tR,TestDef tD,MetricValue mV where (v.id=c.versionId or v.baseId=c.id) and c.id=tR.idChangeList and tR.idTestDef=tD.idTestDef and mV.idTestRun=tR.idTestRun and mV.value!='null' and tD.name=:value1 order by v.id) ").setParameter("value1",value).getResultList(); List<Long> list_change=(List<Long>) JPA.em().createQuery("select count(distinct c) as ttt from Version v, ChangeList c,TestRun tR,TestDef tD,MetricValue mV where (v.id=c.versionId or v.baseId=c.id) and c.id=tR.idChangeList and tR.idTestDef=tD.idTestDef and mV.idTestRun=tR.idTestRun and mV.value!='null' and tD.name=:value1 group by v.id ) ").setParameter("value1",value).getResultList(); List<Version>list_version=new ArrayList<>(); for(int k=0;k<(list_version_chercher).size();++k) { Long a=(Long)list_change.get(k); if(a>= 2) list_version.add(list_version_chercher.get(k)); } List<List<ChangeList>> list_cL= new ArrayList<>(); for(int i=0;i<list_version.size();++i) { List<ChangeList> list=(List<ChangeList>) JPA.em().createQuery("select c from ChangeList c where c.id in(select p.id from ChangeList p where p.versionId=:value1) or c.id in(select v.baseId from Version v where v.id=:value2) ").setParameter("value1",list_version.get(i).id).setParameter("value2",list_version.get(i).id).getResultList(); list_cL.add(i,list); } return ok(comparaisonPage.render(list_version,list_cL,value)); } @Transactional(readOnly = true) public Result getChangeListVersionTestDef(String nameTestDef,String version) { List<ChangeList> list=(List<ChangeList>) JPA.em().createQuery("select distinct c from ChangeList c,TestRun tR,TestDef tD where c.id= tR.idChangeList and tR.idTestDef=tD.idTestDef and tD.name =:value2 and (c.id in(select p.id from ChangeList p where p.versionId=:value1) or c.id in(select v.baseId from Version v where v.id=:value1)) ").setParameter("value1",version).setParameter("value2",nameTestDef).getResultList(); return ok(toJson(list)); } @Transactional(readOnly=true) public Result getMetricValueTest(String reference, String testdef) { List<MetricValue>mv_reference=(List<MetricValue>)JPA.em().createQuery("select distinct m from MetricValue m where m.idTestRun in (select tR.idTestRun from TestRun tR,ChangeList cL where tR.idChangeList=cL.id and cL.id=:value1) and m.idMetricDef in (select mD.idMetricDef from MetricDef mD,MetricTest mT where mD.idMetricDef=mT.idMetricDef and mT.idTestDef in(select t.idTestDef from TestDef t where t.name=:value2))").setParameter("value1",reference).setParameter("value2",testdef).getResultList(); return ok(toJson(mv_reference)); } @Transactional(readOnly = true) public Result getComparerChangeList(String testdef,String reference,String tester) { List<MetricValue>mv_reference=(List<MetricValue>)JPA.em().createQuery("select distinct m from MetricValue m where m.idTestRun in (select tR.idTestRun from TestRun tR,ChangeList cL where tR.idChangeList=cL.id and cL.id=:value1) and m.idMetricDef in (select mD.idMetricDef from MetricDef mD,MetricTest mT where mD.idMetricDef=mT.idMetricDef and mT.idTestDef in(select t.idTestDef from TestDef t where t.name=:value2) )").setParameter("value1",reference).setParameter("value2",testdef).getResultList(); List<MetricValue>mv_tester=(List<MetricValue>)JPA.em().createQuery("select distinct m from MetricValue m where m.idTestRun in (select tR.idTestRun from TestRun tR,ChangeList cL where tR.idChangeList=cL.id and cL.id=:value1) and m.idMetricDef in (select mD.idMetricDef from MetricDef mD,MetricTest mT where mD.idMetricDef=mT.idMetricDef and mT.idTestDef in(select t.idTestDef from TestDef t where t.name=:value2))").setParameter("value1",tester).setParameter("value2",testdef).getResultList(); String resultat="neutre"; for(int i=0;i<mv_tester.size();++i) { String metricdefid=mv_reference.get(i).idMetricDef; for(int j=0;j<mv_reference.size();++j) { if((mv_reference.get(j).idMetricDef).equals(metricdefid)) { double tolerancePourcentage =Double.parseDouble((String)JPA.em().createQuery("select mD.tolerance from MetricDef mD where mD.idMetricDef=:value").setParameter("value",metricdefid).getSingleResult()); double tolerance_metrique=(tolerancePourcentage)/100; double tolerance=tolerance_metrique*(Double.parseDouble((mv_reference.get(j).value))); double value_reference=Double.parseDouble(mv_reference.get(j).value); double value_tester=Double.parseDouble(mv_tester.get(i).value); if(value_reference>value_tester) { if(value_reference>(value_tester+tolerance)) resultat="avance"; else { if(resultat.equals("avance")) ; else resultat="neutre"; } } else { if(value_reference==value_tester) { if(resultat.equals("avance")) ; else resultat="neutre"; } else { if((value_reference+tolerance)<value_tester) { resultat="retrait"; return ok(toJson(resultat)); } else { if(resultat.equals("avance")) ; else resultat="neutre"; } } } } } } return ok(toJson(resultat)); } @Transactional(readOnly = true) public Result getValidateVersion(String testName,String versionId) { String id_head=(String) JPA.em().createQuery("select v.headId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); String id_base=(String) JPA.em().createQuery("select v.baseId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); Long head=(Long) JPA.em().createQuery("select count(tR) from TestRun tR, TestDef tD where tR.idChangeList=:value1 and tR.idTestDef=tD.idTestDef and tD.name=:value2").setParameter("value1",id_head).setParameter("value2",testName).getSingleResult(); Long base=(Long) JPA.em().createQuery("select count(tR) from TestRun tR, TestDef tD where tR.idChangeList=:value1 and tR.idTestDef=tD.idTestDef and tD.name=:value2").setParameter("value1",id_base).setParameter("value2",testName).getSingleResult(); if(head!=0 && base!=0) { return ok(toJson("true")); } else return ok(toJson("false")); } @Transactional(readOnly = true) public Result validateVersion(String testName,String versionId) { String id_head=(String) JPA.em().createQuery("select v.headId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); String id_base=(String) JPA.em().createQuery("select v.baseId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); return getComparerChangeList(testName,id_base,id_head); } //ajouter @Transactional(readOnly = true) public Result getMetricDefNom(String nameTestDef) { List<MetricDef> list_metric=(List<MetricDef>)JPA.em().createQuery("select distinct mD from MetricDef mD,MetricTest mT,TestDef tD where mD.idMetricDef=mT.idMetricDef and mT.idTestDef=tD.idTestDef and tD.name=:value").setParameter("value",nameTestDef).getResultList(); return ok(toJson(list_metric)); } @Transactional(readOnly = true) public Result getMetricValuesTemplateValidate(String testDef, String versionId) { String id_head=(String) JPA.em().createQuery("select v.headId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); String id_base=(String) JPA.em().createQuery("select v.baseId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); List<MetricValue> listMetricValueBase=(List<MetricValue>)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, TestDef tD,ChangeList cL,MetricTest mT,MetricDef mD where tD.name=:value1 and mT.idMetricDef=mD.idMetricDef and mT.idTestDef=tD.idTestDef and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2 order by mV.idMetricValue").setParameter("value1",testDef).setParameter("value2",id_base).getResultList(); List<MetricValue> listMetricValueHead=(List<MetricValue>)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, TestDef tD,ChangeList cL,MetricTest mT,MetricDef mD where tD.name=:value1 and mT.idMetricDef=mD.idMetricDef and mT.idTestDef=tD.idTestDef and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2 order by mV.idMetricValue").setParameter("value1",testDef).setParameter("value2",id_head).getResultList(); List<List<MetricValue>> list_metric=new ArrayList<>(); list_metric.add(listMetricValueBase); list_metric.add(listMetricValueHead); return ok(toJson(list_metric)); } @Transactional(readOnly = true) public Result getHeadBaseId(String versionId) { List<String> list=(List<String>)JPA.em().createQuery("select cL.id from ChangeList cL,Version v where (cL.id=v.headId or cL.id=v.baseId) and v.id=:value order by cL.id").setParameter("value",versionId).getResultList(); return ok(toJson(list)); } @Transactional(readOnly = true) public Result getMetricValuesTemplateCompare(String nameTestDef,String reference,String comp) { List<MetricValue> listMetricValueReference=(List<MetricValue>)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, TestDef tD,ChangeList cL,MetricTest mT,MetricDef mD where tD.name=:value1 and mT.idMetricDef=mD.idMetricDef and mT.idTestDef=tD.idTestDef and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2 order by mV.idMetricValue").setParameter("value1",nameTestDef).setParameter("value2",reference).getResultList(); List<MetricValue> listMetricValueHead=(List<MetricValue>)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, TestDef tD,ChangeList cL,MetricTest mT,MetricDef mD where tD.name=:value1 and mT.idMetricDef=mD.idMetricDef and mT.idTestDef=tD.idTestDef and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2 order by mV.idMetricValue").setParameter("value1",nameTestDef).setParameter("value2",comp).getResultList(); List<List<MetricValue>> list_metric=new ArrayList<>(); list_metric.add(listMetricValueReference); list_metric.add(listMetricValueHead); return ok(toJson(list_metric)); } @Transactional(readOnly = true) public Result getmetricValueTemplateCompare(String metricChoixId,String reference,String comp) { MetricValue metricValueReference=(MetricValue)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, ChangeList cL where mV.idMetricDef=:value1 and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2").setParameter("value1",metricChoixId).setParameter("value2",reference).getSingleResult(); MetricValue metricValueHead=(MetricValue)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, ChangeList cL where mV.idMetricDef=:value1 and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2").setParameter("value1",metricChoixId).setParameter("value2",comp).getSingleResult(); List<MetricValue> list_metric=new ArrayList<>(); list_metric.add(metricValueReference); list_metric.add(metricValueHead); return ok(toJson(list_metric)); } @Transactional(readOnly = true) public Result getComparerChangeListUnique(String metricId,String reference,String tester) { MetricValue mv_reference=(MetricValue) JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR,ChangeList cL where mV.idMetricDef=:value1 and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2").setParameter("value1",metricId).setParameter("value2",reference).getSingleResult(); MetricValue mv_tester=(MetricValue) JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, ChangeList cL where mV.idMetricDef=:value1 and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2").setParameter("value1",metricId).setParameter("value2",tester).getSingleResult(); String resultat="neutre"; double tolerancePourcentage =Double.parseDouble((String)JPA.em().createQuery("select mD.tolerance from MetricDef mD where mD.idMetricDef=:value").setParameter("value",metricId).getSingleResult()); double tolerance_metrique=(tolerancePourcentage)/100; double tolerance=tolerance_metrique*(Double.parseDouble((mv_reference.value))); double value_reference=Double.parseDouble(mv_reference.value); double value_tester=Double.parseDouble(mv_tester.value); if(value_reference>value_tester) { if(value_reference>(value_tester+tolerance)) resultat="avance"; else { if(resultat.equals("avance")) ; else resultat="neutre"; } } else { if(value_reference==value_tester) { if(resultat.equals("avance")) ; else resultat="neutre"; } else { if((value_reference+tolerance)<value_tester) { resultat="retrait"; return ok(toJson(resultat)); } else { if(resultat.equals("avance")) ; else resultat="neutre"; } } } return ok(toJson(resultat)); } public Result getIndex2() { return ok(index2.render()); } ////////////////////////////Register Part @Transactional public Result signUp(String type) { DynamicForm dynamicForm = Form.form().bindFromRequest(); String email= dynamicForm.get("email"); String password=dynamicForm.get("password"); Long count=(Long)JPA.em().createQuery("select count(u) from User u where u.email=:value").setParameter("value",email).getSingleResult(); if(count!=0) { return redirect(routes.Application.getSignUp()); } else { User user = new User(); user.setEmail(email); user.setPassword(password); if(type.equals("Testeur")) user.setisAdmin(true); if(type.equals("Developpeur")) user.setisAdmin(false); JPA.em().persist(user); session().clear(); session("username",email); if(user.isAdmin==false) { return redirect(routes.Application.index()); } else { return redirect(routes.Application.index2()); } } } @Transactional(readOnly = true) public Result accueil() { return ok(accueil.render()); } @Transactional(readOnly = true) public Result getSignUp() { return ok(signUp.render()); } @Transactional public Result login() { DynamicForm dynamicForm = Form.form().bindFromRequest(); String email= dynamicForm.get("email"); String password=dynamicForm.get("password"); byte[] a=User.getSha512(password); Long count=(Long)JPA.em().createQuery("select count(u) from User u where u.email=:value1 ").setParameter("value1",email).getSingleResult(); if (count==0) { // return ok(signUp.render("user does not exist")); //return ok(signUp.render()); return redirect(routes.Application.getLoginPage()); } else{ User user=(User) JPA.em().createQuery("select u from User u where u.email=:value1").setParameter("value1",email).getSingleResult(); if(Arrays.equals(a,user.shaPassword)) { session().clear(); session("username", email); if(user.isAdmin==true) // return ok(index2.render()); return redirect(routes.Application.getIndex2Page()); else // return ok(index.render()); return redirect(routes.Application.index()); } else { // return ok(signUp.render("wrong password")); // return ok(signUp.render()); return redirect(routes.Application.getLoginPage()); } } } @Transactional(readOnly = true) public Result getUsers() { List<User> s=(List<User>)JPA.em().createQuery("select u from User u ").getResultList(); return ok(toJson(s)); } @Transactional(readOnly = true) public Result logout() { session().clear(); // session().destroy(); // return ok(signUp.render("signed Out")); return ok(signUp.render()); } @Transactional(readOnly = true) public Result getCouleurMetriqueValidate(String testName,String versionId) { String id_head=(String) JPA.em().createQuery("select v.headId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); String id_base=(String) JPA.em().createQuery("select v.baseId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); return getCouleurMetriqueComparer(testName,id_base,id_head); /* String base=(String)JPA.em().createQuery("select v.baseId from Version v where v.id=:value").setParameter("value",versionId).getSingleResult(); String head=(String)JPA.em().createQuery("select v.headId from Version v where v.id=:value").setParameter("value",versionId).getSingleResult(); // List<MetricValue> String metricValeurBase=(String) JPA.em().createQuery("select distinct m.value from MetricValue m ,TestRun tR, MetricDef mD,TestDef tD where tR.idChangeList=:value3 and m.idTestRun=tR.idTestRun and m.idMetricDef=mD.idMetricDef and mD.name=:value1 and tD.idTestDef=tR.idTestDef and tD.name=:value2").setParameter("value1",metricDefName).setParameter("value2",testDefName).setParameter("value3",base).getSingleResult(); String metricValeurHead=(String) JPA.em().createQuery("select distinct m.value from MetricValue m ,TestRun tR, MetricDef mD,TestDef tD where tR.idChangeList=:value3 and m.idTestRun=tR.idTestRun and m.idMetricDef=mD.idMetricDef and mD.name=:value1 and tD.idTestDef=tR.idTestDef and tD.name=:value2").setParameter("value1",metricDefName).setParameter("value2",testDefName).setParameter("value3",head).getSingleResult(); String tolerance =(String) JPA.em().createQuery("select m.tolerance from MetricDef m where m.name=:value").setParameter("value",metricDefName).getSingleResult(); String resultat="neutre"; Double toleranceChiffre=(Double.parseDouble(tolerance))/100; Double toleranceUtilise=toleranceChiffre*(Double.parseDouble((metricValeurBase))); Double value_reference=Double.parseDouble(metricValeurBase); Double value_tester=Double.parseDouble(metricValeurHead); if(value_reference>value_tester) { if(value_reference>(value_tester+toleranceUtilise)) resultat="avance"; else { if(resultat.equals("avance")) ; else resultat="neutre"; } } else { if(value_reference==value_tester) { if(resultat.equals("avance")) ; else resultat="neutre"; } else { if((value_reference+toleranceUtilise)<value_tester) { resultat="retrait"; return ok(toJson(resultat)); } else { if(resultat.equals("avance")) ; else resultat="neutre"; } } } return ok(toJson(resultat)); */ } @Transactional(readOnly = true) public Result getCouleurMetriqueComparer(String testdef,String reference,String tester) { List<String>couleur=new ArrayList<>(); List<MetricValue>mv_reference=(List<MetricValue>)JPA.em().createQuery("select distinct m from MetricValue m where m.idTestRun in (select tR.idTestRun from TestRun tR,ChangeList cL where tR.idChangeList=cL.id and cL.id=:value1) and m.idMetricDef in (select mD.idMetricDef from MetricDef mD,MetricTest mT where mD.idMetricDef=mT.idMetricDef and mT.idTestDef in(select t.idTestDef from TestDef t where t.name=:value2)) order by m.idMetricValue").setParameter("value1",reference).setParameter("value2",testdef).getResultList(); List<MetricValue>mv_tester=(List<MetricValue>)JPA.em().createQuery("select distinct m from MetricValue m where m.idTestRun in (select tR.idTestRun from TestRun tR,ChangeList cL where tR.idChangeList=cL.id and cL.id=:value1) and m.idMetricDef in (select mD.idMetricDef from MetricDef mD,MetricTest mT where mD.idMetricDef=mT.idMetricDef and mT.idTestDef in(select t.idTestDef from TestDef t where t.name=:value2)) order by m.idMetricValue").setParameter("value1",tester).setParameter("value2",testdef).getResultList(); String resultat="neutre"; for(int i=0;i<mv_tester.size();++i) { String metricdefid=mv_reference.get(i).idMetricDef; for(int j=0;j<mv_reference.size();++j) { if((mv_reference.get(j).idMetricDef).equals(metricdefid)) { double tolerancePourcentage =Double.parseDouble((String)JPA.em().createQuery("select mD.tolerance from MetricDef mD where mD.idMetricDef=:value").setParameter("value",metricdefid).getSingleResult()); double tolerance_metrique=(tolerancePourcentage)/100; double tolerance=tolerance_metrique*(Double.parseDouble((mv_reference.get(j).value))); double value_reference=Double.parseDouble(mv_reference.get(j).value); double value_tester=Double.parseDouble(mv_tester.get(i).value); if(value_reference>value_tester) { if(value_reference>(value_tester+tolerance)) //resultat="avance"; couleur.add(i,"avance"); else { couleur.add(i,"neutre"); } } else { if(value_reference==value_tester) { couleur.add(i,"neutre"); } else { if((value_reference+tolerance)<value_tester) { //resultat="retrait"; // return ok(toJson(resultat)); couleur.add(i,"retrait"); } else { couleur.add(i,"neutre"); } } } } } } return ok(toJson(couleur)); } public Result index2() { return ok(index2.render()); } @Transactional(readOnly = true) public Result getNomVersionCorrespondant(String changeList) { String nom= (String) JPA.em().createQuery("select distinct v.name from Version v,ChangeList cL where cL.id=:value and cL.versionId=v.id").setParameter("value",changeList).getSingleResult(); return ok(toJson(nom)); } @Transactional(readOnly = true) public Result getChangeListById(String versionId) { List<ChangeList> list_ChangeList=(List<ChangeList>)JPA.em().createQuery("select distinct cL from ChangeList cL where cL.id in (select c.id from ChangeList c where c.versionId=:value) or cL.id in (select b.baseId from Version b where b.id=:value) order by cL.id").setParameter("value",versionId).getResultList(); return ok(toJson(list_ChangeList)); } @Transactional public Result deleteAllRows() { JPA.em().createQuery("DELETE FROM ChangeList").executeUpdate(); JPA.em().createQuery("DELETE FROM MetricDef").executeUpdate(); JPA.em().createQuery("DELETE FROM MetricTest").executeUpdate(); JPA.em().createQuery("DELETE FROM MetricValue").executeUpdate(); JPA.em().createQuery("DELETE FROM TestDef").executeUpdate(); JPA.em().createQuery("DELETE FROM TestRun").executeUpdate(); JPA.em().createQuery("DELETE FROM User").executeUpdate(); JPA.em().createQuery("DELETE FROM Version").executeUpdate(); return redirect(routes.Application.getLoginPage()); } }
UTF-8
Java
38,394
java
Application.java
Java
[ { "context": "t.current().session();\n String email=session.get(\"username\");\n Version version = Form.form(Version.class).bi", "end": 1257, "score": 0.9084150195121765, "start": 1249, "tag": "USERNAME", "value": "username" }, { "context": "eList.versionId=id;\n changeList.user=session.get(\"username\");\n Version version=(Version) JPA.em().find(Versi", "end": 11536, "score": 0.9974592328071594, "start": 11528, "tag": "USERNAME", "value": "username" }, { "context": "r();\n user.setEmail(email);\n user.setPassword(password);\n if(type.equals(\"Testeur\"))\n user.setisAdmi", "end": 28043, "score": 0.8276932835578918, "start": 28035, "tag": "PASSWORD", "value": "password" }, { "context": ".get(\"email\");\n String password=dynamicForm.get(\"password\");\n byte[] a=User.getSha512(password);\n\n Long c", "end": 28822, "score": 0.585976243019104, "start": 28814, "tag": "PASSWORD", "value": "password" } ]
null
[]
package controllers; import play.*; import play.mvc.*; import play.db.jpa.*; import views.html.*; import models.Person; import models.Version; import models.ChangeList; import models.MetricTest; import models.MetricDef; import models.TestDef; import models.TestRun; import models.MetricValue; import models.User; import play.data.Form; import java.util.List; import java.util.*; import java.util.ArrayList; import static play.libs.Json.*; import play.data.DynamicForm; import play.data.Form; import play.mvc.Http; import play.mvc.Http.Session; public class Application extends Controller { public Result index() { return ok(index.render()); } public Result getLoginPage() { return ok(signUp.render()); } public Result getIndex2Page() { return ok(index2.render()); } public Result getTestPage() { return ok(tester.render()); } @Transactional(readOnly = true) public Result getAllChangeLists() { List<ChangeList> ListchangeList = (List<ChangeList>) JPA.em().createQuery("select p from ChangeList p order by p.versionId").getResultList(); return ok(toJson(ListchangeList)); } @Transactional public Result addVersion() { Session session = Http.Context.current().session(); String email=session.get("username"); Version version = Form.form(Version.class).bindFromRequest().get(); JPA.em().persist(version); ChangeList change=new ChangeList(); String id_version1; version= (Version) JPA.em().createQuery("SELECT p from Version p where p.name =:name").setParameter("name",version.name).getSingleResult(); id_version1=version.id; change.setversionId(id_version1); change.description = "Base" + version.id; change.user=email; JPA.em().persist(change); change=(ChangeList) JPA.em().createQuery("SELECT p from ChangeList p WHERE p.versionId =:versionid").setParameter("versionid",id_version1).getSingleResult(); String id_change=(String) change.id; Version version_base=(Version) JPA.em().find(Version.class,id_version1); version_base.setheadId(""+id_change); version_base.setbaseId(""+id_change); JPA.em().merge(version_base); return redirect(routes.Application.index()); //return redirect(routes.Application.getTestPage()); } @Transactional public Result addVersion3(String id,String versionName) { Version version=new Version(); version.setheadId(id); version.setbaseId(id); version.name=(String)versionName; JPA.em().persist(version); return redirect(routes.Application.index()); } @Transactional public Result createmetric() { MetricDef metric=new MetricDef(); DynamicForm dynamicForm = Form.form().bindFromRequest(); String name= dynamicForm.get("name"); String description=dynamicForm.get("description"); String tolerance=dynamicForm.get("tolerance"); metric.name=name; metric.description=description; metric.tolerance=tolerance; JPA.em().persist(metric); return redirect(routes.Application.getIndex2()); } //ajouter les contraintes qui vont empecher a lutilisateur de creer des versions de meme nom, et des testdef aussi. @Transactional public Result createTest(String tags) { String[] array = tags.split(","); TestDef test=new TestDef(); DynamicForm dynamicForm = Form.form().bindFromRequest(); String name= dynamicForm.get("name"); String description=dynamicForm.get("description"); test.name=name; test.description=description; JPA.em().persist(test); TestDef test_modifier=(TestDef) JPA.em().createQuery("select DISTINCT p from TestDef p where p.name=:name1 and p.description=:name2").setParameter("name1",name).setParameter("name2",description).getSingleResult(); String test_id=test_modifier.idTestDef; for(int i=0;i<array.length;++i) { MetricTest metric=new MetricTest(); metric.idTestDef=test_id; metric.idMetricDef=array[i]; JPA.em().persist(metric); } return redirect(routes.Application.getIndex2()); } ///parler du workaroundd @Transactional public Result addMetricValue( ) { DynamicForm dynamicForm = Form.form().bindFromRequest(); List<List <MetricDef>> liste_metri=new ArrayList<>(); List<TestRun> list_testRun=(List<TestRun>)JPA.em().createQuery("select distinct p from TestRun p, MetricValue v where p.idTestRun=v.idTestRun and v.value=:valeur").setParameter("valeur","null").getResultList(); for(int i=0;i<list_testRun.size();++i) { String test=list_testRun.get(i).idTestDef; List<MetricDef> testdef=(List<MetricDef>)JPA.em().createQuery("select distinct s from MetricTest p, TestDef t, MetricDef s where p.idMetricDef=s.idMetricDef AND p.idTestDef=t.idTestDef AND t.idTestDef=:value").setParameter("value",test).getResultList(); liste_metri.add(i,testdef); for(int j=0;j<testdef.size();++j) { String metric_id=testdef.get(j).idMetricDef; String test_id= list_testRun.get(i).idTestRun; MetricValue metric_value=(MetricValue) JPA.em().createQuery("select p from MetricValue p where p.idTestRun=:test_id and p.idMetricDef=:metric_id").setParameter("test_id",test_id).setParameter("metric_id",metric_id).getSingleResult(); String value=dynamicForm.get(testdef.get(j).idMetricDef+test_id); if(value.equals("")) { ; } else{ metric_value.value=value; JPA.em().merge(metric_value); } } } return redirect(routes.Application.getIndex2Page()); } @Transactional(readOnly = true) public Result getTestDefOrder() { List<TestRun> list_testRun=(List<TestRun>)JPA.em().createQuery("select distinct p from TestRun p, MetricValue v where p.idTestRun=v.idTestRun and v.value=:valeur").setParameter("valeur","null").getResultList(); List<TestDef> list_testDef=new ArrayList<>(); for(int i=0;i<list_testRun.size();++i) { // String valeur=list_testRun.get(i).idTestDef; TestDef td=(TestDef)JPA.em().createQuery("select td from TestDef td where td.idTestDef=:value").setParameter("value",list_testRun.get(i).idTestDef).getSingleResult(); list_testDef.add(i,td); } return ok(toJson(list_testDef)); } @Transactional(readOnly = true) public Result getMetricValue() { List<MetricValue> metricValue = (List<MetricValue>) JPA.em().createQuery("select p from MetricValue p order by p.idMetricValue").getResultList(); return ok(toJson(metricValue)); } @Transactional(readOnly = true) public Result getTestmetrique() { List<MetricTest> metricTest = (List<MetricTest>) JPA.em().createQuery("select p from MetricTest p").getResultList(); return ok(toJson(metricTest)); } @Transactional(readOnly = true) public Result getTest() { List<TestDef> list_test = (List<TestDef>) JPA.em().createQuery("select p from TestDef p").getResultList(); return ok(toJson(list_test)); } @Transactional(readOnly = true) public Result getTesteurNeedsTest() { List<TestRun> list_testRun=(List<TestRun>)JPA.em().createQuery("select distinct p from TestRun p, MetricValue v where p.idTestRun=v.idTestRun and v.value=:valeur").setParameter("valeur","null").getResultList(); return ok(toJson(list_testRun)); } @Transactional(readOnly = true) public Result getTesteurNeedsMetric() { List<List <MetricDef>> liste_metri=new ArrayList<>(); List<TestRun> list_testRun=(List<TestRun>)JPA.em().createQuery("select distinct p from TestRun p, MetricValue v where p.idTestRun=v.idTestRun and v.value=:valeur").setParameter("valeur","null").getResultList(); for(int i=0;i<list_testRun.size();++i) { String test=list_testRun.get(i).idTestDef; List<MetricDef> testdef=(List<MetricDef>)JPA.em().createQuery("select distinct s from MetricTest p, TestDef t, MetricDef s where p.idMetricDef=s.idMetricDef AND p.idTestDef=t.idTestDef AND t.idTestDef=:value").setParameter("value",test).getResultList(); liste_metri.add(i,testdef); } return ok(toJson(liste_metri)); } // @Transactional(readOnly = true) public Result getTestRunCreate(String id) { List<TestDef> list_test = (List<TestDef>) JPA.em().createQuery("select p from TestDef p").getResultList(); return ok(toJson(list_test)); } @Transactional(readOnly = true) public Result getTesteurWork() { return ok(index2.render()); } @Transactional public Result getTestRunDexideCreate(String id_test_def,String id_changeList) { // TestRun t=new TestRun(); String count=(String) JPA.em().createQuery("select count(x) from TestRun x where x.idTestDef=:name1 and x.idChangeList=:name2").setParameter("name1",id_test_def).setParameter("name2",id_changeList).getSingleResult().toString(); if(count.equals("0")) { TestRun t=new TestRun(); t.idTestDef=id_test_def; t.idChangeList=id_changeList; JPA.em().persist(t); String id_testRun=(String) JPA.em().createQuery("SELECT x.id FROM TestRun x WHERE x.idTestDef=:id1 and x.idChangeList=:id2").setParameter("id1",id_test_def).setParameter("id2",id_changeList).getSingleResult(); List<MetricDef> testdef=(List<MetricDef>)JPA.em().createQuery("select s from MetricTest p, TestDef t, MetricDef s where p.idMetricDef=s.idMetricDef AND p.idTestDef=t.idTestDef AND t.idTestDef=:value").setParameter("value",id_test_def).getResultList(); for(int i=0;i<testdef.size();++i) { MetricValue m=new MetricValue(); m.idTestRun=id_testRun; m.idMetricDef=testdef.get(i).idMetricDef; m.value="null"; JPA.em().persist(m); } } else { TestRun t= (TestRun) JPA.em().createQuery("select distinct t from TestRun t where t.idTestDef=:value1 and t.idChangeList=:value2").setParameter("value1",id_test_def).setParameter("value2",id_changeList).getSingleResult(); String id_test_run = t.idTestRun; List<MetricValue> m_value= (List<MetricValue>) JPA.em().createQuery("select m from MetricValue m where m.idTestRun=:value").setParameter("value",id_test_run).getResultList(); for(int i=0;i<m_value.size();++i) { m_value.get(i).value="null"; JPA.em().merge(m_value.get(i)); } //je met ;les valeurs du testRun a null } return redirect(routes.Application.index()); } @Transactional(readOnly = true) public Result getTestRunAll() { List <TestRun> list_test_run=(List<TestRun>) JPA.em().createQuery("select p from TestRun p").getResultList(); return ok(toJson(list_test_run)); } @Transactional(readOnly = true) public Result getmetric() { List<MetricDef> metrics = (List<MetricDef>) JPA.em().createQuery("select p from MetricDef p").getResultList(); return ok(toJson(metrics)); } @Transactional(readOnly = true) public Result getVersions() { List<Version> versions = (List<Version>) JPA.em().createQuery("select p from Version p order by p.id").getResultList(); return ok(toJson(versions)); } @Transactional public Result addChangeList() { ChangeList changeList = Form.form(ChangeList.class).bindFromRequest().get(); JPA.em().persist(changeList); return redirect(routes.Application.index()); } @Transactional public Result addChangeList2(String id,String description) { Session session = Http.Context.current().session(); ChangeList changeList=new ChangeList(); changeList.description=description; changeList.versionId=id; changeList.user=session.get("username"); Version version=(Version) JPA.em().find(Version.class,id); JPA.em().persist(changeList); String change=(String) JPA.em().createQuery("SELECT MAX(c.id) FROM ChangeList c,Version v WHERE (c.versionId=v.id or c.id=v.baseId) and c.versionId=:id1").setParameter("id1",id).getSingleResult(); version.setheadId(change); JPA.em().merge(version); return redirect(routes.Application.index()); } @Transactional(readOnly = true) public Result getChangeLists() { List<ChangeList> changeLists = (List<ChangeList>) JPA.em().createQuery("select p from ChangeList p").getResultList(); return ok(toJson(changeLists)); } @Transactional(readOnly = true) public Result getTestDef() { List<TestDef> liste_test_def=(List<TestDef>)JPA.em().createQuery("select p from TestDef p").getResultList(); return ok(toJson(liste_test_def)); } //comparaison entre changeList @Transactional(readOnly = true) public Result getComparePage(String value) { List<Version> list_version_chercher=(List<Version>) JPA.em().createQuery("select distinct v from Version v, ChangeList c,TestRun tR,TestDef tD,MetricValue mV where (v.id=c.versionId or v.baseId=c.id) and c.id=tR.idChangeList and tR.idTestDef=tD.idTestDef and mV.idTestRun=tR.idTestRun and mV.value!='null' and tD.name=:value1 order by v.id) ").setParameter("value1",value).getResultList(); List<Long> list_change=(List<Long>) JPA.em().createQuery("select count(distinct c) as ttt from Version v, ChangeList c,TestRun tR,TestDef tD,MetricValue mV where (v.id=c.versionId or v.baseId=c.id) and c.id=tR.idChangeList and tR.idTestDef=tD.idTestDef and mV.idTestRun=tR.idTestRun and mV.value!='null' and tD.name=:value1 group by v.id ) ").setParameter("value1",value).getResultList(); List<Version>list_version=new ArrayList<>(); for(int k=0;k<(list_version_chercher).size();++k) { Long a=(Long)list_change.get(k); if(a>= 2) list_version.add(list_version_chercher.get(k)); } List<List<ChangeList>> list_cL= new ArrayList<>(); for(int i=0;i<list_version.size();++i) { List<ChangeList> list=(List<ChangeList>) JPA.em().createQuery("select c from ChangeList c where c.id in(select p.id from ChangeList p where p.versionId=:value1) or c.id in(select v.baseId from Version v where v.id=:value2) ").setParameter("value1",list_version.get(i).id).setParameter("value2",list_version.get(i).id).getResultList(); list_cL.add(i,list); } return ok(comparaisonPage.render(list_version,list_cL,value)); } @Transactional(readOnly = true) public Result getChangeListVersionTestDef(String nameTestDef,String version) { List<ChangeList> list=(List<ChangeList>) JPA.em().createQuery("select distinct c from ChangeList c,TestRun tR,TestDef tD where c.id= tR.idChangeList and tR.idTestDef=tD.idTestDef and tD.name =:value2 and (c.id in(select p.id from ChangeList p where p.versionId=:value1) or c.id in(select v.baseId from Version v where v.id=:value1)) ").setParameter("value1",version).setParameter("value2",nameTestDef).getResultList(); return ok(toJson(list)); } @Transactional(readOnly=true) public Result getMetricValueTest(String reference, String testdef) { List<MetricValue>mv_reference=(List<MetricValue>)JPA.em().createQuery("select distinct m from MetricValue m where m.idTestRun in (select tR.idTestRun from TestRun tR,ChangeList cL where tR.idChangeList=cL.id and cL.id=:value1) and m.idMetricDef in (select mD.idMetricDef from MetricDef mD,MetricTest mT where mD.idMetricDef=mT.idMetricDef and mT.idTestDef in(select t.idTestDef from TestDef t where t.name=:value2))").setParameter("value1",reference).setParameter("value2",testdef).getResultList(); return ok(toJson(mv_reference)); } @Transactional(readOnly = true) public Result getComparerChangeList(String testdef,String reference,String tester) { List<MetricValue>mv_reference=(List<MetricValue>)JPA.em().createQuery("select distinct m from MetricValue m where m.idTestRun in (select tR.idTestRun from TestRun tR,ChangeList cL where tR.idChangeList=cL.id and cL.id=:value1) and m.idMetricDef in (select mD.idMetricDef from MetricDef mD,MetricTest mT where mD.idMetricDef=mT.idMetricDef and mT.idTestDef in(select t.idTestDef from TestDef t where t.name=:value2) )").setParameter("value1",reference).setParameter("value2",testdef).getResultList(); List<MetricValue>mv_tester=(List<MetricValue>)JPA.em().createQuery("select distinct m from MetricValue m where m.idTestRun in (select tR.idTestRun from TestRun tR,ChangeList cL where tR.idChangeList=cL.id and cL.id=:value1) and m.idMetricDef in (select mD.idMetricDef from MetricDef mD,MetricTest mT where mD.idMetricDef=mT.idMetricDef and mT.idTestDef in(select t.idTestDef from TestDef t where t.name=:value2))").setParameter("value1",tester).setParameter("value2",testdef).getResultList(); String resultat="neutre"; for(int i=0;i<mv_tester.size();++i) { String metricdefid=mv_reference.get(i).idMetricDef; for(int j=0;j<mv_reference.size();++j) { if((mv_reference.get(j).idMetricDef).equals(metricdefid)) { double tolerancePourcentage =Double.parseDouble((String)JPA.em().createQuery("select mD.tolerance from MetricDef mD where mD.idMetricDef=:value").setParameter("value",metricdefid).getSingleResult()); double tolerance_metrique=(tolerancePourcentage)/100; double tolerance=tolerance_metrique*(Double.parseDouble((mv_reference.get(j).value))); double value_reference=Double.parseDouble(mv_reference.get(j).value); double value_tester=Double.parseDouble(mv_tester.get(i).value); if(value_reference>value_tester) { if(value_reference>(value_tester+tolerance)) resultat="avance"; else { if(resultat.equals("avance")) ; else resultat="neutre"; } } else { if(value_reference==value_tester) { if(resultat.equals("avance")) ; else resultat="neutre"; } else { if((value_reference+tolerance)<value_tester) { resultat="retrait"; return ok(toJson(resultat)); } else { if(resultat.equals("avance")) ; else resultat="neutre"; } } } } } } return ok(toJson(resultat)); } @Transactional(readOnly = true) public Result getValidateVersion(String testName,String versionId) { String id_head=(String) JPA.em().createQuery("select v.headId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); String id_base=(String) JPA.em().createQuery("select v.baseId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); Long head=(Long) JPA.em().createQuery("select count(tR) from TestRun tR, TestDef tD where tR.idChangeList=:value1 and tR.idTestDef=tD.idTestDef and tD.name=:value2").setParameter("value1",id_head).setParameter("value2",testName).getSingleResult(); Long base=(Long) JPA.em().createQuery("select count(tR) from TestRun tR, TestDef tD where tR.idChangeList=:value1 and tR.idTestDef=tD.idTestDef and tD.name=:value2").setParameter("value1",id_base).setParameter("value2",testName).getSingleResult(); if(head!=0 && base!=0) { return ok(toJson("true")); } else return ok(toJson("false")); } @Transactional(readOnly = true) public Result validateVersion(String testName,String versionId) { String id_head=(String) JPA.em().createQuery("select v.headId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); String id_base=(String) JPA.em().createQuery("select v.baseId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); return getComparerChangeList(testName,id_base,id_head); } //ajouter @Transactional(readOnly = true) public Result getMetricDefNom(String nameTestDef) { List<MetricDef> list_metric=(List<MetricDef>)JPA.em().createQuery("select distinct mD from MetricDef mD,MetricTest mT,TestDef tD where mD.idMetricDef=mT.idMetricDef and mT.idTestDef=tD.idTestDef and tD.name=:value").setParameter("value",nameTestDef).getResultList(); return ok(toJson(list_metric)); } @Transactional(readOnly = true) public Result getMetricValuesTemplateValidate(String testDef, String versionId) { String id_head=(String) JPA.em().createQuery("select v.headId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); String id_base=(String) JPA.em().createQuery("select v.baseId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); List<MetricValue> listMetricValueBase=(List<MetricValue>)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, TestDef tD,ChangeList cL,MetricTest mT,MetricDef mD where tD.name=:value1 and mT.idMetricDef=mD.idMetricDef and mT.idTestDef=tD.idTestDef and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2 order by mV.idMetricValue").setParameter("value1",testDef).setParameter("value2",id_base).getResultList(); List<MetricValue> listMetricValueHead=(List<MetricValue>)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, TestDef tD,ChangeList cL,MetricTest mT,MetricDef mD where tD.name=:value1 and mT.idMetricDef=mD.idMetricDef and mT.idTestDef=tD.idTestDef and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2 order by mV.idMetricValue").setParameter("value1",testDef).setParameter("value2",id_head).getResultList(); List<List<MetricValue>> list_metric=new ArrayList<>(); list_metric.add(listMetricValueBase); list_metric.add(listMetricValueHead); return ok(toJson(list_metric)); } @Transactional(readOnly = true) public Result getHeadBaseId(String versionId) { List<String> list=(List<String>)JPA.em().createQuery("select cL.id from ChangeList cL,Version v where (cL.id=v.headId or cL.id=v.baseId) and v.id=:value order by cL.id").setParameter("value",versionId).getResultList(); return ok(toJson(list)); } @Transactional(readOnly = true) public Result getMetricValuesTemplateCompare(String nameTestDef,String reference,String comp) { List<MetricValue> listMetricValueReference=(List<MetricValue>)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, TestDef tD,ChangeList cL,MetricTest mT,MetricDef mD where tD.name=:value1 and mT.idMetricDef=mD.idMetricDef and mT.idTestDef=tD.idTestDef and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2 order by mV.idMetricValue").setParameter("value1",nameTestDef).setParameter("value2",reference).getResultList(); List<MetricValue> listMetricValueHead=(List<MetricValue>)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, TestDef tD,ChangeList cL,MetricTest mT,MetricDef mD where tD.name=:value1 and mT.idMetricDef=mD.idMetricDef and mT.idTestDef=tD.idTestDef and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2 order by mV.idMetricValue").setParameter("value1",nameTestDef).setParameter("value2",comp).getResultList(); List<List<MetricValue>> list_metric=new ArrayList<>(); list_metric.add(listMetricValueReference); list_metric.add(listMetricValueHead); return ok(toJson(list_metric)); } @Transactional(readOnly = true) public Result getmetricValueTemplateCompare(String metricChoixId,String reference,String comp) { MetricValue metricValueReference=(MetricValue)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, ChangeList cL where mV.idMetricDef=:value1 and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2").setParameter("value1",metricChoixId).setParameter("value2",reference).getSingleResult(); MetricValue metricValueHead=(MetricValue)JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, ChangeList cL where mV.idMetricDef=:value1 and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2").setParameter("value1",metricChoixId).setParameter("value2",comp).getSingleResult(); List<MetricValue> list_metric=new ArrayList<>(); list_metric.add(metricValueReference); list_metric.add(metricValueHead); return ok(toJson(list_metric)); } @Transactional(readOnly = true) public Result getComparerChangeListUnique(String metricId,String reference,String tester) { MetricValue mv_reference=(MetricValue) JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR,ChangeList cL where mV.idMetricDef=:value1 and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2").setParameter("value1",metricId).setParameter("value2",reference).getSingleResult(); MetricValue mv_tester=(MetricValue) JPA.em().createQuery("select distinct mV from MetricValue mV,TestRun tR, ChangeList cL where mV.idMetricDef=:value1 and cL.id=tR.idChangeList and mV.idTestRun=tR.idTestRun and cL.id=:value2").setParameter("value1",metricId).setParameter("value2",tester).getSingleResult(); String resultat="neutre"; double tolerancePourcentage =Double.parseDouble((String)JPA.em().createQuery("select mD.tolerance from MetricDef mD where mD.idMetricDef=:value").setParameter("value",metricId).getSingleResult()); double tolerance_metrique=(tolerancePourcentage)/100; double tolerance=tolerance_metrique*(Double.parseDouble((mv_reference.value))); double value_reference=Double.parseDouble(mv_reference.value); double value_tester=Double.parseDouble(mv_tester.value); if(value_reference>value_tester) { if(value_reference>(value_tester+tolerance)) resultat="avance"; else { if(resultat.equals("avance")) ; else resultat="neutre"; } } else { if(value_reference==value_tester) { if(resultat.equals("avance")) ; else resultat="neutre"; } else { if((value_reference+tolerance)<value_tester) { resultat="retrait"; return ok(toJson(resultat)); } else { if(resultat.equals("avance")) ; else resultat="neutre"; } } } return ok(toJson(resultat)); } public Result getIndex2() { return ok(index2.render()); } ////////////////////////////Register Part @Transactional public Result signUp(String type) { DynamicForm dynamicForm = Form.form().bindFromRequest(); String email= dynamicForm.get("email"); String password=dynamicForm.get("password"); Long count=(Long)JPA.em().createQuery("select count(u) from User u where u.email=:value").setParameter("value",email).getSingleResult(); if(count!=0) { return redirect(routes.Application.getSignUp()); } else { User user = new User(); user.setEmail(email); user.setPassword(<PASSWORD>); if(type.equals("Testeur")) user.setisAdmin(true); if(type.equals("Developpeur")) user.setisAdmin(false); JPA.em().persist(user); session().clear(); session("username",email); if(user.isAdmin==false) { return redirect(routes.Application.index()); } else { return redirect(routes.Application.index2()); } } } @Transactional(readOnly = true) public Result accueil() { return ok(accueil.render()); } @Transactional(readOnly = true) public Result getSignUp() { return ok(signUp.render()); } @Transactional public Result login() { DynamicForm dynamicForm = Form.form().bindFromRequest(); String email= dynamicForm.get("email"); String password=dynamicForm.get("<PASSWORD>"); byte[] a=User.getSha512(password); Long count=(Long)JPA.em().createQuery("select count(u) from User u where u.email=:value1 ").setParameter("value1",email).getSingleResult(); if (count==0) { // return ok(signUp.render("user does not exist")); //return ok(signUp.render()); return redirect(routes.Application.getLoginPage()); } else{ User user=(User) JPA.em().createQuery("select u from User u where u.email=:value1").setParameter("value1",email).getSingleResult(); if(Arrays.equals(a,user.shaPassword)) { session().clear(); session("username", email); if(user.isAdmin==true) // return ok(index2.render()); return redirect(routes.Application.getIndex2Page()); else // return ok(index.render()); return redirect(routes.Application.index()); } else { // return ok(signUp.render("wrong password")); // return ok(signUp.render()); return redirect(routes.Application.getLoginPage()); } } } @Transactional(readOnly = true) public Result getUsers() { List<User> s=(List<User>)JPA.em().createQuery("select u from User u ").getResultList(); return ok(toJson(s)); } @Transactional(readOnly = true) public Result logout() { session().clear(); // session().destroy(); // return ok(signUp.render("signed Out")); return ok(signUp.render()); } @Transactional(readOnly = true) public Result getCouleurMetriqueValidate(String testName,String versionId) { String id_head=(String) JPA.em().createQuery("select v.headId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); String id_base=(String) JPA.em().createQuery("select v.baseId from Version v where v.id=:value1").setParameter("value1",versionId).getSingleResult(); return getCouleurMetriqueComparer(testName,id_base,id_head); /* String base=(String)JPA.em().createQuery("select v.baseId from Version v where v.id=:value").setParameter("value",versionId).getSingleResult(); String head=(String)JPA.em().createQuery("select v.headId from Version v where v.id=:value").setParameter("value",versionId).getSingleResult(); // List<MetricValue> String metricValeurBase=(String) JPA.em().createQuery("select distinct m.value from MetricValue m ,TestRun tR, MetricDef mD,TestDef tD where tR.idChangeList=:value3 and m.idTestRun=tR.idTestRun and m.idMetricDef=mD.idMetricDef and mD.name=:value1 and tD.idTestDef=tR.idTestDef and tD.name=:value2").setParameter("value1",metricDefName).setParameter("value2",testDefName).setParameter("value3",base).getSingleResult(); String metricValeurHead=(String) JPA.em().createQuery("select distinct m.value from MetricValue m ,TestRun tR, MetricDef mD,TestDef tD where tR.idChangeList=:value3 and m.idTestRun=tR.idTestRun and m.idMetricDef=mD.idMetricDef and mD.name=:value1 and tD.idTestDef=tR.idTestDef and tD.name=:value2").setParameter("value1",metricDefName).setParameter("value2",testDefName).setParameter("value3",head).getSingleResult(); String tolerance =(String) JPA.em().createQuery("select m.tolerance from MetricDef m where m.name=:value").setParameter("value",metricDefName).getSingleResult(); String resultat="neutre"; Double toleranceChiffre=(Double.parseDouble(tolerance))/100; Double toleranceUtilise=toleranceChiffre*(Double.parseDouble((metricValeurBase))); Double value_reference=Double.parseDouble(metricValeurBase); Double value_tester=Double.parseDouble(metricValeurHead); if(value_reference>value_tester) { if(value_reference>(value_tester+toleranceUtilise)) resultat="avance"; else { if(resultat.equals("avance")) ; else resultat="neutre"; } } else { if(value_reference==value_tester) { if(resultat.equals("avance")) ; else resultat="neutre"; } else { if((value_reference+toleranceUtilise)<value_tester) { resultat="retrait"; return ok(toJson(resultat)); } else { if(resultat.equals("avance")) ; else resultat="neutre"; } } } return ok(toJson(resultat)); */ } @Transactional(readOnly = true) public Result getCouleurMetriqueComparer(String testdef,String reference,String tester) { List<String>couleur=new ArrayList<>(); List<MetricValue>mv_reference=(List<MetricValue>)JPA.em().createQuery("select distinct m from MetricValue m where m.idTestRun in (select tR.idTestRun from TestRun tR,ChangeList cL where tR.idChangeList=cL.id and cL.id=:value1) and m.idMetricDef in (select mD.idMetricDef from MetricDef mD,MetricTest mT where mD.idMetricDef=mT.idMetricDef and mT.idTestDef in(select t.idTestDef from TestDef t where t.name=:value2)) order by m.idMetricValue").setParameter("value1",reference).setParameter("value2",testdef).getResultList(); List<MetricValue>mv_tester=(List<MetricValue>)JPA.em().createQuery("select distinct m from MetricValue m where m.idTestRun in (select tR.idTestRun from TestRun tR,ChangeList cL where tR.idChangeList=cL.id and cL.id=:value1) and m.idMetricDef in (select mD.idMetricDef from MetricDef mD,MetricTest mT where mD.idMetricDef=mT.idMetricDef and mT.idTestDef in(select t.idTestDef from TestDef t where t.name=:value2)) order by m.idMetricValue").setParameter("value1",tester).setParameter("value2",testdef).getResultList(); String resultat="neutre"; for(int i=0;i<mv_tester.size();++i) { String metricdefid=mv_reference.get(i).idMetricDef; for(int j=0;j<mv_reference.size();++j) { if((mv_reference.get(j).idMetricDef).equals(metricdefid)) { double tolerancePourcentage =Double.parseDouble((String)JPA.em().createQuery("select mD.tolerance from MetricDef mD where mD.idMetricDef=:value").setParameter("value",metricdefid).getSingleResult()); double tolerance_metrique=(tolerancePourcentage)/100; double tolerance=tolerance_metrique*(Double.parseDouble((mv_reference.get(j).value))); double value_reference=Double.parseDouble(mv_reference.get(j).value); double value_tester=Double.parseDouble(mv_tester.get(i).value); if(value_reference>value_tester) { if(value_reference>(value_tester+tolerance)) //resultat="avance"; couleur.add(i,"avance"); else { couleur.add(i,"neutre"); } } else { if(value_reference==value_tester) { couleur.add(i,"neutre"); } else { if((value_reference+tolerance)<value_tester) { //resultat="retrait"; // return ok(toJson(resultat)); couleur.add(i,"retrait"); } else { couleur.add(i,"neutre"); } } } } } } return ok(toJson(couleur)); } public Result index2() { return ok(index2.render()); } @Transactional(readOnly = true) public Result getNomVersionCorrespondant(String changeList) { String nom= (String) JPA.em().createQuery("select distinct v.name from Version v,ChangeList cL where cL.id=:value and cL.versionId=v.id").setParameter("value",changeList).getSingleResult(); return ok(toJson(nom)); } @Transactional(readOnly = true) public Result getChangeListById(String versionId) { List<ChangeList> list_ChangeList=(List<ChangeList>)JPA.em().createQuery("select distinct cL from ChangeList cL where cL.id in (select c.id from ChangeList c where c.versionId=:value) or cL.id in (select b.baseId from Version b where b.id=:value) order by cL.id").setParameter("value",versionId).getResultList(); return ok(toJson(list_ChangeList)); } @Transactional public Result deleteAllRows() { JPA.em().createQuery("DELETE FROM ChangeList").executeUpdate(); JPA.em().createQuery("DELETE FROM MetricDef").executeUpdate(); JPA.em().createQuery("DELETE FROM MetricTest").executeUpdate(); JPA.em().createQuery("DELETE FROM MetricValue").executeUpdate(); JPA.em().createQuery("DELETE FROM TestDef").executeUpdate(); JPA.em().createQuery("DELETE FROM TestRun").executeUpdate(); JPA.em().createQuery("DELETE FROM User").executeUpdate(); JPA.em().createQuery("DELETE FROM Version").executeUpdate(); return redirect(routes.Application.getLoginPage()); } }
38,398
0.656587
0.651977
924
40.547619
70.755852
527
false
false
0
0
0
0
0
0
0.640693
false
false
13
93e14299e814ce4456f381f8c5ba61b92c6d491e
23,510,651,010,178
c163e06c698d511a87ed9adef17800b2a86962a9
/src/main/java/com/example/battleship/model/Cell.java
0943f8c718f8f0e12a93d5449f27608e0c1216f8
[]
no_license
qwang3q/battleship-spring-react
https://github.com/qwang3q/battleship-spring-react
160eb0ef3391b5e249cda94059f6f5f2e8541126
f4a46e6a12df1723bbcc5fb3473ff5c6486452c8
refs/heads/master
2020-04-06T09:07:23.542000
2018-11-13T06:16:40
2018-11-13T06:16:40
157,329,878
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.battleship.model; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.*; import java.io.Serializable; import java.util.function.IntBinaryOperator; /** * Represents the common properties of a cell in the map of the battleship game. */ @Entity public class Cell implements Serializable { private boolean isShipCell; private boolean isHit; private boolean isSunk; private int idOnBoard; @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @ManyToOne(cascade = CascadeType.MERGE) @JoinColumn(name = "board_id") @JsonBackReference private Board map; @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "ship_id") @JsonBackReference private Ship ship; /** * Creates a cell. * @param isHit represents whether the cell is hit, true means the cell was hit, false otherwise */ public Cell(Boolean isShipCell, Boolean isHit) { this.isHit = isHit; this.isShipCell = isShipCell; } public Cell() { this(false, false); } public int getIdOnBoard() { return idOnBoard; } public void setIdOnBoard(int id) { this.idOnBoard = id; } public boolean isShipCell() { return isShipCell; } public void setShipCell(boolean shipCell) { isShipCell = shipCell; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Boolean getHit() { return isHit; } public void setHit(Boolean hit) { isHit = hit; } public boolean isSunk() { return isSunk; } public void setSunk(boolean sunk) { isSunk = sunk; } public Board getMap() { return map; } public void setMap(Board map) { this.map = map; } public Ship getShip() { return ship; } public void setShip(Ship ship) { this.ship = ship; } }
UTF-8
Java
2,035
java
Cell.java
Java
[]
null
[]
package com.example.battleship.model; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.*; import java.io.Serializable; import java.util.function.IntBinaryOperator; /** * Represents the common properties of a cell in the map of the battleship game. */ @Entity public class Cell implements Serializable { private boolean isShipCell; private boolean isHit; private boolean isSunk; private int idOnBoard; @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @ManyToOne(cascade = CascadeType.MERGE) @JoinColumn(name = "board_id") @JsonBackReference private Board map; @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "ship_id") @JsonBackReference private Ship ship; /** * Creates a cell. * @param isHit represents whether the cell is hit, true means the cell was hit, false otherwise */ public Cell(Boolean isShipCell, Boolean isHit) { this.isHit = isHit; this.isShipCell = isShipCell; } public Cell() { this(false, false); } public int getIdOnBoard() { return idOnBoard; } public void setIdOnBoard(int id) { this.idOnBoard = id; } public boolean isShipCell() { return isShipCell; } public void setShipCell(boolean shipCell) { isShipCell = shipCell; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Boolean getHit() { return isHit; } public void setHit(Boolean hit) { isHit = hit; } public boolean isSunk() { return isSunk; } public void setSunk(boolean sunk) { isSunk = sunk; } public Board getMap() { return map; } public void setMap(Board map) { this.map = map; } public Ship getShip() { return ship; } public void setShip(Ship ship) { this.ship = ship; } }
2,035
0.619165
0.619165
103
18.757282
18.419842
100
false
false
0
0
0
0
0
0
0.320388
false
false
13
b3a33645d15745f17b1ab2dfd84034466d47bb3a
17,093,969,870,649
414b6e92b5596bab9f0e13365f862bb29b14ee11
/src/prjTriangleAdv/PartitionerKeyClosure.java
b67165baca28c4fc6cc192c8bf8873eeb4a7a53f
[]
no_license
nickxbs/LabBigData
https://github.com/nickxbs/LabBigData
ddb20d132a278ad548c6fbc41743b1343e0c1cba
3bab5fc1d635d88505ec143cbe81eccf403e1778
refs/heads/master
2021-01-22T23:48:04.574000
2017-06-29T20:44:39
2017-06-29T20:44:39
14,316,407
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package prjTriangleAdv; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapreduce.Partitioner; public class PartitionerKeyClosure extends Partitioner<KeyClosure, Writable> { public int getPartition(KeyClosure bucketItem, Writable intWritable, int numPartitions) { return bucketItem.getBucketIndex()%numPartitions; } }
UTF-8
Java
341
java
PartitionerKeyClosure.java
Java
[]
null
[]
package prjTriangleAdv; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapreduce.Partitioner; public class PartitionerKeyClosure extends Partitioner<KeyClosure, Writable> { public int getPartition(KeyClosure bucketItem, Writable intWritable, int numPartitions) { return bucketItem.getBucketIndex()%numPartitions; } }
341
0.821114
0.821114
13
25.307692
31.096338
90
false
false
0
0
0
0
0
0
0.846154
false
false
13
295c1b5ec597af1fcda62c0a56a38b164445e26b
31,018,253,825,899
33744ede7a884baafd036070b59cf67afcc67efc
/auth-service/src/main/java/com/nayanzin/authservice/accounts/AccountConfig.java
891cd1ae44ebce54067e8a83af4c510ce4654a9f
[]
no_license
Nayanzin-Alexander/cloud-native-java-ch-8-edge
https://github.com/Nayanzin-Alexander/cloud-native-java-ch-8-edge
54d5cda249cd384c59a36c3686295343dcfa9795
f289aa251ab3a726faea74492f0ad27894f07e31
refs/heads/master
2020-04-28T14:51:06.945000
2019-05-16T05:42:06
2019-05-16T05:42:06
175,351,344
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nayanzin.authservice.accounts; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; @Configuration public class AccountConfig { @Bean UserDetailsService userDetailsService(AccountJpaRepository accountJpaRepository) { return username -> accountJpaRepository.findByUsername(username) .map(account -> User.builder() .username(account.getUsername()) .password(account.getPassword()) .disabled(!account.isActive()) .accountExpired(!account.isActive()) .credentialsExpired(!account.isActive()) .accountLocked(!account.isActive()) .authorities("ROLE_ADMIN", "ROLE_USER") .build()) .orElseThrow( () -> new UsernameNotFoundException(String.format("Username %s not found!", username))); } }
UTF-8
Java
1,236
java
AccountConfig.java
Java
[ { "context": ".getUsername())\n .password(account.getPassword())\n .disabled(!account.isA", "end": 742, "score": 0.9724352359771729, "start": 723, "tag": "PASSWORD", "value": "account.getPassword" } ]
null
[]
package com.nayanzin.authservice.accounts; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; @Configuration public class AccountConfig { @Bean UserDetailsService userDetailsService(AccountJpaRepository accountJpaRepository) { return username -> accountJpaRepository.findByUsername(username) .map(account -> User.builder() .username(account.getUsername()) .password(<PASSWORD>()) .disabled(!account.isActive()) .accountExpired(!account.isActive()) .credentialsExpired(!account.isActive()) .accountLocked(!account.isActive()) .authorities("ROLE_ADMIN", "ROLE_USER") .build()) .orElseThrow( () -> new UsernameNotFoundException(String.format("Username %s not found!", username))); } }
1,227
0.640777
0.640777
27
44.777779
29.3186
112
false
false
0
0
0
0
0
0
0.333333
false
false
13
29afae5e9722e9842ebc61852dfe34afdb0d47a2
2,078,764,216,734
1469c792be57c63ff05b5e0f0bac6d00850695f9
/sveikata/src/main/java/lt/sveikata/user/UserController.java
ac3f70c0d118c401d61806cc50c70731487d2a69
[]
no_license
igrazenaite/sveikataForSecondSprint
https://github.com/igrazenaite/sveikataForSecondSprint
b8c3690f1f2aef255373461e278ffb67a7415ae7
35db1d420ecf60c610c26c8dc642978f40251967
refs/heads/master
2021-04-29T20:49:06.272000
2018-02-15T08:10:11
2018-02-15T08:10:11
121,604,514
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lt.sveikata.user; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; //import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @Autowired private UserRepository userRepository; // @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = "/allUsers", method = RequestMethod.GET) public List<UserForClient> giveAllUser() { return getUserService().receiveAllUsers(); } // @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = "/admin/addNewUser", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public void createUser(@RequestBody final AddNewUser newUser) { userService.addNewUser(newUser); } // @PreAuthorize("hasRole('ADMIN')") @PutMapping("/user/{id}") public ResponseEntity<User> updateUser(@PathVariable(value = "id") Long id, @Valid @RequestBody User userDetails) { User user = userRepository.findOne(id); // if (user == null) { // return ResponseEntity.notFound().build(); // } // user.setRole("SUSPENDED"); user.setSuspended(true); User updatedUser = userRepository.save(user); return ResponseEntity.ok(updatedUser); } // @RequestMapping(/*value = "/admin/findUser/manageUser", */path = "/{id}", method = RequestMethod.DELETE) // @ResponseStatus(HttpStatus.NO_CONTENT) // public void deleteAdminFromDatabase(@PathVariable final Long id) { // userService.deleteUser(id); // } // @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = "/admin/findUser/manageUser/{id=7}", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.CREATED) public void updateExistingAdmin(@RequestBody final User user, @PathVariable final Long id) { userService.updateUser(user, id); } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } }
UTF-8
Java
2,537
java
UserController.java
Java
[]
null
[]
package lt.sveikata.user; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; //import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @Autowired private UserRepository userRepository; // @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = "/allUsers", method = RequestMethod.GET) public List<UserForClient> giveAllUser() { return getUserService().receiveAllUsers(); } // @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = "/admin/addNewUser", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public void createUser(@RequestBody final AddNewUser newUser) { userService.addNewUser(newUser); } // @PreAuthorize("hasRole('ADMIN')") @PutMapping("/user/{id}") public ResponseEntity<User> updateUser(@PathVariable(value = "id") Long id, @Valid @RequestBody User userDetails) { User user = userRepository.findOne(id); // if (user == null) { // return ResponseEntity.notFound().build(); // } // user.setRole("SUSPENDED"); user.setSuspended(true); User updatedUser = userRepository.save(user); return ResponseEntity.ok(updatedUser); } // @RequestMapping(/*value = "/admin/findUser/manageUser", */path = "/{id}", method = RequestMethod.DELETE) // @ResponseStatus(HttpStatus.NO_CONTENT) // public void deleteAdminFromDatabase(@PathVariable final Long id) { // userService.deleteUser(id); // } // @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = "/admin/findUser/manageUser/{id=7}", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.CREATED) public void updateExistingAdmin(@RequestBody final User user, @PathVariable final Long id) { userService.updateUser(user, id); } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } }
2,537
0.771384
0.770989
76
32.394737
27.751282
116
false
false
0
0
0
0
0
0
1.25
false
false
13
f75472887f74d30a71daa00641b02a51fa406795
5,849,745,468,124
12b771559c783c7af09750ad46476f242419526f
/codes-demo/src/main/java/hyuki/design/bridge/displaydemo/api/extender/CountDisplay.java
eb300bcf8eb5a761229b8077794422f1b7570ecc
[]
no_license
shixiangweii/codes
https://github.com/shixiangweii/codes
2532dabb636a0eed60a41cfa5dfcb191fd808387
13d5551dae4905fecae69eff9867429a32779401
refs/heads/master
2022-12-22T01:27:44.586000
2021-06-13T06:36:06
2021-06-13T06:36:06
115,195,692
5
1
null
false
2022-12-16T01:20:15
2017-12-23T12:59:39
2021-06-13T06:37:30
2022-12-16T01:20:12
543
3
1
35
Java
false
false
package hyuki.design.bridge.displaydemo.api.extender; import hyuki.design.bridge.displaydemo.api.Display; import hyuki.design.bridge.displaydemo.api.impler.api.DisplayImpl; /** * Description: * User: shixiangweii * Date: 2019-01-26 * Time: 21:02 * * @author shixiangweii */ public class CountDisplay extends Display { public CountDisplay(DisplayImpl impl) { super(impl); } public void multiDisplay(int times) { open(); for (int i = 0; i < times; i++) { print(); } close(); } }
UTF-8
Java
555
java
CountDisplay.java
Java
[ { "context": "ler.api.DisplayImpl;\n\n/**\n * Description:\n * User: shixiangweii\n * Date: 2019-01-26\n * Time: 21:02\n *\n * @author ", "end": 216, "score": 0.9995676279067993, "start": 204, "tag": "USERNAME", "value": "shixiangweii" }, { "context": "i\n * Date: 2019-01-26\n * Time: 21:02\n *\n * @author shixiangweii\n */\npublic class CountDisplay extends Display {\n ", "end": 278, "score": 0.9992254376411438, "start": 266, "tag": "USERNAME", "value": "shixiangweii" } ]
null
[]
package hyuki.design.bridge.displaydemo.api.extender; import hyuki.design.bridge.displaydemo.api.Display; import hyuki.design.bridge.displaydemo.api.impler.api.DisplayImpl; /** * Description: * User: shixiangweii * Date: 2019-01-26 * Time: 21:02 * * @author shixiangweii */ public class CountDisplay extends Display { public CountDisplay(DisplayImpl impl) { super(impl); } public void multiDisplay(int times) { open(); for (int i = 0; i < times; i++) { print(); } close(); } }
555
0.630631
0.607207
26
20.346153
18.861729
66
false
false
0
0
0
0
0
0
0.346154
false
false
13
94e9b4529cee090ae09d099a0affd0d9612b9514
24,172,075,987,766
402bd9095a94134dd558ff254485a615112096c3
/src/main/java/NN/Cost.java
487d00b6baeb96c2064202f117d35970a561fb5d
[ "MIT" ]
permissive
PLAZMAMA/NeuralNet_From_Scratch
https://github.com/PLAZMAMA/NeuralNet_From_Scratch
b42ed3ccff1913fb9422e7e59afa189a299aced9
d7dba021d67c18c8beb06ba391026c6ea7083e8d
refs/heads/master
2020-12-15T13:59:14.677000
2020-03-08T02:58:28
2020-03-08T02:58:28
235,127,158
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package NN; interface Cost{ public double calculate_cost(double[] output, double[] label); public double deriv_calculate(double output, double label); }
UTF-8
Java
161
java
Cost.java
Java
[]
null
[]
package NN; interface Cost{ public double calculate_cost(double[] output, double[] label); public double deriv_calculate(double output, double label); }
161
0.73913
0.73913
6
26
27.736858
66
false
false
0
0
0
0
0
0
0.833333
false
false
13
836f46cffc2140e14e93abfd311c1f4f4fc70c1c
29,532,195,147,799
0db12fdc312f55668533d8dd454b1557d38c3b14
/DesignPattern/src/com/jayfulmath/designpattern/command/OrderWaiter.java
a6e8c40e43003240c29b9c6f91eafedfd0d6a5d7
[]
no_license
demanluandyuki/Examples
https://github.com/demanluandyuki/Examples
e85a3ddda13060022d51f7942107e68f6e11fe1b
cdbe323a0110bd6cb90233f06f21f875dfe1cc9e
refs/heads/master
2021-01-17T07:01:52.588000
2016-05-11T08:52:20
2016-05-11T08:52:20
26,155,948
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jayfulmath.designpattern.command; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.Executor; import com.jayfulmath.designpattern.command.cooker.ISubject; import com.jayfulmath.designpattern.command.cooker.StandardCooker; public class OrderWaiter extends Thread{ Queue<Menu> _mMenuQueue = new LinkedList<Menu>(); boolean flag = true; private Object objlock = new Object(); String name; PVObject mMenuEmpty = new PVObject("menuobject"); private StandardCooker _mMeatCook = null; private StandardCooker _mFruitCook = null; private StandardCooker _mVegetableCook = null; private List<ISubject> mListSub = new ArrayList<ISubject>(); private List<StandardCooker> mListCooker = new ArrayList<StandardCooker>(); public OrderWaiter(String name) { this.name = name; mMenuEmpty.Init(1); _mMeatCook = CookerFactory.CreateCooker("meat"); _mFruitCook = CookerFactory.CreateCooker("fruit"); _mVegetableCook = CookerFactory.CreateCooker("vegetable"); _mMeatCook.mPvoObject.Init(1); _mFruitCook.mPvoObject.Init(1); _mVegetableCook.mPvoObject.Init(1); mListCooker.add(_mMeatCook); mListCooker.add(_mFruitCook); mListCooker.add(_mVegetableCook); mListSub.addAll(mListCooker); } public void customerOrderMenu(Customer customer) { for(ISubject sub:mListSub) { sub.Attach(customer); } synchronized(objlock){ _mMenuQueue.offer(customer.get_mMenu()); mMenuEmpty.V(); } } public void executeCookerThread(Executor mExcutor) { mExcutor.execute(_mFruitCook); mExcutor.execute(_mMeatCook); mExcutor.execute(_mVegetableCook); } /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { System.out.println(name+" Start order,thread id "+Thread.currentThread().getId()); GlobalValue._mCountDown.countDown(); while(flag) { //等待菜单不为空权限 mMenuEmpty.P(); synchronized(objlock){ Menu menu = _mMenuQueue.poll(); if(menu!=null) { if(menu.get_mMeat()>0) { _mMeatCook.addCustomer(menu.get_mCustomId()); _mMeatCook.mPvoObject.V(); } if(menu.get_mFruit()>0) { _mFruitCook.addCustomer(menu.get_mCustomId()); _mFruitCook.mPvoObject.V(); } if(menu.get_mVegetable()>0) { _mVegetableCook.addCustomer(menu.get_mCustomId()); _mVegetableCook.mPvoObject.V(); } } } } GlobalValue._mCountDownEnd.countDown(); System.out.println(name+" thred is end"); } /** * @return the mListSub */ public List<ISubject> getmListSub() { return mListSub; } public void stopOrderWaiting() { flag = false; mMenuEmpty.V(); for(StandardCooker sub:mListCooker) { sub.stopRunning(); } } }
GB18030
Java
2,809
java
OrderWaiter.java
Java
[]
null
[]
package com.jayfulmath.designpattern.command; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.Executor; import com.jayfulmath.designpattern.command.cooker.ISubject; import com.jayfulmath.designpattern.command.cooker.StandardCooker; public class OrderWaiter extends Thread{ Queue<Menu> _mMenuQueue = new LinkedList<Menu>(); boolean flag = true; private Object objlock = new Object(); String name; PVObject mMenuEmpty = new PVObject("menuobject"); private StandardCooker _mMeatCook = null; private StandardCooker _mFruitCook = null; private StandardCooker _mVegetableCook = null; private List<ISubject> mListSub = new ArrayList<ISubject>(); private List<StandardCooker> mListCooker = new ArrayList<StandardCooker>(); public OrderWaiter(String name) { this.name = name; mMenuEmpty.Init(1); _mMeatCook = CookerFactory.CreateCooker("meat"); _mFruitCook = CookerFactory.CreateCooker("fruit"); _mVegetableCook = CookerFactory.CreateCooker("vegetable"); _mMeatCook.mPvoObject.Init(1); _mFruitCook.mPvoObject.Init(1); _mVegetableCook.mPvoObject.Init(1); mListCooker.add(_mMeatCook); mListCooker.add(_mFruitCook); mListCooker.add(_mVegetableCook); mListSub.addAll(mListCooker); } public void customerOrderMenu(Customer customer) { for(ISubject sub:mListSub) { sub.Attach(customer); } synchronized(objlock){ _mMenuQueue.offer(customer.get_mMenu()); mMenuEmpty.V(); } } public void executeCookerThread(Executor mExcutor) { mExcutor.execute(_mFruitCook); mExcutor.execute(_mMeatCook); mExcutor.execute(_mVegetableCook); } /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { System.out.println(name+" Start order,thread id "+Thread.currentThread().getId()); GlobalValue._mCountDown.countDown(); while(flag) { //等待菜单不为空权限 mMenuEmpty.P(); synchronized(objlock){ Menu menu = _mMenuQueue.poll(); if(menu!=null) { if(menu.get_mMeat()>0) { _mMeatCook.addCustomer(menu.get_mCustomId()); _mMeatCook.mPvoObject.V(); } if(menu.get_mFruit()>0) { _mFruitCook.addCustomer(menu.get_mCustomId()); _mFruitCook.mPvoObject.V(); } if(menu.get_mVegetable()>0) { _mVegetableCook.addCustomer(menu.get_mCustomId()); _mVegetableCook.mPvoObject.V(); } } } } GlobalValue._mCountDownEnd.countDown(); System.out.println(name+" thred is end"); } /** * @return the mListSub */ public List<ISubject> getmListSub() { return mListSub; } public void stopOrderWaiting() { flag = false; mMenuEmpty.V(); for(StandardCooker sub:mListCooker) { sub.stopRunning(); } } }
2,809
0.69545
0.692942
118
22.652542
19.593054
84
false
false
0
0
0
0
0
0
2.516949
false
false
13
f70baf1145d41f131aa4db5a2bb42112228238ea
31,018,253,834,559
e695797feb4cbd088d3d3656ef8b5cd8c9e71266
/src/br/com/gft/model/Carro.java
fa2ab639faa46bec42c71759b0f106dc3c15b41e
[]
no_license
pablopachecoo/Heranca01
https://github.com/pablopachecoo/Heranca01
ca5d3644992d831bd313aaec2678c675587b91a4
640a03b0cdc17f794375a869ca46cddda4093a8c
refs/heads/master
2020-12-08T03:13:02.839000
2020-01-09T17:40:45
2020-01-09T17:40:45
232,867,143
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.gft.model; import br.com.gft.model.Veiculo; public class Carro extends Veiculo { private String Marca; private int Portas; private int Ano; public Carro(String modelo, int velocidade, int passageiros, int combustivel, String marca, int portas, int ano) { super(modelo, velocidade, passageiros, combustivel); Marca = marca; Portas = portas; Ano = ano; } public String getMarca() { return Marca; } public void setMarca(String marca) { Marca = marca; } public int getPortas() { return Portas; } public void setPortas(int portas) { Portas = portas; } public int getAno() { return Ano; } public void setAno(int ano) { Ano = ano; } }
UTF-8
Java
689
java
Carro.java
Java
[]
null
[]
package br.com.gft.model; import br.com.gft.model.Veiculo; public class Carro extends Veiculo { private String Marca; private int Portas; private int Ano; public Carro(String modelo, int velocidade, int passageiros, int combustivel, String marca, int portas, int ano) { super(modelo, velocidade, passageiros, combustivel); Marca = marca; Portas = portas; Ano = ano; } public String getMarca() { return Marca; } public void setMarca(String marca) { Marca = marca; } public int getPortas() { return Portas; } public void setPortas(int portas) { Portas = portas; } public int getAno() { return Ano; } public void setAno(int ano) { Ano = ano; } }
689
0.690856
0.690856
41
15.829268
20.669174
115
false
false
0
0
0
0
0
0
1.487805
false
false
13
cafd8d9f63699eac3f05a3d73848562d57b88329
12,592,844,139,752
d85fb3133c1b8778d4c3443cbd8c93ea0477a5de
/MeiburgerLibrary/src/uuu/meiburger/test/TestCustomerCheckId.java
570aca873b240deb9ae1cae03c37953faa3bf81d
[]
no_license
paranoialove/Meiburger
https://github.com/paranoialove/Meiburger
89d4d507f33dc6bca5d1e7ea983006e588aebfce
312c50033e720a4ce2073781a3ec3f28b9d238e1
refs/heads/master
2021-01-10T05:25:00.764000
2016-03-28T06:05:36
2016-03-28T06:05:36
54,326,916
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 uuu.meiburger.test; import uuu.meiburger.domain.Customer; import uuu.meiburger.domain.MeiException; /** * * @author Administrator */ public class TestCustomerCheckId { public static void main(String[] args) { final Customer c ; try{ c = new Customer("A123456787","John", "123456", "123@uuu.com.tw"); c.setId("A123456787"); System.out.println(c.checkId("A123456789")); }catch(MeiException ex){ System.out.println(ex); } } }
UTF-8
Java
751
java
TestCustomerCheckId.java
Java
[ { "context": "burger.domain.MeiException;\r\n\r\n/**\r\n *\r\n * @author Administrator\r\n */\r\npublic class TestCustomerCheckId {\r\n pub", "end": 338, "score": 0.9122997522354126, "start": 325, "tag": "USERNAME", "value": "Administrator" }, { "context": "try{\r\n c = new Customer(\"A123456787\",\"John\", \"123456\", \"123@uuu.com.tw\");\r\n c.set", "end": 517, "score": 0.9585171341896057, "start": 513, "tag": "NAME", "value": "John" }, { "context": "c = new Customer(\"A123456787\",\"John\", \"123456\", \"123@uuu.com.tw\");\r\n c.setId(\"A123456787\"); \r\n ", "end": 545, "score": 0.9999282956123352, "start": 531, "tag": "EMAIL", "value": "123@uuu.com.tw" } ]
null
[]
/* * 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 uuu.meiburger.test; import uuu.meiburger.domain.Customer; import uuu.meiburger.domain.MeiException; /** * * @author Administrator */ public class TestCustomerCheckId { public static void main(String[] args) { final Customer c ; try{ c = new Customer("A123456787","John", "123456", "<EMAIL>"); c.setId("A123456787"); System.out.println(c.checkId("A123456789")); }catch(MeiException ex){ System.out.println(ex); } } }
744
0.604527
0.556591
27
25.814816
23.284134
79
false
false
0
0
0
0
0
0
0.518519
false
false
13
ec3365e72553468bc6bff3dd6fd60aea00acdfc2
20,418,274,577,384
dadc758764ed69aa639e99f23d1659a35cda47d6
/RPG/RPG/ComprarKit.java
2bbd39a94d11658a17129f843ad67efe6ed83efa
[]
no_license
AstridGMC/Practica1
https://github.com/AstridGMC/Practica1
06d072b5dedd1f6f01910f2c50ddd9219439ae98
886269da96c958540aa6e6b1c11583e32200bf9c
refs/heads/master
2020-05-02T08:22:23.829000
2019-03-27T00:01:58
2019-03-27T00:01:58
177,829,516
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package RPG; import java.util.Scanner; public class ComprarKit { private static final int PRECIO_KMENOR = 40; private static final int PRECIO_KMAYOR=60; private static final int PRECIO_ARMA=200; private static int k=0; //contador private static int tamaño=0; protected static Kit[] kits = new Kit[10]; private static Scanner scanner = new Scanner(System.in); public static Kit[] getKits() { return kits; } public static void setKits(Kit[] kits) { ComprarKit.kits = kits; } public static void comprarKits(){ System.out.println("1.- para comprar kit MENOR precio: "+ PRECIO_KMENOR + " monedas"); System.out.println(" este kit repara tu vehiculo 25 puntos de vida\n"); System.out.println("2.- para comprar kit MAYOR precio: "+ PRECIO_KMAYOR + " monedas "); System.out.println(" este kit repara tu vehiculo 50 puntos de vida\n"); int opcion = Integer.valueOf(scanner.nextLine()); switch(opcion){ case 1: if (Jugador.getMyOro()>= PRECIO_KMENOR){ tamaño= tamaño +1; System.out.println("se ha agregado un Kit menor"); KitMenor kitMenor = new KitMenor("Kit Menor"); kits[k]= kitMenor; k++; Jugador.myOro= (Jugador.myOro - PRECIO_KMENOR); }else { System.out.println("no tienes dinero suficiente "); MenuPrincipal.regresarAlMenuT(); } break; case 2: if (Jugador.getMyOro()>= PRECIO_KMAYOR){ tamaño ++; System.out.println("se ha agregado un kit mayor"); Jugador.myOro= (Jugador.myOro - PRECIO_KMAYOR); KitMayor kitMayor = new KitMayor("Kit Mayor"); kits[k]= kitMayor; k++;} else { System.out.println("no tienes dinero suficiente "); MenuPrincipal.regresarAlMenuT(); } break; default: comprarKits(); } } public static void mostrarMisKits(){ for(int j=0;j<tamaño;j++){ if(kits[j] == null){ System.out.println("no has comprado ningun kit"); System.out.println("desea regresar al menu S/N"); String res= scanner.nextLine(); switch(res){ case "s": MenuPrincipal.menuPrincipal(); break; case "S": MenuPrincipal.menuPrincipal(); break; default: mostrarMisKits(); } } else{ System.out.println(kits[j].toStringK()); } } } }
UTF-8
Java
3,013
java
ComprarKit.java
Java
[]
null
[]
package RPG; import java.util.Scanner; public class ComprarKit { private static final int PRECIO_KMENOR = 40; private static final int PRECIO_KMAYOR=60; private static final int PRECIO_ARMA=200; private static int k=0; //contador private static int tamaño=0; protected static Kit[] kits = new Kit[10]; private static Scanner scanner = new Scanner(System.in); public static Kit[] getKits() { return kits; } public static void setKits(Kit[] kits) { ComprarKit.kits = kits; } public static void comprarKits(){ System.out.println("1.- para comprar kit MENOR precio: "+ PRECIO_KMENOR + " monedas"); System.out.println(" este kit repara tu vehiculo 25 puntos de vida\n"); System.out.println("2.- para comprar kit MAYOR precio: "+ PRECIO_KMAYOR + " monedas "); System.out.println(" este kit repara tu vehiculo 50 puntos de vida\n"); int opcion = Integer.valueOf(scanner.nextLine()); switch(opcion){ case 1: if (Jugador.getMyOro()>= PRECIO_KMENOR){ tamaño= tamaño +1; System.out.println("se ha agregado un Kit menor"); KitMenor kitMenor = new KitMenor("Kit Menor"); kits[k]= kitMenor; k++; Jugador.myOro= (Jugador.myOro - PRECIO_KMENOR); }else { System.out.println("no tienes dinero suficiente "); MenuPrincipal.regresarAlMenuT(); } break; case 2: if (Jugador.getMyOro()>= PRECIO_KMAYOR){ tamaño ++; System.out.println("se ha agregado un kit mayor"); Jugador.myOro= (Jugador.myOro - PRECIO_KMAYOR); KitMayor kitMayor = new KitMayor("Kit Mayor"); kits[k]= kitMayor; k++;} else { System.out.println("no tienes dinero suficiente "); MenuPrincipal.regresarAlMenuT(); } break; default: comprarKits(); } } public static void mostrarMisKits(){ for(int j=0;j<tamaño;j++){ if(kits[j] == null){ System.out.println("no has comprado ningun kit"); System.out.println("desea regresar al menu S/N"); String res= scanner.nextLine(); switch(res){ case "s": MenuPrincipal.menuPrincipal(); break; case "S": MenuPrincipal.menuPrincipal(); break; default: mostrarMisKits(); } } else{ System.out.println(kits[j].toStringK()); } } } }
3,013
0.486702
0.479721
83
35.228916
23.89451
99
false
false
0
0
0
0
0
0
0.554217
false
false
13
e88f76da2175fa80142f0f0c8155859f2e63ba7b
25,829,933,330,595
dc7b8512d5468d3a03a5ef750c2cfc184a08bfdd
/PushServiceDemo_android/PushServiceDemo/src/main/java/com/xisue/pushservicedemo/util/PushMessageCounter.java
253bb5dc742e4d37d3632d8de1e8304cdda86b56
[]
no_license
micweaver/How-to-do-Push
https://github.com/micweaver/How-to-do-Push
ca0cb6f36af6dce4f86641674ed8bd5033b727c3
bd785f918ba0a312e26b1552e3583c16771176d0
refs/heads/master
2020-07-31T03:46:12.682000
2014-08-01T02:59:21
2014-08-01T02:59:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xisue.pushservicedemo.util; import android.content.Context; import android.content.SharedPreferences; /** * * 这个类用来保存收到的Message的custom id。 * * Created by yinxiaoliu on 14-7-30. */ public class PushMessageCounter { public static final String SP_NAME = "PushMessageCounter"; public static final String NO_KEY = "no."; public static void saveNo(Context context, int no) { SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_APPEND); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(NO_KEY, no); editor.commit(); } public static int readNo(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_APPEND); return sharedPreferences.getInt(NO_KEY, 0); } }
UTF-8
Java
883
java
PushMessageCounter.java
Java
[ { "context": "*\n * 这个类用来保存收到的Message的custom id。\n *\n * Created by yinxiaoliu on 14-7-30.\n */\npublic class PushMessageCounter {", "end": 182, "score": 0.9995105862617493, "start": 172, "tag": "USERNAME", "value": "yinxiaoliu" }, { "context": "unter\";\n\n public static final String NO_KEY = \"no.\";\n\n public static void saveNo(Context context, i", "end": 344, "score": 0.9803947806358337, "start": 339, "tag": "KEY", "value": "no.\";" } ]
null
[]
package com.xisue.pushservicedemo.util; import android.content.Context; import android.content.SharedPreferences; /** * * 这个类用来保存收到的Message的custom id。 * * Created by yinxiaoliu on 14-7-30. */ public class PushMessageCounter { public static final String SP_NAME = "PushMessageCounter"; public static final String NO_KEY = "no."; public static void saveNo(Context context, int no) { SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_APPEND); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(NO_KEY, no); editor.commit(); } public static int readNo(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_APPEND); return sharedPreferences.getInt(NO_KEY, 0); } }
883
0.717113
0.710128
30
27.633333
29.919317
105
false
false
0
0
0
0
0
0
0.533333
false
false
13
ae68dca05ff1f0e54e7deaf52187c34e9e4011aa
15,410,342,722,585
aa5a473e5938f98c61357c955fbccf414ea28902
/src/test/java/com/wcunha/robo/util/SuporteAutomato.java
b93e9faaacc7b1dd4851cb4391aa0230c3f5b2f2
[]
no_license
WalaceCR/cronos
https://github.com/WalaceCR/cronos
47bd00ce8a41ccb93288667e8b50925812fbbfeb
8919dc8c57053c25ef7214ea6aab2a4f089341d6
refs/heads/master
2021-06-29T21:09:25.843000
2019-06-22T19:17:29
2019-06-22T19:17:29
164,306,812
0
0
null
false
2020-10-13T11:32:55
2019-01-06T12:53:18
2019-06-22T19:18:37
2020-10-13T11:32:54
58
0
0
1
Java
false
false
package com.wcunha.robo.util; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class SuporteAutomato { private static SuporteAutomato instance = null; WebDriver driver; /*construtor necessário para utilizar o Singleton*/ private SuporteAutomato(){ } /*iniciar o ChromeDriver*/ public void setarChrome(){ WebDriverManager.chromedriver().setup(); this.driver = new ChromeDriver(); } /*retorna o chromedriver iniciado*/ public WebDriver getDriver(){ return this.driver; } /*aguardar carregamento da página*/ public void waitForPageLoad(WebDriver driver) throws Exception { try { ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete"); } }; WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(pageLoadCondition); } catch (Exception e) { throw e; } } /*aguardar o elemento ser clicável*/ public boolean isClickable(WebElement webe){ try { WebDriverWait wait = new WebDriverWait(this.driver, 10); wait.until(ExpectedConditions.elementToBeClickable(webe)); return true; } catch (Exception e){ return false; } } /*Fecho o chrome no final de todos os testes*/ public void fecharChrome() { this.driver.close(); } /*Método responsável pela captura da instância da classe * para que esta seja chamada apenas uma vez e então em tempo * de execução ao invés de criar novas instâncias com new utilizo * a mesma instância criada (Singleton)*/ public static SuporteAutomato getInstance() { if (instance == null) { instance = new SuporteAutomato(); } return instance; } /*Maximizar a janela*/ public void maximizarJanela(){ this.driver.manage().window().maximize(); } /*Limpar cookies*/ public void limparCookies(){ this.driver.manage().deleteAllCookies(); } }
UTF-8
Java
2,678
java
SuporteAutomato.java
Java
[ { "context": "package com.wcunha.robo.util;\n\nimport io.github.bonigarcia.wdm.WebDriverManager;\nimport org.openqa.selenium.", "end": 58, "score": 0.9993190765380859, "start": 48, "tag": "USERNAME", "value": "bonigarcia" } ]
null
[]
package com.wcunha.robo.util; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class SuporteAutomato { private static SuporteAutomato instance = null; WebDriver driver; /*construtor necessário para utilizar o Singleton*/ private SuporteAutomato(){ } /*iniciar o ChromeDriver*/ public void setarChrome(){ WebDriverManager.chromedriver().setup(); this.driver = new ChromeDriver(); } /*retorna o chromedriver iniciado*/ public WebDriver getDriver(){ return this.driver; } /*aguardar carregamento da página*/ public void waitForPageLoad(WebDriver driver) throws Exception { try { ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete"); } }; WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(pageLoadCondition); } catch (Exception e) { throw e; } } /*aguardar o elemento ser clicável*/ public boolean isClickable(WebElement webe){ try { WebDriverWait wait = new WebDriverWait(this.driver, 10); wait.until(ExpectedConditions.elementToBeClickable(webe)); return true; } catch (Exception e){ return false; } } /*Fecho o chrome no final de todos os testes*/ public void fecharChrome() { this.driver.close(); } /*Método responsável pela captura da instância da classe * para que esta seja chamada apenas uma vez e então em tempo * de execução ao invés de criar novas instâncias com new utilizo * a mesma instância criada (Singleton)*/ public static SuporteAutomato getInstance() { if (instance == null) { instance = new SuporteAutomato(); } return instance; } /*Maximizar a janela*/ public void maximizarJanela(){ this.driver.manage().window().maximize(); } /*Limpar cookies*/ public void limparCookies(){ this.driver.manage().deleteAllCookies(); } }
2,678
0.639535
0.638035
90
28.622223
24.1567
127
false
false
0
0
0
0
0
0
0.333333
false
false
13
1ab7ff109c789e6b989145e2575bc97654ec5cdc
32,074,815,829,356
126b744387b326f12250a5d3b05c164fb8bedad8
/src/test/java/jedi/kafka/model/StringConsumer.java
86983fe9505ded8e249fc7e6211a5534cc631573
[]
no_license
mesutsaritas/jedi-kafka-client
https://github.com/mesutsaritas/jedi-kafka-client
c2987fcbbeec5b2d6c38c0dc627bb8f17832a64b
466069be43bd16a03c2fdb2c64aef7c923b0037f
refs/heads/main
2023-01-11T01:48:26.744000
2020-11-17T11:09:48
2020-11-17T11:09:48
315,442,957
1
0
null
true
2020-11-23T21:17:15
2020-11-23T21:17:14
2020-11-17T11:09:51
2020-11-17T11:10:48
44
0
0
0
null
false
false
package jedi.kafka.model; import java.util.concurrent.atomic.AtomicLong; import jedi.kafka.service.ConsumerHandler; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Slf4j public class StringConsumer implements ConsumerHandler<String> { @Getter private AtomicLong counter = new AtomicLong(); @Setter private Response response; @Override public Response onMessage(String message) { log.debug(counter.incrementAndGet()+"-Recieved message "+message); return response; } }
UTF-8
Java
528
java
StringConsumer.java
Java
[]
null
[]
package jedi.kafka.model; import java.util.concurrent.atomic.AtomicLong; import jedi.kafka.service.ConsumerHandler; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Slf4j public class StringConsumer implements ConsumerHandler<String> { @Getter private AtomicLong counter = new AtomicLong(); @Setter private Response response; @Override public Response onMessage(String message) { log.debug(counter.incrementAndGet()+"-Recieved message "+message); return response; } }
528
0.767045
0.761364
23
22
21.048597
70
false
false
0
0
0
0
0
0
0.434783
false
false
13
7e7d9f184fd8d961f4908a8803cfea549508d5e2
7,679,401,540,802
ca9d48c1833a50289e6a67f3cc34f9756b0ca263
/src/pasa/cbentley/powerdata/src4/utils/TrieUtils.java
88dfdba4214758cee5453e862399705ff0ff224a
[]
no_license
cpbentley/pasa_cbentley_powerdata_src4
https://github.com/cpbentley/pasa_cbentley_powerdata_src4
0c3ab16c8d1aaba4d845503f688d05119144ebbf
4de3dc03f6b182a7add1bbfa648074f64db91db2
refs/heads/master
2020-12-20T10:23:53.765000
2020-10-15T23:05:04
2020-10-15T23:05:04
236,041,509
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pasa.cbentley.powerdata.src4.utils; import pasa.cbentley.byteobjects.src4.core.BOModuleAbstract; import pasa.cbentley.byteobjects.src4.core.ByteObjectManaged; import pasa.cbentley.core.src4.ctx.UCtx; import pasa.cbentley.core.src4.logging.Dctx; import pasa.cbentley.core.src4.structs.IntToStrings; import pasa.cbentley.core.src4.utils.StringUtils; import pasa.cbentley.powerdata.spec.src4.power.itech.ITechCharCol; import pasa.cbentley.powerdata.spec.src4.power.string.IPowerLinkTrieData; import pasa.cbentley.powerdata.spec.src4.power.trie.IPowerCharTrie; import pasa.cbentley.powerdata.src4.ctx.PDCtx; import pasa.cbentley.powerdata.src4.trie.PowerCharTrie; import pasa.cbentley.powerdata.src4.trie.PowerTrieLink; public class TrieUtils implements ITechCharCol { private PDCtx pdc; public TrieUtils(PDCtx pdc) { this.pdc = pdc; } //#mdebug public String toString() { return Dctx.toString(this); } public void toString(Dctx dc) { dc.root(this, "TrieUtils"); toStringPrivate(dc); } public String toString1Line() { return Dctx.toString1Line(this); } public void toString1Line(Dctx dc) { dc.root1Line(this, "TrieUtils"); toStringPrivate(dc); } public UCtx toStringGetUCtx() { return pdc.getUCtx(); } private void toStringPrivate(Dctx dc) { } //#enddebug }
UTF-8
Java
1,431
java
TrieUtils.java
Java
[]
null
[]
package pasa.cbentley.powerdata.src4.utils; import pasa.cbentley.byteobjects.src4.core.BOModuleAbstract; import pasa.cbentley.byteobjects.src4.core.ByteObjectManaged; import pasa.cbentley.core.src4.ctx.UCtx; import pasa.cbentley.core.src4.logging.Dctx; import pasa.cbentley.core.src4.structs.IntToStrings; import pasa.cbentley.core.src4.utils.StringUtils; import pasa.cbentley.powerdata.spec.src4.power.itech.ITechCharCol; import pasa.cbentley.powerdata.spec.src4.power.string.IPowerLinkTrieData; import pasa.cbentley.powerdata.spec.src4.power.trie.IPowerCharTrie; import pasa.cbentley.powerdata.src4.ctx.PDCtx; import pasa.cbentley.powerdata.src4.trie.PowerCharTrie; import pasa.cbentley.powerdata.src4.trie.PowerTrieLink; public class TrieUtils implements ITechCharCol { private PDCtx pdc; public TrieUtils(PDCtx pdc) { this.pdc = pdc; } //#mdebug public String toString() { return Dctx.toString(this); } public void toString(Dctx dc) { dc.root(this, "TrieUtils"); toStringPrivate(dc); } public String toString1Line() { return Dctx.toString1Line(this); } public void toString1Line(Dctx dc) { dc.root1Line(this, "TrieUtils"); toStringPrivate(dc); } public UCtx toStringGetUCtx() { return pdc.getUCtx(); } private void toStringPrivate(Dctx dc) { } //#enddebug }
1,431
0.709993
0.698113
55
24.018183
22.493223
73
false
false
0
0
0
0
0
0
0.436364
false
false
13
a3b4a8d5dbdd4ef99efc817cdc08357e3a2a8d81
27,264,452,463,201
d526c4f5d02a89f51060267f360654e6be89ee4c
/src/main/java/com/newx/pojo/QuestionWithBLOBs.java
3d6215c00c0be0ca71845da46f30057f6b6bcdde
[]
no_license
zxxwin/onlineExaminationSystem
https://github.com/zxxwin/onlineExaminationSystem
5df08a21fc15ba86dbc652f2c551fb003b94fe9b
27b4c258b8b36d58bcac1a9a7a3b6f22186b016f
refs/heads/master
2020-12-02T07:46:22.437000
2017-07-10T03:39:19
2017-07-10T03:39:19
96,724,036
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.newx.pojo; public class QuestionWithBLOBs extends Question { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column question.question_content * * @mbggenerated */ private String questionContent; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column question.answer * * @mbggenerated */ private String answer; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table question * * @mbggenerated */ public QuestionWithBLOBs(Integer questionId, Integer questionType, Integer subcategoryId, String option1, String option2, String option3, String option4, String option5, Integer level, Integer delete, String questionContent, String answer) { super(questionId, questionType, subcategoryId, option1, option2, option3, option4, option5, level, delete); this.questionContent = questionContent; this.answer = answer; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table question * * @mbggenerated */ public QuestionWithBLOBs() { super(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column question.question_content * * @return the value of question.question_content * * @mbggenerated */ public String getQuestionContent() { return questionContent; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column question.question_content * * @param questionContent the value for question.question_content * * @mbggenerated */ public void setQuestionContent(String questionContent) { this.questionContent = questionContent == null ? null : questionContent.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column question.answer * * @return the value of question.answer * * @mbggenerated */ public String getAnswer() { return answer; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column question.answer * * @param answer the value for question.answer * * @mbggenerated */ public void setAnswer(String answer) { this.answer = answer == null ? null : answer.trim(); } }
UTF-8
Java
2,679
java
QuestionWithBLOBs.java
Java
[]
null
[]
package com.newx.pojo; public class QuestionWithBLOBs extends Question { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column question.question_content * * @mbggenerated */ private String questionContent; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column question.answer * * @mbggenerated */ private String answer; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table question * * @mbggenerated */ public QuestionWithBLOBs(Integer questionId, Integer questionType, Integer subcategoryId, String option1, String option2, String option3, String option4, String option5, Integer level, Integer delete, String questionContent, String answer) { super(questionId, questionType, subcategoryId, option1, option2, option3, option4, option5, level, delete); this.questionContent = questionContent; this.answer = answer; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table question * * @mbggenerated */ public QuestionWithBLOBs() { super(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column question.question_content * * @return the value of question.question_content * * @mbggenerated */ public String getQuestionContent() { return questionContent; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column question.question_content * * @param questionContent the value for question.question_content * * @mbggenerated */ public void setQuestionContent(String questionContent) { this.questionContent = questionContent == null ? null : questionContent.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column question.answer * * @return the value of question.answer * * @mbggenerated */ public String getAnswer() { return answer; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column question.answer * * @param answer the value for question.answer * * @mbggenerated */ public void setAnswer(String answer) { this.answer = answer == null ? null : answer.trim(); } }
2,679
0.656588
0.652856
89
29.11236
35.153416
245
false
false
0
0
0
0
0
0
0.348315
false
false
13
42febe0eb3c3b93a1401c66d5077ed07d5e47e8e
13,855,564,514,640
9c1e301a4122723b19d2835b47d4529e3806c107
/app/src/main/java/com/example/ui_igr203/TableActivity.java
f8b0f447a80526fd41a54e283d119fcb8c0b2d2b
[]
no_license
clementlandrin/UI_IGR203
https://github.com/clementlandrin/UI_IGR203
08def3f5256badd6bcc522b76e324fa026f205a9
22df5d1136a7fa85504bad68f3c18a5da0319a4e
refs/heads/master
2020-04-23T16:54:51.364000
2019-09-24T18:27:32
2019-09-24T18:27:32
171,314,218
0
0
null
false
2019-04-05T09:20:08
2019-02-18T16:05:32
2019-04-05T09:19:07
2019-04-05T09:20:07
660
0
0
0
Java
false
false
package com.example.ui_igr203; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Bundle; import androidx.annotation.NonNull; import com.google.android.material.bottomnavigation.BottomNavigationView; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.text.SpannableString; import android.text.style.TextAppearanceSpan; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class TableActivity extends AppCompatActivity implements View.OnClickListener { private ImageButton center_table; private int chair_number; private View four_choice_menu; private Button choice; private View startedFromChoicesButton; private float initial_choice_x; private float initial_choice_y; private boolean started_from_center_table; private boolean four_choice_menu_was_displayed; private boolean choice_selected; private boolean category_choice_selected; private boolean dragging; private Button category1; private Button category2; private Button category3; private Button category4; List<String> beers; List<String> wines; List<String> strongAlcohols; List<String> aPartager; List<String> charcuterie; List<String> salades; List<String> autres; List<String> boeuf; List<String> boeufHache; List<String> burgers; List<String> poissons; List<String> fromages; List<String> dessert; List<String> glaces; List<String> cafe; private BottomNavigationView navigation; List<String> aperitifCategories; List<String> entreeCategories; List<String> dishCategories; List<String> dessertCategories; List<String> currentCategory; private int currentColor; private void setCategoryText(List<String> categories) { if (categories == null) { Log.e("Setting category text", "categories is null"); return; } if (categories.size() < 4) { category4.setText(""); category4.setBackgroundColor(Color.WHITE); if (categories.size() < 3) { category3.setText(""); category3.setBackgroundColor(Color.WHITE); if (categories.size() < 2) { category2.setText(""); category2.setBackgroundColor(Color.WHITE); if (categories.size() < 1) { category1.setText(""); category1.setBackgroundColor(Color.WHITE); } } } } for (int i = 0; i < categories.size(); i++) { switch (i) { case 0: category1.setText(categories.get(0)); category1.setBackgroundColor(Color.GRAY); break; case 1: category2.setText(categories.get(1)); category2.setBackgroundColor(Color.GRAY); break; case 2: category3.setText(categories.get(2)); category3.setBackgroundColor(Color.GRAY); break; case 3: category4.setText(categories.get(3)); category4.setBackgroundColor(Color.GRAY); break; } } } private void clearChairColor() { ((ImageView)findViewById(R.id.chair_1)).setColorFilter(Color.BLACK); ((ImageView)findViewById(R.id.chair_2)).setColorFilter(Color.BLACK); ((ImageView)findViewById(R.id.chair_3)).setColorFilter(Color.BLACK); ((ImageView)findViewById(R.id.chair_4)).setColorFilter(Color.BLACK); } private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_aperitif: center_table.setColorFilter(getResources().getColor(R.color.aperitifColor), PorterDuff.Mode.SRC_IN); choice.setVisibility(View.INVISIBLE); currentCategory = aperitifCategories; currentColor = getResources().getColor(R.color.aperitifColor); setCategoryText(currentCategory); choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); clearChairColor(); category_choice_selected = false; return true; case R.id.navigation_entree: center_table.setColorFilter(getResources().getColor(R.color.entreeColor), PorterDuff.Mode.SRC_IN); choice.setVisibility(View.INVISIBLE); currentCategory = entreeCategories; currentColor = getResources().getColor(R.color.entreeColor); setCategoryText(currentCategory); choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); clearChairColor(); category_choice_selected = false; return true; case R.id.navigation_dish: center_table.setColorFilter(getResources().getColor(R.color.dishColor), PorterDuff.Mode.SRC_IN); choice.setVisibility(View.INVISIBLE); currentCategory = dishCategories; currentColor = getResources().getColor(R.color.dishColor); setCategoryText(currentCategory); choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); clearChairColor(); category_choice_selected = false; return true; case R.id.navigation_dessert: center_table.setColorFilter(getResources().getColor(R.color.dessertColor), PorterDuff.Mode.SRC_IN); choice.setVisibility(View.INVISIBLE); currentCategory = dessertCategories; currentColor = getResources().getColor(R.color.dessertColor); setCategoryText(currentCategory); choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); clearChairColor(); category_choice_selected = false; return true; } return false; } }; private String ReadMenu() { try { BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(getFilesDir() + File.separator + "menu.txt"))); String read; StringBuilder builder = new StringBuilder(""); while ((read = bufferedReader.readLine()) != null) { builder.append(read); } Log.d("Output", builder.toString()); bufferedReader.close(); return builder.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } private void initializeChairs() { if (chair_number < 4) { findViewById(R.id.chair_4).setVisibility(View.INVISIBLE); if (chair_number < 3) { findViewById(R.id.chair_3).setVisibility(View.INVISIBLE); if (chair_number < 2) { findViewById(R.id.chair_2).setVisibility(View.INVISIBLE); if (chair_number < 1) { findViewById(R.id.chair_1).setVisibility(View.INVISIBLE); } } } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.send_to_kitchen: new AlertDialog.Builder(TableActivity.this) .setTitle("Envoyer en cuisine") .setMessage("- Plat 1\n- Plat 2\n.\n.\n.") .setPositiveButton("Confirmer", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // send to kitchen Intent intent = new Intent(TableActivity.this, RestaurantRoomActivity.class); startActivity(intent); } }).setNegativeButton("Annuler", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Cancel } }).show(); } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.orderingmenu, menu); return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] split = ReadMenu().split("'"); if (split.length != 0) { Log.i("Set category from file", "size is not 0"); aperitifCategories = new ArrayList<>(); entreeCategories = new ArrayList<>(); dishCategories = new ArrayList<>(); dessertCategories = new ArrayList<>(); beers = new ArrayList<>(); beers.add("Blanche"); beers.add("Blonde"); beers.add("Ambrée"); beers.add("Brune"); wines = new ArrayList<>(); wines.add("Rouge"); wines.add("Rosé"); wines.add("Blanc"); strongAlcohols = new ArrayList<>(); strongAlcohols.add("Cognac"); strongAlcohols.add("Liqueur"); strongAlcohols.add("Whisky"); strongAlcohols.add("Rhum"); aPartager = new ArrayList<>(); aPartager.add("Planche de charcuterie"); aPartager.add("Planche mixte"); aPartager.add("Duo de rillettes"); charcuterie = new ArrayList<>(); charcuterie.add("Rosette de Lyon"); charcuterie.add("Rillettes"); charcuterie.add("Terrine de campagne"); charcuterie.add("Pâté en croûte"); salades = new ArrayList<>(); salades.add("Du soleil"); salades.add("Chèvre chaud"); autres = new ArrayList<>(); autres.add("Fromage blanc"); autres.add("Oeuf poché"); boeuf = new ArrayList<>(); boeuf.add("Côte"); boeuf.add("Onglet"); boeuf.add("Entrecôte"); boeuf.add("Mariné"); boeufHache = new ArrayList<>(); boeufHache.add("Super hâché"); boeufHache.add("Tartare"); boeufHache.add("Carpaccio"); boeufHache.add("Steak hâché"); burgers = new ArrayList<>(); burgers.add("Rustique"); burgers.add("Traditionnel"); burgers.add("Décalé"); burgers.add("Bon vivant"); poissons = new ArrayList<>(); poissons.add("Cabillaud"); poissons.add("Bar"); poissons.add("Saumon"); fromages = new ArrayList<>(); fromages.add("Cabécou"); fromages.add("Camembert"); fromages.add("Faisselle"); dessert = new ArrayList<>(); dessert.add("Tartare de fruits"); dessert.add("Ile flottante"); dessert.add("Mousse au chocolat"); dessert.add("Tarte aux pommes"); glaces = new ArrayList<>(); glaces.add("Liégeoises"); glaces.add("Sorbert"); glaces.add("Griotte"); glaces.add("Petite maison"); cafe = new ArrayList<>(); cafe.add("Douceur"); cafe.add("Gourmand"); cafe.add("Paille café"); for (int i = 0; i < split.length; i++) { String[] splitTmp = split[i].split(","); switch (i) { case 0: Log.i("Set category from file", "entering case 0"); for (int j = 0; j < splitTmp.length; j++) { Log.i("Set from file 0", splitTmp[j]); aperitifCategories.add(splitTmp[j]); } break; case 1: Log.i("Set category from file", "entering case 1"); for (int j = 0; j < splitTmp.length; j++) { Log.i("Set from file 1", splitTmp[j]); entreeCategories.add(splitTmp[j]); } break; case 2: Log.i("Set category from file", "entering case 2"); for (int j = 0; j < splitTmp.length; j++) { Log.i("Set from file 2", splitTmp[j]); dishCategories.add(splitTmp[j]); } break; case 3: Log.i("Set category from file", "entering case 3"); for (int j = 0; j < splitTmp.length; j++) { Log.i("Set from file 3", splitTmp[j]); dessertCategories.add(splitTmp[j]); } break; } } } currentCategory = aperitifCategories; currentColor = getResources().getColor(R.color.aperitifColor); startedFromChoicesButton = null; setContentView(R.layout.activity_table); chair_number = getIntent().getIntExtra("chair_number", 0); initializeChairs(); findViewById(R.id.chair_1).setOnClickListener(this); findViewById(R.id.chair_2).setOnClickListener(this); findViewById(R.id.chair_3).setOnClickListener(this); findViewById(R.id.chair_4).setOnClickListener(this); four_choice_menu_was_displayed = false; started_from_center_table = false; choice_selected = false; category_choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); findViewById(R.id.delete_choice).setOnClickListener(this); dragging = false; center_table = findViewById(R.id.center_table); center_table.setOnClickListener(this); choice = findViewById(R.id.choice); choice.setVisibility(View.INVISIBLE); choice.setTextColor(Color.WHITE); choice.setBackgroundColor(Color.BLACK); choice.setOnClickListener(this); choice.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // Layout has happened here. initial_choice_x = choice.getX(); initial_choice_y = choice.getY(); } }); four_choice_menu = findViewById(R.id.four_choice); four_choice_menu.setVisibility(View.INVISIBLE); category1 = findViewById(R.id.category1); category2 = findViewById(R.id.category2); category3 = findViewById(R.id.category3); category4 = findViewById(R.id.category4); category1.setOnClickListener(this); category2.setOnClickListener(this); category3.setOnClickListener(this); category4.setOnClickListener(this); setCategoryText(currentCategory); navigation = findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); SpannableString aperitifString = new SpannableString(getResources().getString(R.string.title_aperitif)); aperitifString.setSpan(new TextAppearanceSpan(this, R.style.AperitifTextAppearance), 0, aperitifString.length(), 0); SpannableString entreeString = new SpannableString(getResources().getString(R.string.title_entree)); entreeString.setSpan(new TextAppearanceSpan(this, R.style.EntreeTextAppearance), 0, entreeString.length(), 0); SpannableString dishString = new SpannableString(getResources().getString(R.string.title_dish)); dishString.setSpan(new TextAppearanceSpan(this, R.style.DishTextAppearance), 0, dishString.length(), 0); SpannableString dessertString = new SpannableString(getResources().getString(R.string.title_dessert)); dessertString.setSpan(new TextAppearanceSpan(this, R.style.DessertTextAppearance), 0, dessertString.length(), 0); navigation.getMenu().findItem(R.id.navigation_aperitif).getIcon().setColorFilter(getResources().getColor(R.color.aperitifColor), PorterDuff.Mode.SRC_IN); navigation.getMenu().findItem(R.id.navigation_aperitif).setTitle(aperitifString); navigation.getMenu().findItem(R.id.navigation_entree).getIcon().setColorFilter(getResources().getColor(R.color.entreeColor), PorterDuff.Mode.SRC_IN); navigation.getMenu().findItem(R.id.navigation_entree).setTitle(entreeString); navigation.getMenu().findItem(R.id.navigation_dish).getIcon().setColorFilter(getResources().getColor(R.color.dishColor), PorterDuff.Mode.SRC_IN); navigation.getMenu().findItem(R.id.navigation_dish).setTitle(dishString); navigation.getMenu().findItem(R.id.navigation_dessert).getIcon().setColorFilter(getResources().getColor(R.color.dessertColor), PorterDuff.Mode.SRC_IN); navigation.getMenu().findItem(R.id.navigation_dessert).setTitle(dessertString); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); if (getIntent().getStringExtra("table_id") != null) { actionBar.setTitle(getResources().getString(R.string.title_activity_table) + getIntent().getStringExtra("table_id")); } else { actionBar.setTitle(getResources().getString(R.string.title_activity_table) + getResources().getString(R.string.table_id_unkwnown)); } } private void trigerChoice(View v) { switch(v.getId()) { case R.id.category1: if (currentCategory.size() > 0) { if(!category_choice_selected) { switch (currentStep) { case "Aperitif": currentCategory = beers; setCategoryText(currentCategory); break; case "Entree": currentCategory = aPartager; setCategoryText(currentCategory); break; case "Plat": currentCategory = boeuf; setCategoryText(currentCategory); break; case "Dessert": currentCategory = fromages; setCategoryText(currentCategory); break; } category_choice_selected = true; } else { choice.setText(category1.getText()); choice.setVisibility(View.VISIBLE); four_choice_menu.setVisibility(View.INVISIBLE); choice_selected = true; switch (currentStep) { case "Aperitif": currentCategory = aperitifCategories; break; case "Entree": currentCategory = entreeCategories; break; case "Plat": currentCategory = dishCategories; break; case "Dessert": currentCategory = dessertCategories; break; } findViewById(R.id.delete_choice).setVisibility(View.VISIBLE); category_choice_selected = false; } } break; case R.id.category2: if (currentCategory.size() > 1) { if(!category_choice_selected) { switch (currentStep) { case "Aperitif": currentCategory = wines; setCategoryText(currentCategory); break; case "Entree": currentCategory = charcuterie; setCategoryText(currentCategory); break; case "Plat": currentCategory = boeufHache; setCategoryText(currentCategory); break; case "Dessert": currentCategory = dessert; setCategoryText(currentCategory); break; } category_choice_selected = true; } else { choice.setText(category2.getText()); choice.setVisibility(View.VISIBLE); choice_selected = true; switch (currentStep) { case "Aperitif": currentCategory = aperitifCategories; break; case "Entree": currentCategory = entreeCategories; break; case "Plat": currentCategory = dishCategories; break; case "Dessert": currentCategory = dessertCategories; break; } findViewById(R.id.delete_choice).setVisibility(View.VISIBLE); four_choice_menu.setVisibility(View.INVISIBLE); category_choice_selected = false; } } break; case R.id.category3: if (currentCategory.size() > 2) { if(!category_choice_selected) { switch (currentStep) { case "Aperitif": currentCategory = strongAlcohols; setCategoryText(currentCategory); break; case "Entree": currentCategory = salades; setCategoryText(currentCategory); break; case "Plat": currentCategory = burgers; setCategoryText(currentCategory); break; case "Dessert": currentCategory = glaces; setCategoryText(currentCategory); break; } category_choice_selected = true; } else { choice.setText(category3.getText()); choice.setVisibility(View.VISIBLE); choice_selected = true; switch (currentStep) { case "Aperitif": currentCategory = aperitifCategories; break; case "Entree": currentCategory = entreeCategories; break; case "Plat": currentCategory = dishCategories; break; case "Dessert": currentCategory = dessertCategories; break; } findViewById(R.id.delete_choice).setVisibility(View.VISIBLE); four_choice_menu.setVisibility(View.INVISIBLE); category_choice_selected = false; } } break; case R.id.category4: if (currentCategory.size() > 3) { if(!category_choice_selected) { switch (currentStep) { case "Entree": currentCategory = autres; setCategoryText(currentCategory); break; case "Plat": currentCategory = poissons; setCategoryText(currentCategory); break; case "Dessert": currentCategory = cafe; setCategoryText(currentCategory); break; } category_choice_selected = true; } else { choice.setText(category4.getText()); choice.setVisibility(View.VISIBLE); choice_selected = true; switch (currentStep) { case "Aperitif": currentCategory = aperitifCategories; break; case "Entree": currentCategory = entreeCategories; break; case "Plat": currentCategory = dishCategories; break; case "Dessert": currentCategory = dessertCategories; break; } findViewById(R.id.delete_choice).setVisibility(View.VISIBLE); four_choice_menu.setVisibility(View.INVISIBLE); category_choice_selected = false; } } break; } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.center_table: break; case R.id.delete_choice: choice.setVisibility(View.INVISIBLE); findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); choice_selected = false; category_choice_selected = false; case R.id.chair_1: if(!choice_selected && !dragging) { ((ImageView)findViewById(R.id.chair_1)).setColorFilter(Color.BLACK); // TODO undo the order for this chair for this step (aperitif, entree, dish, dessert) } break; case R.id.chair_2: if(!choice_selected && !dragging) { ((ImageView)findViewById(R.id.chair_2)).setColorFilter(Color.BLACK); // TODO undo the order for this chair for this step (aperitif, entree, dish, dessert) } break; case R.id.chair_3: if(!choice_selected && !dragging) { ((ImageView)findViewById(R.id.chair_3)).setColorFilter(Color.BLACK); // TODO undo the order for this chair for this step (aperitif, entree, dish, dessert) } break; case R.id.chair_4: if(!choice_selected && !dragging) { ((ImageView)findViewById(R.id.chair_4)).setColorFilter(Color.BLACK); // TODO undo the order for this chair for this step (aperitif, entree, dish, dessert) } break; } } <<<<<<< HEAD ======= private void discardChoosenItem(int chair_id) { try { BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(getFilesDir() + File.separator + "table-"+getIntent().getIntExtra("table_id",0)+"_chair-"+Integer.toString(chair_id)+".txt"))); String read; StringBuilder builder = new StringBuilder(""); while ((read = bufferedReader.readLine()) != null) { builder.append(read); } Log.d("Output", builder.toString()); bufferedReader.close(); if(builder.toString().contains(currentStep+":")) { //TODO delete currentStep+":"+choosen_item then rewrite the file } } catch (IOException e) { e.printStackTrace(); } } >>>>>>> 12d654820198a88528c373e3570c6d651b2b5692 private boolean checkIsOnView(float x, float y, View view) { float density = getResources().getDisplayMetrics().density; int[] location = new int[2]; view.getLocationOnScreen(location); if ((x > location[0]) && (x < location[0] + view.getWidth() * density / 2)) { if ((y > location[1]) && (y < location[1] + view.getHeight() * density / 2)) { return true; } } return false; } private boolean checkIsOnChair(float x, float y, View view) { if (x > view.getLeft() && (x < view.getLeft() + view.getWidth())) { if (y > view.getTop() + getSupportActionBar().getHeight() && (y < view.getTop() + view.getHeight() + getSupportActionBar().getHeight())) { return true; } } return false; } private boolean clickOnReleaseButton(float x, float y, boolean trigger) { int[] location = new int[2]; float density = getResources().getDisplayMetrics().density; center_table.getLocationOnScreen(location); float centerX = location[0] + center_table.getWidth() * density / 4; float centerY = location[1] + center_table.getHeight() * density / 4; if (y > navigation.getY()) { return false; } if (x < centerX && y < centerY) { if(trigger) { trigerChoice(category1); } return true; } else if (x > centerX && y < centerY) { if(trigger) { trigerChoice(category2); } return true; } else if (x > centerX && y > centerY) { if(trigger) { trigerChoice(category3); } return true; } else if (x < centerX && y > centerY) { if(trigger) { trigerChoice(category4); } return true; } return false; } @Override public boolean dispatchTouchEvent(MotionEvent event) { int action = event.getActionMasked(); Log.i("onTouchEvent", "trigerred"); switch (action) { case MotionEvent.ACTION_DOWN: if (!choice_selected) { Log.i("onTouchEvent", "ACTION_DOWN"); four_choice_menu_was_displayed = (four_choice_menu.getVisibility() == View.VISIBLE); if (checkIsOnView(event.getX(), event.getY(), center_table) && four_choice_menu != null) { started_from_center_table = true; setCategoryText(currentCategory); four_choice_menu.setVisibility(View.VISIBLE); } else { started_from_center_table = false; } } else { if (checkIsOnView(event.getX(), event.getY(), choice)) { dragging = true; } } break; case MotionEvent.ACTION_MOVE: Log.i("onTouchEvent", "ACTION_MOVE"); if (dragging) { choice.setX(event.getRawX()-getResources().getDisplayMetrics().density*choice.getWidth()/4); choice.setY(event.getRawY()-getResources().getDisplayMetrics().density*choice.getHeight()/2-getSupportActionBar().getHeight()); } break; case MotionEvent.ACTION_UP: Log.i("onTouchEvent", "ACTION_UP"); if (!choice_selected) { if (!checkIsOnView(event.getX(), event.getY(), center_table) && four_choice_menu != null) { if (four_choice_menu.getVisibility() == View.VISIBLE) { clickOnReleaseButton(event.getX(), event.getY(), true); } } else if (checkIsOnView(event.getX(), event.getY(), center_table) && four_choice_menu_was_displayed && four_choice_menu != null) { four_choice_menu.setVisibility(View.INVISIBLE); choice_selected = false; category_choice_selected = false; switch (currentStep) { case "Aperitif": currentCategory = aperitifCategories; break; case "Entree": currentCategory = entreeCategories; break; case "Plat": currentCategory = dishCategories; break; case "Dessert": currentCategory = dessertCategories; setCategoryText(currentCategory); break; } setCategoryText(currentCategory); } } else if (dragging) { Log.i("onTouch", "start drop"); int chairId = releaseDropOnChair(event.getX(), event.getY()); Log.i("releaseDropOnChair", "result : " + Integer.toString(chairId)); if (chairId != 0) { //TODO add the choice to the order for the good person switch(chairId) { case 1: ((ImageView)findViewById(R.id.chair_1)).setColorFilter(currentColor); break; case 2: ((ImageView)findViewById(R.id.chair_2)).setColorFilter(currentColor); break; case 3: ((ImageView)findViewById(R.id.chair_3)).setColorFilter(currentColor); break; case 4: ((ImageView)findViewById(R.id.chair_4)).setColorFilter(currentColor); break; } choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); choice.setVisibility(View.INVISIBLE); choice.setX(initial_choice_x); choice.setY(initial_choice_y); } else { choice.setVisibility(View.VISIBLE); choice.setX(initial_choice_x); choice.setY(initial_choice_y); } dragging = false; } break; case MotionEvent.ACTION_CANCEL: Log.i("onTouchEvent", "ACTION_CANCEL"); break; } return super.dispatchTouchEvent(event); } private int releaseDropOnChair(float x, float y) { Log.i("releaseDropOnChair","chair number : "+Integer.toString(chair_number)); if (chair_number > 0 && checkIsOnChair(x, y, findViewById(R.id.chair_1))) { Log.i("releaseDropOnChair","1"); return 1; } else if (chair_number > 1 && checkIsOnChair(x, y, findViewById(R.id.chair_2))) { Log.i("releaseDropOnChair","2"); return 2; } else if (chair_number > 2 && checkIsOnChair(x, y, findViewById(R.id.chair_3))) { Log.i("releaseDropOnChair","3"); return 3; } else if (chair_number > 3 && checkIsOnChair(x, y, findViewById(R.id.chair_4))) { Log.i("releaseDropOnChair","4"); return 4; } return 0; } }
UTF-8
Java
39,118
java
TableActivity.java
Java
[ { "context": "ers = new ArrayList<>();\n beers.add(\"Blanche\");\n beers.add(\"Blonde\");\n b", "end": 10377, "score": 0.6761770248413086, "start": 10372, "tag": "NAME", "value": "anche" }, { "context": " beers.add(\"Blanche\");\n beers.add(\"Blonde\");\n beers.add(\"Ambrée\");\n b", "end": 10410, "score": 0.8493161797523499, "start": 10404, "tag": "NAME", "value": "Blonde" }, { "context": " beers.add(\"Blonde\");\n beers.add(\"Ambrée\");\n beers.add(\"Brune\");\n ", "end": 10441, "score": 0.6117864847183228, "start": 10437, "tag": "NAME", "value": "Ambr" }, { "context": " beers.add(\"Ambrée\");\n beers.add(\"Brune\");\n wines = new ArrayList<>();\n ", "end": 10475, "score": 0.9635007381439209, "start": 10470, "tag": "NAME", "value": "Brune" }, { "context": " wines.add(\"Rouge\");\n wines.add(\"Rosé\");\n wines.add(\"Blanc\");\n st", "end": 10577, "score": 0.6783046722412109, "start": 10573, "tag": "NAME", "value": "Rosé" }, { "context": "alades.add(\"Du soleil\");\n salades.add(\"Chèvre chaud\");\n autres = new ArrayList<>", "end": 11355, "score": 0.5831159949302673, "start": 11353, "tag": "NAME", "value": "Ch" }, { "context": "es.add(\"Du soleil\");\n salades.add(\"Chèvre chaud\");\n autres = new ArrayList<>();\n ", "end": 11362, "score": 0.5894254446029663, "start": 11357, "tag": "NAME", "value": "re ch" }, { "context": "e.add(\"Super hâché\");\n boeufHache.add(\"Tartare\");\n boeufHache.add(\"Carpaccio\");\n ", "end": 11782, "score": 0.9934307932853699, "start": 11775, "tag": "NAME", "value": "Tartare" }, { "context": "Hache.add(\"Tartare\");\n boeufHache.add(\"Carpaccio\");\n boeufHache.add(\"Steak hâché\");\n ", "end": 11823, "score": 0.9136765599250793, "start": 11814, "tag": "NAME", "value": "Carpaccio" }, { "context": "che.add(\"Carpaccio\");\n boeufHache.add(\"Steak hâché\");\n burgers = new ArrayList<>();\n ", "end": 11866, "score": 0.9502175450325012, "start": 11855, "tag": "NAME", "value": "Steak hâché" }, { "context": "ers = new ArrayList<>();\n burgers.add(\"Rustique\");\n burgers.add(\"Traditionnel\");\n ", "end": 11944, "score": 0.9241163730621338, "start": 11936, "tag": "NAME", "value": "Rustique" }, { "context": "ers.add(\"Traditionnel\");\n burgers.add(\"Décalé\");\n burgers.add(\"Bon vivant\");\n ", "end": 12020, "score": 0.9035695791244507, "start": 12014, "tag": "NAME", "value": "Décalé" }, { "context": "ns = new ArrayList<>();\n poissons.add(\"Cabillaud\");\n poissons.add(\"Bar\");\n p", "end": 12140, "score": 0.9920604825019836, "start": 12131, "tag": "NAME", "value": "Cabillaud" }, { "context": "ssons.add(\"Cabillaud\");\n poissons.add(\"Bar\");\n poissons.add(\"Saumon\");\n ", "end": 12173, "score": 0.8555104732513428, "start": 12170, "tag": "NAME", "value": "Bar" }, { "context": " poissons.add(\"Bar\");\n poissons.add(\"Saumon\");\n fromages = new ArrayList<>();\n ", "end": 12209, "score": 0.9044947028160095, "start": 12203, "tag": "NAME", "value": "Saumon" }, { "context": "es = new ArrayList<>();\n fromages.add(\"Cabécou\");\n fromages.add(\"Camembert\");\n ", "end": 12288, "score": 0.9948314428329468, "start": 12281, "tag": "NAME", "value": "Cabécou" }, { "context": "romages.add(\"Cabécou\");\n fromages.add(\"Camembert\");\n fromages.add(\"Faisselle\");\n ", "end": 12327, "score": 0.9859461784362793, "start": 12318, "tag": "NAME", "value": "Camembert" }, { "context": "s.add(\"Camembert\");\n fromages.add(\"Faisselle\");\n dessert = new ArrayList<>();\n ", "end": 12364, "score": 0.6978816390037537, "start": 12361, "tag": "NAME", "value": "sel" }, { "context": "glaces.add(\"Liégeoises\");\n glaces.add(\"Sorbert\");\n glaces.add(\"Griotte\");\n ", "end": 12700, "score": 0.9636362195014954, "start": 12693, "tag": "NAME", "value": "Sorbert" }, { "context": " cafe.add(\"Douceur\");\n cafe.add(\"Gourmand\");\n cafe.add(\"Paille café\");\n\n ", "end": 12881, "score": 0.712090790271759, "start": 12873, "tag": "NAME", "value": "Gourmand" } ]
null
[]
package com.example.ui_igr203; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Bundle; import androidx.annotation.NonNull; import com.google.android.material.bottomnavigation.BottomNavigationView; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.text.SpannableString; import android.text.style.TextAppearanceSpan; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class TableActivity extends AppCompatActivity implements View.OnClickListener { private ImageButton center_table; private int chair_number; private View four_choice_menu; private Button choice; private View startedFromChoicesButton; private float initial_choice_x; private float initial_choice_y; private boolean started_from_center_table; private boolean four_choice_menu_was_displayed; private boolean choice_selected; private boolean category_choice_selected; private boolean dragging; private Button category1; private Button category2; private Button category3; private Button category4; List<String> beers; List<String> wines; List<String> strongAlcohols; List<String> aPartager; List<String> charcuterie; List<String> salades; List<String> autres; List<String> boeuf; List<String> boeufHache; List<String> burgers; List<String> poissons; List<String> fromages; List<String> dessert; List<String> glaces; List<String> cafe; private BottomNavigationView navigation; List<String> aperitifCategories; List<String> entreeCategories; List<String> dishCategories; List<String> dessertCategories; List<String> currentCategory; private int currentColor; private void setCategoryText(List<String> categories) { if (categories == null) { Log.e("Setting category text", "categories is null"); return; } if (categories.size() < 4) { category4.setText(""); category4.setBackgroundColor(Color.WHITE); if (categories.size() < 3) { category3.setText(""); category3.setBackgroundColor(Color.WHITE); if (categories.size() < 2) { category2.setText(""); category2.setBackgroundColor(Color.WHITE); if (categories.size() < 1) { category1.setText(""); category1.setBackgroundColor(Color.WHITE); } } } } for (int i = 0; i < categories.size(); i++) { switch (i) { case 0: category1.setText(categories.get(0)); category1.setBackgroundColor(Color.GRAY); break; case 1: category2.setText(categories.get(1)); category2.setBackgroundColor(Color.GRAY); break; case 2: category3.setText(categories.get(2)); category3.setBackgroundColor(Color.GRAY); break; case 3: category4.setText(categories.get(3)); category4.setBackgroundColor(Color.GRAY); break; } } } private void clearChairColor() { ((ImageView)findViewById(R.id.chair_1)).setColorFilter(Color.BLACK); ((ImageView)findViewById(R.id.chair_2)).setColorFilter(Color.BLACK); ((ImageView)findViewById(R.id.chair_3)).setColorFilter(Color.BLACK); ((ImageView)findViewById(R.id.chair_4)).setColorFilter(Color.BLACK); } private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_aperitif: center_table.setColorFilter(getResources().getColor(R.color.aperitifColor), PorterDuff.Mode.SRC_IN); choice.setVisibility(View.INVISIBLE); currentCategory = aperitifCategories; currentColor = getResources().getColor(R.color.aperitifColor); setCategoryText(currentCategory); choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); clearChairColor(); category_choice_selected = false; return true; case R.id.navigation_entree: center_table.setColorFilter(getResources().getColor(R.color.entreeColor), PorterDuff.Mode.SRC_IN); choice.setVisibility(View.INVISIBLE); currentCategory = entreeCategories; currentColor = getResources().getColor(R.color.entreeColor); setCategoryText(currentCategory); choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); clearChairColor(); category_choice_selected = false; return true; case R.id.navigation_dish: center_table.setColorFilter(getResources().getColor(R.color.dishColor), PorterDuff.Mode.SRC_IN); choice.setVisibility(View.INVISIBLE); currentCategory = dishCategories; currentColor = getResources().getColor(R.color.dishColor); setCategoryText(currentCategory); choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); clearChairColor(); category_choice_selected = false; return true; case R.id.navigation_dessert: center_table.setColorFilter(getResources().getColor(R.color.dessertColor), PorterDuff.Mode.SRC_IN); choice.setVisibility(View.INVISIBLE); currentCategory = dessertCategories; currentColor = getResources().getColor(R.color.dessertColor); setCategoryText(currentCategory); choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); clearChairColor(); category_choice_selected = false; return true; } return false; } }; private String ReadMenu() { try { BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(getFilesDir() + File.separator + "menu.txt"))); String read; StringBuilder builder = new StringBuilder(""); while ((read = bufferedReader.readLine()) != null) { builder.append(read); } Log.d("Output", builder.toString()); bufferedReader.close(); return builder.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } private void initializeChairs() { if (chair_number < 4) { findViewById(R.id.chair_4).setVisibility(View.INVISIBLE); if (chair_number < 3) { findViewById(R.id.chair_3).setVisibility(View.INVISIBLE); if (chair_number < 2) { findViewById(R.id.chair_2).setVisibility(View.INVISIBLE); if (chair_number < 1) { findViewById(R.id.chair_1).setVisibility(View.INVISIBLE); } } } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.send_to_kitchen: new AlertDialog.Builder(TableActivity.this) .setTitle("Envoyer en cuisine") .setMessage("- Plat 1\n- Plat 2\n.\n.\n.") .setPositiveButton("Confirmer", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // send to kitchen Intent intent = new Intent(TableActivity.this, RestaurantRoomActivity.class); startActivity(intent); } }).setNegativeButton("Annuler", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Cancel } }).show(); } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.orderingmenu, menu); return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] split = ReadMenu().split("'"); if (split.length != 0) { Log.i("Set category from file", "size is not 0"); aperitifCategories = new ArrayList<>(); entreeCategories = new ArrayList<>(); dishCategories = new ArrayList<>(); dessertCategories = new ArrayList<>(); beers = new ArrayList<>(); beers.add("Blanche"); beers.add("Blonde"); beers.add("Ambrée"); beers.add("Brune"); wines = new ArrayList<>(); wines.add("Rouge"); wines.add("Rosé"); wines.add("Blanc"); strongAlcohols = new ArrayList<>(); strongAlcohols.add("Cognac"); strongAlcohols.add("Liqueur"); strongAlcohols.add("Whisky"); strongAlcohols.add("Rhum"); aPartager = new ArrayList<>(); aPartager.add("Planche de charcuterie"); aPartager.add("Planche mixte"); aPartager.add("Duo de rillettes"); charcuterie = new ArrayList<>(); charcuterie.add("Rosette de Lyon"); charcuterie.add("Rillettes"); charcuterie.add("Terrine de campagne"); charcuterie.add("Pâté en croûte"); salades = new ArrayList<>(); salades.add("Du soleil"); salades.add("Chèv<NAME>aud"); autres = new ArrayList<>(); autres.add("Fromage blanc"); autres.add("Oeuf poché"); boeuf = new ArrayList<>(); boeuf.add("Côte"); boeuf.add("Onglet"); boeuf.add("Entrecôte"); boeuf.add("Mariné"); boeufHache = new ArrayList<>(); boeufHache.add("Super hâché"); boeufHache.add("Tartare"); boeufHache.add("Carpaccio"); boeufHache.add("<NAME>"); burgers = new ArrayList<>(); burgers.add("Rustique"); burgers.add("Traditionnel"); burgers.add("Décalé"); burgers.add("Bon vivant"); poissons = new ArrayList<>(); poissons.add("Cabillaud"); poissons.add("Bar"); poissons.add("Saumon"); fromages = new ArrayList<>(); fromages.add("Cabécou"); fromages.add("Camembert"); fromages.add("Faisselle"); dessert = new ArrayList<>(); dessert.add("Tartare de fruits"); dessert.add("Ile flottante"); dessert.add("Mousse au chocolat"); dessert.add("Tarte aux pommes"); glaces = new ArrayList<>(); glaces.add("Liégeoises"); glaces.add("Sorbert"); glaces.add("Griotte"); glaces.add("Petite maison"); cafe = new ArrayList<>(); cafe.add("Douceur"); cafe.add("Gourmand"); cafe.add("Paille café"); for (int i = 0; i < split.length; i++) { String[] splitTmp = split[i].split(","); switch (i) { case 0: Log.i("Set category from file", "entering case 0"); for (int j = 0; j < splitTmp.length; j++) { Log.i("Set from file 0", splitTmp[j]); aperitifCategories.add(splitTmp[j]); } break; case 1: Log.i("Set category from file", "entering case 1"); for (int j = 0; j < splitTmp.length; j++) { Log.i("Set from file 1", splitTmp[j]); entreeCategories.add(splitTmp[j]); } break; case 2: Log.i("Set category from file", "entering case 2"); for (int j = 0; j < splitTmp.length; j++) { Log.i("Set from file 2", splitTmp[j]); dishCategories.add(splitTmp[j]); } break; case 3: Log.i("Set category from file", "entering case 3"); for (int j = 0; j < splitTmp.length; j++) { Log.i("Set from file 3", splitTmp[j]); dessertCategories.add(splitTmp[j]); } break; } } } currentCategory = aperitifCategories; currentColor = getResources().getColor(R.color.aperitifColor); startedFromChoicesButton = null; setContentView(R.layout.activity_table); chair_number = getIntent().getIntExtra("chair_number", 0); initializeChairs(); findViewById(R.id.chair_1).setOnClickListener(this); findViewById(R.id.chair_2).setOnClickListener(this); findViewById(R.id.chair_3).setOnClickListener(this); findViewById(R.id.chair_4).setOnClickListener(this); four_choice_menu_was_displayed = false; started_from_center_table = false; choice_selected = false; category_choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); findViewById(R.id.delete_choice).setOnClickListener(this); dragging = false; center_table = findViewById(R.id.center_table); center_table.setOnClickListener(this); choice = findViewById(R.id.choice); choice.setVisibility(View.INVISIBLE); choice.setTextColor(Color.WHITE); choice.setBackgroundColor(Color.BLACK); choice.setOnClickListener(this); choice.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // Layout has happened here. initial_choice_x = choice.getX(); initial_choice_y = choice.getY(); } }); four_choice_menu = findViewById(R.id.four_choice); four_choice_menu.setVisibility(View.INVISIBLE); category1 = findViewById(R.id.category1); category2 = findViewById(R.id.category2); category3 = findViewById(R.id.category3); category4 = findViewById(R.id.category4); category1.setOnClickListener(this); category2.setOnClickListener(this); category3.setOnClickListener(this); category4.setOnClickListener(this); setCategoryText(currentCategory); navigation = findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); SpannableString aperitifString = new SpannableString(getResources().getString(R.string.title_aperitif)); aperitifString.setSpan(new TextAppearanceSpan(this, R.style.AperitifTextAppearance), 0, aperitifString.length(), 0); SpannableString entreeString = new SpannableString(getResources().getString(R.string.title_entree)); entreeString.setSpan(new TextAppearanceSpan(this, R.style.EntreeTextAppearance), 0, entreeString.length(), 0); SpannableString dishString = new SpannableString(getResources().getString(R.string.title_dish)); dishString.setSpan(new TextAppearanceSpan(this, R.style.DishTextAppearance), 0, dishString.length(), 0); SpannableString dessertString = new SpannableString(getResources().getString(R.string.title_dessert)); dessertString.setSpan(new TextAppearanceSpan(this, R.style.DessertTextAppearance), 0, dessertString.length(), 0); navigation.getMenu().findItem(R.id.navigation_aperitif).getIcon().setColorFilter(getResources().getColor(R.color.aperitifColor), PorterDuff.Mode.SRC_IN); navigation.getMenu().findItem(R.id.navigation_aperitif).setTitle(aperitifString); navigation.getMenu().findItem(R.id.navigation_entree).getIcon().setColorFilter(getResources().getColor(R.color.entreeColor), PorterDuff.Mode.SRC_IN); navigation.getMenu().findItem(R.id.navigation_entree).setTitle(entreeString); navigation.getMenu().findItem(R.id.navigation_dish).getIcon().setColorFilter(getResources().getColor(R.color.dishColor), PorterDuff.Mode.SRC_IN); navigation.getMenu().findItem(R.id.navigation_dish).setTitle(dishString); navigation.getMenu().findItem(R.id.navigation_dessert).getIcon().setColorFilter(getResources().getColor(R.color.dessertColor), PorterDuff.Mode.SRC_IN); navigation.getMenu().findItem(R.id.navigation_dessert).setTitle(dessertString); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); if (getIntent().getStringExtra("table_id") != null) { actionBar.setTitle(getResources().getString(R.string.title_activity_table) + getIntent().getStringExtra("table_id")); } else { actionBar.setTitle(getResources().getString(R.string.title_activity_table) + getResources().getString(R.string.table_id_unkwnown)); } } private void trigerChoice(View v) { switch(v.getId()) { case R.id.category1: if (currentCategory.size() > 0) { if(!category_choice_selected) { switch (currentStep) { case "Aperitif": currentCategory = beers; setCategoryText(currentCategory); break; case "Entree": currentCategory = aPartager; setCategoryText(currentCategory); break; case "Plat": currentCategory = boeuf; setCategoryText(currentCategory); break; case "Dessert": currentCategory = fromages; setCategoryText(currentCategory); break; } category_choice_selected = true; } else { choice.setText(category1.getText()); choice.setVisibility(View.VISIBLE); four_choice_menu.setVisibility(View.INVISIBLE); choice_selected = true; switch (currentStep) { case "Aperitif": currentCategory = aperitifCategories; break; case "Entree": currentCategory = entreeCategories; break; case "Plat": currentCategory = dishCategories; break; case "Dessert": currentCategory = dessertCategories; break; } findViewById(R.id.delete_choice).setVisibility(View.VISIBLE); category_choice_selected = false; } } break; case R.id.category2: if (currentCategory.size() > 1) { if(!category_choice_selected) { switch (currentStep) { case "Aperitif": currentCategory = wines; setCategoryText(currentCategory); break; case "Entree": currentCategory = charcuterie; setCategoryText(currentCategory); break; case "Plat": currentCategory = boeufHache; setCategoryText(currentCategory); break; case "Dessert": currentCategory = dessert; setCategoryText(currentCategory); break; } category_choice_selected = true; } else { choice.setText(category2.getText()); choice.setVisibility(View.VISIBLE); choice_selected = true; switch (currentStep) { case "Aperitif": currentCategory = aperitifCategories; break; case "Entree": currentCategory = entreeCategories; break; case "Plat": currentCategory = dishCategories; break; case "Dessert": currentCategory = dessertCategories; break; } findViewById(R.id.delete_choice).setVisibility(View.VISIBLE); four_choice_menu.setVisibility(View.INVISIBLE); category_choice_selected = false; } } break; case R.id.category3: if (currentCategory.size() > 2) { if(!category_choice_selected) { switch (currentStep) { case "Aperitif": currentCategory = strongAlcohols; setCategoryText(currentCategory); break; case "Entree": currentCategory = salades; setCategoryText(currentCategory); break; case "Plat": currentCategory = burgers; setCategoryText(currentCategory); break; case "Dessert": currentCategory = glaces; setCategoryText(currentCategory); break; } category_choice_selected = true; } else { choice.setText(category3.getText()); choice.setVisibility(View.VISIBLE); choice_selected = true; switch (currentStep) { case "Aperitif": currentCategory = aperitifCategories; break; case "Entree": currentCategory = entreeCategories; break; case "Plat": currentCategory = dishCategories; break; case "Dessert": currentCategory = dessertCategories; break; } findViewById(R.id.delete_choice).setVisibility(View.VISIBLE); four_choice_menu.setVisibility(View.INVISIBLE); category_choice_selected = false; } } break; case R.id.category4: if (currentCategory.size() > 3) { if(!category_choice_selected) { switch (currentStep) { case "Entree": currentCategory = autres; setCategoryText(currentCategory); break; case "Plat": currentCategory = poissons; setCategoryText(currentCategory); break; case "Dessert": currentCategory = cafe; setCategoryText(currentCategory); break; } category_choice_selected = true; } else { choice.setText(category4.getText()); choice.setVisibility(View.VISIBLE); choice_selected = true; switch (currentStep) { case "Aperitif": currentCategory = aperitifCategories; break; case "Entree": currentCategory = entreeCategories; break; case "Plat": currentCategory = dishCategories; break; case "Dessert": currentCategory = dessertCategories; break; } findViewById(R.id.delete_choice).setVisibility(View.VISIBLE); four_choice_menu.setVisibility(View.INVISIBLE); category_choice_selected = false; } } break; } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.center_table: break; case R.id.delete_choice: choice.setVisibility(View.INVISIBLE); findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); choice_selected = false; category_choice_selected = false; case R.id.chair_1: if(!choice_selected && !dragging) { ((ImageView)findViewById(R.id.chair_1)).setColorFilter(Color.BLACK); // TODO undo the order for this chair for this step (aperitif, entree, dish, dessert) } break; case R.id.chair_2: if(!choice_selected && !dragging) { ((ImageView)findViewById(R.id.chair_2)).setColorFilter(Color.BLACK); // TODO undo the order for this chair for this step (aperitif, entree, dish, dessert) } break; case R.id.chair_3: if(!choice_selected && !dragging) { ((ImageView)findViewById(R.id.chair_3)).setColorFilter(Color.BLACK); // TODO undo the order for this chair for this step (aperitif, entree, dish, dessert) } break; case R.id.chair_4: if(!choice_selected && !dragging) { ((ImageView)findViewById(R.id.chair_4)).setColorFilter(Color.BLACK); // TODO undo the order for this chair for this step (aperitif, entree, dish, dessert) } break; } } <<<<<<< HEAD ======= private void discardChoosenItem(int chair_id) { try { BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(getFilesDir() + File.separator + "table-"+getIntent().getIntExtra("table_id",0)+"_chair-"+Integer.toString(chair_id)+".txt"))); String read; StringBuilder builder = new StringBuilder(""); while ((read = bufferedReader.readLine()) != null) { builder.append(read); } Log.d("Output", builder.toString()); bufferedReader.close(); if(builder.toString().contains(currentStep+":")) { //TODO delete currentStep+":"+choosen_item then rewrite the file } } catch (IOException e) { e.printStackTrace(); } } >>>>>>> 12d654820198a88528c373e3570c6d651b2b5692 private boolean checkIsOnView(float x, float y, View view) { float density = getResources().getDisplayMetrics().density; int[] location = new int[2]; view.getLocationOnScreen(location); if ((x > location[0]) && (x < location[0] + view.getWidth() * density / 2)) { if ((y > location[1]) && (y < location[1] + view.getHeight() * density / 2)) { return true; } } return false; } private boolean checkIsOnChair(float x, float y, View view) { if (x > view.getLeft() && (x < view.getLeft() + view.getWidth())) { if (y > view.getTop() + getSupportActionBar().getHeight() && (y < view.getTop() + view.getHeight() + getSupportActionBar().getHeight())) { return true; } } return false; } private boolean clickOnReleaseButton(float x, float y, boolean trigger) { int[] location = new int[2]; float density = getResources().getDisplayMetrics().density; center_table.getLocationOnScreen(location); float centerX = location[0] + center_table.getWidth() * density / 4; float centerY = location[1] + center_table.getHeight() * density / 4; if (y > navigation.getY()) { return false; } if (x < centerX && y < centerY) { if(trigger) { trigerChoice(category1); } return true; } else if (x > centerX && y < centerY) { if(trigger) { trigerChoice(category2); } return true; } else if (x > centerX && y > centerY) { if(trigger) { trigerChoice(category3); } return true; } else if (x < centerX && y > centerY) { if(trigger) { trigerChoice(category4); } return true; } return false; } @Override public boolean dispatchTouchEvent(MotionEvent event) { int action = event.getActionMasked(); Log.i("onTouchEvent", "trigerred"); switch (action) { case MotionEvent.ACTION_DOWN: if (!choice_selected) { Log.i("onTouchEvent", "ACTION_DOWN"); four_choice_menu_was_displayed = (four_choice_menu.getVisibility() == View.VISIBLE); if (checkIsOnView(event.getX(), event.getY(), center_table) && four_choice_menu != null) { started_from_center_table = true; setCategoryText(currentCategory); four_choice_menu.setVisibility(View.VISIBLE); } else { started_from_center_table = false; } } else { if (checkIsOnView(event.getX(), event.getY(), choice)) { dragging = true; } } break; case MotionEvent.ACTION_MOVE: Log.i("onTouchEvent", "ACTION_MOVE"); if (dragging) { choice.setX(event.getRawX()-getResources().getDisplayMetrics().density*choice.getWidth()/4); choice.setY(event.getRawY()-getResources().getDisplayMetrics().density*choice.getHeight()/2-getSupportActionBar().getHeight()); } break; case MotionEvent.ACTION_UP: Log.i("onTouchEvent", "ACTION_UP"); if (!choice_selected) { if (!checkIsOnView(event.getX(), event.getY(), center_table) && four_choice_menu != null) { if (four_choice_menu.getVisibility() == View.VISIBLE) { clickOnReleaseButton(event.getX(), event.getY(), true); } } else if (checkIsOnView(event.getX(), event.getY(), center_table) && four_choice_menu_was_displayed && four_choice_menu != null) { four_choice_menu.setVisibility(View.INVISIBLE); choice_selected = false; category_choice_selected = false; switch (currentStep) { case "Aperitif": currentCategory = aperitifCategories; break; case "Entree": currentCategory = entreeCategories; break; case "Plat": currentCategory = dishCategories; break; case "Dessert": currentCategory = dessertCategories; setCategoryText(currentCategory); break; } setCategoryText(currentCategory); } } else if (dragging) { Log.i("onTouch", "start drop"); int chairId = releaseDropOnChair(event.getX(), event.getY()); Log.i("releaseDropOnChair", "result : " + Integer.toString(chairId)); if (chairId != 0) { //TODO add the choice to the order for the good person switch(chairId) { case 1: ((ImageView)findViewById(R.id.chair_1)).setColorFilter(currentColor); break; case 2: ((ImageView)findViewById(R.id.chair_2)).setColorFilter(currentColor); break; case 3: ((ImageView)findViewById(R.id.chair_3)).setColorFilter(currentColor); break; case 4: ((ImageView)findViewById(R.id.chair_4)).setColorFilter(currentColor); break; } choice_selected = false; findViewById(R.id.delete_choice).setVisibility(View.INVISIBLE); choice.setVisibility(View.INVISIBLE); choice.setX(initial_choice_x); choice.setY(initial_choice_y); } else { choice.setVisibility(View.VISIBLE); choice.setX(initial_choice_x); choice.setY(initial_choice_y); } dragging = false; } break; case MotionEvent.ACTION_CANCEL: Log.i("onTouchEvent", "ACTION_CANCEL"); break; } return super.dispatchTouchEvent(event); } private int releaseDropOnChair(float x, float y) { Log.i("releaseDropOnChair","chair number : "+Integer.toString(chair_number)); if (chair_number > 0 && checkIsOnChair(x, y, findViewById(R.id.chair_1))) { Log.i("releaseDropOnChair","1"); return 1; } else if (chair_number > 1 && checkIsOnChair(x, y, findViewById(R.id.chair_2))) { Log.i("releaseDropOnChair","2"); return 2; } else if (chair_number > 2 && checkIsOnChair(x, y, findViewById(R.id.chair_3))) { Log.i("releaseDropOnChair","3"); return 3; } else if (chair_number > 3 && checkIsOnChair(x, y, findViewById(R.id.chair_4))) { Log.i("releaseDropOnChair","4"); return 4; } return 0; } }
39,112
0.490422
0.485537
908
42.060574
26.865213
161
false
false
0
0
0
0
0
0
0.689427
false
false
13
e5cce31a4c5a87e9d931c883ec9c88f1f5935b6f
17,626,545,847,513
b1cf2907bb42a59266d36e8fdd8aaf398e81bf37
/src/main/java/mops/rheinjug2/repositories/EventRepository.java
fafbcf73aa91c820beb449f4c671820046ec44bd
[]
no_license
hhu-propra2-2019/abschlussprojekt-grossbrandtmeister
https://github.com/hhu-propra2-2019/abschlussprojekt-grossbrandtmeister
72fedf86e00156e5b162646b93a27b9d9acfbfa6
06cbac80441ddcbc36d6c5a19ff27b465ece76e7
refs/heads/master
2022-04-15T08:56:51.209000
2020-04-05T18:52:29
2020-04-05T18:52:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mops.rheinjug2.repositories; import java.util.List; import mops.rheinjug2.entities.Event; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @Repository @SuppressWarnings("PMD.AvoidDuplicateLiterals") public interface EventRepository extends CrudRepository<Event, Long> { @Query(value = "SELECT COUNT(*) FROM student_event WHERE student_event.event = :id") int countStudentsPerEventById(@Param("id") Long id); @Query(value = "SELECT student FROM student_event WHERE student_event.event = :id") List<Long> findAllStudentsIdsPerEventById(@Param("id") Long id); @Query(value = "SELECT * FROM event WHERE meetup_id = :id") Event findEventByMeetupId(@Param("id") String id); @Query(value = "SELECT * FROM event WHERE status = :status") List<Event> findEventsByStatus(@Param("status") String status); @Query(value = "SELECT COUNT(*) FROM student_event WHERE" + " submitted_summary = TRUE AND accepted = FALSE") int getNumberOfSubmittedAndUnacceptedSummaries(); }
UTF-8
Java
1,173
java
EventRepository.java
Java
[]
null
[]
package mops.rheinjug2.repositories; import java.util.List; import mops.rheinjug2.entities.Event; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @Repository @SuppressWarnings("PMD.AvoidDuplicateLiterals") public interface EventRepository extends CrudRepository<Event, Long> { @Query(value = "SELECT COUNT(*) FROM student_event WHERE student_event.event = :id") int countStudentsPerEventById(@Param("id") Long id); @Query(value = "SELECT student FROM student_event WHERE student_event.event = :id") List<Long> findAllStudentsIdsPerEventById(@Param("id") Long id); @Query(value = "SELECT * FROM event WHERE meetup_id = :id") Event findEventByMeetupId(@Param("id") String id); @Query(value = "SELECT * FROM event WHERE status = :status") List<Event> findEventsByStatus(@Param("status") String status); @Query(value = "SELECT COUNT(*) FROM student_event WHERE" + " submitted_summary = TRUE AND accepted = FALSE") int getNumberOfSubmittedAndUnacceptedSummaries(); }
1,173
0.766411
0.764706
29
39.448277
28.381132
86
false
false
0
0
0
0
0
0
0.448276
false
false
13
1a47ffb51e9698612ab8848f9113061b01b5486a
3,839,700,817,477
5ca0847eb39c793362701debbb285761b9575150
/src/ru/spbstu/telematics/lecture6/NaturalMonitor.java
26969faa87cbd98d26805d2d287fbd0f0b9e20e9
[]
no_license
1ukash/java2014
https://github.com/1ukash/java2014
36a314f9ab519e20deeaf713b5a6a3f3972217f5
29462356fa22534b3d5a33c31fc413feedccb105
refs/heads/master
2016-09-06T16:19:53.187000
2015-01-10T20:17:20
2015-01-10T20:17:20
23,658,387
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.spbstu.telematics.lecture6; public class NaturalMonitor { private int a; private int b; private double c; public synchronized int getA() { return a; } public synchronized void setA(int a) { this.a = a; } public synchronized int getB() { return b; } public synchronized void setB(int b) { this.b = b; } public synchronized double getC() { return c; } public synchronized void setC(double c) { this.c = c; } }
UTF-8
Java
447
java
NaturalMonitor.java
Java
[]
null
[]
package ru.spbstu.telematics.lecture6; public class NaturalMonitor { private int a; private int b; private double c; public synchronized int getA() { return a; } public synchronized void setA(int a) { this.a = a; } public synchronized int getB() { return b; } public synchronized void setB(int b) { this.b = b; } public synchronized double getC() { return c; } public synchronized void setC(double c) { this.c = c; } }
447
0.680089
0.677852
25
16.879999
14.297748
42
false
false
0
0
0
0
0
0
1.48
false
false
13
4d3194e32f821f83f2fc39fff1a06b23c1b582d5
24,206,435,732,773
8f70fe0e87e308fe3dc8cfe9a515a315ed131d18
/src/test/java/com/sugarcrm/test/cases/Cases_23854.java
3774aff822b4b6ab033a5bd7be3c75a41c915190
[]
no_license
mustaeenbasit/LKW-Walter_Automation
https://github.com/mustaeenbasit/LKW-Walter_Automation
76fd02c34c766bc34a5c300e3f5943664c70d67b
a97f4feca8e51c21f3cef1949573a8e4909e7143
refs/heads/master
2020-04-09T17:54:32.252000
2018-12-05T09:49:29
2018-12-05T09:49:29
160,495,697
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sugarcrm.test.cases; import com.sugarcrm.candybean.datasource.FieldSet; import com.sugarcrm.sugar.VoodooControl; import com.sugarcrm.sugar.VoodooUtils; import com.sugarcrm.sugar.records.ContactRecord; import com.sugarcrm.sugar.views.StandardSubpanel; import com.sugarcrm.test.SugarTest; import org.junit.Test; public class Cases_23854 extends SugarTest { ContactRecord myContact; StandardSubpanel casesSubpanel; FieldSet customData; public void setup() throws Exception { customData = testData.get(testName).get(0); myContact= (ContactRecord)sugar().contacts.api.create(); sugar().login(); } /** * Clear all entered search field by click “Clear” button on pop-up select window after search action * * @throws Exception */ @Test public void Cases_23854_execute() throws Exception { VoodooUtils.voodoo.log.info("Running " + testName + "..."); // Go to Contact Record View myContact.navToRecord(); casesSubpanel = sugar().contacts.recordView.subpanels.get(sugar().cases.moduleNamePlural); // Click “Create” button in Cases subpanel casesSubpanel.addRecord(); // Show More sugar().cases.createDrawer.showMore(); // TODO: VOOD-518 & VOOD-1161 need lib support for select team on cases module VoodooControl teamfieldCtrl = new VoodooControl("a", "css", ".fld_team_name.edit .select2-choice"); teamfieldCtrl.click(); // Enter search string in Team field VoodooControl searchCtrl = new VoodooControl("input", "css", "#select2-drop div input"); searchCtrl.set(sugar().users.getQAUser().get("userName").substring(0, 1)); sugar().alerts.waitForLoadingExpiration(); // Verify the team has been found as soon as you typed the string VoodooControl searchResultCtrl = new VoodooControl("ul", "css", "#select2-drop [role='listbox']"); searchResultCtrl.assertContains(sugar().users.getQAUser().get("userName"), true); searchResultCtrl.click(); teamfieldCtrl.click(); // Clear the Search String searchCtrl.set(""); // Verify The team link was replaced with "Search and Select" when you cleared the search input field VoodooControl searchResultCtrl1 = new VoodooControl("div", "css", "#select2-drop ul:nth-child(3) li div"); searchResultCtrl1.assertContains(customData.get("text"), true); searchResultCtrl1.click(); sugar().alerts.waitForLoadingExpiration(); sugar().teams.searchSelect.cancel(); sugar().cases.createDrawer.cancel(); VoodooUtils.voodoo.log.info(testName + "complete."); } public void cleanup() throws Exception {} }
UTF-8
Java
2,529
java
Cases_23854.java
Java
[]
null
[]
package com.sugarcrm.test.cases; import com.sugarcrm.candybean.datasource.FieldSet; import com.sugarcrm.sugar.VoodooControl; import com.sugarcrm.sugar.VoodooUtils; import com.sugarcrm.sugar.records.ContactRecord; import com.sugarcrm.sugar.views.StandardSubpanel; import com.sugarcrm.test.SugarTest; import org.junit.Test; public class Cases_23854 extends SugarTest { ContactRecord myContact; StandardSubpanel casesSubpanel; FieldSet customData; public void setup() throws Exception { customData = testData.get(testName).get(0); myContact= (ContactRecord)sugar().contacts.api.create(); sugar().login(); } /** * Clear all entered search field by click “Clear” button on pop-up select window after search action * * @throws Exception */ @Test public void Cases_23854_execute() throws Exception { VoodooUtils.voodoo.log.info("Running " + testName + "..."); // Go to Contact Record View myContact.navToRecord(); casesSubpanel = sugar().contacts.recordView.subpanels.get(sugar().cases.moduleNamePlural); // Click “Create” button in Cases subpanel casesSubpanel.addRecord(); // Show More sugar().cases.createDrawer.showMore(); // TODO: VOOD-518 & VOOD-1161 need lib support for select team on cases module VoodooControl teamfieldCtrl = new VoodooControl("a", "css", ".fld_team_name.edit .select2-choice"); teamfieldCtrl.click(); // Enter search string in Team field VoodooControl searchCtrl = new VoodooControl("input", "css", "#select2-drop div input"); searchCtrl.set(sugar().users.getQAUser().get("userName").substring(0, 1)); sugar().alerts.waitForLoadingExpiration(); // Verify the team has been found as soon as you typed the string VoodooControl searchResultCtrl = new VoodooControl("ul", "css", "#select2-drop [role='listbox']"); searchResultCtrl.assertContains(sugar().users.getQAUser().get("userName"), true); searchResultCtrl.click(); teamfieldCtrl.click(); // Clear the Search String searchCtrl.set(""); // Verify The team link was replaced with "Search and Select" when you cleared the search input field VoodooControl searchResultCtrl1 = new VoodooControl("div", "css", "#select2-drop ul:nth-child(3) li div"); searchResultCtrl1.assertContains(customData.get("text"), true); searchResultCtrl1.click(); sugar().alerts.waitForLoadingExpiration(); sugar().teams.searchSelect.cancel(); sugar().cases.createDrawer.cancel(); VoodooUtils.voodoo.log.info(testName + "complete."); } public void cleanup() throws Exception {} }
2,529
0.741769
0.730662
69
35.536232
30.515181
108
false
false
0
0
0
0
0
0
1.84058
false
false
13
66a294e13bf314696c2cfa799c7d01ebc0dbde2b
24,206,435,733,249
e85db1b35e31991badae75e7a6faafc7e8437e74
/src/main/java/example/dao/UserDaoImpl.java
34fb34192c129a579af760b58a5a64807097a13b
[]
no_license
NhungPhan0801/portal
https://github.com/NhungPhan0801/portal
c808a4ebbcedd4602bef9dde548deed8cc0f8082
250d92a132f9667b0a4c8f2eb5078bec774dc9c7
refs/heads/master
2020-03-28T18:31:43.206000
2018-09-15T10:44:45
2018-09-15T10:44:45
148,889,158
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package example.dao; import example.persistence.entities.RoleEntity; import example.persistence.entities.UserEntity; import example.repository.HibernateRepositoryImpl; public class UserDaoImpl extends HibernateRepositoryImpl<Integer, UserEntity> implements UserDao { }
UTF-8
Java
271
java
UserDaoImpl.java
Java
[]
null
[]
package example.dao; import example.persistence.entities.RoleEntity; import example.persistence.entities.UserEntity; import example.repository.HibernateRepositoryImpl; public class UserDaoImpl extends HibernateRepositoryImpl<Integer, UserEntity> implements UserDao { }
271
0.859779
0.859779
8
32.875
32.165344
98
false
false
0
0
0
0
0
0
0.625
false
false
13
a16fdf82b0c2fea9338c942d4fe82232bf963c00
10,436,770,588,183
a208527a67d28848ff3ded37df5ac7bd69273035
/src/com/athensoft/content/ad/dao/AdRecommendDaoJdbcImpl.java
fa26e136905e4826b44e5746ffd764e9dd2f56e9
[]
no_license
info-athensoft/athensoft_acp
https://github.com/info-athensoft/athensoft_acp
f2f2cdfbf554dcced06b4fd7534c08048d957859
74d2488124bf419918d875f2b9d0fa5faa490817
refs/heads/master
2021-01-12T01:20:50.720000
2019-03-13T20:45:06
2019-03-13T20:45:06
78,372,693
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.athensoft.content.ad.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import com.athensoft.base.dao.BaseDaoJdbcImpl; import com.athensoft.content.ad.entity.AdRecommend; @Repository @Qualifier("adRecommendDaoJdbcImpl") public class AdRecommendDaoJdbcImpl extends BaseDaoJdbcImpl implements AdRecommendDao { private static final Logger logger = Logger.getLogger(AdRecommendDaoJdbcImpl.class); private final String TABLE = "ad_recommend"; @Override public List<AdRecommend> findAll() { StringBuffer sbf = new StringBuffer(); sbf.append("SELECT "); sbf.append("global_id, "); sbf.append("ad_uuid, "); sbf.append("page_id, "); sbf.append("page_name, "); sbf.append("rcmd_score, "); sbf.append("rcmd_rank, "); sbf.append("rcmd_status "); sbf.append(" FROM " + TABLE); sbf.append(" ORDER BY page_id"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); return jdbc.query(sql, paramSource, new AdRecommendRowMapper()); } @Override public List<AdRecommend> findByPageId(int pageId) { StringBuffer sbf = new StringBuffer(); sbf.append("SELECT "); sbf.append("global_id, "); sbf.append("ad_uuid, "); sbf.append("page_id, "); sbf.append("page_name, "); sbf.append("rcmd_score, "); sbf.append("rcmd_rank, "); sbf.append("rcmd_status "); sbf.append(" FROM " + TABLE); sbf.append(" WHERE page_id=:page_id"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("page_id", pageId); return jdbc.query(sql, paramSource, new AdRecommendRowMapper()); } @Override public AdRecommend findById(int globalId) { StringBuffer sbf = new StringBuffer(); sbf.append("SELECT "); sbf.append("global_id, "); sbf.append("ad_uuid, "); sbf.append("page_id, "); sbf.append("page_name, "); sbf.append("rcmd_score, "); sbf.append("rcmd_rank, "); sbf.append("rcmd_status "); sbf.append(" FROM " + TABLE); sbf.append(" WHERE global_id = :globalId"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("globalId", globalId); AdRecommend x = new AdRecommend(); try { x = jdbc.queryForObject(sql, paramSource, new AdRecommendRowMapper()); } catch (Exception ex) { x = null; } return x; } @Override public List<AdRecommend> findByFilter(String queryString) { StringBuffer sbf = new StringBuffer(); sbf.append("SELECT "); sbf.append("global_id, "); sbf.append("ad_uuid, "); sbf.append("page_id, "); sbf.append("page_name, "); sbf.append("rcmd_score, "); sbf.append("rcmd_rank, "); sbf.append("rcmd_status "); sbf.append(" FROM " + TABLE); sbf.append(" WHERE 1=1 "); sbf.append(queryString); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); List<AdRecommend> x = new ArrayList<AdRecommend>(); try { x = jdbc.query(sql, paramSource, new AdRecommendRowMapper()); } catch (Exception ex) { x = null; } return x; } @Override public int create(AdRecommend x) { StringBuffer sbf = new StringBuffer(); sbf.append(" INSERT INTO ").append(TABLE); sbf.append(" ("); sbf.append(" ad_uuid,"); sbf.append(" page_id, "); sbf.append(" page_name, "); sbf.append(" rcmd_score, "); sbf.append(" rcmd_rank, "); sbf.append(" rcmd_status "); sbf.append(" ) VALUES ("); sbf.append(" :ad_uuid,"); sbf.append(" :page_id, "); sbf.append(" :page_name, "); sbf.append(" :rcmd_score, "); sbf.append(" :rcmd_rank, "); sbf.append(" :rcmd_status "); sbf.append(" )"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("ad_uuid", x.getAdUUID()); paramSource.addValue("page_id", x.getPageId()); paramSource.addValue("page_name", x.getPageName()); paramSource.addValue("rcmd_score", x.getRcmdScore()); paramSource.addValue("rcmd_rank", x.getRcmdRank()); paramSource.addValue("rcmd_status", x.getRcmdStatus()); int res = 0; try { res = jdbc.update(sql, paramSource); } catch (Exception ex) { ex.printStackTrace(); } return res; } @Override public int update(AdRecommend x) { StringBuffer sbf = new StringBuffer(); sbf.append(" UPDATE ").append(TABLE); sbf.append(" SET ad_uuid=:ad_uuid,"); sbf.append(" page_id=:page_id,"); sbf.append(" page_name=:page_name,"); sbf.append(" rcmd_rank=:rcmd_rank,"); // sbf.append(" rcmd_score=:rcmd_score,"); sbf.append(" rcmd_status=:rcmd_status "); sbf.append(" WHERE global_id=:global_id"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("ad_uuid", x.getAdUUID()); paramSource.addValue("page_id", x.getPageId()); paramSource.addValue("page_name", x.getPageName()); paramSource.addValue("rcmd_rank", x.getRcmdRank()); paramSource.addValue("rcmd_status", x.getRcmdStatus()); paramSource.addValue("global_id", x.getGlobalId()); return jdbc.update(sql, paramSource); } @Override public int[] updateBatch(List<AdRecommend> adRecommendList) { logger.debug("updateBatch() adRecommendList size=" + adRecommendList == null ? "NULL" : adRecommendList.size()); StringBuffer sbf = new StringBuffer(); sbf.append("UPDATE ").append(TABLE); sbf.append(" SET"); sbf.append(" ad_status=:adStatus"); sbf.append(" WHERE ad_uuid =:adUUID"); String sql = sbf.toString(); List<SqlParameterSource> parameters = new ArrayList<SqlParameterSource>(); for (AdRecommend x : adRecommendList) { parameters.add(new BeanPropertySqlParameterSource(x)); } // jdbc.batchUpdate(sql, parameters.toArray(new SqlParameterSource[0])); return jdbc.batchUpdate(sql, parameters.toArray(new SqlParameterSource[0])); } @Override public int delete(AdRecommend x) { StringBuffer sbf = new StringBuffer(); sbf.append(" DELETE FROM ").append(TABLE); sbf.append(" WHERE global_id=:global_id"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("global_id", x.getGlobalId()); return jdbc.update(sql, paramSource); } private static class AdRecommendRowMapper implements RowMapper<AdRecommend> { public AdRecommend mapRow(ResultSet rs, int rowNumber) throws SQLException { AdRecommend x = new AdRecommend(); x.setGlobalId(rs.getInt("global_id")); x.setAdUUID(rs.getString("ad_uuid")); x.setPageId(rs.getInt("page_id")); x.setPageName(rs.getString("page_name")); x.setRcmdRank(rs.getInt("rcmd_rank")); x.setRcmdScore(rs.getDouble("rcmd_score")); x.setRcmdStatus(rs.getInt("rcmd_status")); return x; } } }
UTF-8
Java
7,431
java
AdRecommendDaoJdbcImpl.java
Java
[]
null
[]
package com.athensoft.content.ad.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import com.athensoft.base.dao.BaseDaoJdbcImpl; import com.athensoft.content.ad.entity.AdRecommend; @Repository @Qualifier("adRecommendDaoJdbcImpl") public class AdRecommendDaoJdbcImpl extends BaseDaoJdbcImpl implements AdRecommendDao { private static final Logger logger = Logger.getLogger(AdRecommendDaoJdbcImpl.class); private final String TABLE = "ad_recommend"; @Override public List<AdRecommend> findAll() { StringBuffer sbf = new StringBuffer(); sbf.append("SELECT "); sbf.append("global_id, "); sbf.append("ad_uuid, "); sbf.append("page_id, "); sbf.append("page_name, "); sbf.append("rcmd_score, "); sbf.append("rcmd_rank, "); sbf.append("rcmd_status "); sbf.append(" FROM " + TABLE); sbf.append(" ORDER BY page_id"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); return jdbc.query(sql, paramSource, new AdRecommendRowMapper()); } @Override public List<AdRecommend> findByPageId(int pageId) { StringBuffer sbf = new StringBuffer(); sbf.append("SELECT "); sbf.append("global_id, "); sbf.append("ad_uuid, "); sbf.append("page_id, "); sbf.append("page_name, "); sbf.append("rcmd_score, "); sbf.append("rcmd_rank, "); sbf.append("rcmd_status "); sbf.append(" FROM " + TABLE); sbf.append(" WHERE page_id=:page_id"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("page_id", pageId); return jdbc.query(sql, paramSource, new AdRecommendRowMapper()); } @Override public AdRecommend findById(int globalId) { StringBuffer sbf = new StringBuffer(); sbf.append("SELECT "); sbf.append("global_id, "); sbf.append("ad_uuid, "); sbf.append("page_id, "); sbf.append("page_name, "); sbf.append("rcmd_score, "); sbf.append("rcmd_rank, "); sbf.append("rcmd_status "); sbf.append(" FROM " + TABLE); sbf.append(" WHERE global_id = :globalId"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("globalId", globalId); AdRecommend x = new AdRecommend(); try { x = jdbc.queryForObject(sql, paramSource, new AdRecommendRowMapper()); } catch (Exception ex) { x = null; } return x; } @Override public List<AdRecommend> findByFilter(String queryString) { StringBuffer sbf = new StringBuffer(); sbf.append("SELECT "); sbf.append("global_id, "); sbf.append("ad_uuid, "); sbf.append("page_id, "); sbf.append("page_name, "); sbf.append("rcmd_score, "); sbf.append("rcmd_rank, "); sbf.append("rcmd_status "); sbf.append(" FROM " + TABLE); sbf.append(" WHERE 1=1 "); sbf.append(queryString); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); List<AdRecommend> x = new ArrayList<AdRecommend>(); try { x = jdbc.query(sql, paramSource, new AdRecommendRowMapper()); } catch (Exception ex) { x = null; } return x; } @Override public int create(AdRecommend x) { StringBuffer sbf = new StringBuffer(); sbf.append(" INSERT INTO ").append(TABLE); sbf.append(" ("); sbf.append(" ad_uuid,"); sbf.append(" page_id, "); sbf.append(" page_name, "); sbf.append(" rcmd_score, "); sbf.append(" rcmd_rank, "); sbf.append(" rcmd_status "); sbf.append(" ) VALUES ("); sbf.append(" :ad_uuid,"); sbf.append(" :page_id, "); sbf.append(" :page_name, "); sbf.append(" :rcmd_score, "); sbf.append(" :rcmd_rank, "); sbf.append(" :rcmd_status "); sbf.append(" )"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("ad_uuid", x.getAdUUID()); paramSource.addValue("page_id", x.getPageId()); paramSource.addValue("page_name", x.getPageName()); paramSource.addValue("rcmd_score", x.getRcmdScore()); paramSource.addValue("rcmd_rank", x.getRcmdRank()); paramSource.addValue("rcmd_status", x.getRcmdStatus()); int res = 0; try { res = jdbc.update(sql, paramSource); } catch (Exception ex) { ex.printStackTrace(); } return res; } @Override public int update(AdRecommend x) { StringBuffer sbf = new StringBuffer(); sbf.append(" UPDATE ").append(TABLE); sbf.append(" SET ad_uuid=:ad_uuid,"); sbf.append(" page_id=:page_id,"); sbf.append(" page_name=:page_name,"); sbf.append(" rcmd_rank=:rcmd_rank,"); // sbf.append(" rcmd_score=:rcmd_score,"); sbf.append(" rcmd_status=:rcmd_status "); sbf.append(" WHERE global_id=:global_id"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("ad_uuid", x.getAdUUID()); paramSource.addValue("page_id", x.getPageId()); paramSource.addValue("page_name", x.getPageName()); paramSource.addValue("rcmd_rank", x.getRcmdRank()); paramSource.addValue("rcmd_status", x.getRcmdStatus()); paramSource.addValue("global_id", x.getGlobalId()); return jdbc.update(sql, paramSource); } @Override public int[] updateBatch(List<AdRecommend> adRecommendList) { logger.debug("updateBatch() adRecommendList size=" + adRecommendList == null ? "NULL" : adRecommendList.size()); StringBuffer sbf = new StringBuffer(); sbf.append("UPDATE ").append(TABLE); sbf.append(" SET"); sbf.append(" ad_status=:adStatus"); sbf.append(" WHERE ad_uuid =:adUUID"); String sql = sbf.toString(); List<SqlParameterSource> parameters = new ArrayList<SqlParameterSource>(); for (AdRecommend x : adRecommendList) { parameters.add(new BeanPropertySqlParameterSource(x)); } // jdbc.batchUpdate(sql, parameters.toArray(new SqlParameterSource[0])); return jdbc.batchUpdate(sql, parameters.toArray(new SqlParameterSource[0])); } @Override public int delete(AdRecommend x) { StringBuffer sbf = new StringBuffer(); sbf.append(" DELETE FROM ").append(TABLE); sbf.append(" WHERE global_id=:global_id"); String sql = sbf.toString(); MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("global_id", x.getGlobalId()); return jdbc.update(sql, paramSource); } private static class AdRecommendRowMapper implements RowMapper<AdRecommend> { public AdRecommend mapRow(ResultSet rs, int rowNumber) throws SQLException { AdRecommend x = new AdRecommend(); x.setGlobalId(rs.getInt("global_id")); x.setAdUUID(rs.getString("ad_uuid")); x.setPageId(rs.getInt("page_id")); x.setPageName(rs.getString("page_name")); x.setRcmdRank(rs.getInt("rcmd_rank")); x.setRcmdScore(rs.getDouble("rcmd_score")); x.setRcmdStatus(rs.getInt("rcmd_status")); return x; } } }
7,431
0.675818
0.67501
232
30.030172
22.023968
114
false
false
0
0
0
0
0
0
2.491379
false
false
13
446b550c3e3d16382d9ff805da5a33c8652b1c7e
34,780,645,203,370
2240d3e794583f25ce49a23bb7d7930882580c82
/test/src/test/java/hudson/model/ViewTest.java
5cb4d7eaa1b0492cbdd8ad245b8255593188da46
[ "MIT" ]
permissive
oleg-nenashev/jenkins
https://github.com/oleg-nenashev/jenkins
f78f747aa5f0c656d6ffe3258707b11e1e861027
597e6431ba410ee2fde137d86bd607e078d48edd
refs/heads/master
2023-01-23T07:21:41.970000
2020-07-21T04:57:41
2020-07-21T04:57:41
14,375,421
2
3
MIT
true
2023-01-02T15:04:51
2013-11-13T20:24:23
2022-06-25T02:39:03
2023-01-02T15:04:48
133,355
2
2
7
Java
false
false
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts * * 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: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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 hudson.model; import com.cloudbees.hudson.plugins.folder.Folder; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.html.DomNodeUtil; import hudson.views.ViewsTabBar; import jenkins.model.Jenkins; import org.jenkins.ui.icon.Icon; import org.jenkins.ui.icon.IconSet; import org.jvnet.hudson.test.Issue; import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlLabel; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlRadioButtonInput; import com.gargoylesoftware.htmlunit.util.NameValuePair; import hudson.XmlFile; import hudson.matrix.AxisList; import hudson.matrix.LabelAxis; import hudson.matrix.MatrixProject; import hudson.model.Queue.Task; import hudson.model.Node.Mode; import org.jvnet.hudson.test.Email; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.w3c.dom.Text; import static hudson.model.Messages.Hudson_ViewName; import hudson.security.ACL; import hudson.security.AccessDeniedException2; import hudson.slaves.DumbSlave; import hudson.util.FormValidation; import hudson.util.HudsonIsLoading; import java.io.File; import java.io.IOException; import java.util.Collection; import java.net.HttpURLConnection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.LogRecord; import jenkins.model.ProjectNamingStrategy; import jenkins.security.NotReallyRoleSensitiveCallable; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import javax.servlet.ServletException; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.LoggerRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.MockFolder; import org.jvnet.hudson.test.TestExtension; import org.jvnet.hudson.test.recipes.LocalData; import org.kohsuke.stapler.DataBoundConstructor; /** * @author Kohsuke Kawaguchi */ public class ViewTest { @Rule public JenkinsRule j = new JenkinsRule(); @Rule public LoggerRule logging = new LoggerRule(); @Issue("JENKINS-7100") @Test public void xHudsonHeader() throws Exception { assertNotNull(j.createWebClient().goTo("").getWebResponse().getResponseHeaderValue("X-Hudson")); } @Issue("JENKINS-43848") @Test public void testNoCacheHeadersAreSet() throws Exception { List<NameValuePair> responseHeaders = j.createWebClient() .goTo("view/all/itemCategories", "application/json") .getWebResponse() .getResponseHeaders(); final Map<String, String> values = new HashMap<>(); for(NameValuePair p : responseHeaders) { values.put(p.getName(), p.getValue()); } String resp = values.get("Cache-Control"); assertThat(resp, is("no-cache, no-store, must-revalidate")); assertThat(values.get("Expires"), is("0")); assertThat(values.get("Pragma"), is("no-cache")); } /** * Creating two views with the same name. */ @Email("http://d.hatena.ne.jp/ssogabe/20090101/1230744150") @Test public void conflictingName() throws Exception { assertNull(j.jenkins.getView("foo")); WebClient wc = j.createWebClient(); HtmlForm form = wc.goTo("newView").getFormByName("createItem"); form.getInputByName("name").setValueAttribute("foo"); form.getRadioButtonsByName("mode").get(0).setChecked(true); j.submit(form); assertNotNull(j.jenkins.getView("foo")); wc.setThrowExceptionOnFailingStatusCode(false); // do it again and verify an error Page page = j.submit(form); assertEquals("shouldn't be allowed to create two views of the same name.", HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode()); } @Test public void privateView() throws Exception { j.createFreeStyleProject("project1"); User user = User.get("me", true); // create user WebClient wc = j.createWebClient(); HtmlPage userPage = wc.goTo("user/me"); HtmlAnchor privateViewsLink = userPage.getAnchorByText("My Views"); assertNotNull("My Views link not available", privateViewsLink); HtmlPage privateViewsPage = (HtmlPage) privateViewsLink.click(); Text viewLabel = (Text) privateViewsPage.getFirstByXPath("//div[@class='tabBar']//div[@class='tab active']/a/text()"); assertTrue("'All' view should be selected", viewLabel.getTextContent().contains(Hudson_ViewName())); View listView = listView("listView"); HtmlPage newViewPage = wc.goTo("user/me/my-views/newView"); HtmlForm form = newViewPage.getFormByName("createItem"); form.getInputByName("name").setValueAttribute("proxy-view"); ((HtmlRadioButtonInput) form.getInputByValue("hudson.model.ProxyView")).setChecked(true); HtmlPage proxyViewConfigurePage = j.submit(form); View proxyView = user.getProperty(MyViewsProperty.class).getView("proxy-view"); assertNotNull(proxyView); form = proxyViewConfigurePage.getFormByName("viewConfig"); form.getSelectByName("proxiedViewName").setSelectedAttribute("listView", true); j.submit(form); assertTrue(proxyView instanceof ProxyView); assertEquals(((ProxyView) proxyView).getProxiedViewName(), "listView"); assertEquals(((ProxyView) proxyView).getProxiedView(), listView); } @Test public void deleteView() throws Exception { WebClient wc = j.createWebClient(); ListView v = listView("list"); HtmlPage delete = wc.getPage(v, "delete"); j.submit(delete.getFormByName("delete")); assertNull(j.jenkins.getView("list")); User user = User.get("user", true); MyViewsProperty p = user.getProperty(MyViewsProperty.class); v = new ListView("list", p); p.addView(v); delete = wc.getPage(v, "delete"); j.submit(delete.getFormByName("delete")); assertNull(p.getView("list")); } @Issue("JENKINS-9367") @Test public void persistence() throws Exception { ListView view = listView("foo"); ListView v = (ListView) Jenkins.XSTREAM.fromXML(Jenkins.XSTREAM.toXML(view)); System.out.println(v.getProperties()); assertNotNull(v.getProperties()); } @Issue("JENKINS-9367") @Test public void allImagesCanBeLoaded() throws Exception { User.get("user", true); // as long as the cloudbees-folder is included as test dependency, its Folder will load icon boolean folderPluginActive = (j.jenkins.getPlugin("cloudbees-folder") != null); // link to Folder class is done here to ensure if we remove the dependency, this code will fail and so will be removed boolean folderPluginClassesLoaded = (j.jenkins.getDescriptor(Folder.class) != null); // this could be written like this to avoid the hard dependency: // boolean folderPluginClassesLoaded = (j.jenkins.getDescriptor("com.cloudbees.hudson.plugins.folder.Folder") != null); if (!folderPluginActive && folderPluginClassesLoaded) { // reset the icon added by Folder because the plugin resources are not reachable IconSet.icons.addIcon(new Icon("icon-folder icon-md", "24x24/folder.gif", "width: 24px; height: 24px;")); } WebClient webClient = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); webClient.getOptions().setJavaScriptEnabled(false); j.assertAllImageLoadSuccessfully(webClient.goTo("asynchPeople")); } @Issue("JENKINS-16608") @Test public void notAllowedName() throws Exception { WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); HtmlForm form = wc.goTo("newView").getFormByName("createItem"); form.getInputByName("name").setValueAttribute(".."); form.getRadioButtonsByName("mode").get(0).setChecked(true); HtmlPage page = j.submit(form); assertEquals("\"..\" should not be allowed.", HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode()); } @Ignore("verified manually in Winstone but org.mortbay.JettyResponse.sendRedirect (6.1.26) seems to mangle the location") @Issue("JENKINS-18373") @Test public void unicodeName() throws Exception { HtmlForm form = j.createWebClient().goTo("newView").getFormByName("createItem"); String name = "I ♥ NY"; form.getInputByName("name").setValueAttribute(name); form.getRadioButtonsByName("mode").get(0).setChecked(true); j.submit(form); View view = j.jenkins.getView(name); assertNotNull(view); j.submit(j.createWebClient().getPage(view, "configure").getFormByName("viewConfig")); } @Issue("JENKINS-17302") @Test public void doConfigDotXml() throws Exception { ListView view = listView("v"); view.description = "one"; WebClient wc = j.createWebClient(); String xml = wc.goToXml("view/v/config.xml").getWebResponse().getContentAsString(); assertTrue(xml, xml.contains("<description>one</description>")); xml = xml.replace("<description>one</description>", "<description>two</description>"); WebRequest req = new WebRequest(wc.createCrumbedUrl("view/v/config.xml"), HttpMethod.POST); req.setRequestBody(xml); req.setEncodingType(null); wc.getPage(req); assertEquals("two", view.getDescription()); xml = new XmlFile(Jenkins.XSTREAM, new File(j.jenkins.getRootDir(), "config.xml")).asString(); assertTrue(xml, xml.contains("<description>two</description>")); } @Issue("JENKINS-21017") @Test public void doConfigDotXmlReset() throws Exception { ListView view = listView("v"); view.description = "one"; WebClient wc = j.createWebClient(); String xml = wc.goToXml("view/v/config.xml").getWebResponse().getContentAsString(); assertThat(xml, containsString("<description>one</description>")); xml = xml.replace("<description>one</description>", ""); WebRequest req = new WebRequest(wc.createCrumbedUrl("view/v/config.xml"), HttpMethod.POST); req.setRequestBody(xml); req.setEncodingType(null); wc.getPage(req); assertEquals(null, view.getDescription()); // did not work xml = new XmlFile(Jenkins.XSTREAM, new File(j.jenkins.getRootDir(), "config.xml")).asString(); assertThat(xml, not(containsString("<description>"))); // did not work assertEquals(j.jenkins, view.getOwner()); } @Test public void testGetQueueItems() throws IOException, Exception{ ListView view1 = listView("view1"); view1.filterQueue = true; ListView view2 = listView("view2"); view2.filterQueue = true; FreeStyleProject inView1 = j.createFreeStyleProject("in-view1"); inView1.setAssignedLabel(j.jenkins.getLabelAtom("without-any-slave")); view1.add(inView1); MatrixProject inView2 = j.jenkins.createProject(MatrixProject.class, "in-view2"); inView2.setAssignedLabel(j.jenkins.getLabelAtom("without-any-slave")); view2.add(inView2); FreeStyleProject notInView = j.createFreeStyleProject("not-in-view"); notInView.setAssignedLabel(j.jenkins.getLabelAtom("without-any-slave")); FreeStyleProject inBothViews = j.createFreeStyleProject("in-both-views"); inBothViews.setAssignedLabel(j.jenkins.getLabelAtom("without-any-slave")); view1.add(inBothViews); view2.add(inBothViews); Queue.getInstance().schedule(notInView, 0); Queue.getInstance().schedule(inView1, 0); Queue.getInstance().schedule(inView2, 0); Queue.getInstance().schedule(inBothViews, 0); Thread.sleep(1000); assertContainsItems(view1, inView1, inBothViews); assertNotContainsItems(view1, notInView, inView2); assertContainsItems(view2, inView2, inBothViews); assertNotContainsItems(view2, notInView, inView1); } private void assertContainsItems(View view, Task... items) { for (Task job: items) { assertTrue( "Queued items for " + view.getDisplayName() + " should contain " + job.getDisplayName(), view.getQueueItems().contains(Queue.getInstance().getItem(job)) ); } } private void assertNotContainsItems(View view, Task... items) { for (Task job: items) { assertFalse( "Queued items for " + view.getDisplayName() + " should not contain " + job.getDisplayName(), view.getQueueItems().contains(Queue.getInstance().getItem(job)) ); } } @Test public void testGetComputers() throws IOException, Exception{ ListView view1 = listView("view1"); ListView view2 = listView("view2"); ListView view3 = listView("view3"); view1.filterExecutors=true; view2.filterExecutors=true; view3.filterExecutors=true; Slave slave0 = j.createOnlineSlave(j.jenkins.getLabel("label0")); Slave slave1 = j.createOnlineSlave(j.jenkins.getLabel("label1")); Slave slave2 = j.createOnlineSlave(j.jenkins.getLabel("label2")); Slave slave3 = j.createOnlineSlave(j.jenkins.getLabel("label0")); Slave slave4 = j.createOnlineSlave(j.jenkins.getLabel("label4")); FreeStyleProject freestyleJob = j.createFreeStyleProject("free"); view1.add(freestyleJob); freestyleJob.setAssignedLabel(j.jenkins.getLabel("label0||label2")); MatrixProject matrixJob = j.jenkins.createProject(MatrixProject.class, "matrix"); view1.add(matrixJob); matrixJob.setAxes(new AxisList( new LabelAxis("label", Collections.singletonList("label1")) )); FreeStyleProject noLabelJob = j.createFreeStyleProject("not-assigned-label"); view3.add(noLabelJob); noLabelJob.setAssignedLabel(null); FreeStyleProject foreignJob = j.createFreeStyleProject("in-other-view"); view2.add(foreignJob); foreignJob.setAssignedLabel(j.jenkins.getLabel("label0||label1")); // contains all agents having labels associated with freestyleJob or matrixJob assertContainsNodes(view1, slave0, slave1, slave2, slave3); assertNotContainsNodes(view1, slave4); // contains all agents having labels associated with foreignJob assertContainsNodes(view2, slave0, slave1, slave3); assertNotContainsNodes(view2, slave2, slave4); // contains all slaves as it contains noLabelJob that can run everywhere assertContainsNodes(view3, slave0, slave1, slave2, slave3, slave4); } @Test @Issue("JENKINS-21474") public void testGetComputersNPE() throws Exception { ListView view = listView("aView"); view.filterExecutors = true; DumbSlave dedicatedSlave = j.createOnlineSlave(); dedicatedSlave.setMode(Mode.EXCLUSIVE); view.add(j.createFreeStyleProject()); FreeStyleProject tiedJob = j.createFreeStyleProject(); tiedJob.setAssignedNode(dedicatedSlave); view.add(tiedJob); DumbSlave notIncludedSlave = j.createOnlineSlave(); notIncludedSlave.setMode(Mode.EXCLUSIVE); assertContainsNodes(view, j.jenkins, dedicatedSlave); assertNotContainsNodes(view, notIncludedSlave); } private void assertContainsNodes(View view, Node... slaves) { for (Node slave: slaves) { assertTrue( "Filtered executors for " + view.getDisplayName() + " should contain " + slave.getDisplayName(), view.getComputers().contains(slave.toComputer()) ); } } private void assertNotContainsNodes(View view, Node... slaves) { for (Node slave: slaves) { assertFalse( "Filtered executors for " + view.getDisplayName() + " should not contain " + slave.getDisplayName(), view.getComputers().contains(slave.toComputer()) ); } } @Test public void testGetItem() throws Exception{ ListView view = listView("foo"); FreeStyleProject job1 = j.createFreeStyleProject("free"); MatrixProject job2 = j.jenkins.createProject(MatrixProject.class, "matrix"); FreeStyleProject job3 = j.createFreeStyleProject("not-included"); view.jobNames.add(job2.getDisplayName()); view.jobNames.add(job1.getDisplayName()); assertEquals("View should return job " + job1.getDisplayName(),job1, view.getItem("free")); assertNotNull("View should return null.", view.getItem("not-included")); } @Test public void testRename() throws Exception { ListView view = listView("foo"); view.rename("renamed"); assertEquals("View should have name foo.", "renamed", view.getDisplayName()); ListView view2 = listView("foo"); try{ view2.rename("renamed"); fail("Attempt to rename job with a name used by another view with the same owner should throw exception"); } catch(Exception Exception){ } assertEquals("View should not be renamed if required name has another view with the same owner", "foo", view2.getDisplayName()); } @Test public void testGetOwnerItemGroup() throws Exception { ListView view = listView("foo"); assertEquals("View should have owner jenkins.",j.jenkins.getItemGroup(), view.getOwner().getItemGroup()); } @Test public void testGetOwnerPrimaryView() throws Exception{ ListView view = listView("foo"); j.jenkins.setPrimaryView(view); assertEquals("View should have primary view " + view.getDisplayName(),view, view.getOwner().getPrimaryView()); } @Test public void testSave() throws Exception{ ListView view = listView("foo"); FreeStyleProject job = j.createFreeStyleProject("free"); view.jobNames.add("free"); view.save(); j.jenkins.doReload(); //wait until all configuration are reloaded if(j.jenkins.servletContext.getAttribute("app") instanceof HudsonIsLoading){ Thread.sleep(500); } assertTrue("View does not contains job free after load.", j.jenkins.getView(view.getDisplayName()).contains(j.jenkins.getItem(job.getName()))); } @Test public void testGetProperties() throws Exception { View view = listView("foo"); Thread.sleep(100000); HtmlForm f = j.createWebClient().getPage(view, "configure").getFormByName("viewConfig"); ((HtmlLabel) DomNodeUtil.selectSingleNode(f, ".//LABEL[text()='Test property']")).click(); j.submit(f); assertNotNull("View should contain ViewPropertyImpl property.", view.getProperties().get(PropertyImpl.class)); } private ListView listView(String name) throws IOException { ListView view = new ListView(name, j.jenkins); j.jenkins.addView(view); return view; } public static class PropertyImpl extends ViewProperty { public String name; @DataBoundConstructor public PropertyImpl(String name) { this.name = name; } @TestExtension public static class DescriptorImpl extends ViewPropertyDescriptor { @Override public String getDisplayName() { return "Test property"; } } } @Issue("JENKINS-20509") @Test public void checkJobName() throws Exception { j.createFreeStyleProject("topprj"); final MockFolder d1 = j.createFolder("d1"); d1.createProject(FreeStyleProject.class, "subprj"); final MockFolder d2 = j.createFolder("d2"); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.ADMINISTER).everywhere().to("admin"). grant(Jenkins.READ).everywhere().toEveryone(). grant(Job.READ).everywhere().toEveryone(). grant(Item.CREATE).onFolders(d1).to("dev")); // not on root or d2 ACL.impersonate(Jenkins.ANONYMOUS, new NotReallyRoleSensitiveCallable<Void,Exception>() { @Override public Void call() throws Exception { try { assertCheckJobName(j.jenkins, "whatever", FormValidation.Kind.OK); fail("should not have been allowed"); } catch (AccessDeniedException2 x) { // OK } return null; } }); ACL.impersonate(User.get("dev").impersonate(), new NotReallyRoleSensitiveCallable<Void,Exception>() { @Override public Void call() throws Exception { try { assertCheckJobName(j.jenkins, "whatever", FormValidation.Kind.OK); fail("should not have been allowed"); } catch (AccessDeniedException2 x) { // OK } try { assertCheckJobName(d2, "whatever", FormValidation.Kind.OK); fail("should not have been allowed"); } catch (AccessDeniedException2 x) { // OK } assertCheckJobName(d1, "whatever", FormValidation.Kind.OK); return null; } }); ACL.impersonate(User.get("admin").impersonate(), new NotReallyRoleSensitiveCallable<Void,Exception>() { @Override public Void call() throws Exception { assertCheckJobName(j.jenkins, "whatever", FormValidation.Kind.OK); assertCheckJobName(d1, "whatever", FormValidation.Kind.OK); assertCheckJobName(d2, "whatever", FormValidation.Kind.OK); assertCheckJobName(j.jenkins, "d1", FormValidation.Kind.ERROR); assertCheckJobName(j.jenkins, "topprj", FormValidation.Kind.ERROR); assertCheckJobName(d1, "subprj", FormValidation.Kind.ERROR); assertCheckJobName(j.jenkins, "", FormValidation.Kind.OK); assertCheckJobName(j.jenkins, "foo/bie", FormValidation.Kind.ERROR); assertCheckJobName(d2, "New", FormValidation.Kind.OK); j.jenkins.setProjectNamingStrategy(new ProjectNamingStrategy.PatternProjectNamingStrategy("[a-z]+", "", true)); assertCheckJobName(d2, "New", FormValidation.Kind.ERROR); assertCheckJobName(d2, "new", FormValidation.Kind.OK); return null; } }); JenkinsRule.WebClient wc = j.createWebClient().withBasicCredentials("admin"); assertEquals("original ${rootURL}/checkJobName still supported", "<div/>", wc.goTo("checkJobName?value=stuff").getWebResponse().getContentAsString()); assertEquals("but now possible on a view in a folder", "<div/>", wc.goTo("job/d1/view/All/checkJobName?value=stuff").getWebResponse().getContentAsString()); } private void assertCheckJobName(ViewGroup context, String name, FormValidation.Kind expected) { assertEquals(expected, context.getPrimaryView().doCheckJobName(name).kind); } @Issue("JENKINS-41825") @Test public void brokenGetItems() throws Exception { logging.capture(100).record("", Level.INFO); j.jenkins.addView(new BrokenView()); j.createWebClient().goTo("view/broken/"); boolean found = false; LOGS: for (LogRecord record : logging.getRecords()) { for (Throwable t = record.getThrown(); t != null; t = t.getCause()) { if (t instanceof IllegalStateException && BrokenView.ERR.equals(t.getMessage())) { found = true; break LOGS; } } } assertTrue(found); } private static class BrokenView extends ListView { static final String ERR = "oops I cannot retrieve items"; BrokenView() { super("broken"); } @Override public List<TopLevelItem> getItems() { throw new IllegalStateException(ERR); } } @Test @Issue("JENKINS-36908") @LocalData public void testAllViewCreatedIfNoPrimary() throws Exception { assertNotNull(j.getInstance().getView("All")); } @Test @Issue("JENKINS-36908") @LocalData public void testAllViewNotCreatedIfPrimary() throws Exception { assertNull(j.getInstance().getView("All")); } @Test @Issue("JENKINS-43322") public void shouldFindNestedViewByName() throws Exception { //given String testNestedViewName = "right2ndNestedView"; View right2ndNestedView = mockedViewWithName(testNestedViewName); //and View left2ndNestedView = mockedViewWithName("left2ndNestedView"); DummyCompositeView rightNestedGroupView = new DummyCompositeView("rightNestedGroupView", left2ndNestedView, right2ndNestedView); //and listView("leftTopLevelView"); j.jenkins.addView(rightNestedGroupView); //when View foundNestedView = j.jenkins.getView(testNestedViewName); //then assertEquals(right2ndNestedView, foundNestedView); } private View mockedViewWithName(String viewName) { return given(mock(View.class).getViewName()).willReturn(viewName).getMock(); } //Duplication with ViewTest.CompositeView from core unit test module - unfortunately it is inaccessible from here private static class DummyCompositeView extends View implements ViewGroup { private final List<View> views; private List<TopLevelItem> jobs; private String primaryView; private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) { protected List<View> views() { return views; } protected String primaryView() { return primaryView; } protected void primaryView(String name) { primaryView = name; } }; DummyCompositeView(final String name, View... views) { super(name); this.primaryView = views[0].getViewName(); this.views = asList(views); } private DummyCompositeView withJobs(TopLevelItem... jobs) { this.jobs = asList(jobs); return this; } @Override public Collection<TopLevelItem> getItems() { return this.jobs; } @Override public Collection<View> getViews() { return viewGroupMixIn.getViews(); } @Override public boolean canDelete(View view) { return viewGroupMixIn.canDelete(view); } @Override public void deleteView(View view) throws IOException { viewGroupMixIn.deleteView(view); } @Override public View getView(String name) { return viewGroupMixIn.getView(name); } @Override public View getPrimaryView() { return viewGroupMixIn.getPrimaryView(); } @Override public void onViewRenamed(View view, String oldName, String newName) { viewGroupMixIn.onViewRenamed(view, oldName, newName); } @Override public ViewsTabBar getViewsTabBar() { return null; } @Override public ItemGroup<? extends TopLevelItem> getItemGroup() { return null; } @Override public List<Action> getViewActions() { return null; } @Override public boolean contains(TopLevelItem item) { return false; } @Override protected void submit(StaplerRequest req) throws IOException, ServletException, Descriptor.FormException { } @Override public Item doCreateItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { return null; } } }
UTF-8
Java
30,449
java
ViewTest.java
Java
[ { "context": "* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts\n *\n * Permission is hereby grante", "end": 94, "score": 0.9998597502708435, "start": 77, "tag": "NAME", "value": "Kohsuke Kawaguchi" }, { "context": "4-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts\n *\n * Permission is hereby granted, free of charg", "end": 110, "score": 0.9998601078987122, "start": 96, "tag": "NAME", "value": "Tom Huybrechts" }, { "context": "suke.stapler.DataBoundConstructor;\n\n/**\n * @author Kohsuke Kawaguchi\n */\npublic class ViewTest {\n\n @Rule public Jen", "end": 3901, "score": 0.9998424649238586, "start": 3884, "tag": "NAME", "value": "Kohsuke Kawaguchi" }, { "context": ".getView(\"list\"));\n\n User user = User.get(\"user\", true);\n MyViewsProperty p = user.getProp", "end": 7792, "score": 0.9969486594200134, "start": 7788, "tag": "USERNAME", "value": "user" }, { "context": "anBeLoaded() throws Exception {\n User.get(\"user\", true);\n\n // as long as the cloudbees-fol", "end": 8488, "score": 0.9943374991416931, "start": 8484, "tag": "USERNAME", "value": "user" }, { "context": " }\n });\n ACL.impersonate(User.get(\"dev\").impersonate(), new NotReallyRoleSensitiveCallab", "end": 22989, "score": 0.879179060459137, "start": 22986, "tag": "USERNAME", "value": "dev" }, { "context": " }\n });\n ACL.impersonate(User.get(\"admin\").impersonate(), new NotReallyRoleSensitiveCallab", "end": 23825, "score": 0.9761065244674683, "start": 23820, "tag": "USERNAME", "value": "admin" } ]
null
[]
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., <NAME>, <NAME> * * 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: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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 hudson.model; import com.cloudbees.hudson.plugins.folder.Folder; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.html.DomNodeUtil; import hudson.views.ViewsTabBar; import jenkins.model.Jenkins; import org.jenkins.ui.icon.Icon; import org.jenkins.ui.icon.IconSet; import org.jvnet.hudson.test.Issue; import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlLabel; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlRadioButtonInput; import com.gargoylesoftware.htmlunit.util.NameValuePair; import hudson.XmlFile; import hudson.matrix.AxisList; import hudson.matrix.LabelAxis; import hudson.matrix.MatrixProject; import hudson.model.Queue.Task; import hudson.model.Node.Mode; import org.jvnet.hudson.test.Email; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.w3c.dom.Text; import static hudson.model.Messages.Hudson_ViewName; import hudson.security.ACL; import hudson.security.AccessDeniedException2; import hudson.slaves.DumbSlave; import hudson.util.FormValidation; import hudson.util.HudsonIsLoading; import java.io.File; import java.io.IOException; import java.util.Collection; import java.net.HttpURLConnection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.LogRecord; import jenkins.model.ProjectNamingStrategy; import jenkins.security.NotReallyRoleSensitiveCallable; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import javax.servlet.ServletException; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.LoggerRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.MockFolder; import org.jvnet.hudson.test.TestExtension; import org.jvnet.hudson.test.recipes.LocalData; import org.kohsuke.stapler.DataBoundConstructor; /** * @author <NAME> */ public class ViewTest { @Rule public JenkinsRule j = new JenkinsRule(); @Rule public LoggerRule logging = new LoggerRule(); @Issue("JENKINS-7100") @Test public void xHudsonHeader() throws Exception { assertNotNull(j.createWebClient().goTo("").getWebResponse().getResponseHeaderValue("X-Hudson")); } @Issue("JENKINS-43848") @Test public void testNoCacheHeadersAreSet() throws Exception { List<NameValuePair> responseHeaders = j.createWebClient() .goTo("view/all/itemCategories", "application/json") .getWebResponse() .getResponseHeaders(); final Map<String, String> values = new HashMap<>(); for(NameValuePair p : responseHeaders) { values.put(p.getName(), p.getValue()); } String resp = values.get("Cache-Control"); assertThat(resp, is("no-cache, no-store, must-revalidate")); assertThat(values.get("Expires"), is("0")); assertThat(values.get("Pragma"), is("no-cache")); } /** * Creating two views with the same name. */ @Email("http://d.hatena.ne.jp/ssogabe/20090101/1230744150") @Test public void conflictingName() throws Exception { assertNull(j.jenkins.getView("foo")); WebClient wc = j.createWebClient(); HtmlForm form = wc.goTo("newView").getFormByName("createItem"); form.getInputByName("name").setValueAttribute("foo"); form.getRadioButtonsByName("mode").get(0).setChecked(true); j.submit(form); assertNotNull(j.jenkins.getView("foo")); wc.setThrowExceptionOnFailingStatusCode(false); // do it again and verify an error Page page = j.submit(form); assertEquals("shouldn't be allowed to create two views of the same name.", HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode()); } @Test public void privateView() throws Exception { j.createFreeStyleProject("project1"); User user = User.get("me", true); // create user WebClient wc = j.createWebClient(); HtmlPage userPage = wc.goTo("user/me"); HtmlAnchor privateViewsLink = userPage.getAnchorByText("My Views"); assertNotNull("My Views link not available", privateViewsLink); HtmlPage privateViewsPage = (HtmlPage) privateViewsLink.click(); Text viewLabel = (Text) privateViewsPage.getFirstByXPath("//div[@class='tabBar']//div[@class='tab active']/a/text()"); assertTrue("'All' view should be selected", viewLabel.getTextContent().contains(Hudson_ViewName())); View listView = listView("listView"); HtmlPage newViewPage = wc.goTo("user/me/my-views/newView"); HtmlForm form = newViewPage.getFormByName("createItem"); form.getInputByName("name").setValueAttribute("proxy-view"); ((HtmlRadioButtonInput) form.getInputByValue("hudson.model.ProxyView")).setChecked(true); HtmlPage proxyViewConfigurePage = j.submit(form); View proxyView = user.getProperty(MyViewsProperty.class).getView("proxy-view"); assertNotNull(proxyView); form = proxyViewConfigurePage.getFormByName("viewConfig"); form.getSelectByName("proxiedViewName").setSelectedAttribute("listView", true); j.submit(form); assertTrue(proxyView instanceof ProxyView); assertEquals(((ProxyView) proxyView).getProxiedViewName(), "listView"); assertEquals(((ProxyView) proxyView).getProxiedView(), listView); } @Test public void deleteView() throws Exception { WebClient wc = j.createWebClient(); ListView v = listView("list"); HtmlPage delete = wc.getPage(v, "delete"); j.submit(delete.getFormByName("delete")); assertNull(j.jenkins.getView("list")); User user = User.get("user", true); MyViewsProperty p = user.getProperty(MyViewsProperty.class); v = new ListView("list", p); p.addView(v); delete = wc.getPage(v, "delete"); j.submit(delete.getFormByName("delete")); assertNull(p.getView("list")); } @Issue("JENKINS-9367") @Test public void persistence() throws Exception { ListView view = listView("foo"); ListView v = (ListView) Jenkins.XSTREAM.fromXML(Jenkins.XSTREAM.toXML(view)); System.out.println(v.getProperties()); assertNotNull(v.getProperties()); } @Issue("JENKINS-9367") @Test public void allImagesCanBeLoaded() throws Exception { User.get("user", true); // as long as the cloudbees-folder is included as test dependency, its Folder will load icon boolean folderPluginActive = (j.jenkins.getPlugin("cloudbees-folder") != null); // link to Folder class is done here to ensure if we remove the dependency, this code will fail and so will be removed boolean folderPluginClassesLoaded = (j.jenkins.getDescriptor(Folder.class) != null); // this could be written like this to avoid the hard dependency: // boolean folderPluginClassesLoaded = (j.jenkins.getDescriptor("com.cloudbees.hudson.plugins.folder.Folder") != null); if (!folderPluginActive && folderPluginClassesLoaded) { // reset the icon added by Folder because the plugin resources are not reachable IconSet.icons.addIcon(new Icon("icon-folder icon-md", "24x24/folder.gif", "width: 24px; height: 24px;")); } WebClient webClient = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); webClient.getOptions().setJavaScriptEnabled(false); j.assertAllImageLoadSuccessfully(webClient.goTo("asynchPeople")); } @Issue("JENKINS-16608") @Test public void notAllowedName() throws Exception { WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); HtmlForm form = wc.goTo("newView").getFormByName("createItem"); form.getInputByName("name").setValueAttribute(".."); form.getRadioButtonsByName("mode").get(0).setChecked(true); HtmlPage page = j.submit(form); assertEquals("\"..\" should not be allowed.", HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode()); } @Ignore("verified manually in Winstone but org.mortbay.JettyResponse.sendRedirect (6.1.26) seems to mangle the location") @Issue("JENKINS-18373") @Test public void unicodeName() throws Exception { HtmlForm form = j.createWebClient().goTo("newView").getFormByName("createItem"); String name = "I ♥ NY"; form.getInputByName("name").setValueAttribute(name); form.getRadioButtonsByName("mode").get(0).setChecked(true); j.submit(form); View view = j.jenkins.getView(name); assertNotNull(view); j.submit(j.createWebClient().getPage(view, "configure").getFormByName("viewConfig")); } @Issue("JENKINS-17302") @Test public void doConfigDotXml() throws Exception { ListView view = listView("v"); view.description = "one"; WebClient wc = j.createWebClient(); String xml = wc.goToXml("view/v/config.xml").getWebResponse().getContentAsString(); assertTrue(xml, xml.contains("<description>one</description>")); xml = xml.replace("<description>one</description>", "<description>two</description>"); WebRequest req = new WebRequest(wc.createCrumbedUrl("view/v/config.xml"), HttpMethod.POST); req.setRequestBody(xml); req.setEncodingType(null); wc.getPage(req); assertEquals("two", view.getDescription()); xml = new XmlFile(Jenkins.XSTREAM, new File(j.jenkins.getRootDir(), "config.xml")).asString(); assertTrue(xml, xml.contains("<description>two</description>")); } @Issue("JENKINS-21017") @Test public void doConfigDotXmlReset() throws Exception { ListView view = listView("v"); view.description = "one"; WebClient wc = j.createWebClient(); String xml = wc.goToXml("view/v/config.xml").getWebResponse().getContentAsString(); assertThat(xml, containsString("<description>one</description>")); xml = xml.replace("<description>one</description>", ""); WebRequest req = new WebRequest(wc.createCrumbedUrl("view/v/config.xml"), HttpMethod.POST); req.setRequestBody(xml); req.setEncodingType(null); wc.getPage(req); assertEquals(null, view.getDescription()); // did not work xml = new XmlFile(Jenkins.XSTREAM, new File(j.jenkins.getRootDir(), "config.xml")).asString(); assertThat(xml, not(containsString("<description>"))); // did not work assertEquals(j.jenkins, view.getOwner()); } @Test public void testGetQueueItems() throws IOException, Exception{ ListView view1 = listView("view1"); view1.filterQueue = true; ListView view2 = listView("view2"); view2.filterQueue = true; FreeStyleProject inView1 = j.createFreeStyleProject("in-view1"); inView1.setAssignedLabel(j.jenkins.getLabelAtom("without-any-slave")); view1.add(inView1); MatrixProject inView2 = j.jenkins.createProject(MatrixProject.class, "in-view2"); inView2.setAssignedLabel(j.jenkins.getLabelAtom("without-any-slave")); view2.add(inView2); FreeStyleProject notInView = j.createFreeStyleProject("not-in-view"); notInView.setAssignedLabel(j.jenkins.getLabelAtom("without-any-slave")); FreeStyleProject inBothViews = j.createFreeStyleProject("in-both-views"); inBothViews.setAssignedLabel(j.jenkins.getLabelAtom("without-any-slave")); view1.add(inBothViews); view2.add(inBothViews); Queue.getInstance().schedule(notInView, 0); Queue.getInstance().schedule(inView1, 0); Queue.getInstance().schedule(inView2, 0); Queue.getInstance().schedule(inBothViews, 0); Thread.sleep(1000); assertContainsItems(view1, inView1, inBothViews); assertNotContainsItems(view1, notInView, inView2); assertContainsItems(view2, inView2, inBothViews); assertNotContainsItems(view2, notInView, inView1); } private void assertContainsItems(View view, Task... items) { for (Task job: items) { assertTrue( "Queued items for " + view.getDisplayName() + " should contain " + job.getDisplayName(), view.getQueueItems().contains(Queue.getInstance().getItem(job)) ); } } private void assertNotContainsItems(View view, Task... items) { for (Task job: items) { assertFalse( "Queued items for " + view.getDisplayName() + " should not contain " + job.getDisplayName(), view.getQueueItems().contains(Queue.getInstance().getItem(job)) ); } } @Test public void testGetComputers() throws IOException, Exception{ ListView view1 = listView("view1"); ListView view2 = listView("view2"); ListView view3 = listView("view3"); view1.filterExecutors=true; view2.filterExecutors=true; view3.filterExecutors=true; Slave slave0 = j.createOnlineSlave(j.jenkins.getLabel("label0")); Slave slave1 = j.createOnlineSlave(j.jenkins.getLabel("label1")); Slave slave2 = j.createOnlineSlave(j.jenkins.getLabel("label2")); Slave slave3 = j.createOnlineSlave(j.jenkins.getLabel("label0")); Slave slave4 = j.createOnlineSlave(j.jenkins.getLabel("label4")); FreeStyleProject freestyleJob = j.createFreeStyleProject("free"); view1.add(freestyleJob); freestyleJob.setAssignedLabel(j.jenkins.getLabel("label0||label2")); MatrixProject matrixJob = j.jenkins.createProject(MatrixProject.class, "matrix"); view1.add(matrixJob); matrixJob.setAxes(new AxisList( new LabelAxis("label", Collections.singletonList("label1")) )); FreeStyleProject noLabelJob = j.createFreeStyleProject("not-assigned-label"); view3.add(noLabelJob); noLabelJob.setAssignedLabel(null); FreeStyleProject foreignJob = j.createFreeStyleProject("in-other-view"); view2.add(foreignJob); foreignJob.setAssignedLabel(j.jenkins.getLabel("label0||label1")); // contains all agents having labels associated with freestyleJob or matrixJob assertContainsNodes(view1, slave0, slave1, slave2, slave3); assertNotContainsNodes(view1, slave4); // contains all agents having labels associated with foreignJob assertContainsNodes(view2, slave0, slave1, slave3); assertNotContainsNodes(view2, slave2, slave4); // contains all slaves as it contains noLabelJob that can run everywhere assertContainsNodes(view3, slave0, slave1, slave2, slave3, slave4); } @Test @Issue("JENKINS-21474") public void testGetComputersNPE() throws Exception { ListView view = listView("aView"); view.filterExecutors = true; DumbSlave dedicatedSlave = j.createOnlineSlave(); dedicatedSlave.setMode(Mode.EXCLUSIVE); view.add(j.createFreeStyleProject()); FreeStyleProject tiedJob = j.createFreeStyleProject(); tiedJob.setAssignedNode(dedicatedSlave); view.add(tiedJob); DumbSlave notIncludedSlave = j.createOnlineSlave(); notIncludedSlave.setMode(Mode.EXCLUSIVE); assertContainsNodes(view, j.jenkins, dedicatedSlave); assertNotContainsNodes(view, notIncludedSlave); } private void assertContainsNodes(View view, Node... slaves) { for (Node slave: slaves) { assertTrue( "Filtered executors for " + view.getDisplayName() + " should contain " + slave.getDisplayName(), view.getComputers().contains(slave.toComputer()) ); } } private void assertNotContainsNodes(View view, Node... slaves) { for (Node slave: slaves) { assertFalse( "Filtered executors for " + view.getDisplayName() + " should not contain " + slave.getDisplayName(), view.getComputers().contains(slave.toComputer()) ); } } @Test public void testGetItem() throws Exception{ ListView view = listView("foo"); FreeStyleProject job1 = j.createFreeStyleProject("free"); MatrixProject job2 = j.jenkins.createProject(MatrixProject.class, "matrix"); FreeStyleProject job3 = j.createFreeStyleProject("not-included"); view.jobNames.add(job2.getDisplayName()); view.jobNames.add(job1.getDisplayName()); assertEquals("View should return job " + job1.getDisplayName(),job1, view.getItem("free")); assertNotNull("View should return null.", view.getItem("not-included")); } @Test public void testRename() throws Exception { ListView view = listView("foo"); view.rename("renamed"); assertEquals("View should have name foo.", "renamed", view.getDisplayName()); ListView view2 = listView("foo"); try{ view2.rename("renamed"); fail("Attempt to rename job with a name used by another view with the same owner should throw exception"); } catch(Exception Exception){ } assertEquals("View should not be renamed if required name has another view with the same owner", "foo", view2.getDisplayName()); } @Test public void testGetOwnerItemGroup() throws Exception { ListView view = listView("foo"); assertEquals("View should have owner jenkins.",j.jenkins.getItemGroup(), view.getOwner().getItemGroup()); } @Test public void testGetOwnerPrimaryView() throws Exception{ ListView view = listView("foo"); j.jenkins.setPrimaryView(view); assertEquals("View should have primary view " + view.getDisplayName(),view, view.getOwner().getPrimaryView()); } @Test public void testSave() throws Exception{ ListView view = listView("foo"); FreeStyleProject job = j.createFreeStyleProject("free"); view.jobNames.add("free"); view.save(); j.jenkins.doReload(); //wait until all configuration are reloaded if(j.jenkins.servletContext.getAttribute("app") instanceof HudsonIsLoading){ Thread.sleep(500); } assertTrue("View does not contains job free after load.", j.jenkins.getView(view.getDisplayName()).contains(j.jenkins.getItem(job.getName()))); } @Test public void testGetProperties() throws Exception { View view = listView("foo"); Thread.sleep(100000); HtmlForm f = j.createWebClient().getPage(view, "configure").getFormByName("viewConfig"); ((HtmlLabel) DomNodeUtil.selectSingleNode(f, ".//LABEL[text()='Test property']")).click(); j.submit(f); assertNotNull("View should contain ViewPropertyImpl property.", view.getProperties().get(PropertyImpl.class)); } private ListView listView(String name) throws IOException { ListView view = new ListView(name, j.jenkins); j.jenkins.addView(view); return view; } public static class PropertyImpl extends ViewProperty { public String name; @DataBoundConstructor public PropertyImpl(String name) { this.name = name; } @TestExtension public static class DescriptorImpl extends ViewPropertyDescriptor { @Override public String getDisplayName() { return "Test property"; } } } @Issue("JENKINS-20509") @Test public void checkJobName() throws Exception { j.createFreeStyleProject("topprj"); final MockFolder d1 = j.createFolder("d1"); d1.createProject(FreeStyleProject.class, "subprj"); final MockFolder d2 = j.createFolder("d2"); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.ADMINISTER).everywhere().to("admin"). grant(Jenkins.READ).everywhere().toEveryone(). grant(Job.READ).everywhere().toEveryone(). grant(Item.CREATE).onFolders(d1).to("dev")); // not on root or d2 ACL.impersonate(Jenkins.ANONYMOUS, new NotReallyRoleSensitiveCallable<Void,Exception>() { @Override public Void call() throws Exception { try { assertCheckJobName(j.jenkins, "whatever", FormValidation.Kind.OK); fail("should not have been allowed"); } catch (AccessDeniedException2 x) { // OK } return null; } }); ACL.impersonate(User.get("dev").impersonate(), new NotReallyRoleSensitiveCallable<Void,Exception>() { @Override public Void call() throws Exception { try { assertCheckJobName(j.jenkins, "whatever", FormValidation.Kind.OK); fail("should not have been allowed"); } catch (AccessDeniedException2 x) { // OK } try { assertCheckJobName(d2, "whatever", FormValidation.Kind.OK); fail("should not have been allowed"); } catch (AccessDeniedException2 x) { // OK } assertCheckJobName(d1, "whatever", FormValidation.Kind.OK); return null; } }); ACL.impersonate(User.get("admin").impersonate(), new NotReallyRoleSensitiveCallable<Void,Exception>() { @Override public Void call() throws Exception { assertCheckJobName(j.jenkins, "whatever", FormValidation.Kind.OK); assertCheckJobName(d1, "whatever", FormValidation.Kind.OK); assertCheckJobName(d2, "whatever", FormValidation.Kind.OK); assertCheckJobName(j.jenkins, "d1", FormValidation.Kind.ERROR); assertCheckJobName(j.jenkins, "topprj", FormValidation.Kind.ERROR); assertCheckJobName(d1, "subprj", FormValidation.Kind.ERROR); assertCheckJobName(j.jenkins, "", FormValidation.Kind.OK); assertCheckJobName(j.jenkins, "foo/bie", FormValidation.Kind.ERROR); assertCheckJobName(d2, "New", FormValidation.Kind.OK); j.jenkins.setProjectNamingStrategy(new ProjectNamingStrategy.PatternProjectNamingStrategy("[a-z]+", "", true)); assertCheckJobName(d2, "New", FormValidation.Kind.ERROR); assertCheckJobName(d2, "new", FormValidation.Kind.OK); return null; } }); JenkinsRule.WebClient wc = j.createWebClient().withBasicCredentials("admin"); assertEquals("original ${rootURL}/checkJobName still supported", "<div/>", wc.goTo("checkJobName?value=stuff").getWebResponse().getContentAsString()); assertEquals("but now possible on a view in a folder", "<div/>", wc.goTo("job/d1/view/All/checkJobName?value=stuff").getWebResponse().getContentAsString()); } private void assertCheckJobName(ViewGroup context, String name, FormValidation.Kind expected) { assertEquals(expected, context.getPrimaryView().doCheckJobName(name).kind); } @Issue("JENKINS-41825") @Test public void brokenGetItems() throws Exception { logging.capture(100).record("", Level.INFO); j.jenkins.addView(new BrokenView()); j.createWebClient().goTo("view/broken/"); boolean found = false; LOGS: for (LogRecord record : logging.getRecords()) { for (Throwable t = record.getThrown(); t != null; t = t.getCause()) { if (t instanceof IllegalStateException && BrokenView.ERR.equals(t.getMessage())) { found = true; break LOGS; } } } assertTrue(found); } private static class BrokenView extends ListView { static final String ERR = "oops I cannot retrieve items"; BrokenView() { super("broken"); } @Override public List<TopLevelItem> getItems() { throw new IllegalStateException(ERR); } } @Test @Issue("JENKINS-36908") @LocalData public void testAllViewCreatedIfNoPrimary() throws Exception { assertNotNull(j.getInstance().getView("All")); } @Test @Issue("JENKINS-36908") @LocalData public void testAllViewNotCreatedIfPrimary() throws Exception { assertNull(j.getInstance().getView("All")); } @Test @Issue("JENKINS-43322") public void shouldFindNestedViewByName() throws Exception { //given String testNestedViewName = "right2ndNestedView"; View right2ndNestedView = mockedViewWithName(testNestedViewName); //and View left2ndNestedView = mockedViewWithName("left2ndNestedView"); DummyCompositeView rightNestedGroupView = new DummyCompositeView("rightNestedGroupView", left2ndNestedView, right2ndNestedView); //and listView("leftTopLevelView"); j.jenkins.addView(rightNestedGroupView); //when View foundNestedView = j.jenkins.getView(testNestedViewName); //then assertEquals(right2ndNestedView, foundNestedView); } private View mockedViewWithName(String viewName) { return given(mock(View.class).getViewName()).willReturn(viewName).getMock(); } //Duplication with ViewTest.CompositeView from core unit test module - unfortunately it is inaccessible from here private static class DummyCompositeView extends View implements ViewGroup { private final List<View> views; private List<TopLevelItem> jobs; private String primaryView; private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) { protected List<View> views() { return views; } protected String primaryView() { return primaryView; } protected void primaryView(String name) { primaryView = name; } }; DummyCompositeView(final String name, View... views) { super(name); this.primaryView = views[0].getViewName(); this.views = asList(views); } private DummyCompositeView withJobs(TopLevelItem... jobs) { this.jobs = asList(jobs); return this; } @Override public Collection<TopLevelItem> getItems() { return this.jobs; } @Override public Collection<View> getViews() { return viewGroupMixIn.getViews(); } @Override public boolean canDelete(View view) { return viewGroupMixIn.canDelete(view); } @Override public void deleteView(View view) throws IOException { viewGroupMixIn.deleteView(view); } @Override public View getView(String name) { return viewGroupMixIn.getView(name); } @Override public View getPrimaryView() { return viewGroupMixIn.getPrimaryView(); } @Override public void onViewRenamed(View view, String oldName, String newName) { viewGroupMixIn.onViewRenamed(view, oldName, newName); } @Override public ViewsTabBar getViewsTabBar() { return null; } @Override public ItemGroup<? extends TopLevelItem> getItemGroup() { return null; } @Override public List<Action> getViewActions() { return null; } @Override public boolean contains(TopLevelItem item) { return false; } @Override protected void submit(StaplerRequest req) throws IOException, ServletException, Descriptor.FormException { } @Override public Item doCreateItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { return null; } } }
30,419
0.656781
0.648701
745
39.868458
31.46126
164
false
false
0
0
0
0
0
0
0.751678
false
false
13
140d790246b8ef2d2ffc285e4b6f94448396420c
26,199,300,565,961
539cb2e7f341eada4ef7e88c0bee4ec94dea2e6e
/src/rta/tid/YellowTIDManip.java
a189ec6da580604ed235594335296949f7430458
[]
no_license
CasualPokePlayer/gb-rta-bruteforce
https://github.com/CasualPokePlayer/gb-rta-bruteforce
9437ed6675712dc142aea14dabedf4574240f8a6
783f48577889e37980e03b9402967292a62e32ce
refs/heads/master
2021-03-20T21:09:31.075000
2021-01-23T03:34:27
2021-01-23T03:34:27
247,234,639
0
0
null
true
2020-03-14T07:51:03
2020-03-14T07:51:02
2019-01-01T14:55:34
2019-01-01T14:55:32
1,596
0
0
0
null
false
false
package rta.tid; import rta.YellowAddr; import rta.gambatte.Gb; import rta.gambatte.LoadFlags; import java.io.*; import java.util.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class YellowTIDManip { private static final int NO_INPUT = 0x00; private static final int A = 0x01; private static final int B = 0x02; private static final int SELECT = 0x04; private static final int START = 0x08; private static final int UP = 0x40; /* Change this to increase/decrease number of intro sequence combinations processed */ private static final int MAX_COST = 3600; // ~1 minute /* Change this to include/exclude the intro buffers with smaller windows for success */ private static final boolean includeTightWindows = true; private static Strat gfSkip = new Strat("_gfskip", 61, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {START}, new Integer[] {1}); private static Strat gfWait = new Strat("_gfwait", 61+253, new Integer[] {YellowAddr.delayAtEndOfShootingStarAddr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static List<Strat> gf = Arrays.asList(gfSkip, gfWait); private static Strat intro0 = new Strat("_intro0", 147, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A}, new Integer[] {1}); private static Strat intro1 = new Strat("_intro1", 147 + 140, new Integer[] {YellowAddr.intro2Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat intro2 = new Strat("_intro2", 147 + 275, new Integer[] {YellowAddr.intro4Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat intro3 = new Strat("_intro3", 147 + 411, new Integer[] {YellowAddr.intro6Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat intro4 = new Strat("_intro4", 147 + 594, new Integer[] {YellowAddr.intro8Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat intro5 = new Strat("_intro5", 147 + 729, new Integer[] {YellowAddr.intro10Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat intro6 = new Strat("_intro6", 147 + 864, new Integer[] {YellowAddr.intro12Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat introwait = new Strat("_introwait", 147 + 1199, new Integer[] {YellowAddr.titleScreenAddr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static List<Strat> intro = Arrays.asList(intro0, intro1, intro2, intro3, intro4, intro5, intro6, introwait); private static Strat newGame = new Strat("_newgame", 20 + 20, new Integer[] {YellowAddr.joypadAddr, YellowAddr.postTIDAddr}, new Integer[] {A, NO_INPUT}, new Integer[] {1, 0}); private static Strat backout = new Strat("_backout", 140 + 20, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {B}, new Integer[] {1}); private static Strat title = new Strat("_title", 90, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {START}, new Integer[] {1}); private static Strat titleUsb = new Strat("_title(usb)", 90, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {UP | SELECT | B}, new Integer[] {1}); private static Strat csCancel = new Strat("_cscancel", 365, new Integer[] {YellowAddr.printLetterDelayAddr, YellowAddr.noYesAddr, YellowAddr.joypadAddr}, new Integer[] {B, B, A}, new Integer[] {0, 0, 1}); private static ResetStrat gfReset = new ResetStrat("_gfreset", 371, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); private static ResetStrat intro0Reset = new ResetStrat("_intro0(reset)", 371, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); private static ResetStrat intro1Reset = new ResetStrat("_intro1(reset)", 371 + 140, new Integer[] {YellowAddr.intro2Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static ResetStrat intro2Reset = new ResetStrat("_intro2(reset)", 371 + 275, new Integer[] {YellowAddr.intro4Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static ResetStrat intro3Reset = new ResetStrat("_intro3(reset)", 371 + 411, new Integer[] {YellowAddr.intro6Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static ResetStrat intro4Reset = new ResetStrat("_intro4(reset)", 371 + 594, new Integer[] {YellowAddr.intro8Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static ResetStrat intro5Reset = new ResetStrat("_intro5(reset)", 371 + 729, new Integer[] {YellowAddr.intro10Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static ResetStrat intro6Reset = new ResetStrat("_intro6(reset)", 371 + 864, new Integer[] {YellowAddr.intro12Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static List<Strat> introReset = Arrays.asList(intro0Reset, intro1Reset, intro2Reset, intro3Reset, intro4Reset, intro5Reset, intro6Reset); private static ResetStrat ngReset = new ResetStrat("_ngreset", 371, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); private static ResetStrat oakReset = new ResetStrat("_oakreset", 371 + 119, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); private static ResetStrat titleReset = new ResetStrat("_title(reset)", 371, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); private static ResetStrat csReset = new ResetStrat("_csreset", 371, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); static class Strat { String name; int cost; Integer[] addr; Integer[] input; Integer[] advanceFrames; Strat(String name, int cost, Integer[] addr, Integer[] input, Integer[] advanceFrames) { this.addr = addr; this.cost = cost; this.name = name; this.input = input; this.advanceFrames = advanceFrames; } public void execute(Gb gb) { for (int i = 0; i < addr.length; i++) { gb.advanceWithJoypadToAddress(input[i], addr[i]); for (int j = 0; j < advanceFrames[i]; j++) { gb.advanceFrame(input[i]); } } } } private static class ResetStrat extends Strat { ResetStrat(String name, int cost, Integer[] addr, Integer[] input, Integer[] advanceFrames) { super(name, cost, addr, input, advanceFrames); } @Override public void execute(Gb gb) { for (int i = 0; i < addr.length; i++) { gb.advanceWithJoypadToAddress(input[i], addr[i]); for (int j = 0; j < advanceFrames[i]; j++) { gb.advanceFrame(input[i]); } } gb.advanceWithJoypadToAddress(A | B | START | SELECT, YellowAddr.softResetAddr); } } static class IntroSequence extends ArrayList<Strat> implements Comparable<IntroSequence> { IntroSequence(Strat... strats) { super(Arrays.asList(strats)); } IntroSequence(IntroSequence other) { super(other); } @Override public String toString() { String ret = "yellow"; for(Strat s : this) { ret += s.name; } return ret; } void execute(Gb gb) { for(Strat s : this) { s.execute(gb); } } int cost() { return this.stream().mapToInt((Strat s) -> s.cost).sum(); } @Override public int compareTo(IntroSequence o) { return this.cost() - o.cost(); } } private static ArrayList<IntroSequence> permute(List<? extends Strat> sl1, List<? extends Strat> sl2) { ArrayList<IntroSequence> seqs = new ArrayList<>(); for(Strat s1 : sl1) { for(Strat s2 : sl2) { IntroSequence seq = new IntroSequence(); seq.add(s1); seq.add(s2); seqs.add(seq); } } return seqs; } private static IntroSequence append(IntroSequence seq, Strat... strats) { IntroSequence newSeq = new IntroSequence(seq); newSeq.addAll(Arrays.asList(strats)); return newSeq; } private static IntroSequence append(IntroSequence seq1, IntroSequence seq2) { IntroSequence newSeq = new IntroSequence(seq1); newSeq.addAll(seq2); return newSeq; } private static IntroSequence append(Strat strat, IntroSequence seq) { IntroSequence newSeq = new IntroSequence(strat); newSeq.addAll(seq); return newSeq; } public static void main(String[] args) throws IOException, InterruptedException { if (!new File("roms").exists()) { new File("roms").mkdir(); System.err.println("I need ROMs to simulate!"); System.exit(0); } File file = new File("yellow_tids.txt"); PrintWriter writer = new PrintWriter(file); ArrayList<IntroSequence> newGameSequences = new ArrayList<>(); ArrayList<IntroSequence> resetSequences = new ArrayList<>(); resetSequences.add(new IntroSequence(gfReset)); if(includeTightWindows) { resetSequences.addAll(permute(gf, introReset)); } else { resetSequences.add(new IntroSequence(gfSkip, intro0Reset)); resetSequences.add(new IntroSequence(gfWait, intro0Reset)); } ArrayList<IntroSequence> s3seqs = new ArrayList<>(); if(includeTightWindows) { s3seqs.addAll(permute(gf, intro)); } else { s3seqs.add(new IntroSequence(gfSkip, intro0)); s3seqs.add(new IntroSequence(gfWait, intro0)); s3seqs.add(new IntroSequence(gfSkip, introwait)); s3seqs.add(new IntroSequence(gfWait, introwait)); } while(!s3seqs.isEmpty()) { ArrayList<IntroSequence> s4seqs = new ArrayList<>(); for(IntroSequence s3 : s3seqs) { int ngcost = s3.cost() + 90 + 20 + 20; int ngmax = (MAX_COST - ngcost - 498); if(ngmax>=0) { s4seqs.add(append(s3, title)); } int rscost = ngcost + 371 + 61 + 147; int rsmax = (MAX_COST - rscost - 498); if(rsmax >= 0) { resetSequences.add(append(s3, titleReset)); resetSequences.add(append(s3, titleUsb, csCancel)); resetSequences.add(append(s3, titleUsb, csReset)); resetSequences.add(append(s3, title, ngReset)); } } s3seqs.clear(); for(IntroSequence s4 : s4seqs) { IntroSequence seq = append(s4, newGame); newGameSequences.add(seq); int ngcost = s4.cost() + 20 + 20; if((MAX_COST - 498 - ngcost) >= 140 + 90) { s3seqs.add(append(s4, backout)); } int rscost = s4.cost() + 20 + 20 + 119; if((MAX_COST - 498 - rscost) >= 371 + 61 + 147 + 90 + 20 + 20) { resetSequences.add(append(s4, newGame, oakReset)); } } } Collections.sort(resetSequences); ArrayList<IntroSequence> introSequences = new ArrayList<>(newGameSequences); while(!newGameSequences.isEmpty()) { Collections.sort(newGameSequences); ListIterator<IntroSequence> ngIter = newGameSequences.listIterator(); while(ngIter.hasNext()) { IntroSequence ng = ngIter.next(); ngIter.remove(); for (IntroSequence rs : resetSequences) { if (rs.cost() + ng.cost() <= MAX_COST - 498) { IntroSequence newSeq = append(rs, ng); introSequences.add(newSeq); ngIter.add(newSeq); } else { break; } } } } System.out.println("Number of intro sequences: " + introSequences.size()); Collections.sort(introSequences); // Init gambatte with 1 session // TODO: Parallelism? Gb gb = new Gb(); gb.loadBios("roms/gbc_bios.bin"); gb.loadRom("roms/pokeyellow.gbc", LoadFlags.DEFAULT_LOAD_FLAGS); gb.advanceToAddress(YellowAddr.initAddr); byte[] PostBios = gb.saveState(); for(IntroSequence seq : introSequences) { seq.execute(gb); int tid = readTID(gb); writer.println( seq.toString() + ": " + String.format("0x%4s", Integer.toHexString(tid).toUpperCase()).replace(' ', '0') + " (" + String.format("%5s)", tid).replace(' ', '0') + ", Offset: " + String.format("%.02f", (gb.getGbpTime() - 0.47))); gb.loadState(PostBios); writer.flush(); System.out.printf("Current Cost: %d%n", seq.cost()); } writer.close(); } private static int readTID(Gb gb) { return (gb.readMemory(0xD358) << 8) | gb.readMemory(0xD359); } }
UTF-8
Java
13,770
java
YellowTIDManip.java
Java
[]
null
[]
package rta.tid; import rta.YellowAddr; import rta.gambatte.Gb; import rta.gambatte.LoadFlags; import java.io.*; import java.util.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class YellowTIDManip { private static final int NO_INPUT = 0x00; private static final int A = 0x01; private static final int B = 0x02; private static final int SELECT = 0x04; private static final int START = 0x08; private static final int UP = 0x40; /* Change this to increase/decrease number of intro sequence combinations processed */ private static final int MAX_COST = 3600; // ~1 minute /* Change this to include/exclude the intro buffers with smaller windows for success */ private static final boolean includeTightWindows = true; private static Strat gfSkip = new Strat("_gfskip", 61, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {START}, new Integer[] {1}); private static Strat gfWait = new Strat("_gfwait", 61+253, new Integer[] {YellowAddr.delayAtEndOfShootingStarAddr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static List<Strat> gf = Arrays.asList(gfSkip, gfWait); private static Strat intro0 = new Strat("_intro0", 147, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A}, new Integer[] {1}); private static Strat intro1 = new Strat("_intro1", 147 + 140, new Integer[] {YellowAddr.intro2Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat intro2 = new Strat("_intro2", 147 + 275, new Integer[] {YellowAddr.intro4Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat intro3 = new Strat("_intro3", 147 + 411, new Integer[] {YellowAddr.intro6Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat intro4 = new Strat("_intro4", 147 + 594, new Integer[] {YellowAddr.intro8Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat intro5 = new Strat("_intro5", 147 + 729, new Integer[] {YellowAddr.intro10Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat intro6 = new Strat("_intro6", 147 + 864, new Integer[] {YellowAddr.intro12Addr, YellowAddr.joypadAddr}, new Integer[] {NO_INPUT, A}, new Integer[] {0, 1}); private static Strat introwait = new Strat("_introwait", 147 + 1199, new Integer[] {YellowAddr.titleScreenAddr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static List<Strat> intro = Arrays.asList(intro0, intro1, intro2, intro3, intro4, intro5, intro6, introwait); private static Strat newGame = new Strat("_newgame", 20 + 20, new Integer[] {YellowAddr.joypadAddr, YellowAddr.postTIDAddr}, new Integer[] {A, NO_INPUT}, new Integer[] {1, 0}); private static Strat backout = new Strat("_backout", 140 + 20, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {B}, new Integer[] {1}); private static Strat title = new Strat("_title", 90, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {START}, new Integer[] {1}); private static Strat titleUsb = new Strat("_title(usb)", 90, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {UP | SELECT | B}, new Integer[] {1}); private static Strat csCancel = new Strat("_cscancel", 365, new Integer[] {YellowAddr.printLetterDelayAddr, YellowAddr.noYesAddr, YellowAddr.joypadAddr}, new Integer[] {B, B, A}, new Integer[] {0, 0, 1}); private static ResetStrat gfReset = new ResetStrat("_gfreset", 371, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); private static ResetStrat intro0Reset = new ResetStrat("_intro0(reset)", 371, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); private static ResetStrat intro1Reset = new ResetStrat("_intro1(reset)", 371 + 140, new Integer[] {YellowAddr.intro2Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static ResetStrat intro2Reset = new ResetStrat("_intro2(reset)", 371 + 275, new Integer[] {YellowAddr.intro4Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static ResetStrat intro3Reset = new ResetStrat("_intro3(reset)", 371 + 411, new Integer[] {YellowAddr.intro6Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static ResetStrat intro4Reset = new ResetStrat("_intro4(reset)", 371 + 594, new Integer[] {YellowAddr.intro8Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static ResetStrat intro5Reset = new ResetStrat("_intro5(reset)", 371 + 729, new Integer[] {YellowAddr.intro10Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static ResetStrat intro6Reset = new ResetStrat("_intro6(reset)", 371 + 864, new Integer[] {YellowAddr.intro12Addr}, new Integer[] {NO_INPUT}, new Integer[] {0}); private static List<Strat> introReset = Arrays.asList(intro0Reset, intro1Reset, intro2Reset, intro3Reset, intro4Reset, intro5Reset, intro6Reset); private static ResetStrat ngReset = new ResetStrat("_ngreset", 371, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); private static ResetStrat oakReset = new ResetStrat("_oakreset", 371 + 119, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); private static ResetStrat titleReset = new ResetStrat("_title(reset)", 371, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); private static ResetStrat csReset = new ResetStrat("_csreset", 371, new Integer[] {YellowAddr.joypadAddr}, new Integer[] {A | B | START | SELECT}, new Integer[] {0}); static class Strat { String name; int cost; Integer[] addr; Integer[] input; Integer[] advanceFrames; Strat(String name, int cost, Integer[] addr, Integer[] input, Integer[] advanceFrames) { this.addr = addr; this.cost = cost; this.name = name; this.input = input; this.advanceFrames = advanceFrames; } public void execute(Gb gb) { for (int i = 0; i < addr.length; i++) { gb.advanceWithJoypadToAddress(input[i], addr[i]); for (int j = 0; j < advanceFrames[i]; j++) { gb.advanceFrame(input[i]); } } } } private static class ResetStrat extends Strat { ResetStrat(String name, int cost, Integer[] addr, Integer[] input, Integer[] advanceFrames) { super(name, cost, addr, input, advanceFrames); } @Override public void execute(Gb gb) { for (int i = 0; i < addr.length; i++) { gb.advanceWithJoypadToAddress(input[i], addr[i]); for (int j = 0; j < advanceFrames[i]; j++) { gb.advanceFrame(input[i]); } } gb.advanceWithJoypadToAddress(A | B | START | SELECT, YellowAddr.softResetAddr); } } static class IntroSequence extends ArrayList<Strat> implements Comparable<IntroSequence> { IntroSequence(Strat... strats) { super(Arrays.asList(strats)); } IntroSequence(IntroSequence other) { super(other); } @Override public String toString() { String ret = "yellow"; for(Strat s : this) { ret += s.name; } return ret; } void execute(Gb gb) { for(Strat s : this) { s.execute(gb); } } int cost() { return this.stream().mapToInt((Strat s) -> s.cost).sum(); } @Override public int compareTo(IntroSequence o) { return this.cost() - o.cost(); } } private static ArrayList<IntroSequence> permute(List<? extends Strat> sl1, List<? extends Strat> sl2) { ArrayList<IntroSequence> seqs = new ArrayList<>(); for(Strat s1 : sl1) { for(Strat s2 : sl2) { IntroSequence seq = new IntroSequence(); seq.add(s1); seq.add(s2); seqs.add(seq); } } return seqs; } private static IntroSequence append(IntroSequence seq, Strat... strats) { IntroSequence newSeq = new IntroSequence(seq); newSeq.addAll(Arrays.asList(strats)); return newSeq; } private static IntroSequence append(IntroSequence seq1, IntroSequence seq2) { IntroSequence newSeq = new IntroSequence(seq1); newSeq.addAll(seq2); return newSeq; } private static IntroSequence append(Strat strat, IntroSequence seq) { IntroSequence newSeq = new IntroSequence(strat); newSeq.addAll(seq); return newSeq; } public static void main(String[] args) throws IOException, InterruptedException { if (!new File("roms").exists()) { new File("roms").mkdir(); System.err.println("I need ROMs to simulate!"); System.exit(0); } File file = new File("yellow_tids.txt"); PrintWriter writer = new PrintWriter(file); ArrayList<IntroSequence> newGameSequences = new ArrayList<>(); ArrayList<IntroSequence> resetSequences = new ArrayList<>(); resetSequences.add(new IntroSequence(gfReset)); if(includeTightWindows) { resetSequences.addAll(permute(gf, introReset)); } else { resetSequences.add(new IntroSequence(gfSkip, intro0Reset)); resetSequences.add(new IntroSequence(gfWait, intro0Reset)); } ArrayList<IntroSequence> s3seqs = new ArrayList<>(); if(includeTightWindows) { s3seqs.addAll(permute(gf, intro)); } else { s3seqs.add(new IntroSequence(gfSkip, intro0)); s3seqs.add(new IntroSequence(gfWait, intro0)); s3seqs.add(new IntroSequence(gfSkip, introwait)); s3seqs.add(new IntroSequence(gfWait, introwait)); } while(!s3seqs.isEmpty()) { ArrayList<IntroSequence> s4seqs = new ArrayList<>(); for(IntroSequence s3 : s3seqs) { int ngcost = s3.cost() + 90 + 20 + 20; int ngmax = (MAX_COST - ngcost - 498); if(ngmax>=0) { s4seqs.add(append(s3, title)); } int rscost = ngcost + 371 + 61 + 147; int rsmax = (MAX_COST - rscost - 498); if(rsmax >= 0) { resetSequences.add(append(s3, titleReset)); resetSequences.add(append(s3, titleUsb, csCancel)); resetSequences.add(append(s3, titleUsb, csReset)); resetSequences.add(append(s3, title, ngReset)); } } s3seqs.clear(); for(IntroSequence s4 : s4seqs) { IntroSequence seq = append(s4, newGame); newGameSequences.add(seq); int ngcost = s4.cost() + 20 + 20; if((MAX_COST - 498 - ngcost) >= 140 + 90) { s3seqs.add(append(s4, backout)); } int rscost = s4.cost() + 20 + 20 + 119; if((MAX_COST - 498 - rscost) >= 371 + 61 + 147 + 90 + 20 + 20) { resetSequences.add(append(s4, newGame, oakReset)); } } } Collections.sort(resetSequences); ArrayList<IntroSequence> introSequences = new ArrayList<>(newGameSequences); while(!newGameSequences.isEmpty()) { Collections.sort(newGameSequences); ListIterator<IntroSequence> ngIter = newGameSequences.listIterator(); while(ngIter.hasNext()) { IntroSequence ng = ngIter.next(); ngIter.remove(); for (IntroSequence rs : resetSequences) { if (rs.cost() + ng.cost() <= MAX_COST - 498) { IntroSequence newSeq = append(rs, ng); introSequences.add(newSeq); ngIter.add(newSeq); } else { break; } } } } System.out.println("Number of intro sequences: " + introSequences.size()); Collections.sort(introSequences); // Init gambatte with 1 session // TODO: Parallelism? Gb gb = new Gb(); gb.loadBios("roms/gbc_bios.bin"); gb.loadRom("roms/pokeyellow.gbc", LoadFlags.DEFAULT_LOAD_FLAGS); gb.advanceToAddress(YellowAddr.initAddr); byte[] PostBios = gb.saveState(); for(IntroSequence seq : introSequences) { seq.execute(gb); int tid = readTID(gb); writer.println( seq.toString() + ": " + String.format("0x%4s", Integer.toHexString(tid).toUpperCase()).replace(' ', '0') + " (" + String.format("%5s)", tid).replace(' ', '0') + ", Offset: " + String.format("%.02f", (gb.getGbpTime() - 0.47))); gb.loadState(PostBios); writer.flush(); System.out.printf("Current Cost: %d%n", seq.cost()); } writer.close(); } private static int readTID(Gb gb) { return (gb.readMemory(0xD358) << 8) | gb.readMemory(0xD359); } }
13,770
0.58947
0.562527
411
32.503651
23.73868
149
false
false
0
0
0
0
0
0
1.201946
false
false
13
07279dd534db3c5dca1480a3389bb63df17f2760
26,199,300,565,705
6f672fb72caedccb841ee23f53e32aceeaf1895e
/Music-Audio/shazam_source/src/com/mopub/mobileads/c/a$1.java
25274c6079d22d8c4d63fb53c70baeaec2e7e4ad
[]
no_license
cha63506/CompSecurity
https://github.com/cha63506/CompSecurity
5c69743f660b9899146ed3cf21eceabe3d5f4280
eee7e74f4088b9c02dd711c061fc04fb1e4e2654
refs/heads/master
2018-03-23T04:15:18.480000
2015-12-19T01:29:58
2015-12-19T01:29:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.mopub.mobileads.c; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import com.mopub.common.c.a; // Referenced classes of package com.mopub.mobileads.c: // a public static final class ult extends WebChromeClient { public final boolean onJsAlert(WebView webview, String s, String s1, JsResult jsresult) { a.b(s1); jsresult.confirm(); return true; } public final boolean onJsBeforeUnload(WebView webview, String s, String s1, JsResult jsresult) { a.b(s1); jsresult.confirm(); return true; } public final boolean onJsConfirm(WebView webview, String s, String s1, JsResult jsresult) { a.b(s1); jsresult.confirm(); return true; } public final boolean onJsPrompt(WebView webview, String s, String s1, String s2, JsPromptResult jspromptresult) { a.b(s1); jspromptresult.confirm(); return true; } public ult() { } }
UTF-8
Java
1,261
java
a$1.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus", "end": 61, "score": 0.9996330142021179, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.mopub.mobileads.c; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import com.mopub.common.c.a; // Referenced classes of package com.mopub.mobileads.c: // a public static final class ult extends WebChromeClient { public final boolean onJsAlert(WebView webview, String s, String s1, JsResult jsresult) { a.b(s1); jsresult.confirm(); return true; } public final boolean onJsBeforeUnload(WebView webview, String s, String s1, JsResult jsresult) { a.b(s1); jsresult.confirm(); return true; } public final boolean onJsConfirm(WebView webview, String s, String s1, JsResult jsresult) { a.b(s1); jsresult.confirm(); return true; } public final boolean onJsPrompt(WebView webview, String s, String s1, String s2, JsPromptResult jspromptresult) { a.b(s1); jspromptresult.confirm(); return true; } public ult() { } }
1,251
0.666138
0.65345
50
24.219999
27.946585
115
false
false
0
0
0
0
0
0
0.62
false
false
13
e50a177292ac768c54590f54dea0f52d812b8eec
33,844,342,344,987
ed21762ee6c04b4ed86b146a858253d93f8b3f4d
/src/main/java/com/qa/cinema/rest/SeatTypeEndPoint.java
5338cfd0a4156d3a30949d555491c71ff082f11c
[]
no_license
QAConsulting/QA-Cinemas-Team3
https://github.com/QAConsulting/QA-Cinemas-Team3
8693316d1aac9e71cd0c61e002b6085ea29e7649
f50cfe95e4492fe94b60a61bc8de455a36f607f2
refs/heads/master
2017-05-11T13:38:25.946000
2017-03-10T01:39:27
2017-03-10T01:39:27
82,668,020
2
2
null
false
2017-03-06T15:46:55
2017-02-21T10:39:22
2017-03-05T17:22:37
2017-03-06T15:46:55
5,747
2
0
0
Java
null
null
package com.qa.cinema.rest; import javax.inject.Inject; import com.qa.cinema.service.SeatTypeService; import javax.ws.rs.*; @Path("/seattype") public class SeatTypeEndPoint { @Inject private SeatTypeService seatTypeService; @GET @Path("/json") @Produces({ "application/json" }) public String getAllSeatTypes() { return seatTypeService.getAllSeatTypes(); } @GET @Path("/json/{id}") @Produces({ "application/json" }) public String getSeatTypeById(@PathParam("id") Long seatTypeId) { return seatTypeService.getSeatTypeById(seatTypeId); } @POST @Path("/json") @Produces({ "application/json" }) public String addNewSeatType(String seatTypeJson) { return seatTypeService.addNewSeatType(seatTypeJson); } @PUT @Path("/json/{id}") @Produces({ "application/json" }) public String updateSeatType(@PathParam("id") Long seatTypeId, String seatTypeUpdate) { return seatTypeService.updateSeatType(seatTypeId, seatTypeUpdate); } @DELETE @Path("/json/{id}") @Produces({ "application/json" }) public String removeSeatType(@PathParam("id") Long seatTypeId) { return seatTypeService.removeSeatType(seatTypeId); } }
UTF-8
Java
1,194
java
SeatTypeEndPoint.java
Java
[]
null
[]
package com.qa.cinema.rest; import javax.inject.Inject; import com.qa.cinema.service.SeatTypeService; import javax.ws.rs.*; @Path("/seattype") public class SeatTypeEndPoint { @Inject private SeatTypeService seatTypeService; @GET @Path("/json") @Produces({ "application/json" }) public String getAllSeatTypes() { return seatTypeService.getAllSeatTypes(); } @GET @Path("/json/{id}") @Produces({ "application/json" }) public String getSeatTypeById(@PathParam("id") Long seatTypeId) { return seatTypeService.getSeatTypeById(seatTypeId); } @POST @Path("/json") @Produces({ "application/json" }) public String addNewSeatType(String seatTypeJson) { return seatTypeService.addNewSeatType(seatTypeJson); } @PUT @Path("/json/{id}") @Produces({ "application/json" }) public String updateSeatType(@PathParam("id") Long seatTypeId, String seatTypeUpdate) { return seatTypeService.updateSeatType(seatTypeId, seatTypeUpdate); } @DELETE @Path("/json/{id}") @Produces({ "application/json" }) public String removeSeatType(@PathParam("id") Long seatTypeId) { return seatTypeService.removeSeatType(seatTypeId); } }
1,194
0.70268
0.70268
50
21.879999
22.685362
88
false
false
0
0
0
0
0
0
1
false
false
13
641390e64a07486cbc1ae1f79cc7b61a956a4d81
34,909,494,229,223
943d6f3e551c9f1b1460dc55d0cec55fa94faf79
/src/leetcode/LC1768MergeTwoStrings.java
99f21012c05b76f04190173a10b290d8b498d0e6
[]
no_license
enataraj/Coding
https://github.com/enataraj/Coding
1dab3a8361724e0fed60d14b12ad550c99b196e1
1bfe76b053f215437f02c872b184f51d617f151f
refs/heads/master
2023-08-12T12:36:58.698000
2021-10-04T06:33:37
2021-10-04T06:33:37
272,099,079
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode; public class LC1768MergeTwoStrings { public String mergeAlternately(String word1, String word2) { int i = 0; StringBuffer strBuffer = new StringBuffer(); while (i < word1.length() && i < word2.length()) { strBuffer.append(word1.charAt(i)); strBuffer.append(word2.charAt(i)); i++; } if (i < word1.length()) { strBuffer.append(word1.substring(i, word1.length())); } if (i < word2.length()) { strBuffer.append(word2.substring(i, word2.length())); } return strBuffer.toString(); } public static void main(String[] args) { LC1768MergeTwoStrings obj = new LC1768MergeTwoStrings(); String word2 = "Elu"; String word1 = "Malai"; System.out.println(obj.mergeAlternately(word1, word2)); } }
UTF-8
Java
882
java
LC1768MergeTwoStrings.java
Java
[]
null
[]
package leetcode; public class LC1768MergeTwoStrings { public String mergeAlternately(String word1, String word2) { int i = 0; StringBuffer strBuffer = new StringBuffer(); while (i < word1.length() && i < word2.length()) { strBuffer.append(word1.charAt(i)); strBuffer.append(word2.charAt(i)); i++; } if (i < word1.length()) { strBuffer.append(word1.substring(i, word1.length())); } if (i < word2.length()) { strBuffer.append(word2.substring(i, word2.length())); } return strBuffer.toString(); } public static void main(String[] args) { LC1768MergeTwoStrings obj = new LC1768MergeTwoStrings(); String word2 = "Elu"; String word1 = "Malai"; System.out.println(obj.mergeAlternately(word1, word2)); } }
882
0.575964
0.543084
28
30.5
22.783922
65
false
false
0
0
0
0
0
0
0.607143
false
false
13
cb05fc967276d803fd1e4b26478dd1f45e9bf909
34,986,803,641,380
b1b90ca4b8e4e58d6935e270dfcf959cc346e013
/DistributedComputingLab4/src/main/java/com/rmv/dc/lab4/с/AddTripRunnable.java
7da0e611d8bd30645982173ad7cef1587168606f
[ "MIT" ]
permissive
RostyslavMV/DistributedComputing
https://github.com/RostyslavMV/DistributedComputing
47a9ad5a18f5e1343e7e393c0476ae886a189de6
b26199b1fa029a40f925f8f76585b25eac93b8e4
refs/heads/main
2023-06-04T16:33:09.252000
2021-06-13T17:33:40
2021-06-13T17:33:40
335,694,112
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rmv.dc.lab4.с; import lombok.AllArgsConstructor; @AllArgsConstructor public class AddTripRunnable implements Runnable { private final TripGraph tripGraph; private final int a; private final int b; private final int price; @Override public void run() { } private void addTrip(int a, int b) { try { tripGraph.getReadWriteLock().writeLock(); tripGraph.getTrips().add(new Trip(a, b, price)); tripGraph.getReadWriteLock().writeUnlock(); } catch (InterruptedException e) { e.printStackTrace(); } } }
UTF-8
Java
621
java
AddTripRunnable.java
Java
[]
null
[]
package com.rmv.dc.lab4.с; import lombok.AllArgsConstructor; @AllArgsConstructor public class AddTripRunnable implements Runnable { private final TripGraph tripGraph; private final int a; private final int b; private final int price; @Override public void run() { } private void addTrip(int a, int b) { try { tripGraph.getReadWriteLock().writeLock(); tripGraph.getTrips().add(new Trip(a, b, price)); tripGraph.getReadWriteLock().writeUnlock(); } catch (InterruptedException e) { e.printStackTrace(); } } }
621
0.629032
0.627419
27
21.962963
19.054466
60
false
false
0
0
0
0
0
0
0.481481
false
false
13
24cf01a11a02874dda28cb9d0c712d21b7cdc464
11,381,663,395,006
50eb323b124a012e802bbaa2807ab400139ef12f
/src/main/java/com/sicogep/controller/CronogramaController.java
e6f57efaf281892376d5c173dab7c98fb0e2bc2a
[]
no_license
jeancedron/sicogep
https://github.com/jeancedron/sicogep
368c07ef5e34bafdcaa082996f80f8e389833ae1
a06694b79b1fd90197ac64c97b164a435e97ecb5
refs/heads/master
2020-04-08T08:34:22.943000
2015-06-26T00:30:07
2015-06-26T00:30:07
34,368,756
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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.sicogep.controller; import com.sicogep.dto.ProyectoDTO; import com.sicogep.dto.TareaDTO; import com.sicogep.service.TareaService; import com.sicogep.util.JsonTransformer; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * * @author Jean Cedron */ @RestController public class CronogramaController { @Autowired JsonTransformer jsonTransformer; @Autowired TareaService tareaService; @RequestMapping(value = "/cronograma/update/{idProyecto}", consumes = "application/json", produces = "application/json", method = RequestMethod.POST) public void saveOrUpdate(@RequestBody String tareasJson, HttpServletRequest request, HttpServletResponse response, @PathVariable("idProyecto") Integer idProyecto) { try { TareaDTO tareas = (TareaDTO) jsonTransformer.fromJson(tareasJson, TareaDTO.class); tareaService.saveOrUpdate(tareas, idProyecto); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } @RequestMapping(value = "/cronograma/{idProyecto}", produces = "application/json", method = RequestMethod.GET) public void getAllCronogramas(HttpServletRequest request, HttpServletResponse response, @PathVariable("idProyecto") Integer idProyecto) { try { TareaDTO tarea = tareaService.getAllTarea(idProyecto); String json = jsonTransformer.toJson(tarea); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(json); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
UTF-8
Java
2,457
java
CronogramaController.java
Java
[ { "context": ".annotation.RestController;\r\n\r\n/**\r\n *\r\n * @author Jean Cedron\r\n */\r\n@RestController\r\npublic class CronogramaCon", "end": 910, "score": 0.9998627305030823, "start": 899, "tag": "NAME", "value": "Jean Cedron" } ]
null
[]
/* * 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.sicogep.controller; import com.sicogep.dto.ProyectoDTO; import com.sicogep.dto.TareaDTO; import com.sicogep.service.TareaService; import com.sicogep.util.JsonTransformer; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * * @author <NAME> */ @RestController public class CronogramaController { @Autowired JsonTransformer jsonTransformer; @Autowired TareaService tareaService; @RequestMapping(value = "/cronograma/update/{idProyecto}", consumes = "application/json", produces = "application/json", method = RequestMethod.POST) public void saveOrUpdate(@RequestBody String tareasJson, HttpServletRequest request, HttpServletResponse response, @PathVariable("idProyecto") Integer idProyecto) { try { TareaDTO tareas = (TareaDTO) jsonTransformer.fromJson(tareasJson, TareaDTO.class); tareaService.saveOrUpdate(tareas, idProyecto); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } @RequestMapping(value = "/cronograma/{idProyecto}", produces = "application/json", method = RequestMethod.GET) public void getAllCronogramas(HttpServletRequest request, HttpServletResponse response, @PathVariable("idProyecto") Integer idProyecto) { try { TareaDTO tarea = tareaService.getAllTarea(idProyecto); String json = jsonTransformer.toJson(tarea); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(json); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
2,452
0.71917
0.71917
59
39.64407
38.232014
168
false
false
0
0
0
0
0
0
0.694915
false
false
13
004ccf7cadad1b24e17a14c57cacf83ca3f996bb
35,656,818,526,541
c77941d4a4969e6db364832171d73760e4dff89b
/week11-week11_43.GameOfLife/src/game/PersonalBoard.java
5a2832e49e2ef4d8f7e982b40c7c33be20f8962d
[]
no_license
theonegaron/JavaProjects
https://github.com/theonegaron/JavaProjects
2ea9d0b5b9eda1bd0cc3850531c93650743e6de8
1f6a00c4f8e10facb289281745a0b2988009fd74
refs/heads/master
2020-04-05T12:59:26.254000
2018-07-11T14:17:03
2018-07-11T14:17:03
94,997,516
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 game; import gameoflife.GameOfLifeBoard; import java.util.Random; /** * * @author costa */ public class PersonalBoard extends GameOfLifeBoard{ public PersonalBoard(int width, int length) { super(width, length); } @Override public void turnToLiving(int x, int y) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { getBoard() [x][y] = true; } } @Override public void turnToDead(int x, int y) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { getBoard() [x][y] = false; } } @Override public boolean isAlive(int x, int y) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { return getBoard() [x][y]; } return false; } @Override public void initiateRandomCells(double probabilityForEachCell) { Random generator = new Random(); for (int y = 0; y < getHeight(); y++) { for (int x = 0; x < getWidth(); x++) { double probCompare = generator.nextDouble(); if (probCompare <= probabilityForEachCell) { turnToLiving(x,y); } else { turnToDead(x,y); } } } } @Override public int getNumberOfLivingNeighbours(int x, int y) { int alive = 0; for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) { dy++; } if (isAlive(x+dx,y+dy)) { alive++; } } } return alive; } @Override public void manageCell(int x, int y, int livingNeighbours) { boolean alive = isAlive(x,y); if (alive) { if (livingNeighbours < 2 || livingNeighbours > 3) { turnToDead(x,y); } } else { if (livingNeighbours == 3) { turnToLiving(x,y); } } } }
UTF-8
Java
2,245
java
PersonalBoard.java
Java
[ { "context": "eBoard;\nimport java.util.Random;\n/**\n *\n * @author costa\n */\npublic class PersonalBoard extends GameOfLife", "end": 283, "score": 0.5102437734603882, "start": 278, "tag": "NAME", "value": "costa" } ]
null
[]
/* * 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 game; import gameoflife.GameOfLifeBoard; import java.util.Random; /** * * @author costa */ public class PersonalBoard extends GameOfLifeBoard{ public PersonalBoard(int width, int length) { super(width, length); } @Override public void turnToLiving(int x, int y) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { getBoard() [x][y] = true; } } @Override public void turnToDead(int x, int y) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { getBoard() [x][y] = false; } } @Override public boolean isAlive(int x, int y) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { return getBoard() [x][y]; } return false; } @Override public void initiateRandomCells(double probabilityForEachCell) { Random generator = new Random(); for (int y = 0; y < getHeight(); y++) { for (int x = 0; x < getWidth(); x++) { double probCompare = generator.nextDouble(); if (probCompare <= probabilityForEachCell) { turnToLiving(x,y); } else { turnToDead(x,y); } } } } @Override public int getNumberOfLivingNeighbours(int x, int y) { int alive = 0; for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) { dy++; } if (isAlive(x+dx,y+dy)) { alive++; } } } return alive; } @Override public void manageCell(int x, int y, int livingNeighbours) { boolean alive = isAlive(x,y); if (alive) { if (livingNeighbours < 2 || livingNeighbours > 3) { turnToDead(x,y); } } else { if (livingNeighbours == 3) { turnToLiving(x,y); } } } }
2,245
0.478396
0.470379
86
25.10465
20.719629
79
false
false
0
0
0
0
0
0
0.534884
false
false
13
9d095dde7dad61806e33ad86a60eb405f4e95c53
32,839,320,011,683
b59db7dd335f4266b84d269a3417843cfbc571a5
/src/main/java/com/tms/stankevich/dao/FriendRequestRepository.java
62fee4df5375aa3cf8fbde93235acdf3792aa939
[]
no_license
AmberInsane/DiplomaProject
https://github.com/AmberInsane/DiplomaProject
e50d502115fa323167e5c6f8523f32a85e54c006
8f074df7141e4dd93c2120e4c6fac7eb7e52e99c
refs/heads/master
2022-11-26T12:12:09.379000
2020-05-09T17:17:44
2020-05-09T17:17:44
253,024,333
2
0
null
false
2022-11-24T09:17:39
2020-04-04T14:54:33
2020-05-09T17:18:00
2022-11-24T09:17:38
868
1
0
6
TSQL
false
false
package com.tms.stankevich.dao; import com.tms.stankevich.domain.user.*; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface FriendRequestRepository extends JpaRepository<FriendRequest, Long> { Optional<FriendRequest> findByUserRequestAndUserResponse(User userRequest, User userResponse); List<FriendRequest> findByUserResponseAndStatus(User userResponse, FriendRequestStatus status); List<FriendRequest> findByUserRequestAndStatus(User user, FriendRequestStatus sd); }
UTF-8
Java
564
java
FriendRequestRepository.java
Java
[]
null
[]
package com.tms.stankevich.dao; import com.tms.stankevich.domain.user.*; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface FriendRequestRepository extends JpaRepository<FriendRequest, Long> { Optional<FriendRequest> findByUserRequestAndUserResponse(User userRequest, User userResponse); List<FriendRequest> findByUserResponseAndStatus(User userResponse, FriendRequestStatus status); List<FriendRequest> findByUserRequestAndStatus(User user, FriendRequestStatus sd); }
564
0.829787
0.829787
15
36.599998
37.749702
99
false
false
0
0
0
0
0
0
0.8
false
false
13
bcd4fc8562f02fef75f518dd62a968d81c631eca
39,247,411,161,048
d818735e95ef1370b64684888573ae726a068400
/src/BullsNCows.java
9643d796ddb9bd321e07966a6474b5c88e3208ed
[ "MIT" ]
permissive
TristanBilot/Mastermind-Game
https://github.com/TristanBilot/Mastermind-Game
214123717c0a4121daf3faa426b8b641d27b307e
4149a40b752eceeb873bbd5ff6093e3fc7147c5b
refs/heads/master
2020-04-14T03:58:39.520000
2018-12-30T22:36:46
2018-12-30T22:36:46
163,622,155
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Represents bulls and cows for a mastermind game */ public final class BullsNCows { /** * Number of bulls */ public final int bulls; /** * Number of cows */ public final int cows; /** * Constructor of BullsNCows * * @param bulls * Number of bulls * @param cows * Number of cows */ public BullsNCows(int bulls, int cows) { this.bulls = bulls; this.cows = cows; } /** * Returns a string which represents this BullsNCows * * @return * The string representation of this BullsNCows */ public String toString() { return "bulls : " + bulls + ", cows : " + cows; } /** * Determine if a BullsNCows equals another one * * Two BullsNCows are equals if their number of * bulls and their number of cows are the same */ public boolean egal(BullsNCows bc) { return this.bulls == bc.bulls; } }
UTF-8
Java
1,028
java
BullsNCows.java
Java
[]
null
[]
/** * Represents bulls and cows for a mastermind game */ public final class BullsNCows { /** * Number of bulls */ public final int bulls; /** * Number of cows */ public final int cows; /** * Constructor of BullsNCows * * @param bulls * Number of bulls * @param cows * Number of cows */ public BullsNCows(int bulls, int cows) { this.bulls = bulls; this.cows = cows; } /** * Returns a string which represents this BullsNCows * * @return * The string representation of this BullsNCows */ public String toString() { return "bulls : " + bulls + ", cows : " + cows; } /** * Determine if a BullsNCows equals another one * * Two BullsNCows are equals if their number of * bulls and their number of cows are the same */ public boolean egal(BullsNCows bc) { return this.bulls == bc.bulls; } }
1,028
0.530156
0.530156
49
19.979591
18.136095
60
false
false
0
0
0
0
0
0
0.163265
false
false
13
da2dc7f238ee368e81bde1914457ab9e07163ef0
39,599,598,471,294
09834bd70f8f4641df81dc209aef3182c3cff3dc
/src/main/java/md/alexb/springdatarest/repository/VenueRepository.java
292e99627600769403df69b10588905a7ce142e0
[]
no_license
Mtactitian/spring-data-rest
https://github.com/Mtactitian/spring-data-rest
5fe1e92caa3420cf7d9b13a01018184ce9b57aa5
dd1804aa761d9170c80c8e89c91843f57e0a6bcc
refs/heads/master
2021-01-24T02:47:39.159000
2018-02-27T20:12:24
2018-02-27T20:12:24
122,862,573
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package md.alexb.springdatarest.repository; import md.alexb.springdatarest.model.Venue; import org.springframework.data.repository.CrudRepository; public interface VenueRepository extends CrudRepository<Venue,Integer> { }
UTF-8
Java
224
java
VenueRepository.java
Java
[]
null
[]
package md.alexb.springdatarest.repository; import md.alexb.springdatarest.model.Venue; import org.springframework.data.repository.CrudRepository; public interface VenueRepository extends CrudRepository<Venue,Integer> { }
224
0.848214
0.848214
7
31
28.081514
72
false
false
0
0
0
0
0
0
0.571429
false
false
13
1c143768103962f69d16d81eb8f70538635d4629
1,520,418,429,009
edaa0a9237ff8b95e3328b5feede16f4a5290ad1
/src/primitives/Example4.java
afad8ea2cdb676aa843330dd4a4da4b1bce99f4d
[]
no_license
lifeanddeath/oracle-certification-javaSE8-programmer
https://github.com/lifeanddeath/oracle-certification-javaSE8-programmer
b879a949064628f03b774595c1567ee4b24430c1
d1765c36085dffba5589c23f6086d12e0d3da5b0
refs/heads/master
2020-08-23T15:55:12.425000
2020-02-12T19:14:50
2020-02-12T19:14:50
216,655,749
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package primitives; public class Example4 { public int printNumber(int number) { return number; } public int getNumber() { short a = 10; int number = printNumber(a); return number; } public static void main(String... args) { System.out.println(new Example4().getNumber()); System.out.println("2"+ 33+'s'); System.out.println(new Integer(3)); switch(new Integer(4)) { }; } }
UTF-8
Java
416
java
Example4.java
Java
[]
null
[]
package primitives; public class Example4 { public int printNumber(int number) { return number; } public int getNumber() { short a = 10; int number = printNumber(a); return number; } public static void main(String... args) { System.out.println(new Example4().getNumber()); System.out.println("2"+ 33+'s'); System.out.println(new Integer(3)); switch(new Integer(4)) { }; } }
416
0.639423
0.617788
25
15.64
15.278429
49
false
false
0
0
0
0
0
0
1.64
false
false
13
887676e9864957e9dac49b8f215b141054e4f77f
7,327,214,275,058
0167571e8c0d3d69baad6660196a01d4e33ee251
/src/main/java/com/visma/hackathon/web/HackathonController.java
38ec2e0df31a9f3d32e90dca2ed9a59234a9a1e3
[]
no_license
VismaOpenSourceOrg/hackathon
https://github.com/VismaOpenSourceOrg/hackathon
e8849a5f0275eed05d16cd2a06b3262f68abb0cf
807e80e676568350002fbf2846f65246707d9113
refs/heads/master
2023-01-29T22:37:34.720000
2019-08-28T13:43:30
2019-08-28T13:43:30
157,112,194
2
0
null
false
2023-01-13T22:57:38
2018-11-11T19:13:54
2019-08-28T13:43:34
2023-01-13T22:57:38
3,555
2
0
26
Java
false
false
package com.visma.hackathon.web; import com.visma.hackathon.entity.Hackathon; import com.visma.hackathon.entity.HackathonStatus; import com.visma.hackathon.entity.HackerRole; import com.visma.hackathon.repository.HackathonRepository; import com.visma.hackathon.entity.User; import com.visma.hackathon.service.AuthService; import org.hibernate.ObjectNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.time.ZonedDateTime; import java.util.UUID; @RestController @RequestMapping("/api/hackathon") public class HackathonController { private static final Logger log = LoggerFactory.getLogger(HackathonController.class); @Autowired private HackathonRepository hackathonRepository; @Autowired private AuthService authService; @GetMapping("/active") public Hackathon getCurrentHackathon() { return hackathonRepository.findFirstByStatus(HackathonStatus.ACTIVE).orElse(null); } @GetMapping("/{uuid}") public Hackathon getById(@PathVariable UUID uuid) { return hackathonRepository.findById(uuid).orElseThrow(() -> new ObjectNotFoundException(uuid, "Hackathon" )); } @GetMapping public Iterable<Hackathon> getHackathons() { return hackathonRepository.findAll(); } @PostMapping public Hackathon create(@RequestBody CreationDTO body) { checkWriteAuthorization(); ZonedDateTime dt = ZonedDateTime.now(); Hackathon hackathon = new Hackathon(); hackathon.setTitle(body.getTitle()); hackathon.setDescription(body.getDescription()); hackathon.setCreatedBy(authService.getLoggedInUser()); hackathon.setStatus(body.status); hackathon.setCreated(dt); hackathon.setUpdated(dt); Hackathon createdHackathon = hackathonRepository.save(hackathon); log.info("Created hackathon: " + createdHackathon); return createdHackathon; } @PutMapping("/{uuid}") public Hackathon update(@PathVariable UUID uuid, @RequestBody CreationDTO body) { checkWriteAuthorization(); Hackathon hackathon = hackathonRepository.findById(uuid).orElseThrow(() -> new ObjectNotFoundException(uuid, "Hackathon" )); hackathon.setTitle(body.getTitle()); hackathon.setDescription(body.getDescription()); hackathon.setStatus(body.getStatus()); hackathon.setUpdated(ZonedDateTime.now()); Hackathon updatedHackathon = hackathonRepository.save(hackathon); log.info("Updated hackathon: " + updatedHackathon); return updatedHackathon; } private void checkWriteAuthorization() { User authUser = authService.getLoggedInUser(); if (authUser.hasRole(HackerRole.ADMINISTRATOR)) { return; } throw new SecurityException("Unauthorized write to hackathon "); } static class CreationDTO { private String title; private String description; private HackathonStatus status; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public HackathonStatus getStatus() { return status; } public void setStatus(HackathonStatus status) { this.status = status; } } }
UTF-8
Java
3,645
java
HackathonController.java
Java
[]
null
[]
package com.visma.hackathon.web; import com.visma.hackathon.entity.Hackathon; import com.visma.hackathon.entity.HackathonStatus; import com.visma.hackathon.entity.HackerRole; import com.visma.hackathon.repository.HackathonRepository; import com.visma.hackathon.entity.User; import com.visma.hackathon.service.AuthService; import org.hibernate.ObjectNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.time.ZonedDateTime; import java.util.UUID; @RestController @RequestMapping("/api/hackathon") public class HackathonController { private static final Logger log = LoggerFactory.getLogger(HackathonController.class); @Autowired private HackathonRepository hackathonRepository; @Autowired private AuthService authService; @GetMapping("/active") public Hackathon getCurrentHackathon() { return hackathonRepository.findFirstByStatus(HackathonStatus.ACTIVE).orElse(null); } @GetMapping("/{uuid}") public Hackathon getById(@PathVariable UUID uuid) { return hackathonRepository.findById(uuid).orElseThrow(() -> new ObjectNotFoundException(uuid, "Hackathon" )); } @GetMapping public Iterable<Hackathon> getHackathons() { return hackathonRepository.findAll(); } @PostMapping public Hackathon create(@RequestBody CreationDTO body) { checkWriteAuthorization(); ZonedDateTime dt = ZonedDateTime.now(); Hackathon hackathon = new Hackathon(); hackathon.setTitle(body.getTitle()); hackathon.setDescription(body.getDescription()); hackathon.setCreatedBy(authService.getLoggedInUser()); hackathon.setStatus(body.status); hackathon.setCreated(dt); hackathon.setUpdated(dt); Hackathon createdHackathon = hackathonRepository.save(hackathon); log.info("Created hackathon: " + createdHackathon); return createdHackathon; } @PutMapping("/{uuid}") public Hackathon update(@PathVariable UUID uuid, @RequestBody CreationDTO body) { checkWriteAuthorization(); Hackathon hackathon = hackathonRepository.findById(uuid).orElseThrow(() -> new ObjectNotFoundException(uuid, "Hackathon" )); hackathon.setTitle(body.getTitle()); hackathon.setDescription(body.getDescription()); hackathon.setStatus(body.getStatus()); hackathon.setUpdated(ZonedDateTime.now()); Hackathon updatedHackathon = hackathonRepository.save(hackathon); log.info("Updated hackathon: " + updatedHackathon); return updatedHackathon; } private void checkWriteAuthorization() { User authUser = authService.getLoggedInUser(); if (authUser.hasRole(HackerRole.ADMINISTRATOR)) { return; } throw new SecurityException("Unauthorized write to hackathon "); } static class CreationDTO { private String title; private String description; private HackathonStatus status; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public HackathonStatus getStatus() { return status; } public void setStatus(HackathonStatus status) { this.status = status; } } }
3,645
0.784362
0.783813
124
28.395161
25.781282
126
false
false
0
0
0
0
0
0
1.556452
false
false
13
8eee8fc070d333c2cf6d73651ae4ba8575825a7c
16,363,825,448,601
e1474fe22468395be6a4c0e22c8bffee027706c2
/timesheet-infra/src/main/java/com/kcfy/techservicemarket/infra/json/MapSnDescComparator.java
6b8d5ae1e97249ac1d85f255c2bc6ef72bf20437
[]
no_license
qh870754310/timesheet
https://github.com/qh870754310/timesheet
c00b02319f173f10d53bf2156d0743c28d164355
6900b8e54548001c8f768838d65275e1dbf5d63f
refs/heads/master
2020-04-28T15:32:04.361000
2019-03-13T08:22:37
2019-03-13T08:22:54
175,377,916
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kcfy.techservicemarket.infra.json; import java.util.Comparator; import java.util.Map; public class MapSnDescComparator implements Comparator<Map<String,Object>> { /** * 按照节点SN排序 */ @Override public int compare(Map<String,Object> o1, Map<String,Object> o2) { int j1 = (int)o1.get("sequence"); int j2 = (int)o2.get("sequence"); return (j1 < j2 ? 1 : (j1 == j2 ? 0 : -1)); } }
UTF-8
Java
414
java
MapSnDescComparator.java
Java
[]
null
[]
package com.kcfy.techservicemarket.infra.json; import java.util.Comparator; import java.util.Map; public class MapSnDescComparator implements Comparator<Map<String,Object>> { /** * 按照节点SN排序 */ @Override public int compare(Map<String,Object> o1, Map<String,Object> o2) { int j1 = (int)o1.get("sequence"); int j2 = (int)o2.get("sequence"); return (j1 < j2 ? 1 : (j1 == j2 ? 0 : -1)); } }
414
0.674129
0.641791
16
24.125
23.782543
76
false
false
0
0
0
0
0
0
1.375
false
false
13
3aac261259f350050c17063fa56d85a94ec62297
15,848,429,352,653
d38ba4e45b9d23af36437ce64b2e73a81b544e27
/src/main/java/org/zelenikr/pia/web/servlet/spring/controller/client/pattern/EditPatternPaymentOrderController.java
4a75858a8625e530213659d6d3fb4ef7bba30ccb
[]
no_license
skup5/R-Bank
https://github.com/skup5/R-Bank
f1588fd2e0c565e07e04e89073851e866453f40e
0aa9aa311903b10d409718cd659ec5f163a32dc7
refs/heads/master
2021-06-12T03:04:34.720000
2017-01-28T21:09:21
2017-01-28T21:09:21
69,337,307
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.zelenikr.pia.web.servlet.spring.controller.client.pattern; import org.springframework.beans.factory.annotation.Autowired; import org.zelenikr.pia.bankcode.BankCodeManager; import org.zelenikr.pia.domain.Currency; import org.zelenikr.pia.domain.PatternPaymentOrder; import org.zelenikr.pia.manager.CurrencyManager; import org.zelenikr.pia.manager.PatternPaymentOrderManager; import org.zelenikr.pia.validation.exception.PatternPaymentOrderValidationException; import org.zelenikr.pia.web.servlet.spring.controller.client.AbstractClientController; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Servlet handling client's edit pattern of payment order request. * * @author Roman Zelenik */ @WebServlet("/client/payment-pattern-edit") public class EditPatternPaymentOrderController extends AbstractClientController { private static final String VIEW_URL = "/view/client/payment-pattern"; private static final String DEFAULT_TEMPLATE_PATH = "client/editPatternPayment"; private static final String EDITED_PATTERN_SESSION = "editedPattern"; private static final String BANK_CODES_ATTRIBUTE = "bankCodes", CURRENCIES_ATTRIBUTE = "currencies", BANK_ACCOUNTS_ATTRIBUTE = "bankAccounts", PREPARED_PATTERN_ATTRIBUTE = "preparedPatternOrder"; private static final String NAME_PARAMETER = "inputPatternName", DATE_PARAMETER = "inputDate", ACCOUNT_NUMBER_PARAMETER = "selectAccount", OFFSET_PARAMETER = "inputOffset", BANK_CODE_PARAMETER = "inputBankCode", AMOUNT_PARAMETER = "inputAmount", CURRENCY_NAME_PARAMETER = "selectCurrency", CONST_SYMBOL_PARAMETER = "inputConstSymbol", VARIABLE_SYMBOL_PARAMETER = "inputVarSymbol", SPECIFIC_SYMBOL_PARAMETER = "inputSpecSymbol", MESSAGE_PARAMETER = "inputMessage"; private PatternPaymentOrderManager patternPaymentOrderManager; private BankCodeManager bankCodeManager; private CurrencyManager currencyManager; @Autowired public void setPatternPaymentOrderManager(PatternPaymentOrderManager patternPaymentOrderManager) { this.patternPaymentOrderManager = patternPaymentOrderManager; } @Autowired public void setBankCodeManager(BankCodeManager bankCodeManager) { this.bankCodeManager = bankCodeManager; } @Autowired public void setCurrencyManager(CurrencyManager currencyManager) { this.currencyManager = currencyManager; } @Override protected String getDefaultTemplatePath() { return DEFAULT_TEMPLATE_PATH; } @Override protected String getViewUrl() { return VIEW_URL; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { log("doGet()"); PatternPaymentOrder editedPattern = (PatternPaymentOrder) req.getSession().getAttribute(EDITED_PATTERN_SESSION); if (editedPattern == null) { resp.sendRedirect("payment-pattern-list"); return; } req.setAttribute(PREPARED_PATTERN_ATTRIBUTE, editedPattern); req.setAttribute(BANK_ACCOUNTS_ATTRIBUTE, getClientBankAccounts(req)); req.setAttribute(BANK_CODES_ATTRIBUTE, bankCodeManager.getBankCodes()); req.setAttribute(CURRENCIES_ATTRIBUTE, currencyManager.getAvailableCurrencies()); dispatch(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PatternPaymentOrder editedPattern = (PatternPaymentOrder) req.getSession().getAttribute(EDITED_PATTERN_SESSION); if (editedPattern == null) { resp.sendRedirect("payment-pattern-list"); return; } String name = req.getParameter(NAME_PARAMETER), dateStr = req.getParameter(DATE_PARAMETER), accountNumber = req.getParameter(ACCOUNT_NUMBER_PARAMETER), offset = req.getParameter(OFFSET_PARAMETER), bankCode = req.getParameter(BANK_CODE_PARAMETER), amountStr = req.getParameter(AMOUNT_PARAMETER), currencyName = req.getParameter(CURRENCY_NAME_PARAMETER), constSymbol = req.getParameter(CONST_SYMBOL_PARAMETER), varSymbol = req.getParameter(VARIABLE_SYMBOL_PARAMETER), specificSymbol = req.getParameter(SPECIFIC_SYMBOL_PARAMETER), message = req.getParameter(MESSAGE_PARAMETER); // validate form parameters Date dueDate = null; try { if (!dateStr.isEmpty()) dueDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr); } catch (ParseException e) { req.setAttribute(ERROR_ATTRIBUTE, e.getLocalizedMessage()); doGet(req, resp); return; } BigDecimal amount = null; try { if (!amountStr.isEmpty()) amount = new BigDecimal(amountStr); } catch (NumberFormatException e) { req.setAttribute(ERROR_ATTRIBUTE, "Invalid amount format."); doGet(req, resp); return; } Currency currency = null; try { if (!currencyName.isEmpty()) currency = Currency.valueOf(currencyName); } catch (IllegalArgumentException e) { req.setAttribute(ERROR_ATTRIBUTE, "Unknown currency."); doGet(req, resp); return; } editedPattern.setName(name); editedPattern.setAmount(amount); editedPattern.setConstSymbol(constSymbol); editedPattern.setCurrency(currency); editedPattern.setDueDate(dueDate); editedPattern.setMessage(message); editedPattern.getOffsetAccount().setBankCode(bankCode); editedPattern.getOffsetAccount().setOffsetAccountNumber(offset); editedPattern.setSpecificSymbol(specificSymbol); editedPattern.setVariableSymbol(varSymbol); try { patternPaymentOrderManager.update(editedPattern, getAuthenticatedClient(req), accountNumber); } catch (PatternPaymentOrderValidationException e) { req.setAttribute(ERROR_ATTRIBUTE, e.getLocalizedMessage()); doGet(req, resp); return; } req.setAttribute(SUCCESS_ATTRIBUTE, "Pattern of payment order was successfully changed."); doGet(req, resp); } }
UTF-8
Java
6,842
java
EditPatternPaymentOrderController.java
Java
[ { "context": "it pattern of payment order request.\n *\n * @author Roman Zelenik\n */\n@WebServlet(\"/client/payment-pattern-edit\")\np", "end": 984, "score": 0.9997729063034058, "start": 971, "tag": "NAME", "value": "Roman Zelenik" } ]
null
[]
package org.zelenikr.pia.web.servlet.spring.controller.client.pattern; import org.springframework.beans.factory.annotation.Autowired; import org.zelenikr.pia.bankcode.BankCodeManager; import org.zelenikr.pia.domain.Currency; import org.zelenikr.pia.domain.PatternPaymentOrder; import org.zelenikr.pia.manager.CurrencyManager; import org.zelenikr.pia.manager.PatternPaymentOrderManager; import org.zelenikr.pia.validation.exception.PatternPaymentOrderValidationException; import org.zelenikr.pia.web.servlet.spring.controller.client.AbstractClientController; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Servlet handling client's edit pattern of payment order request. * * @author <NAME> */ @WebServlet("/client/payment-pattern-edit") public class EditPatternPaymentOrderController extends AbstractClientController { private static final String VIEW_URL = "/view/client/payment-pattern"; private static final String DEFAULT_TEMPLATE_PATH = "client/editPatternPayment"; private static final String EDITED_PATTERN_SESSION = "editedPattern"; private static final String BANK_CODES_ATTRIBUTE = "bankCodes", CURRENCIES_ATTRIBUTE = "currencies", BANK_ACCOUNTS_ATTRIBUTE = "bankAccounts", PREPARED_PATTERN_ATTRIBUTE = "preparedPatternOrder"; private static final String NAME_PARAMETER = "inputPatternName", DATE_PARAMETER = "inputDate", ACCOUNT_NUMBER_PARAMETER = "selectAccount", OFFSET_PARAMETER = "inputOffset", BANK_CODE_PARAMETER = "inputBankCode", AMOUNT_PARAMETER = "inputAmount", CURRENCY_NAME_PARAMETER = "selectCurrency", CONST_SYMBOL_PARAMETER = "inputConstSymbol", VARIABLE_SYMBOL_PARAMETER = "inputVarSymbol", SPECIFIC_SYMBOL_PARAMETER = "inputSpecSymbol", MESSAGE_PARAMETER = "inputMessage"; private PatternPaymentOrderManager patternPaymentOrderManager; private BankCodeManager bankCodeManager; private CurrencyManager currencyManager; @Autowired public void setPatternPaymentOrderManager(PatternPaymentOrderManager patternPaymentOrderManager) { this.patternPaymentOrderManager = patternPaymentOrderManager; } @Autowired public void setBankCodeManager(BankCodeManager bankCodeManager) { this.bankCodeManager = bankCodeManager; } @Autowired public void setCurrencyManager(CurrencyManager currencyManager) { this.currencyManager = currencyManager; } @Override protected String getDefaultTemplatePath() { return DEFAULT_TEMPLATE_PATH; } @Override protected String getViewUrl() { return VIEW_URL; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { log("doGet()"); PatternPaymentOrder editedPattern = (PatternPaymentOrder) req.getSession().getAttribute(EDITED_PATTERN_SESSION); if (editedPattern == null) { resp.sendRedirect("payment-pattern-list"); return; } req.setAttribute(PREPARED_PATTERN_ATTRIBUTE, editedPattern); req.setAttribute(BANK_ACCOUNTS_ATTRIBUTE, getClientBankAccounts(req)); req.setAttribute(BANK_CODES_ATTRIBUTE, bankCodeManager.getBankCodes()); req.setAttribute(CURRENCIES_ATTRIBUTE, currencyManager.getAvailableCurrencies()); dispatch(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PatternPaymentOrder editedPattern = (PatternPaymentOrder) req.getSession().getAttribute(EDITED_PATTERN_SESSION); if (editedPattern == null) { resp.sendRedirect("payment-pattern-list"); return; } String name = req.getParameter(NAME_PARAMETER), dateStr = req.getParameter(DATE_PARAMETER), accountNumber = req.getParameter(ACCOUNT_NUMBER_PARAMETER), offset = req.getParameter(OFFSET_PARAMETER), bankCode = req.getParameter(BANK_CODE_PARAMETER), amountStr = req.getParameter(AMOUNT_PARAMETER), currencyName = req.getParameter(CURRENCY_NAME_PARAMETER), constSymbol = req.getParameter(CONST_SYMBOL_PARAMETER), varSymbol = req.getParameter(VARIABLE_SYMBOL_PARAMETER), specificSymbol = req.getParameter(SPECIFIC_SYMBOL_PARAMETER), message = req.getParameter(MESSAGE_PARAMETER); // validate form parameters Date dueDate = null; try { if (!dateStr.isEmpty()) dueDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr); } catch (ParseException e) { req.setAttribute(ERROR_ATTRIBUTE, e.getLocalizedMessage()); doGet(req, resp); return; } BigDecimal amount = null; try { if (!amountStr.isEmpty()) amount = new BigDecimal(amountStr); } catch (NumberFormatException e) { req.setAttribute(ERROR_ATTRIBUTE, "Invalid amount format."); doGet(req, resp); return; } Currency currency = null; try { if (!currencyName.isEmpty()) currency = Currency.valueOf(currencyName); } catch (IllegalArgumentException e) { req.setAttribute(ERROR_ATTRIBUTE, "Unknown currency."); doGet(req, resp); return; } editedPattern.setName(name); editedPattern.setAmount(amount); editedPattern.setConstSymbol(constSymbol); editedPattern.setCurrency(currency); editedPattern.setDueDate(dueDate); editedPattern.setMessage(message); editedPattern.getOffsetAccount().setBankCode(bankCode); editedPattern.getOffsetAccount().setOffsetAccountNumber(offset); editedPattern.setSpecificSymbol(specificSymbol); editedPattern.setVariableSymbol(varSymbol); try { patternPaymentOrderManager.update(editedPattern, getAuthenticatedClient(req), accountNumber); } catch (PatternPaymentOrderValidationException e) { req.setAttribute(ERROR_ATTRIBUTE, e.getLocalizedMessage()); doGet(req, resp); return; } req.setAttribute(SUCCESS_ATTRIBUTE, "Pattern of payment order was successfully changed."); doGet(req, resp); } }
6,835
0.683718
0.683718
167
39.970058
28.813343
120
false
false
0
0
0
0
0
0
0.712575
false
false
13
3a2846fda306651f19c7239261c097b3ef49250b
24,318,104,865,675
1c8c169a8c6f5f88f5a1284b9f9722413585a78b
/src_ver0.1/cn/minecraftunion/RemoteCraft/Structrue/Enmu/InputType.java
f4ea5d7c2aff4fb25100fc65b8ef6b15baf35b12
[]
no_license
decterous/RemoteCraft_Server
https://github.com/decterous/RemoteCraft_Server
3bebeb7477a020f44cfcf9239fdbdc10f50801e2
26c69494b42351ef91e48df9193e453c1016bb0f
refs/heads/master
2018-02-08T16:38:53.386000
2015-01-03T03:31:08
2015-01-03T03:31:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.minecraftunion.RemoteCraft.Structrue.Enmu; public enum InputType { }
UTF-8
Java
87
java
InputType.java
Java
[]
null
[]
package cn.minecraftunion.RemoteCraft.Structrue.Enmu; public enum InputType { }
87
0.758621
0.758621
7
11.428572
18.623005
53
false
false
0
0
0
0
0
0
0.571429
false
false
13
6fdb66092d565ba79243b610d107aad0245f9c58
32,976,758,962,943
8bd196d98b2af464630a5b70501166a2a7eebeea
/src/pat/FullPermutation.java
d5c2f215ad34d53121251897ce65cab11c94b625
[]
no_license
787178256/ForOffer
https://github.com/787178256/ForOffer
d1fe8324392be34180fda6d29c9f11a5e4c7de6f
2a6631e8142194ae8259e7ef60c52abe36521814
refs/heads/master
2021-07-06T00:05:01.327000
2020-06-07T15:07:20
2020-06-07T15:07:20
184,084,768
1
0
null
false
2020-10-13T14:03:47
2019-04-29T14:18:09
2020-06-07T15:08:03
2020-10-13T14:03:45
535
1
0
1
Java
false
false
package pat; import java.util.*; /** * Created by kimvra on 2019-03-24 */ public class FullPermutation { private static void swap(char[] chars, int i, int j) { char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } private static void permutationHelper(char[] chars, int index, ArrayList<String> list) { if (index == chars.length - 1) { list.add(String.valueOf(chars)); } else { Set<Character> charSet = new HashSet<>(); for (int i = index; i < chars.length; i++) { if (i == index || !charSet.contains(chars[i])) { charSet.add(chars[i]); swap(chars, index, i); permutationHelper(chars, index + 1, list); swap(chars, index, i); } } } } public static ArrayList<String> permutation(String string) { ArrayList<String> list = new ArrayList<>(); if (string != null || string.length() > 0) { permutationHelper(string.toCharArray(), 0, list); Collections.sort(list); } return list; } public static void main(String[] args) { System.out.println(permutation("abc")); } }
UTF-8
Java
1,279
java
FullPermutation.java
Java
[ { "context": "ckage pat;\n\nimport java.util.*;\n\n/**\n * Created by kimvra on 2019-03-24\n */\npublic class FullPermutation {\n", "end": 59, "score": 0.9996100068092346, "start": 53, "tag": "USERNAME", "value": "kimvra" } ]
null
[]
package pat; import java.util.*; /** * Created by kimvra on 2019-03-24 */ public class FullPermutation { private static void swap(char[] chars, int i, int j) { char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } private static void permutationHelper(char[] chars, int index, ArrayList<String> list) { if (index == chars.length - 1) { list.add(String.valueOf(chars)); } else { Set<Character> charSet = new HashSet<>(); for (int i = index; i < chars.length; i++) { if (i == index || !charSet.contains(chars[i])) { charSet.add(chars[i]); swap(chars, index, i); permutationHelper(chars, index + 1, list); swap(chars, index, i); } } } } public static ArrayList<String> permutation(String string) { ArrayList<String> list = new ArrayList<>(); if (string != null || string.length() > 0) { permutationHelper(string.toCharArray(), 0, list); Collections.sort(list); } return list; } public static void main(String[] args) { System.out.println(permutation("abc")); } }
1,279
0.517592
0.50821
43
28.744186
23.45812
92
false
false
0
0
0
0
0
0
0.790698
false
false
13
10791cd0b60cd96a6d98c6df9d9ec17c2915a939
19,593,640,838,781
42b48a8942c44eb8c461dd575c261b59e68f8206
/RedPowerCompat-2.0pr6.src/buildcraft/api/transport/IExtractionHandler.java
1f4c581ccc117b96d40cf58c3ecc7cefb0413700
[]
no_license
CollectiveIndustries/MC-RP-MOD
https://github.com/CollectiveIndustries/MC-RP-MOD
65161b5f791cfbe4c33987f6bc41a4d9a0eb8363
72fcc85f10cfff7d08406c198cc4789ee0224795
refs/heads/master
2020-06-11T21:01:47.267000
2014-07-01T01:48:33
2014-07-01T01:48:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package buildcraft.api.transport; import yc; public abstract interface IExtractionHandler { public abstract boolean canExtractItems(IPipe paramIPipe, yc paramyc, int paramInt1, int paramInt2, int paramInt3); public abstract boolean canExtractLiquids(IPipe paramIPipe, yc paramyc, int paramInt1, int paramInt2, int paramInt3); } /* Location: C:\Users\Admiral\Desktop\REDPOWER CODE\RedPowerCompat-2.0pr6.zip * Qualified Name: buildcraft.api.transport.IExtractionHandler * JD-Core Version: 0.7.0.1 */
UTF-8
Java
547
java
IExtractionHandler.java
Java
[ { "context": "amInt3);\r\n}\r\n\r\n\r\r\n/* Location: C:\\Users\\Admiral\\Desktop\\REDPOWER CODE\\RedPowerCompat-2.0pr6.zip\r\r", "end": 391, "score": 0.8452464938163757, "start": 384, "tag": "USERNAME", "value": "Admiral" } ]
null
[]
package buildcraft.api.transport; import yc; public abstract interface IExtractionHandler { public abstract boolean canExtractItems(IPipe paramIPipe, yc paramyc, int paramInt1, int paramInt2, int paramInt3); public abstract boolean canExtractLiquids(IPipe paramIPipe, yc paramyc, int paramInt1, int paramInt2, int paramInt3); } /* Location: C:\Users\Admiral\Desktop\REDPOWER CODE\RedPowerCompat-2.0pr6.zip * Qualified Name: buildcraft.api.transport.IExtractionHandler * JD-Core Version: 0.7.0.1 */
547
0.738574
0.714808
20
25.65
39.15134
119
false
false
0
0
0
0
0
0
0.6
false
false
13
1f6001779197567d7c9a722931dfc6823daad4c0
6,107,443,539,133
2c55167b086b19933d5a28e03c9d210dc26caf4c
/commercetools-models/src/main/java/io/sphere/sdk/types/CustomFieldsDraftBuilder.java
4e54008ba5f74c80834fd0f51ceadce2b642f083
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
commercetools/commercetools-jvm-sdk
https://github.com/commercetools/commercetools-jvm-sdk
02a1b6162aff245dce35a2e17b41c5fc8481cf33
9268215185628611ad12502cb9c844e8b65c2944
refs/heads/master
2023-08-31T20:04:34.331000
2023-08-11T07:43:29
2023-08-11T07:43:29
20,855,247
46
50
NOASSERTION
false
2023-08-11T09:27:43
2014-06-15T12:46:24
2023-08-08T15:05:07
2023-08-11T09:26:47
274,329
58
42
111
Java
false
false
package io.sphere.sdk.types; import com.fasterxml.jackson.databind.JsonNode; import io.sphere.sdk.json.SphereJsonUtils; import io.sphere.sdk.models.Base; import io.sphere.sdk.models.Builder; import io.sphere.sdk.models.Reference; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import static java.util.Objects.requireNonNull; /** * @see Custom * @see CustomFieldsDraft */ public final class CustomFieldsDraftBuilder extends Base implements Builder<CustomFieldsDraft> { @Nullable private final String typeId; @Nullable private final String typeKey; private Map<String, JsonNode> fields; private CustomFieldsDraftBuilder(@Nullable final String typeId, @Nullable final String typeKey) { this.typeId = typeId; this.typeKey = typeKey; fields = new HashMap<>(); } private CustomFieldsDraftBuilder(final CustomFieldsDraft customFieldsDraft) { typeId = customFieldsDraft.getType().getId(); typeKey = customFieldsDraft.getType().getKey(); fields = new HashMap<>(customFieldsDraft.getFields()); } public static CustomFieldsDraftBuilder ofTypeId(final String typeId) { requireNonNull(typeId); return new CustomFieldsDraftBuilder(typeId, null); } public static CustomFieldsDraftBuilder ofTypeKey(final String typeKey) { requireNonNull(typeKey); return new CustomFieldsDraftBuilder(null, typeKey); } public static CustomFieldsDraftBuilder ofType(final Type type) { return ofTypeId(type.getId()); } public static CustomFieldsDraftBuilder of(final CustomFieldsDraft customFieldsDraft) { return new CustomFieldsDraftBuilder(customFieldsDraft); } public static CustomFieldsDraftBuilder of(final CustomFields customFields) { final Reference<Type> type = customFields.getType(); return new CustomFieldsDraftBuilder(type.getId(), type.getKey()).fields(customFields.getFieldsJsonMap()); } public CustomFieldsDraftBuilder addObject(final String fieldName, final Object object) { final JsonNode jsonNode = SphereJsonUtils.toJsonNode(object); return addJsonField(fieldName, jsonNode); } public CustomFieldsDraftBuilder addObjects(final Map<String, Object> fields) { fields.entrySet().forEach(entry -> addObject(entry.getKey(), entry.getValue())); return this; } public CustomFieldsDraftBuilder fields(final Map<String, JsonNode> fields) { this.fields = fields; return this; } private CustomFieldsDraftBuilder addJsonField(final String fieldName, final JsonNode jsonNode) { fields.put(fieldName, jsonNode); return this; } @Override public CustomFieldsDraft build() { return new CustomFieldsDraftImpl(typeId, typeKey, fields); } @Deprecated public CustomFields buildFields() { return new CustomFieldsImpl(Reference.of(Type.referenceTypeId(), typeId), fields); } }
UTF-8
Java
3,016
java
CustomFieldsDraftBuilder.java
Java
[]
null
[]
package io.sphere.sdk.types; import com.fasterxml.jackson.databind.JsonNode; import io.sphere.sdk.json.SphereJsonUtils; import io.sphere.sdk.models.Base; import io.sphere.sdk.models.Builder; import io.sphere.sdk.models.Reference; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import static java.util.Objects.requireNonNull; /** * @see Custom * @see CustomFieldsDraft */ public final class CustomFieldsDraftBuilder extends Base implements Builder<CustomFieldsDraft> { @Nullable private final String typeId; @Nullable private final String typeKey; private Map<String, JsonNode> fields; private CustomFieldsDraftBuilder(@Nullable final String typeId, @Nullable final String typeKey) { this.typeId = typeId; this.typeKey = typeKey; fields = new HashMap<>(); } private CustomFieldsDraftBuilder(final CustomFieldsDraft customFieldsDraft) { typeId = customFieldsDraft.getType().getId(); typeKey = customFieldsDraft.getType().getKey(); fields = new HashMap<>(customFieldsDraft.getFields()); } public static CustomFieldsDraftBuilder ofTypeId(final String typeId) { requireNonNull(typeId); return new CustomFieldsDraftBuilder(typeId, null); } public static CustomFieldsDraftBuilder ofTypeKey(final String typeKey) { requireNonNull(typeKey); return new CustomFieldsDraftBuilder(null, typeKey); } public static CustomFieldsDraftBuilder ofType(final Type type) { return ofTypeId(type.getId()); } public static CustomFieldsDraftBuilder of(final CustomFieldsDraft customFieldsDraft) { return new CustomFieldsDraftBuilder(customFieldsDraft); } public static CustomFieldsDraftBuilder of(final CustomFields customFields) { final Reference<Type> type = customFields.getType(); return new CustomFieldsDraftBuilder(type.getId(), type.getKey()).fields(customFields.getFieldsJsonMap()); } public CustomFieldsDraftBuilder addObject(final String fieldName, final Object object) { final JsonNode jsonNode = SphereJsonUtils.toJsonNode(object); return addJsonField(fieldName, jsonNode); } public CustomFieldsDraftBuilder addObjects(final Map<String, Object> fields) { fields.entrySet().forEach(entry -> addObject(entry.getKey(), entry.getValue())); return this; } public CustomFieldsDraftBuilder fields(final Map<String, JsonNode> fields) { this.fields = fields; return this; } private CustomFieldsDraftBuilder addJsonField(final String fieldName, final JsonNode jsonNode) { fields.put(fieldName, jsonNode); return this; } @Override public CustomFieldsDraft build() { return new CustomFieldsDraftImpl(typeId, typeKey, fields); } @Deprecated public CustomFields buildFields() { return new CustomFieldsImpl(Reference.of(Type.referenceTypeId(), typeId), fields); } }
3,016
0.720159
0.720159
90
32.511112
31.376652
113
false
false
0
0
0
0
0
0
0.588889
false
false
13
23682aa18d9854ead521d5a638f51715b0fbe6e4
25,383,256,752,771
35e02036141fe80b873b6b628e138cb4fe0c94d7
/FirstJavaProject/src/com/FirstJavaProject/Functions/Functions.java
6fd671f3327e3187cf29f0aae24162fb48beb6d8
[]
no_license
CocoCouq/First_Step_JAVA
https://github.com/CocoCouq/First_Step_JAVA
2e2e62e593dcce6b48ee48c57969b425e116ee34
b24efa9e19a697e0c1dc5dd348aa98168aa081ae
refs/heads/master
2022-04-27T14:18:07.997000
2020-04-29T07:18:28
2020-04-29T07:18:28
257,738,682
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.FirstJavaProject.Functions; import com.FirstJavaProject.Tables.*; import java.util.Scanner; public class Functions { // LIST public static int functionsList() { Scanner READ = new Scanner(System.in); System.out.printf("||================================================||%n"); System.out.printf("|| 1 : Concatenation ||%n"); System.out.printf("|| 2 : Compteur de mots ||%n"); System.out.printf("|| 3 : Fibonacci ||%n"); System.out.printf("|| 4 : Table de multiplication ||%n"); System.out.printf("|| 5 : Compteur de lettres ||%n"); System.out.printf("|| 6 : String Token ||%n"); System.out.printf("||________________________________________________||%n"); System.out.printf("|| ||%n"); System.out.printf("|| QUEL EXERCICE SOUHAITEZ VOUS ? ||%n"); System.out.printf("||________________________________________________||%n"); int exercise = READ.nextInt(); return exercise; } // EXEC public static void exec(int exercise) { switch (exercise) { case 1: Concat.exec(); break; case 2: CountWord.exec(); break; case 3: Fibonacci.exec(); break; case 4: MultiTable.exec(); break; case 5: CountLetters.exec(); break; case 6: StrToken.exec(); break; default: System.out.println("Pas d'exercice correspondant"); } } }
UTF-8
Java
1,891
java
Functions.java
Java
[]
null
[]
package com.FirstJavaProject.Functions; import com.FirstJavaProject.Tables.*; import java.util.Scanner; public class Functions { // LIST public static int functionsList() { Scanner READ = new Scanner(System.in); System.out.printf("||================================================||%n"); System.out.printf("|| 1 : Concatenation ||%n"); System.out.printf("|| 2 : Compteur de mots ||%n"); System.out.printf("|| 3 : Fibonacci ||%n"); System.out.printf("|| 4 : Table de multiplication ||%n"); System.out.printf("|| 5 : Compteur de lettres ||%n"); System.out.printf("|| 6 : String Token ||%n"); System.out.printf("||________________________________________________||%n"); System.out.printf("|| ||%n"); System.out.printf("|| QUEL EXERCICE SOUHAITEZ VOUS ? ||%n"); System.out.printf("||________________________________________________||%n"); int exercise = READ.nextInt(); return exercise; } // EXEC public static void exec(int exercise) { switch (exercise) { case 1: Concat.exec(); break; case 2: CountWord.exec(); break; case 3: Fibonacci.exec(); break; case 4: MultiTable.exec(); break; case 5: CountLetters.exec(); break; case 6: StrToken.exec(); break; default: System.out.println("Pas d'exercice correspondant"); } } }
1,891
0.386568
0.380222
52
35.365383
28.349487
84
false
false
0
0
0
0
0
0
1.423077
false
false
13
e3d9bea0fd2b1189f37b3cd446b914ff95a65439
26,482,768,417,012
f2b45b4c992d9eac73c4876b6c8eb03a39c173d5
/storey-block-code/mopsz-system-util/src/main/java/com/husky/cloud/util/constant/Constant.java
fbd5bb0c38dfbb51b89cff38a051335b99960fc0
[ "Apache-2.0" ]
permissive
cicadasmile/husky-spring-cloud
https://github.com/cicadasmile/husky-spring-cloud
84e2fefbe850d35dbe62b163daf5665471ef11ed
ed6a87b57a900211899f73dd918f53056831ec26
refs/heads/master
2022-03-11T22:07:39.738000
2022-02-22T15:06:09
2022-02-22T15:06:09
218,539,868
75
51
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.husky.cloud.util.constant; public class Constant { public static final String MAP_KEY = "data"; public static final String LOGIN_URI = "/userLogin"; public static final String LOGIN_OUT_URI = "/loginOut"; public static final String USER_ID_KEY = "userId" ; public static final Integer USER_TOKEN_EXPIRE = 3600 ; }
UTF-8
Java
352
java
Constant.java
Java
[ { "context": "tant {\n\n public static final String MAP_KEY = \"data\";\n\n public static final String LOGIN_URI = \"/u", "end": 111, "score": 0.9947203397750854, "start": 107, "tag": "KEY", "value": "data" }, { "context": "\";\n\n public static final String USER_ID_KEY = \"userId\" ;\n\n public static final Integer USER_TOKEN_EX", "end": 286, "score": 0.9973922967910767, "start": 280, "tag": "KEY", "value": "userId" } ]
null
[]
package com.husky.cloud.util.constant; public class Constant { public static final String MAP_KEY = "data"; public static final String LOGIN_URI = "/userLogin"; public static final String LOGIN_OUT_URI = "/loginOut"; public static final String USER_ID_KEY = "userId" ; public static final Integer USER_TOKEN_EXPIRE = 3600 ; }
352
0.701705
0.690341
14
24.142857
25.528296
59
false
false
0
0
0
0
0
0
0.428571
false
false
13
413aa45e4c605a5d8985c74f0f331fb9d5f7811e
21,577,915,757,896
6343af0942316ae0d55f535fd48445e64015a9d7
/app/src/main/java/cn/ljt/app/utils/SaveImageUtils.java
1931036b7b4cb7189a58efd420247c3cd2bd686a
[]
no_license
jiangtaoxingliu/MyAndroidDemo
https://github.com/jiangtaoxingliu/MyAndroidDemo
62545994380d970ac105031d303456eb3cf85ff5
e6c37c6b1bec356f04de2c2da2f82984f22ef9c0
refs/heads/master
2017-12-04T18:43:03.983000
2016-10-31T02:59:25
2016-10-31T02:59:25
71,769,411
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.ljt.app.utils; import android.content.Context; import android.graphics.Bitmap; import android.os.AsyncTask; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import cn.ljt.app.R; /** * Created by Administrator on 2016/10/23. */ public class SaveImageUtils extends AsyncTask<Bitmap, Void, String> { private Context context; private ImageView mImageView; private String url; public SaveImageUtils(Context context, ImageView imageView, String url) { this.mImageView = imageView; this.context = context; this.url = url; } @Override protected String doInBackground(Bitmap... params) { String result = context.getResources().getString(R.string.save_picture_failed); try { File file = new File(url); if (!file.exists()) { file.mkdirs(); } long time = System.currentTimeMillis(); File imageFile = new File(file.getAbsolutePath(), "QRCode_" + time + ".jpg"); FileOutputStream outStream = null; outStream = new FileOutputStream(imageFile); Bitmap image = params[0]; image.compress(Bitmap.CompressFormat.JPEG, 100, outStream); outStream.flush(); outStream.close(); result = context.getResources().getString(R.string.save_picture_success, file.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result) { Toast.makeText(context, result, Toast.LENGTH_SHORT).show(); mImageView.setDrawingCacheEnabled(false); } }
UTF-8
Java
1,762
java
SaveImageUtils.java
Java
[]
null
[]
package cn.ljt.app.utils; import android.content.Context; import android.graphics.Bitmap; import android.os.AsyncTask; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import cn.ljt.app.R; /** * Created by Administrator on 2016/10/23. */ public class SaveImageUtils extends AsyncTask<Bitmap, Void, String> { private Context context; private ImageView mImageView; private String url; public SaveImageUtils(Context context, ImageView imageView, String url) { this.mImageView = imageView; this.context = context; this.url = url; } @Override protected String doInBackground(Bitmap... params) { String result = context.getResources().getString(R.string.save_picture_failed); try { File file = new File(url); if (!file.exists()) { file.mkdirs(); } long time = System.currentTimeMillis(); File imageFile = new File(file.getAbsolutePath(), "QRCode_" + time + ".jpg"); FileOutputStream outStream = null; outStream = new FileOutputStream(imageFile); Bitmap image = params[0]; image.compress(Bitmap.CompressFormat.JPEG, 100, outStream); outStream.flush(); outStream.close(); result = context.getResources().getString(R.string.save_picture_success, file.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result) { Toast.makeText(context, result, Toast.LENGTH_SHORT).show(); mImageView.setDrawingCacheEnabled(false); } }
1,762
0.637344
0.630533
58
29.379311
25.272875
109
false
false
0
0
0
0
0
0
0.706897
false
false
13
d2344ba37cff181f5a8ed121cc14d0e894bc0c82
5,970,004,555,501
5bf28176fe9f2337dbe40a2f79a80fd7c3f86b71
/cn-appoint-api/src/main/java/com/jd/appoint/vo/ControlItemData.java
dee8cc70aec5f1a12ec55c254bd2b0b0b7b51864
[]
no_license
moutainhigh/cn-appoint-demo
https://github.com/moutainhigh/cn-appoint-demo
b78fcc7c0f0fca98bbaeef9bccedf152c71fe839
2daef3149ddce96574765221d58ca642fcf17b14
refs/heads/master
2023-06-10T18:02:19.953000
2019-01-17T02:08:14
2019-01-17T02:08:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jd.appoint.vo; import com.alibaba.fastjson.JSON; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Created by yangyuan on 6/5/18. */ public class ControlItemData { /** * 静态数据 */ private List<Pair<Integer, String>> dataDetail; /** * 动态数据 */ private String url; public List<Pair<Integer, String>> getDataDetail() { return dataDetail; } public void setDataDetail(List<Pair<Integer, String>> dataDetail) { this.dataDetail = dataDetail; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return "ControlItemData{" + "dataDetail=" + dataDetail + ", url='" + url + '\'' + '}'; } }
UTF-8
Java
901
java
ControlItemData.java
Java
[ { "context": "rt java.util.stream.Collectors;\n\n/**\n * Created by yangyuan on 6/5/18.\n */\npublic class ControlItemData {\n\n ", "end": 174, "score": 0.9995996952056885, "start": 166, "tag": "USERNAME", "value": "yangyuan" } ]
null
[]
package com.jd.appoint.vo; import com.alibaba.fastjson.JSON; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Created by yangyuan on 6/5/18. */ public class ControlItemData { /** * 静态数据 */ private List<Pair<Integer, String>> dataDetail; /** * 动态数据 */ private String url; public List<Pair<Integer, String>> getDataDetail() { return dataDetail; } public void setDataDetail(List<Pair<Integer, String>> dataDetail) { this.dataDetail = dataDetail; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return "ControlItemData{" + "dataDetail=" + dataDetail + ", url='" + url + '\'' + '}'; } }
901
0.563842
0.559322
48
17.4375
17.427118
71
false
false
0
0
0
0
0
0
0.333333
false
false
13
45c60d7c1b243d041dbedf92aae2f77b906f7642
18,391,049,991,853
ae362895d23240ae1baa229432844436b2b74c56
/java/src/abbr/_dn.java
7dae0d9f71731aec400bfd795079c0afbfabbffb
[ "MIT" ]
permissive
cwbp/mdpw
https://github.com/cwbp/mdpw
6052eac82a066eefce79d1e419da2dc81fe69a34
febbc382f91fa0ecb823daa440dbfd157fb52940
refs/heads/master
2020-12-19T15:51:04.648000
2020-05-22T02:59:55
2020-05-22T02:59:55
235,780,459
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cwbp.mdpw.abbr; public class _dn extends com.cwbp.mdpw.DataNote {}
UTF-8
Java
81
java
_dn.java
Java
[]
null
[]
package com.cwbp.mdpw.abbr; public class _dn extends com.cwbp.mdpw.DataNote {}
81
0.753086
0.753086
2
38.5
11.5
50
false
false
0
0
0
0
0
0
0.5
false
false
13
766846dd70a3c5c1200615829bde3d913713e826
3,324,304,750,829
65e94aa9f4a75cad9157615b52b99c8c7f642825
/LeeC/017_LetterCombinationsOfAPhoneNumber/Solution.java
151bd848137151c9ddf9b4fcbc74552b3162f304
[]
no_license
fengdanhuang/Program_Example_fred
https://github.com/fengdanhuang/Program_Example_fred
23e55624d8e0177789f79bce65af1acc84d78dea
519fc66f11d2e1b9bb8fb7f9668e1cfba93bc0ef
refs/heads/master
2021-06-26T12:09:54.342000
2019-08-15T18:08:57
2019-08-15T18:08:57
114,918,947
0
0
null
false
2019-08-14T06:01:26
2017-12-20T18:34:44
2019-08-13T00:17:24
2019-08-14T06:01:26
285,000
0
0
0
Java
false
false
import java.util.*; public class Solution { private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; public List<String> letterCombinations(String digits) { System.out.println("digits = " + digits); List<String> ret = new LinkedList<String>(); combination("", digits, 0, ret); System.out.println("ret = " + ret); return ret; } private void combination(String prefix, String digits, int offset, List<String> ret) { System.out.println("Inside combination() recursion:"); System.out.println(" prefix = " + prefix); System.out.println(" digits = " + digits); System.out.println(" offset = " + offset); System.out.println(" ret = " + ret); if (offset >= digits.length()) { ret.add(prefix); return; } String letters = KEYS[(digits.charAt(offset) - '0')]; System.out.println(" letters = " + letters); for (int i = 0; i < letters.length(); i++) { combination(prefix + letters.charAt(i), digits, offset + 1, ret); } } public static void main(String args[]){ Solution s1 = new Solution(); String digits = new String("23"); s1.letterCombinations(digits); } }
UTF-8
Java
1,293
java
Solution.java
Java
[]
null
[]
import java.util.*; public class Solution { private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; public List<String> letterCombinations(String digits) { System.out.println("digits = " + digits); List<String> ret = new LinkedList<String>(); combination("", digits, 0, ret); System.out.println("ret = " + ret); return ret; } private void combination(String prefix, String digits, int offset, List<String> ret) { System.out.println("Inside combination() recursion:"); System.out.println(" prefix = " + prefix); System.out.println(" digits = " + digits); System.out.println(" offset = " + offset); System.out.println(" ret = " + ret); if (offset >= digits.length()) { ret.add(prefix); return; } String letters = KEYS[(digits.charAt(offset) - '0')]; System.out.println(" letters = " + letters); for (int i = 0; i < letters.length(); i++) { combination(prefix + letters.charAt(i), digits, offset + 1, ret); } } public static void main(String args[]){ Solution s1 = new Solution(); String digits = new String("23"); s1.letterCombinations(digits); } }
1,293
0.568446
0.562258
47
26.446808
26.667223
111
false
false
0
0
0
0
0
0
2.085106
false
false
13
f1cdb6bca633b13524d1080d1e1893861b095c2b
6,811,818,140,482
47bfff718c3efd8cdd68170f28df85b119ffa209
/src/main/java/IP/service/UserService.java
57823b0565197e02cedd48348183b790749a96f6
[]
no_license
bridgecrew-perf7/deploy-all
https://github.com/bridgecrew-perf7/deploy-all
ec1532b22cc218289fa462fa51b3787731eecebe
2868cdb8e8c56cbdc5390ea82d4ca2f4cca1b814
refs/heads/master
2023-05-02T05:55:49.524000
2021-05-26T21:19:50
2021-05-26T21:19:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package IP.service; import IP.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import IP.repository.UserRepo; import java.util.ArrayList; import java.util.List; @Service public class UserService { @Autowired private UserRepo repository = new UserRepo(); public List<User> allUsers() { List<User> allUsers = repository.findAll(); if (allUsers.size() == 0) { return new ArrayList<>(); } else { return allUsers; } } }
UTF-8
Java
572
java
UserService.java
Java
[]
null
[]
package IP.service; import IP.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import IP.repository.UserRepo; import java.util.ArrayList; import java.util.List; @Service public class UserService { @Autowired private UserRepo repository = new UserRepo(); public List<User> allUsers() { List<User> allUsers = repository.findAll(); if (allUsers.size() == 0) { return new ArrayList<>(); } else { return allUsers; } } }
572
0.659091
0.657343
31
17.451612
18.238277
62
false
false
0
0
0
0
0
0
0.354839
false
false
13
fd81f0c05e49eee9b4d1effb553c83a4e82f78d0
22,969,485,139,455
17f565220a0267603e686ec2edaf412be60c4ba0
/Practise/src/BankMain.java
7b768234010835960ab17f3f2cb5ad9cc522ac20
[]
no_license
vikclickz/helloworld
https://github.com/vikclickz/helloworld
9b7fd9cd12c1f04cda6fc18541e7a901abaac05d
0d29d9d3f2c10efc0347e1696f8d7c2694e9f367
refs/heads/master
2020-04-08T23:31:49.930000
2015-06-01T04:47:01
2015-06-01T04:47:01
31,186,788
0
0
null
false
2015-06-01T04:47:02
2015-02-22T23:52:07
2015-03-22T18:00:12
2015-06-01T04:47:01
208
0
0
0
Java
null
null
import java.io.ObjectInputStream.GetField; public class BankMain { public BankMain() { // TODO Auto-generated constructor stub } /** * @param args * @throws IllegalAccessException * @throws InstantiationException */ public static void main(String[] args) throws InstantiationException, IllegalAccessException { BankAccount[] accounts = new BankAccount[100]; BankAccount account = BankAccount.class.newInstance(); account.setBalance(400); account.setAccountNumber(75); accounts[75] = account; System.out.println("Account Number is "+accounts[75].accountNumber+" balance is "+accounts[75].balance); accounts[75].withdraw(25); System.out.println("After Withdrawl :: Account Number is "+accounts[75].accountNumber+" balance is "+accounts[75].balance); } }
UTF-8
Java
816
java
BankMain.java
Java
[]
null
[]
import java.io.ObjectInputStream.GetField; public class BankMain { public BankMain() { // TODO Auto-generated constructor stub } /** * @param args * @throws IllegalAccessException * @throws InstantiationException */ public static void main(String[] args) throws InstantiationException, IllegalAccessException { BankAccount[] accounts = new BankAccount[100]; BankAccount account = BankAccount.class.newInstance(); account.setBalance(400); account.setAccountNumber(75); accounts[75] = account; System.out.println("Account Number is "+accounts[75].accountNumber+" balance is "+accounts[75].balance); accounts[75].withdraw(25); System.out.println("After Withdrawl :: Account Number is "+accounts[75].accountNumber+" balance is "+accounts[75].balance); } }
816
0.715686
0.688725
26
29.384615
33.404373
125
false
false
0
0
0
0
0
0
1.423077
false
false
13
e0ef2f45a2ae17ed4b603b7cd88c2f9efbb22a22
9,998,683,869,303
3d6196172c4db8084a26b73122a3083769412510
/src/fr/carbonchat/software/core/swinger/Contact.java
5c5d3fe1117d6d236b8dd456942c48b08cf617a8
[]
no_license
BDoryan/CarbonChat
https://github.com/BDoryan/CarbonChat
e95596422e5a9cd2cf983bc2d82a5ec798caa33d
0b90ab681394f42cb668a8cd6c2865126e7dcd9a
refs/heads/master
2023-02-23T23:47:20.499000
2023-02-09T21:10:43
2023-02-09T21:10:43
137,106,258
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.carbonchat.software.core.swinger; import java.util.Random; import javafx.scene.image.Image; public class Contact { public int id; public Contact(int id) { this.id = id; } public Image getLogo(int width, int height) { Image image = new Image(getClass().getResourceAsStream("/imgs/face-white.png"), width, height, true, true); return image; } public String getUsername() { return "user "+new Random().nextInt(999999); } }
UTF-8
Java
478
java
Contact.java
Java
[]
null
[]
package fr.carbonchat.software.core.swinger; import java.util.Random; import javafx.scene.image.Image; public class Contact { public int id; public Contact(int id) { this.id = id; } public Image getLogo(int width, int height) { Image image = new Image(getClass().getResourceAsStream("/imgs/face-white.png"), width, height, true, true); return image; } public String getUsername() { return "user "+new Random().nextInt(999999); } }
478
0.671548
0.658996
23
18.782608
24.877012
109
false
false
0
0
0
0
0
0
1.304348
false
false
13
b5018cac09f7b30c72dc7f64c093c378cc9cc35d
13,202,729,476,296
c64b66e60e8e40a99d1d02e5f31a819633d119ce
/src/java/com/kparking/oltranz/config/SMSConfig.java
7f330e8bc6d1d881b52bebcec06ac8cd5ec47edd
[]
no_license
iaubain/KvcsParkingModule
https://github.com/iaubain/KvcsParkingModule
14e85a0842b6b49513efb5670ba017fd5231d3a9
928e35ae7440ec196bddd4311e409e80e4fbb3b0
refs/heads/master
2021-01-20T07:51:31.184000
2017-09-02T22:02:39
2017-09-02T22:02:39
83,892,954
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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.kparking.oltranz.config; /** * * @author ISHIMWE Aubain Consolateur. email: iaubain@yahoo.fr / * aubain.c.ishimwe@oltranz.com Tel: +250 785 534 672 / +250 736 864 662 */ public class SMSConfig { public static final String SRC_1 = "KVCS-PARKS"; public static final String SRC_2 = "KVCS-PARKS"; public static final String CAR_IN_MSG = "Mukiriya mwiza umazeguparika, Dear customer you parked, Cher client vous avez gare: "; public static final String CAR_OUT_MSG = "Mukiriya mwiza uvanye imodoka muri parikingi, Dear Customer you moved out your car, Cher client vous venez de sortir votre auto: "; public static final String CAR_ADDED_VALUE = "Mukiriya mwiza, Dear customer, Cher client: "; }
UTF-8
Java
937
java
SMSConfig.java
Java
[ { "context": "om.kparking.oltranz.config;\r\n\r\n/**\r\n *\r\n * @author ISHIMWE Aubain Consolateur. email: iaubain@yahoo.fr /\r\n * aubain.c.ishimwe@o", "end": 276, "score": 0.9997793436050415, "start": 250, "tag": "NAME", "value": "ISHIMWE Aubain Consolateur" }, { "context": "\n *\r\n * @author ISHIMWE Aubain Consolateur. email: iaubain@yahoo.fr /\r\n * aubain.c.ishimwe@oltranz.com Tel: +250 785 ", "end": 301, "score": 0.999920666217804, "start": 285, "tag": "EMAIL", "value": "iaubain@yahoo.fr" }, { "context": " Aubain Consolateur. email: iaubain@yahoo.fr /\r\n * aubain.c.ishimwe@oltranz.com Tel: +250 785 534 672 / +250 736 864 662\r\n */\r\npu", "end": 336, "score": 0.9998633861541748, "start": 308, "tag": "EMAIL", "value": "aubain.c.ishimwe@oltranz.com" } ]
null
[]
/* * 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.kparking.oltranz.config; /** * * @author <NAME>. email: <EMAIL> / * <EMAIL> Tel: +250 785 534 672 / +250 736 864 662 */ public class SMSConfig { public static final String SRC_1 = "KVCS-PARKS"; public static final String SRC_2 = "KVCS-PARKS"; public static final String CAR_IN_MSG = "Mukiriya mwiza umazeguparika, Dear customer you parked, Cher client vous avez gare: "; public static final String CAR_OUT_MSG = "Mukiriya mwiza uvanye imodoka muri parikingi, Dear Customer you moved out your car, Cher client vous venez de sortir votre auto: "; public static final String CAR_ADDED_VALUE = "Mukiriya mwiza, Dear customer, Cher client: "; }
887
0.712914
0.685165
20
44.849998
47.486076
177
false
false
0
0
0
0
0
0
0.75
false
false
13
4fe40656ad1581d3c4ac0e73733aa4d1a156b20b
3,040,836,853,052
d9ba5fc43e53596c9cdc8295deef05a94215570d
/nc-cashier/nc-cashier-facade/src/main/java/com/yeepay/g3/facade/nccashier/dto/OrderProcessorRequestDTO.java
bb4daaff36e539c767627064280fb28f2c394b5c
[]
no_license
P79N6A/11.9
https://github.com/P79N6A/11.9
2189ce53b5adbe629e477d9899e939d87387bcbc
a7dafcb0db716ec3184279f995ed4b5a06a0b92e
refs/heads/master
2021-09-28T02:09:07.464000
2018-11-13T10:01:31
2018-11-13T10:01:31
157,359,968
0
1
null
true
2018-11-13T10:10:55
2018-11-13T10:10:54
2018-11-13T10:05:29
2018-11-13T10:05:21
0
0
0
0
null
false
null
package com.yeepay.g3.facade.nccashier.dto; import com.yeepay.g3.facade.nccashier.enumtype.CashierVersionEnum; import java.io.Serializable; /** * Description * PackageName: com.yeepay.g3.facade.nccashier.dto * * @author pengfei.chen * @since 17/2/17 15:51 */ public class OrderProcessorRequestDTO implements Serializable { private static final long serialVersionUID = -6130270266159095850L; private String token; private String appId; private String openId; private String cardType; private String userType; private String userNo; private CashierVersionEnum CashierVersion; private String directPayType; private String merchantNo; private String userIp; private String bizType; /** * 支付宝生活号 商户透传 */ private String aliUserId; /** * 支付宝生活号 商户透传 */ private String aliAppId; /** * 客户号,部分B2B网银支付所需 */ private String clientId; /** 以下三个字段 微信H5支付所需 **/ private String platForm; private String appName; private String appStatement; /** * 报备费率,用于区分聚合支付线上线下 */ private String reportFee; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo; } public CashierVersionEnum getCashierVersion() { return CashierVersion; } public void setCashierVersion(CashierVersionEnum cashierVersion) { CashierVersion = cashierVersion; } public String getDirectPayType() { return directPayType; } public void setDirectPayType(String directPayType) { this.directPayType = directPayType; } public String getMerchantNo() { return merchantNo; } public void setMerchantNo(String merchantNo) { this.merchantNo = merchantNo; } public String getUserIp() { return userIp; } public void setUserIp(String userIp) { this.userIp = userIp; } public String getBizType() { return bizType; } public void setBizType(String bizType) { this.bizType = bizType; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getAliUserId() { return aliUserId; } public void setAliUserId(String aliUserId) { this.aliUserId = aliUserId; } public String getAliAppId() { return aliAppId; } public void setAliAppId(String aliAppId) { this.aliAppId = aliAppId; } public String getPlatForm() { return platForm; } public void setPlatForm(String platForm) { this.platForm = platForm; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getAppStatement() { return appStatement; } public void setAppStatement(String appStatement) { this.appStatement = appStatement; } public String getReportFee() { return reportFee; } public void setReportFee(String reportFee) { this.reportFee = reportFee; } }
UTF-8
Java
3,968
java
OrderProcessorRequestDTO.java
Java
[ { "context": ": com.yeepay.g3.facade.nccashier.dto\n *\n * @author pengfei.chen\n * @since 17/2/17 15:51\n */\npublic class OrderPro", "end": 239, "score": 0.9672164916992188, "start": 227, "tag": "USERNAME", "value": "pengfei.chen" } ]
null
[]
package com.yeepay.g3.facade.nccashier.dto; import com.yeepay.g3.facade.nccashier.enumtype.CashierVersionEnum; import java.io.Serializable; /** * Description * PackageName: com.yeepay.g3.facade.nccashier.dto * * @author pengfei.chen * @since 17/2/17 15:51 */ public class OrderProcessorRequestDTO implements Serializable { private static final long serialVersionUID = -6130270266159095850L; private String token; private String appId; private String openId; private String cardType; private String userType; private String userNo; private CashierVersionEnum CashierVersion; private String directPayType; private String merchantNo; private String userIp; private String bizType; /** * 支付宝生活号 商户透传 */ private String aliUserId; /** * 支付宝生活号 商户透传 */ private String aliAppId; /** * 客户号,部分B2B网银支付所需 */ private String clientId; /** 以下三个字段 微信H5支付所需 **/ private String platForm; private String appName; private String appStatement; /** * 报备费率,用于区分聚合支付线上线下 */ private String reportFee; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo; } public CashierVersionEnum getCashierVersion() { return CashierVersion; } public void setCashierVersion(CashierVersionEnum cashierVersion) { CashierVersion = cashierVersion; } public String getDirectPayType() { return directPayType; } public void setDirectPayType(String directPayType) { this.directPayType = directPayType; } public String getMerchantNo() { return merchantNo; } public void setMerchantNo(String merchantNo) { this.merchantNo = merchantNo; } public String getUserIp() { return userIp; } public void setUserIp(String userIp) { this.userIp = userIp; } public String getBizType() { return bizType; } public void setBizType(String bizType) { this.bizType = bizType; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getAliUserId() { return aliUserId; } public void setAliUserId(String aliUserId) { this.aliUserId = aliUserId; } public String getAliAppId() { return aliAppId; } public void setAliAppId(String aliAppId) { this.aliAppId = aliAppId; } public String getPlatForm() { return platForm; } public void setPlatForm(String platForm) { this.platForm = platForm; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getAppStatement() { return appStatement; } public void setAppStatement(String appStatement) { this.appStatement = appStatement; } public String getReportFee() { return reportFee; } public void setReportFee(String reportFee) { this.reportFee = reportFee; } }
3,968
0.644826
0.636245
198
18.424242
17.253365
71
false
false
0
0
0
0
0
0
0.510101
false
false
13
5995cc72ebf0f45e487871fdc07966e694b3b1f8
8,546,984,972,580
e61410ca429454d5f312a92a9dd633a428e03fad
/app/src/main/java/com/makeit/sunnycar/drawit/view/BorderView.java
9261ec6e84df9cf8d0a1b5cba2b2b446fd44e4b3
[]
no_license
Kimhuissun/Drawit_Application
https://github.com/Kimhuissun/Drawit_Application
b423832cda2f3a95acb762eafcc91c5f0fc66c61
576c2453aa8223571c9c36fec89df37165e85012
refs/heads/master
2020-09-21T23:18:47.883000
2020-01-27T08:38:26
2020-01-27T08:38:26
224,969,195
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* package com.makeit.sunnycar.drawit.view; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.Rect; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import com.makeit.sunnycar.removevideobackground.R; import com.makeit.sunnycar.drawit.data.Frame; import com.makeit.sunnycar.drawit.handler.ThreshHandler; import com.makeit.sunnycar.drawit.listener.BorderListener; import com.makeit.sunnycar.drawit.thread.GetImage; import com.makeit.sunnycar.drawit.thread.Threshold; public class BorderView extends View{ public static Rect BORDER_DST_RECT=new Rect(); private int WINDOW_WIDTH,WINDOW_HEIGHT; private static float[] CENTER_FACTOR=new float[3]; private Paint paint,redPaint; private BorderListener borderListener; public Rect RED_PAINT_BORDER=new Rect(); private Object context; //public float[] CANVAS_RECT; public BorderView(Context context) { super(context); init(context); } private void init(Context context) { this.context=context; paint=new Paint(); paint.setDither(true); paint.setFilterBitmap(true); paint.setFlags(Paint.DITHER_FLAG|Paint.FILTER_BITMAP_FLAG); redPaint=new Paint(); redPaint.setStyle(Paint.Style.STROKE); redPaint.setColor(Color.RED); redPaint.setStrokeWidth(10.0f); borderListener=new BorderListener(context,this); //CANVAS_RECT=new float[]{0.0f,0.0f, DrawingContourView.WIDTH,DrawingContourView.HEIGHT}; } public BorderView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context); } public BorderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } public BorderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); WINDOW_WIDTH=right-left; WINDOW_HEIGHT=bottom-top; DrawingContourView.setCanvasToCenterFactor(WINDOW_WIDTH,WINDOW_HEIGHT,CENTER_FACTOR); if(CENTER_FACTOR[2]==1){ RED_PAINT_BORDER.set( 0, (int) CENTER_FACTOR[1], (int) (DrawingContourView.WIDTH*CENTER_FACTOR[0]), (int) (DrawingContourView.HEIGHT*CENTER_FACTOR[0]+CENTER_FACTOR[1])); }else { RED_PAINT_BORDER.set( (int) CENTER_FACTOR[1], 0, (int) (DrawingContourView.WIDTH*CENTER_FACTOR[0]+CENTER_FACTOR[1]), (int) (DrawingContourView.HEIGHT*CENTER_FACTOR[0])); } } @Override public void draw(Canvas canvas) { super.draw(canvas); */ /* canvas.scale(CENTER_FACTOR[0],CENTER_FACTOR[0],0,0); if(CENTER_FACTOR[2]==1) canvas.translate(0,CENTER_FACTOR[1]); else canvas.translate(CENTER_FACTOR[1],0);*//* */ /* if(ThreshHandler.METHOD==ThreshHandler.PHOTO_OUTLINE &&ThreshHandler.FINAL_IMAGE!=null) { canvas.drawBitmap(ThreshHandler.FINAL_IMAGE,null,BORDER_DST_RECT, paint); }else *//* if(GetImage.imageViewBitmap!=null){ canvas.drawBitmap(GetImage.imageViewBitmap,null,BORDER_DST_RECT, paint); } canvas.drawRect(RED_PAINT_BORDER,redPaint); } @Override public boolean onTouchEvent(MotionEvent event) { borderListener.onTouchEvent(event); return true; } public void cropBorder(){ Bitmap bitmap= Bitmap.createBitmap(RED_PAINT_BORDER.width(),RED_PAINT_BORDER.height(), Bitmap.Config.ARGB_8888); Canvas canvas=new Canvas(bitmap); canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.SRC_OUT); canvas.drawBitmap(GetImage.imageViewBitmap,(int)(borderListener.bitmapX-RED_PAINT_BORDER.left), (int)(borderListener.bitmapY-RED_PAINT_BORDER.top),paint); //Threshold.FINAL_IMAGE=Bitmap.createScaledBitmap(bitmap,DrawingContourView.WIDTH,DrawingContourView.HEIGHT,true); GetImage.imageViewBitmap=bitmap; } */ /* public void resetBitmapForDraw() { // RED_PAINT_BORDER.offset((int)(borderListener.bitmapX), (int)(borderListener.bitmapY)); *//* */ /*if(ThreshHandler.METHOD==ThreshHandler.PHOTO_OUTLINE){ Bitmap bitmap= Bitmap.createBitmap(RED_PAINT_BORDER.width(),RED_PAINT_BORDER.height(), Bitmap.Config.ARGB_8888); Canvas canvas=new Canvas(bitmap); canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.SRC_OUT); canvas.drawBitmap(ThreshHandler.FINAL_IMAGE,(int)(borderListener.bitmapX-RED_PAINT_BORDER.left), (int)(borderListener.bitmapY-RED_PAINT_BORDER.top),paint); //Threshold.FINAL_IMAGE=Bitmap.createScaledBitmap(bitmap,DrawingContourView.WIDTH,DrawingContourView.HEIGHT,true); ThreshHandler.FINAL_IMAGE=bitmap; }else if(ThreshHandler.METHOD==ThreshHandler.ORIGINAL_PHOTO){ Bitmap bitmap= Bitmap.createBitmap(RED_PAINT_BORDER.width(),RED_PAINT_BORDER.height(), Bitmap.Config.ARGB_8888); Canvas canvas=new Canvas(bitmap); canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.SRC_OUT); canvas.drawBitmap(GetImage.imageViewBitmap,(int)(borderListener.bitmapX-RED_PAINT_BORDER.left), (int)(borderListener.bitmapY-RED_PAINT_BORDER.top),paint); //GetImage.imageViewBitmap=Bitmap.createScaledBitmap(bitmap,DrawingContourView.WIDTH,DrawingContourView.HEIGHT,true); GetImage.imageViewBitmap=bitmap; }*//* */ /* Frame.currentFrame.addSketch(); if(ThreshHandler.FINAL_IMAGE!=null&&!ThreshHandler.FINAL_IMAGE.isRecycled()){ ThreshHandler.FINAL_IMAGE.recycle(); ThreshHandler.FINAL_IMAGE=null; } if(GetImage.imageViewBitmap!=null&&!GetImage.imageViewBitmap.isRecycled()){ GetImage.imageViewBitmap.recycle(); GetImage.imageViewBitmap=null; } ((Activity)context).finish(); }*//* } */
UTF-8
Java
6,675
java
BorderView.java
Java
[]
null
[]
/* package com.makeit.sunnycar.drawit.view; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.Rect; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import com.makeit.sunnycar.removevideobackground.R; import com.makeit.sunnycar.drawit.data.Frame; import com.makeit.sunnycar.drawit.handler.ThreshHandler; import com.makeit.sunnycar.drawit.listener.BorderListener; import com.makeit.sunnycar.drawit.thread.GetImage; import com.makeit.sunnycar.drawit.thread.Threshold; public class BorderView extends View{ public static Rect BORDER_DST_RECT=new Rect(); private int WINDOW_WIDTH,WINDOW_HEIGHT; private static float[] CENTER_FACTOR=new float[3]; private Paint paint,redPaint; private BorderListener borderListener; public Rect RED_PAINT_BORDER=new Rect(); private Object context; //public float[] CANVAS_RECT; public BorderView(Context context) { super(context); init(context); } private void init(Context context) { this.context=context; paint=new Paint(); paint.setDither(true); paint.setFilterBitmap(true); paint.setFlags(Paint.DITHER_FLAG|Paint.FILTER_BITMAP_FLAG); redPaint=new Paint(); redPaint.setStyle(Paint.Style.STROKE); redPaint.setColor(Color.RED); redPaint.setStrokeWidth(10.0f); borderListener=new BorderListener(context,this); //CANVAS_RECT=new float[]{0.0f,0.0f, DrawingContourView.WIDTH,DrawingContourView.HEIGHT}; } public BorderView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context); } public BorderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } public BorderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); WINDOW_WIDTH=right-left; WINDOW_HEIGHT=bottom-top; DrawingContourView.setCanvasToCenterFactor(WINDOW_WIDTH,WINDOW_HEIGHT,CENTER_FACTOR); if(CENTER_FACTOR[2]==1){ RED_PAINT_BORDER.set( 0, (int) CENTER_FACTOR[1], (int) (DrawingContourView.WIDTH*CENTER_FACTOR[0]), (int) (DrawingContourView.HEIGHT*CENTER_FACTOR[0]+CENTER_FACTOR[1])); }else { RED_PAINT_BORDER.set( (int) CENTER_FACTOR[1], 0, (int) (DrawingContourView.WIDTH*CENTER_FACTOR[0]+CENTER_FACTOR[1]), (int) (DrawingContourView.HEIGHT*CENTER_FACTOR[0])); } } @Override public void draw(Canvas canvas) { super.draw(canvas); */ /* canvas.scale(CENTER_FACTOR[0],CENTER_FACTOR[0],0,0); if(CENTER_FACTOR[2]==1) canvas.translate(0,CENTER_FACTOR[1]); else canvas.translate(CENTER_FACTOR[1],0);*//* */ /* if(ThreshHandler.METHOD==ThreshHandler.PHOTO_OUTLINE &&ThreshHandler.FINAL_IMAGE!=null) { canvas.drawBitmap(ThreshHandler.FINAL_IMAGE,null,BORDER_DST_RECT, paint); }else *//* if(GetImage.imageViewBitmap!=null){ canvas.drawBitmap(GetImage.imageViewBitmap,null,BORDER_DST_RECT, paint); } canvas.drawRect(RED_PAINT_BORDER,redPaint); } @Override public boolean onTouchEvent(MotionEvent event) { borderListener.onTouchEvent(event); return true; } public void cropBorder(){ Bitmap bitmap= Bitmap.createBitmap(RED_PAINT_BORDER.width(),RED_PAINT_BORDER.height(), Bitmap.Config.ARGB_8888); Canvas canvas=new Canvas(bitmap); canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.SRC_OUT); canvas.drawBitmap(GetImage.imageViewBitmap,(int)(borderListener.bitmapX-RED_PAINT_BORDER.left), (int)(borderListener.bitmapY-RED_PAINT_BORDER.top),paint); //Threshold.FINAL_IMAGE=Bitmap.createScaledBitmap(bitmap,DrawingContourView.WIDTH,DrawingContourView.HEIGHT,true); GetImage.imageViewBitmap=bitmap; } */ /* public void resetBitmapForDraw() { // RED_PAINT_BORDER.offset((int)(borderListener.bitmapX), (int)(borderListener.bitmapY)); *//* */ /*if(ThreshHandler.METHOD==ThreshHandler.PHOTO_OUTLINE){ Bitmap bitmap= Bitmap.createBitmap(RED_PAINT_BORDER.width(),RED_PAINT_BORDER.height(), Bitmap.Config.ARGB_8888); Canvas canvas=new Canvas(bitmap); canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.SRC_OUT); canvas.drawBitmap(ThreshHandler.FINAL_IMAGE,(int)(borderListener.bitmapX-RED_PAINT_BORDER.left), (int)(borderListener.bitmapY-RED_PAINT_BORDER.top),paint); //Threshold.FINAL_IMAGE=Bitmap.createScaledBitmap(bitmap,DrawingContourView.WIDTH,DrawingContourView.HEIGHT,true); ThreshHandler.FINAL_IMAGE=bitmap; }else if(ThreshHandler.METHOD==ThreshHandler.ORIGINAL_PHOTO){ Bitmap bitmap= Bitmap.createBitmap(RED_PAINT_BORDER.width(),RED_PAINT_BORDER.height(), Bitmap.Config.ARGB_8888); Canvas canvas=new Canvas(bitmap); canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.SRC_OUT); canvas.drawBitmap(GetImage.imageViewBitmap,(int)(borderListener.bitmapX-RED_PAINT_BORDER.left), (int)(borderListener.bitmapY-RED_PAINT_BORDER.top),paint); //GetImage.imageViewBitmap=Bitmap.createScaledBitmap(bitmap,DrawingContourView.WIDTH,DrawingContourView.HEIGHT,true); GetImage.imageViewBitmap=bitmap; }*//* */ /* Frame.currentFrame.addSketch(); if(ThreshHandler.FINAL_IMAGE!=null&&!ThreshHandler.FINAL_IMAGE.isRecycled()){ ThreshHandler.FINAL_IMAGE.recycle(); ThreshHandler.FINAL_IMAGE=null; } if(GetImage.imageViewBitmap!=null&&!GetImage.imageViewBitmap.isRecycled()){ GetImage.imageViewBitmap.recycle(); GetImage.imageViewBitmap=null; } ((Activity)context).finish(); }*//* } */
6,675
0.678801
0.672509
175
37.142857
35.180794
167
false
false
0
0
0
0
0
0
0.937143
false
false
4
1dfc69074f0188e87abbae5382f5e35cdf80d5c3
33,526,514,760,541
7dc15695f44216e62be7339d30d0d63aa1eeb7d9
/08vrd/src/main/java/cn/tedu/controller/HomeServlet.java
081fffce611c4a3b3db04395da9d73c6bd8138f7
[]
no_license
SkyMonster523/skymonster.github.io
https://github.com/SkyMonster523/skymonster.github.io
0e5472950c96daf750623071ba7a73286361cdd3
f14ae135798c2c5ce248b685d4dfc5442e8ac73d
refs/heads/master
2023-01-14T10:42:44.888000
2020-11-23T11:22:42
2020-11-23T11:22:42
315,285,061
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.tedu.controller; import cn.tedu.dao.BannerDao; import cn.tedu.dao.CategoryDao; import cn.tedu.dao.ProductDao; import cn.tedu.entity.Banner; import cn.tedu.entity.Category; import cn.tedu.entity.Product; import cn.tedu.entity.User; import cn.tedu.utils.ThUtils; import org.thymeleaf.context.Context; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; @WebServlet(name = "HomeServlet",urlPatterns = "/home") public class HomeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到分类id String cid = request.getParameter("cid"); //得到查询关键字 String keyword = request.getParameter("keyword"); //取出Session中保存的user对象 HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); /*if(user!=null){ System.out.println("曾经登录过"); }else{ System.out.println("没有登陆过"); }*/ Context context = new Context(); context.setVariable("user",user); CategoryDao dao = new CategoryDao(); List<Category> list = dao.findall(); context.setVariable("list",list); BannerDao bdao = new BannerDao(); List<Banner> blist = bdao.findAll(); context.setVariable("blist",blist); //创建ProductDao 并调用findAll方法 List<Product> pList = null; ProductDao pDao = new ProductDao(); if(cid!=null) {//查分类方法 pList = pDao.findByCid(cid); }else if (keyword!=null){ pList = pDao.findByKeyword(keyword); }else{//查所有 pList = pDao.findall(); } context.setVariable("pList",pList); //查询浏览最多的作品信息 List<Product> vList = pDao.findViewList(); context.setVariable("vList",vList); //查询最受欢迎的作品信息 List<Product> lList = pDao.findLikeList(); context.setVariable("lList",lList); ThUtils.print("home.html",context,response); } }
UTF-8
Java
2,555
java
HomeServlet.java
Java
[]
null
[]
package cn.tedu.controller; import cn.tedu.dao.BannerDao; import cn.tedu.dao.CategoryDao; import cn.tedu.dao.ProductDao; import cn.tedu.entity.Banner; import cn.tedu.entity.Category; import cn.tedu.entity.Product; import cn.tedu.entity.User; import cn.tedu.utils.ThUtils; import org.thymeleaf.context.Context; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; @WebServlet(name = "HomeServlet",urlPatterns = "/home") public class HomeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到分类id String cid = request.getParameter("cid"); //得到查询关键字 String keyword = request.getParameter("keyword"); //取出Session中保存的user对象 HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); /*if(user!=null){ System.out.println("曾经登录过"); }else{ System.out.println("没有登陆过"); }*/ Context context = new Context(); context.setVariable("user",user); CategoryDao dao = new CategoryDao(); List<Category> list = dao.findall(); context.setVariable("list",list); BannerDao bdao = new BannerDao(); List<Banner> blist = bdao.findAll(); context.setVariable("blist",blist); //创建ProductDao 并调用findAll方法 List<Product> pList = null; ProductDao pDao = new ProductDao(); if(cid!=null) {//查分类方法 pList = pDao.findByCid(cid); }else if (keyword!=null){ pList = pDao.findByKeyword(keyword); }else{//查所有 pList = pDao.findall(); } context.setVariable("pList",pList); //查询浏览最多的作品信息 List<Product> vList = pDao.findViewList(); context.setVariable("vList",vList); //查询最受欢迎的作品信息 List<Product> lList = pDao.findLikeList(); context.setVariable("lList",lList); ThUtils.print("home.html",context,response); } }
2,555
0.666529
0.666529
78
30.064102
23.213247
122
false
false
0
0
0
0
0
0
0.717949
false
false
4
3a1b33b2323eb083d1a211cce05598ee35bfbabc
7,928,509,635,256
d24de9be4c3993d9dc726e9a3c74d9662c470226
/reverse/Rocketbank_All_3.12.4_source_from_JADX/sources/com/google/android/gms/internal/zzbla.java
0b54e173321c9ddc57bf269cc6cef91c76edd4df
[]
no_license
MEJIOMAH17/rocketbank-api
https://github.com/MEJIOMAH17/rocketbank-api
b18808ee4a2fdddd8b3045cd16655b0d82e0b13b
fc4eb0cbb4a8f52277fdb09a3b26b4cceef6ff79
refs/heads/master
2022-07-17T20:24:29.721000
2019-07-26T18:55:21
2019-07-26T18:55:21
198,698,231
4
0
null
false
2022-06-20T22:43:15
2019-07-24T19:31:49
2020-04-04T12:47:18
2022-06-20T22:43:14
291,172
2
0
2
Smali
false
false
package com.google.android.gms.internal; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.internal.safeparcel.zza; public class zzbla extends zza { public static final Creator<zzbla> CREATOR = new zzblb(); final int zzaiI; String zzbNy; zzbla(int i, String str) { this.zzaiI = i; this.zzbNy = str; } public void writeToParcel(Parcel parcel, int i) { zzblb.zza(this, parcel, i); } }
UTF-8
Java
490
java
zzbla.java
Java
[]
null
[]
package com.google.android.gms.internal; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.internal.safeparcel.zza; public class zzbla extends zza { public static final Creator<zzbla> CREATOR = new zzblb(); final int zzaiI; String zzbNy; zzbla(int i, String str) { this.zzaiI = i; this.zzbNy = str; } public void writeToParcel(Parcel parcel, int i) { zzblb.zza(this, parcel, i); } }
490
0.67551
0.67551
20
23.5
19.802778
61
false
false
0
0
0
0
0
0
0.7
false
false
4
117d50b2d5bc3fd0423b7f40986c92145d42d69e
13,881,334,301,039
5ba09b5bcb263a1adbbf89cc36f55948066ab31f
/Java/src/Problem040.java
0884ced43f5e8184d643a1a8166c1dd4bacbfce1
[]
no_license
peteparkinson/Project-Euler
https://github.com/peteparkinson/Project-Euler
a5a669ef69172557498563302edbe61a4c985095
1ad4dea85e0cfd65ab07e3a7c908108bb1395537
refs/heads/master
2021-06-01T17:46:38.059000
2020-12-30T19:46:39
2020-12-30T19:46:39
153,541,348
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Project Euler, problem 40 * An irrational decimal fraction is created by concatenating the positive * integers: 0.12345678910'1'112131415161718192021... * * It can be seen that the 12th digit of the fractional part is 1. * * If dn represents the nth digit of the fractional part, find the value of * the following expression. * * d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 * * answer = 210; //correct */ public class Problem040 { public static void main(String[] args){ int num = 0; int answer = 1; for (int i = 0; i <= 1000000; i++) { String iString = String.valueOf(i); int power = Integer.valueOf(iString.length()); for (int j = 0; j < iString.length(); j++) { //seeks specific indexes (10, 100, etc). "- j" cycles digits of the number if(num == Math.pow(10, power) - j){ //System.out.println(iString.charAt(j)); answer *= Integer.parseInt(String.valueOf(String.valueOf(iString.charAt(j)))); } } num += power; } System.out.println(answer); } }
WINDOWS-1252
Java
1,096
java
Problem040.java
Java
[]
null
[]
/* Project Euler, problem 40 * An irrational decimal fraction is created by concatenating the positive * integers: 0.12345678910'1'112131415161718192021... * * It can be seen that the 12th digit of the fractional part is 1. * * If dn represents the nth digit of the fractional part, find the value of * the following expression. * * d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 * * answer = 210; //correct */ public class Problem040 { public static void main(String[] args){ int num = 0; int answer = 1; for (int i = 0; i <= 1000000; i++) { String iString = String.valueOf(i); int power = Integer.valueOf(iString.length()); for (int j = 0; j < iString.length(); j++) { //seeks specific indexes (10, 100, etc). "- j" cycles digits of the number if(num == Math.pow(10, power) - j){ //System.out.println(iString.charAt(j)); answer *= Integer.parseInt(String.valueOf(String.valueOf(iString.charAt(j)))); } } num += power; } System.out.println(answer); } }
1,096
0.612844
0.529358
40
25.25
25.651266
83
false
false
0
0
0
0
0
0
2.05
false
false
4
13169955ea5e85221cca007d1f80c7adf3c36688
13,881,334,301,076
7927b73cc0c30ae36ba46a9cd0dda3a591666afa
/Java-HouBaseExecise/src/src/sinochemcloud/javayichang/CheckingAccount.java
596a92e41baa2bc02007c77d3fb4d1b28b0826c2
[]
no_license
HXINGHAI/java-basic
https://github.com/HXINGHAI/java-basic
641582596a9e97b348ddff79a45530277ad2e70d
273260297437c2a0165b2d061b278896619e9a0f
refs/heads/master
2020-05-02T20:45:17.266000
2019-03-29T06:07:18
2019-03-29T06:07:18
178,200,890
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package src.sinochemcloud.javayichang; import javax.naming.InsufficientResourcesException; public class CheckingAccount { private double balance; private int numbers; public CheckingAccount(int numbers){ this.numbers = numbers; } public void deposit(double amount){ balance = balance + amount; } public void withDraw(double amount) throws MyException{ if (amount <= balance){ balance = balance - amount; }else{ double needs = amount - balance; throw new MyException(needs); } } public double getBalance(){ return balance; } public int getNumbers(){ return numbers; } }
UTF-8
Java
711
java
CheckingAccount.java
Java
[]
null
[]
package src.sinochemcloud.javayichang; import javax.naming.InsufficientResourcesException; public class CheckingAccount { private double balance; private int numbers; public CheckingAccount(int numbers){ this.numbers = numbers; } public void deposit(double amount){ balance = balance + amount; } public void withDraw(double amount) throws MyException{ if (amount <= balance){ balance = balance - amount; }else{ double needs = amount - balance; throw new MyException(needs); } } public double getBalance(){ return balance; } public int getNumbers(){ return numbers; } }
711
0.623066
0.623066
28
24.392857
16.564461
59
false
false
0
0
0
0
0
0
0.392857
false
false
4
2a2f82135fad72972fd5835941549d7fdf9ab81b
31,576,599,616,424
f1abb45d71978a1c6c5622fb2e5941b2765c8656
/Java man exp/Exp23.java
b2b23fd4b2a137bf5797ad21d6ff57d25f20edda
[]
no_license
DevaGaneshB/Java
https://github.com/DevaGaneshB/Java
b0aa21364cb4c63033826079e0ea9fb9a277557a
45bb30aff12757731e994b889156285689d67755
refs/heads/master
2020-03-23T19:07:03.914000
2019-05-20T13:30:56
2019-05-20T13:30:56
141,954,066
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
//The this keyword can be passed as argument in the constructor call. public class Exp23 { Exp23(A4 obj) { this.obj=obj; } void display() { System.out.println(obj.data);//using data member of A4 class } } class A4 extends Exp23 { int data=10; A4() { A4 b=new A4(this); b.display(); } public static void main(String[] args) { A4 a=new A4(); } }
UTF-8
Java
483
java
Exp23.java
Java
[]
null
[]
//The this keyword can be passed as argument in the constructor call. public class Exp23 { Exp23(A4 obj) { this.obj=obj; } void display() { System.out.println(obj.data);//using data member of A4 class } } class A4 extends Exp23 { int data=10; A4() { A4 b=new A4(this); b.display(); } public static void main(String[] args) { A4 a=new A4(); } }
483
0.490683
0.457557
27
15.814815
17.152987
69
false
false
0
0
0
0
0
0
1.185185
false
false
4
cc22592a0a863fd203935a26ef71e44138718232
12,111,807,778,076
837a461adee856e62ced2b48da129d6429404053
/src/main/java/com/valkymorie/task/repository/AccountRepository.java
cca22c5853b6b57fbf156e65ce8a7f9558e17081
[]
no_license
Valkymorie/billCalculator
https://github.com/Valkymorie/billCalculator
96c7a2beec6f17cdbd88b8c29bb8c6690b1ae46e
58b5204fa3092e876acb782b0e44533122e9960f
refs/heads/master
2023-06-19T08:16:35.446000
2021-07-16T12:17:04
2021-07-16T12:17:04
385,727,798
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.valkymorie.task.repository; import com.valkymorie.task.model.Account; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface AccountRepository extends MongoRepository<Account, String >{ List<Account> findAllByName(String name); Optional<Account> findByName(String name); }
UTF-8
Java
500
java
AccountRepository.java
Java
[]
null
[]
package com.valkymorie.task.repository; import com.valkymorie.task.model.Account; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface AccountRepository extends MongoRepository<Account, String >{ List<Account> findAllByName(String name); Optional<Account> findByName(String name); }
500
0.822
0.822
18
26.777779
25.713282
77
false
false
0
0
0
0
0
0
0.555556
false
false
4
03775db5d1e6db6081324cb23a6663b1e1ae7e06
17,351,667,889,260
123bed93a39ee17802602a0474890d8501651da9
/Transcription-Reference/src/com/jomac/transcription/reference/jpa/controllers/RegistrationBeanJpaController.java
995eaf3a052923be71f3ccc196962bdf6faa3a5e
[]
no_license
JOMAC-TRANS/T-Reference
https://github.com/JOMAC-TRANS/T-Reference
c030304a7a5fada834ee08026b86ab040a72e9d4
480b2ec8c7175bd3a6f100c74e7af01606cc09ed
refs/heads/master
2020-12-26T15:44:05.120000
2020-03-04T15:25:26
2020-03-04T15:25:26
237,553,528
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jomac.transcription.reference.jpa.controllers; import com.jomac.transcription.reference.jpa.models.RegistrationBean; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityNotFoundException; import javax.persistence.Query; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; public class RegistrationBeanJpaController implements Serializable { public RegistrationBeanJpaController(EntityManagerFactory emf) { if (emf != null) { emf.getCache().evictAll(); } this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public boolean create(RegistrationBean registrationBean) { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); em.persist(registrationBean); em.getTransaction().commit(); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } finally { if (em != null) { em.close(); } } } public boolean edit(RegistrationBean registrationBean) { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); registrationBean = em.merge(registrationBean); em.getTransaction().commit(); return true; } catch (Exception ex) { return false; } finally { if (em != null) { em.close(); } } } public boolean destroy(RegistrationBean bean) { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); RegistrationBean registrationBean = null; try { registrationBean = em.getReference(RegistrationBean.class, bean.getRegistrationid()); registrationBean.getRegistrationid(); } catch (EntityNotFoundException enfe) { } em.remove(registrationBean == null ? bean : registrationBean); em.getTransaction().commit(); return true; } catch (Exception ex) { return false; } finally { if (em != null) { em.close(); } } } public List<RegistrationBean> findRegistrationBeanEntities() { return findRegistrationBeanEntities(true, -1, -1); } public List<RegistrationBean> findRegistrationBeanEntities(int maxResults, int firstResult) { return findRegistrationBeanEntities(false, maxResults, firstResult); } private List<RegistrationBean> findRegistrationBeanEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(RegistrationBean.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public RegistrationBean findRegistrationBean(Integer id) { EntityManager em = getEntityManager(); try { return em.find(RegistrationBean.class, id); } finally { em.close(); } } public int getRegistrationBeanCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<RegistrationBean> rt = cq.from(RegistrationBean.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } }
UTF-8
Java
4,184
java
RegistrationBeanJpaController.java
Java
[]
null
[]
package com.jomac.transcription.reference.jpa.controllers; import com.jomac.transcription.reference.jpa.models.RegistrationBean; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityNotFoundException; import javax.persistence.Query; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; public class RegistrationBeanJpaController implements Serializable { public RegistrationBeanJpaController(EntityManagerFactory emf) { if (emf != null) { emf.getCache().evictAll(); } this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public boolean create(RegistrationBean registrationBean) { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); em.persist(registrationBean); em.getTransaction().commit(); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } finally { if (em != null) { em.close(); } } } public boolean edit(RegistrationBean registrationBean) { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); registrationBean = em.merge(registrationBean); em.getTransaction().commit(); return true; } catch (Exception ex) { return false; } finally { if (em != null) { em.close(); } } } public boolean destroy(RegistrationBean bean) { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); RegistrationBean registrationBean = null; try { registrationBean = em.getReference(RegistrationBean.class, bean.getRegistrationid()); registrationBean.getRegistrationid(); } catch (EntityNotFoundException enfe) { } em.remove(registrationBean == null ? bean : registrationBean); em.getTransaction().commit(); return true; } catch (Exception ex) { return false; } finally { if (em != null) { em.close(); } } } public List<RegistrationBean> findRegistrationBeanEntities() { return findRegistrationBeanEntities(true, -1, -1); } public List<RegistrationBean> findRegistrationBeanEntities(int maxResults, int firstResult) { return findRegistrationBeanEntities(false, maxResults, firstResult); } private List<RegistrationBean> findRegistrationBeanEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(RegistrationBean.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public RegistrationBean findRegistrationBean(Integer id) { EntityManager em = getEntityManager(); try { return em.find(RegistrationBean.class, id); } finally { em.close(); } } public int getRegistrationBeanCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<RegistrationBean> rt = cq.from(RegistrationBean.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } }
4,184
0.587476
0.586998
130
31.184616
23.284786
111
false
false
0
0
0
0
0
0
0.546154
false
false
4
8ce7af3c634550319b9676929533b6a9f5561946
30,270,929,571,282
f6a6b1162f33f870fd491a672e7fe4451612fb18
/wechat/src/main/java/com/lfc/wechat/base/BaseDialog.java
d9c7a60dbdba62b1697b16ab670865c32208fbd0
[ "Apache-2.0" ]
permissive
LittleFogCat/wechat
https://github.com/LittleFogCat/wechat
7844fac89bc8f94357afd78f3338616456bbd470
83685832f763954d8c3e4f0f8297de9de59b1fd2
refs/heads/master
2021-01-19T09:20:43.731000
2017-09-24T08:19:24
2017-09-24T08:19:24
87,751,119
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lfc.wechat.base; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import com.lfc.wechat.utils.DialogUtils; import butterknife.ButterKnife; /** * Created by LittleFogCat on 2017/9/1. */ public abstract class BaseDialog extends Dialog { public BaseDialog(@NonNull Context context) { super(context); } public BaseDialog(@NonNull Context context, @StyleRes int themeResId) { super(context, themeResId); } protected BaseDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) { super(context, cancelable, cancelListener); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getContentView()); ButterKnife.bind(this); initView(); } protected abstract int getContentView(); protected abstract void initView(); }
UTF-8
Java
1,101
java
BaseDialog.java
Java
[ { "context": "import butterknife.ButterKnife;\n\n/**\n * Created by LittleFogCat on 2017/9/1.\n */\n\npublic abstract class BaseDialo", "end": 352, "score": 0.9995251297950745, "start": 340, "tag": "USERNAME", "value": "LittleFogCat" } ]
null
[]
package com.lfc.wechat.base; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import com.lfc.wechat.utils.DialogUtils; import butterknife.ButterKnife; /** * Created by LittleFogCat on 2017/9/1. */ public abstract class BaseDialog extends Dialog { public BaseDialog(@NonNull Context context) { super(context); } public BaseDialog(@NonNull Context context, @StyleRes int themeResId) { super(context, themeResId); } protected BaseDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) { super(context, cancelable, cancelListener); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getContentView()); ButterKnife.bind(this); initView(); } protected abstract int getContentView(); protected abstract void initView(); }
1,101
0.72752
0.722071
43
24.60465
24.730303
115
false
false
0
0
0
0
0
0
0.55814
false
false
4
7b04ae91d3bc3e86bafdaaeddd7d757dea84ea48
6,313,601,988,285
b8e3e449651bd64e5c126b5f91853428a595b5d8
/portal-application/src/main/java/com/similan/portal/view/wall/WallView.java
2f16d492f1aae160e7da5480873ee869320490b3
[]
no_license
suparna2702/ServiceFabric
https://github.com/suparna2702/ServiceFabric
ee5801a346fda63edf0bea75103e693e52037fc4
d526376f9530f608726fa6ad1b7912b4ec384a82
refs/heads/master
2021-03-22T04:40:41.688000
2016-12-06T02:06:38
2016-12-06T02:06:38
75,250,704
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.similan.portal.view.wall; import java.util.List; import com.similan.service.api.wall.dto.basic.WallEntryDto; import com.similan.service.api.wall.dto.key.IWallContainerKey; public interface WallView<WallContainer extends IWallContainerKey> extends WallPostingView { List<WallEntryDto<WallContainer>> getWallEntries(); void post(); String getPostContent(); }
UTF-8
Java
390
java
WallView.java
Java
[]
null
[]
package com.similan.portal.view.wall; import java.util.List; import com.similan.service.api.wall.dto.basic.WallEntryDto; import com.similan.service.api.wall.dto.key.IWallContainerKey; public interface WallView<WallContainer extends IWallContainerKey> extends WallPostingView { List<WallEntryDto<WallContainer>> getWallEntries(); void post(); String getPostContent(); }
390
0.782051
0.782051
17
21.941177
24.97168
74
false
false
0
0
0
0
0
0
0.411765
false
false
4
d54d92a979da2b41cd7a54a8dac3f1e18def398a
11,278,584,137,644
45ec40cb04347a304d74b3997c8e19e1a5f5489c
/backend/src/main/java/publisaiz/functionalities/users/UploadedRepositoryForUsers.java
dfa0bb4da9bf0fde4516ff429d6ac81da5bb25d0
[]
no_license
missaouib/PUBLISAIZ
https://github.com/missaouib/PUBLISAIZ
1a8b28851b03d2f5b063bc07fffe0d8d47fb0054
4884d38c778d94c4fa9c322e7ce5954c5cfa6d20
refs/heads/master
2020-12-28T17:49:01.860000
2019-10-26T20:27:16
2019-10-26T20:27:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package publisaiz.functionalities.users; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import publisaiz.entities.Uploaded; import publisaiz.entities.User; import java.util.Optional; @Repository interface UploadedRepositoryForUsers extends JpaRepository<Uploaded, Long> { Uploaded findByFileNameEndingWithAndHideFalse(String fileName); Page<Uploaded> findByOwnerAndHideFalse(User owner, Pageable pageable); Optional<Uploaded> findByIdAndHideFalse(Long id); }
UTF-8
Java
635
java
UploadedRepositoryForUsers.java
Java
[]
null
[]
package publisaiz.functionalities.users; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import publisaiz.entities.Uploaded; import publisaiz.entities.User; import java.util.Optional; @Repository interface UploadedRepositoryForUsers extends JpaRepository<Uploaded, Long> { Uploaded findByFileNameEndingWithAndHideFalse(String fileName); Page<Uploaded> findByOwnerAndHideFalse(User owner, Pageable pageable); Optional<Uploaded> findByIdAndHideFalse(Long id); }
635
0.83622
0.83622
19
32.421051
26.680006
76
false
false
0
0
0
0
0
0
0.684211
false
false
4
9ba95e8ffef173e487d529b50b34a5f0f0b96bc0
12,455,405,198,096
997ef8ce05a24521c5cb362edf77279d5b30ea0e
/app/src/main/java/com/phillips/jake/formulaschedule/CountdownFragment.java
b5f1c4b122481579b313409f7df6d02f0821455e
[]
no_license
jphill1314/FormulaSchedule2017
https://github.com/jphill1314/FormulaSchedule2017
ae0ad5e5cf5319e4b0b5b000aee8de36852fd2e4
5ab3817ada222b3e34c2c71ed679e008b88f8a38
refs/heads/master
2021-01-20T08:00:24.388000
2017-03-07T23:06:03
2017-03-07T23:06:03
83,896,200
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.phillips.jake.formulaschedule; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v4.app.Fragment; import android.support.v4.app.NotificationCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.Calendar; /** * A simple {@link Fragment} subclass. */ public class CountdownFragment extends Fragment { ArrayList<RaceWeekend> schedule; public CountdownFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (getArguments() != null){ schedule = getArguments().getParcelableArrayList(MainActivity.SCHEDULE_KEY); } // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_countdown, container, false); populateView(view); return view; } private String nextSession, nextRaceCountry; private long timeToNextRace; private void populateView(View rootView){ nextSession(); TextView tvCountry = (TextView) rootView.findViewById(R.id.next_race_country); TextView tvSession = (TextView) rootView.findViewById(R.id.next_session_name); final TextView tvHours = (TextView) rootView.findViewById(R.id.num_hours_to_next_session); final TextView tvMins = (TextView) rootView.findViewById(R.id.num_min_to_next_session); final TextView tvSecs = (TextView) rootView.findViewById(R.id.num_seconds_to_next_session); final TextView tvDays = (TextView) rootView.findViewById(R.id.num_days_to_next_session); tvCountry.setText(nextRaceCountry); tvSession.setText(nextSession); new CountDownTimer(timeToNextRace, 1000){ public void onTick(long millSecondsLeft){ long days = (millSecondsLeft / (1000 * 3600 * 24)); millSecondsLeft -= days * 24 * 3600 * 1000; long hours = (millSecondsLeft / (1000 * 3600)); millSecondsLeft -= hours * 3600 * 1000; long minutes = (millSecondsLeft / (1000 * 60)); millSecondsLeft -= minutes * 60 * 1000; long seconds = (millSecondsLeft / (1000)); tvDays.setText(days + ""); tvHours.setText(hours + ""); tvMins.setText(minutes + ""); tvSecs.setText(seconds + ""); } public void onFinish(){ } }.start(); } private void nextSession(){ Calendar current = Calendar.getInstance(); Calendar race = Calendar.getInstance(); for(RaceWeekend rw : schedule){ int[] times = rw.getTimes(); race.setTimeInMillis(times[4] * 1000L); if(current.compareTo(race) < 0){ nextRaceCountry = rw.getCountry(); race.setTimeInMillis(times[0] * 1000L); if(current.compareTo(race) < 0){ timeToNextRace = (race.getTimeInMillis() - current.getTimeInMillis()); nextSession = "FP1"; //createNotificationAlarm(race.getTimeInMillis()); createNotificationAlarm(current.getTimeInMillis() + 15 * 1000); SharedPreferences pref = getActivity().getSharedPreferences(getContext().getString(R.string.Shared_Pref_Key), Context.MODE_PRIVATE); SharedPreferences.Editor prefEdit = pref.edit(); prefEdit.putString(getContext().getString(R.string.Shared_Pref_Country), nextRaceCountry); prefEdit.putString(getContext().getString(R.string.Shared_Pref_Session), nextSession); return; } race.setTimeInMillis(times[1] * 1000L); if(current.compareTo(race) < 0){ timeToNextRace = (race.getTimeInMillis() - current.getTimeInMillis()); nextSession = "FP2"; createNotificationAlarm(race.getTimeInMillis()); return; } race.setTimeInMillis(times[2] * 1000L); if(current.compareTo(race) < 0){ timeToNextRace = (race.getTimeInMillis() - current.getTimeInMillis()); nextSession = "FP3"; createNotificationAlarm(race.getTimeInMillis()); return; } race.setTimeInMillis(times[3] * 1000L); if(current.compareTo(race) < 0){ timeToNextRace = (race.getTimeInMillis() - current.getTimeInMillis()); nextSession = "Qualifying"; createNotificationAlarm(race.getTimeInMillis()); return; } race.setTimeInMillis(times[4] * 1000L); timeToNextRace = (race.getTimeInMillis() - current.getTimeInMillis()); nextSession = "Race"; createNotificationAlarm(race.getTimeInMillis()); return; } } } private void createNotificationAlarm(long time){ Intent intent = new Intent(getContext(), SessionNotification.class); PendingIntent pIntent = PendingIntent.getBroadcast(getContext(), 0, intent ,0); AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, time, pIntent); } }
UTF-8
Java
5,867
java
CountdownFragment.java
Java
[]
null
[]
package com.phillips.jake.formulaschedule; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v4.app.Fragment; import android.support.v4.app.NotificationCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.Calendar; /** * A simple {@link Fragment} subclass. */ public class CountdownFragment extends Fragment { ArrayList<RaceWeekend> schedule; public CountdownFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (getArguments() != null){ schedule = getArguments().getParcelableArrayList(MainActivity.SCHEDULE_KEY); } // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_countdown, container, false); populateView(view); return view; } private String nextSession, nextRaceCountry; private long timeToNextRace; private void populateView(View rootView){ nextSession(); TextView tvCountry = (TextView) rootView.findViewById(R.id.next_race_country); TextView tvSession = (TextView) rootView.findViewById(R.id.next_session_name); final TextView tvHours = (TextView) rootView.findViewById(R.id.num_hours_to_next_session); final TextView tvMins = (TextView) rootView.findViewById(R.id.num_min_to_next_session); final TextView tvSecs = (TextView) rootView.findViewById(R.id.num_seconds_to_next_session); final TextView tvDays = (TextView) rootView.findViewById(R.id.num_days_to_next_session); tvCountry.setText(nextRaceCountry); tvSession.setText(nextSession); new CountDownTimer(timeToNextRace, 1000){ public void onTick(long millSecondsLeft){ long days = (millSecondsLeft / (1000 * 3600 * 24)); millSecondsLeft -= days * 24 * 3600 * 1000; long hours = (millSecondsLeft / (1000 * 3600)); millSecondsLeft -= hours * 3600 * 1000; long minutes = (millSecondsLeft / (1000 * 60)); millSecondsLeft -= minutes * 60 * 1000; long seconds = (millSecondsLeft / (1000)); tvDays.setText(days + ""); tvHours.setText(hours + ""); tvMins.setText(minutes + ""); tvSecs.setText(seconds + ""); } public void onFinish(){ } }.start(); } private void nextSession(){ Calendar current = Calendar.getInstance(); Calendar race = Calendar.getInstance(); for(RaceWeekend rw : schedule){ int[] times = rw.getTimes(); race.setTimeInMillis(times[4] * 1000L); if(current.compareTo(race) < 0){ nextRaceCountry = rw.getCountry(); race.setTimeInMillis(times[0] * 1000L); if(current.compareTo(race) < 0){ timeToNextRace = (race.getTimeInMillis() - current.getTimeInMillis()); nextSession = "FP1"; //createNotificationAlarm(race.getTimeInMillis()); createNotificationAlarm(current.getTimeInMillis() + 15 * 1000); SharedPreferences pref = getActivity().getSharedPreferences(getContext().getString(R.string.Shared_Pref_Key), Context.MODE_PRIVATE); SharedPreferences.Editor prefEdit = pref.edit(); prefEdit.putString(getContext().getString(R.string.Shared_Pref_Country), nextRaceCountry); prefEdit.putString(getContext().getString(R.string.Shared_Pref_Session), nextSession); return; } race.setTimeInMillis(times[1] * 1000L); if(current.compareTo(race) < 0){ timeToNextRace = (race.getTimeInMillis() - current.getTimeInMillis()); nextSession = "FP2"; createNotificationAlarm(race.getTimeInMillis()); return; } race.setTimeInMillis(times[2] * 1000L); if(current.compareTo(race) < 0){ timeToNextRace = (race.getTimeInMillis() - current.getTimeInMillis()); nextSession = "FP3"; createNotificationAlarm(race.getTimeInMillis()); return; } race.setTimeInMillis(times[3] * 1000L); if(current.compareTo(race) < 0){ timeToNextRace = (race.getTimeInMillis() - current.getTimeInMillis()); nextSession = "Qualifying"; createNotificationAlarm(race.getTimeInMillis()); return; } race.setTimeInMillis(times[4] * 1000L); timeToNextRace = (race.getTimeInMillis() - current.getTimeInMillis()); nextSession = "Race"; createNotificationAlarm(race.getTimeInMillis()); return; } } } private void createNotificationAlarm(long time){ Intent intent = new Intent(getContext(), SessionNotification.class); PendingIntent pIntent = PendingIntent.getBroadcast(getContext(), 0, intent ,0); AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, time, pIntent); } }
5,867
0.603716
0.585989
155
36.851612
31.237652
152
false
false
0
0
0
0
0
0
0.632258
false
false
4
95390dd69b2e613797734cc123911cc6d2a30122
21,105,469,347,409
ccbaada6c26397841c185499f905a05edb0ea92c
/app/src/main/java/com/example/anushkaweerasekarage/project/Product.java
da3fc5c16fc250e9715041eb4f6b3c835feb3a76
[]
no_license
anushkaWeerasekarage/AndroidStudioSimplePizzaOrdering
https://github.com/anushkaWeerasekarage/AndroidStudioSimplePizzaOrdering
df4cfb4c5051c41f05c49f19bb8b93ac99ac70d2
48668f578e9651bcc1fa01b9b4ca8ac253fa4f33
refs/heads/master
2021-05-08T10:40:38.777000
2018-02-01T16:45:18
2018-02-01T16:45:18
119,855,608
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.anushkaweerasekarage.project; /** * Created by anushkaweerasekarage on 2017-07-29. */ public class Product { private String p_name; private double p_value; private String p_size; public Product(String name, String size, double value) { p_name = name; p_size = size; p_value = value; } String getName() { return p_name; } double getValue() { return p_value; } String getSize() { return p_size; } }
UTF-8
Java
520
java
Product.java
Java
[ { "context": "e.anushkaweerasekarage.project;\n\n/**\n * Created by anushkaweerasekarage on 2017-07-29.\n */\n\npublic class Product {\n pr", "end": 89, "score": 0.9918732047080994, "start": 69, "tag": "USERNAME", "value": "anushkaweerasekarage" } ]
null
[]
package com.example.anushkaweerasekarage.project; /** * Created by anushkaweerasekarage on 2017-07-29. */ public class Product { private String p_name; private double p_value; private String p_size; public Product(String name, String size, double value) { p_name = name; p_size = size; p_value = value; } String getName() { return p_name; } double getValue() { return p_value; } String getSize() { return p_size; } }
520
0.582692
0.567308
31
15.774194
16.019564
60
false
false
0
0
0
0
0
0
0.387097
false
false
4
547f0ca84e55a9b093f622241d4106882069cee6
2,113,123,935,601
f6a0847e11a6524536e7a3f4d8d75b992988d706
/src/dijkstra/Pi.java
81d4c0ea6950f8972ca391869f9b9176f5304b1e
[]
no_license
lukamusic/labyrinthe
https://github.com/lukamusic/labyrinthe
cd0674b1af5a81b93dbf6b438b06a3cfd749ac11
4cb71b1f032011360039e386af5cd991c48f22f6
refs/heads/master
2020-02-29T23:49:15.360000
2014-01-10T20:27:56
2014-01-10T20:27:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dijkstra; import exceptions.ExceptionGraphNotInit; import exceptions.ExceptionIsNotInGraph; import graph.Graph; import graph.Vertex; public class Pi implements PiInterface{ private int[] pi;//donnera la longueur du chemin le plus court private Graph g; public Pi(Graph g){ this.pi = new int[g.getGraphSize()]; for(int i = 0; i<g.getGraphSize();i++){ pi[i]=10000000;//valeur absurdement grande pour les utilisations courantes } this.g = g; } public int getPiOf(Vertex x) throws ExceptionGraphNotInit, ExceptionIsNotInGraph{ if(x.getGraph()==this.g){ return pi[x.getVertexValue()]; } else{ throw new ExceptionIsNotInGraph(x); } } public void setPiOf(Vertex x, int newPi) throws ExceptionGraphNotInit, ExceptionIsNotInGraph{ if(x.getGraph()==this.g){//add exception pi[x.getVertexValue()]=newPi; } else{ throw new ExceptionIsNotInGraph(x); } } }
UTF-8
Java
908
java
Pi.java
Java
[]
null
[]
package dijkstra; import exceptions.ExceptionGraphNotInit; import exceptions.ExceptionIsNotInGraph; import graph.Graph; import graph.Vertex; public class Pi implements PiInterface{ private int[] pi;//donnera la longueur du chemin le plus court private Graph g; public Pi(Graph g){ this.pi = new int[g.getGraphSize()]; for(int i = 0; i<g.getGraphSize();i++){ pi[i]=10000000;//valeur absurdement grande pour les utilisations courantes } this.g = g; } public int getPiOf(Vertex x) throws ExceptionGraphNotInit, ExceptionIsNotInGraph{ if(x.getGraph()==this.g){ return pi[x.getVertexValue()]; } else{ throw new ExceptionIsNotInGraph(x); } } public void setPiOf(Vertex x, int newPi) throws ExceptionGraphNotInit, ExceptionIsNotInGraph{ if(x.getGraph()==this.g){//add exception pi[x.getVertexValue()]=newPi; } else{ throw new ExceptionIsNotInGraph(x); } } }
908
0.721366
0.711454
38
22.894737
24.574045
94
false
false
0
0
0
0
0
0
1.842105
false
false
4
16756730c2da8c407d7d805fd3159fe3d194edcd
9,474,697,923,890
1b88907723185b11ee56f2d86a0ec637c06f2552
/core/src/main/java/com/cqzg168/scm/domain/Area.java
7829b17f664b06b4f2f68038b4e3c82ddb514c55
[]
no_license
nickcdd/zgscm
https://github.com/nickcdd/zgscm
4eda7c7ae74155cdb32f67f5727e5e24cfde0565
6901ddf1ce85b0f8419b127fb720d7c083698491
refs/heads/master
2020-03-06T22:00:35.973000
2018-03-28T06:31:35
2018-03-28T06:31:35
127,092,015
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cqzg168.scm.domain; import com.cqzg168.scm.utils.Constant; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; /** * 地区实体类 * Created by think on 2017/4/26. */ @Entity @Table(name = Constant.TABLE_PREFIX + "area") public class Area extends BaseDomain { private static final long serialVersionUID = -4166076748313820892L; /** * 名称 */ @Column(nullable = false) private String cname; /** * 父id */ @Column(nullable = false) private Long parentSid; /** * 类型:1省;2市;3区县 */ @Column(nullable = false) private Integer type; /** * 排序 */ @Column(nullable = false) private Integer sort; /** * 是否开放:0否;1是 */ @Column(nullable = false) private Integer open; public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public Long getParentSid() { return parentSid; } public void setParentSid(Long parentSid) { this.parentSid = parentSid; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public Integer getOpen() { return open; } public void setOpen(Integer open) { this.open = open; } }
UTF-8
Java
1,645
java
Area.java
Java
[ { "context": "persistence.Table;\r\n\r\n/**\r\n * 地区实体类\r\n * Created by think on 2017/4/26.\r\n */\r\n@Entity\r\n@Table(name = Consta", "end": 214, "score": 0.7290255427360535, "start": 209, "tag": "USERNAME", "value": "think" } ]
null
[]
package com.cqzg168.scm.domain; import com.cqzg168.scm.utils.Constant; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; /** * 地区实体类 * Created by think on 2017/4/26. */ @Entity @Table(name = Constant.TABLE_PREFIX + "area") public class Area extends BaseDomain { private static final long serialVersionUID = -4166076748313820892L; /** * 名称 */ @Column(nullable = false) private String cname; /** * 父id */ @Column(nullable = false) private Long parentSid; /** * 类型:1省;2市;3区县 */ @Column(nullable = false) private Integer type; /** * 排序 */ @Column(nullable = false) private Integer sort; /** * 是否开放:0否;1是 */ @Column(nullable = false) private Integer open; public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public Long getParentSid() { return parentSid; } public void setParentSid(Long parentSid) { this.parentSid = parentSid; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public Integer getOpen() { return open; } public void setOpen(Integer open) { this.open = open; } }
1,645
0.556882
0.533627
82
17.402439
14.977919
71
false
false
0
0
0
0
0
0
0.256098
false
false
4
e78ca70904a8038fe8a7741775b61639497da2e4
18,665,927,916,501
c2a560601da55067347d8644a1b16c1b38ff4969
/src/icehs/science/chapter05/VariousSumTest.java
43be4c1b88bde2f43c9d882a34ae2f77a99019c7
[]
no_license
Homeria/JAVA_EXERCISE
https://github.com/Homeria/JAVA_EXERCISE
33144c64ec84073e496c0e2e8ddfbd953f602390
a0cda9ffbc5899127baccdbeefb279a75339db5a
refs/heads/master
2021-09-03T21:52:29.064000
2018-01-12T09:03:27
2018-01-12T09:03:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package icehs.science.chapter05; public class VariousSumTest { public static void main(String[] args) { // TODO Auto-generated method stub int totalSum = 0; int oddSum = 0; int evenSum = 0; for (int i = 1 ; i <= 1000; i++) { if ((i % 2) == 0) { evenSum += i; } if ((i % 2) != 0) { oddSum += i; } } totalSum = oddSum + evenSum; System.out.println("1부터 1000까지의 합 : " + totalSum); System.out.println("1부터 1000까지 짝수들의 합 : " + evenSum); System.out.println("1부터 1000까지 홀수들의 합 : " + oddSum); } }
UHC
Java
614
java
VariousSumTest.java
Java
[]
null
[]
package icehs.science.chapter05; public class VariousSumTest { public static void main(String[] args) { // TODO Auto-generated method stub int totalSum = 0; int oddSum = 0; int evenSum = 0; for (int i = 1 ; i <= 1000; i++) { if ((i % 2) == 0) { evenSum += i; } if ((i % 2) != 0) { oddSum += i; } } totalSum = oddSum + evenSum; System.out.println("1부터 1000까지의 합 : " + totalSum); System.out.println("1부터 1000까지 짝수들의 합 : " + evenSum); System.out.println("1부터 1000까지 홀수들의 합 : " + oddSum); } }
614
0.54947
0.498233
26
19.76923
17.609673
55
false
false
0
0
0
0
0
0
2.230769
false
false
4
782f4c1232ac9cfe672bd9c13e2f9d4af5a93e19
34,136,400,090,404
8c180938931291c30edad1af6e5f7a9386d462ac
/app/src/main/java/com/ron/exploreapp/adapter/frag_toppicks_adapter.java
b808c820359abd44508bf3662c71f9665f25b3cf
[]
no_license
ronthomas25/exploreapp
https://github.com/ronthomas25/exploreapp
9b63dff0ce86d52dadc754c07fda1779ec5fa3b3
83ad96c8e8584816bc6d9987a40429dd5f3cc60d
refs/heads/master
2023-01-13T06:39:35.429000
2020-11-11T06:36:05
2020-11-11T06:36:05
280,334,077
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ron.exploreapp.adapter; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import com.ron.exploreapp.frag_toppicks.images_toppicks; import com.ron.exploreapp.frag_toppicks.overview_toppicks; import com.ron.exploreapp.frag_toppicks.review_toppicks; import com.ron.exploreapp.fragment_mostsrch.images; import com.ron.exploreapp.fragment_mostsrch.overview; import com.ron.exploreapp.fragment_mostsrch.review; public class frag_toppicks_adapter extends FragmentPagerAdapter { @NonNull int no_tab; String desc; String place; public frag_toppicks_adapter(@NonNull FragmentManager fm, int no_tab, String desc, String place) { super(fm); this.no_tab = no_tab; this.desc=desc; this.place=place; } public Fragment getItem(int position) { switch (position){ case 0: overview_toppicks overview= new overview_toppicks(); Bundle bundle=new Bundle(); bundle.putString("desc",desc); overview.setArguments(bundle); return overview; case 1: images_toppicks images= new images_toppicks(); Bundle bundle2=new Bundle(); bundle2.putString("name",place); images.setArguments(bundle2); return images; case 2: review_toppicks review= new review_toppicks(); return review; default:return null; } } @Override public int getCount() { return no_tab; } }
UTF-8
Java
1,686
java
frag_toppicks_adapter.java
Java
[]
null
[]
package com.ron.exploreapp.adapter; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import com.ron.exploreapp.frag_toppicks.images_toppicks; import com.ron.exploreapp.frag_toppicks.overview_toppicks; import com.ron.exploreapp.frag_toppicks.review_toppicks; import com.ron.exploreapp.fragment_mostsrch.images; import com.ron.exploreapp.fragment_mostsrch.overview; import com.ron.exploreapp.fragment_mostsrch.review; public class frag_toppicks_adapter extends FragmentPagerAdapter { @NonNull int no_tab; String desc; String place; public frag_toppicks_adapter(@NonNull FragmentManager fm, int no_tab, String desc, String place) { super(fm); this.no_tab = no_tab; this.desc=desc; this.place=place; } public Fragment getItem(int position) { switch (position){ case 0: overview_toppicks overview= new overview_toppicks(); Bundle bundle=new Bundle(); bundle.putString("desc",desc); overview.setArguments(bundle); return overview; case 1: images_toppicks images= new images_toppicks(); Bundle bundle2=new Bundle(); bundle2.putString("name",place); images.setArguments(bundle2); return images; case 2: review_toppicks review= new review_toppicks(); return review; default:return null; } } @Override public int getCount() { return no_tab; } }
1,686
0.65777
0.654211
53
30.792454
23.223572
102
false
false
0
0
0
0
0
0
0.716981
false
false
4
d8f56289c0c099eb5ec88448347ca4ffd08d21ae
26,774,826,185,835
8e5288001f21fc9c25f57bf46254ee8e98fa0c85
/api/src/org/labkey/api/security/permissions/AllowedForReadOnlyUser.java
feb2349802d6dc66f45d8a52e22719b36f007d18
[]
no_license
bbimber/platform
https://github.com/bbimber/platform
a0015a46a188acfcc77eb2689d34fee37982589f
74c3dfee4ac2de2469717e8da02d2c8f59ead1db
refs/heads/develop
2023-04-17T00:02:58.916000
2023-04-05T15:23:32
2023-04-05T15:23:32
254,413,705
1
0
null
true
2020-04-09T15:46:43
2020-04-09T15:46:42
2020-04-09T13:17:33
2020-04-09T14:49:44
155,202
0
0
0
null
false
false
package org.labkey.api.security.permissions; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * This annotation is used to mark permissions that are allowed for a user that is logged in as a "ReadOnly" user. */ public @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface AllowedForReadOnlyUser { }
UTF-8
Java
413
java
AllowedForReadOnlyUser.java
Java
[]
null
[]
package org.labkey.api.security.permissions; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * This annotation is used to mark permissions that are allowed for a user that is logged in as a "ReadOnly" user. */ public @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface AllowedForReadOnlyUser { }
413
0.801453
0.801453
13
30.76923
34.992645
114
false
false
0
0
0
0
0
0
0.307692
false
false
4
77ec7bac04fbca8302bf72ec113fdb12b886eeb1
26,774,826,184,108
be50ab08685c0d03b55121c3b8f0ed25bee53578
/base-broker/base-broker-admin/src/main/java/com/aiforest/cloud/broker/admin/service/impl/ReferralsServiceImpl.java
cf4cf996400a3a6fc072d0440e1678ab0db95d85
[]
no_license
panxiaochao/agent_backend
https://github.com/panxiaochao/agent_backend
467a6b43306693eb1413f9066216b9b63877b65d
6fb79575f44242e86290080303bb652528ad9973
refs/heads/master
2023-05-25T12:50:57.148000
2020-10-12T22:59:23
2020-10-12T22:59:23
645,122,822
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright (C) 2018-2019 * All rights reserved, Designed By www.aiforest.com * 注意: * 本软件为www.aiforest.com开发研制,未经购买不得使用 * 购买后可获得全部源代码(禁止转卖、分享、上传到码云、github等开源平台) * 一经发现盗用、分享等行为,将追究法律责任,后果自负 */ package com.aiforest.cloud.broker.admin.service.impl; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.aiforest.cloud.broker.common.entity.Referrals; import com.aiforest.cloud.broker.admin.mapper.ReferralsMapper; import com.aiforest.cloud.broker.admin.service.ReferralsService; import org.springframework.stereotype.Service; /** * 推荐表 * * @author aiforest * @date 2020-09-22 16:07:51 */ @Service public class ReferralsServiceImpl extends ServiceImpl<ReferralsMapper, Referrals> implements ReferralsService { @Override public IPage<Referrals> page1(IPage<Referrals> page, Referrals referrals) { return baseMapper.selectPage1(page, referrals); } }
UTF-8
Java
1,105
java
ReferralsServiceImpl.java
Java
[ { "context": "work.stereotype.Service;\n\n/**\n * 推荐表\n *\n * @author aiforest\n * @date 2020-09-22 16:07:51\n */\n@Service\npublic ", "end": 646, "score": 0.9997031688690186, "start": 638, "tag": "USERNAME", "value": "aiforest" } ]
null
[]
/** * Copyright (C) 2018-2019 * All rights reserved, Designed By www.aiforest.com * 注意: * 本软件为www.aiforest.com开发研制,未经购买不得使用 * 购买后可获得全部源代码(禁止转卖、分享、上传到码云、github等开源平台) * 一经发现盗用、分享等行为,将追究法律责任,后果自负 */ package com.aiforest.cloud.broker.admin.service.impl; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.aiforest.cloud.broker.common.entity.Referrals; import com.aiforest.cloud.broker.admin.mapper.ReferralsMapper; import com.aiforest.cloud.broker.admin.service.ReferralsService; import org.springframework.stereotype.Service; /** * 推荐表 * * @author aiforest * @date 2020-09-22 16:07:51 */ @Service public class ReferralsServiceImpl extends ServiceImpl<ReferralsMapper, Referrals> implements ReferralsService { @Override public IPage<Referrals> page1(IPage<Referrals> page, Referrals referrals) { return baseMapper.selectPage1(page, referrals); } }
1,105
0.78836
0.762963
31
29.483871
28.637751
111
false
false
0
0
0
0
0
0
0.548387
false
false
4
886f2fb3c7a2b741408cc1ca4c0bc1de16e807cd
34,239,479,305,601
49f120b9a2173d4ce4113a46f448a9f5daf776f0
/app/src/main/java/com/yahoo/mobile/client/android/atom/io/JsonRequestBuilder.java
530dbffb330b1a9cb5bb4193f883ce98f126206a
[]
no_license
iTimeTraveler/DecompileNewsDigest
https://github.com/iTimeTraveler/DecompileNewsDigest
b59f083eb99561faa7a5ad0be39076e007de9df7
bbffbe9f650c6de51ab0c353ee7b047f3222d439
refs/heads/master
2020-04-24T07:53:12.845000
2019-03-02T14:42:25
2019-03-02T14:42:25
171,812,365
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yahoo.mobile.client.android.atom.io; import android.net.Uri.Builder; import com.android.volley.Response; import com.android.volley.Response; import com.android.volley.DefaultRetryPolicy; import com.android.volley.RetryPolicy; import java.util.Map; import org.apache.commons.lang3.StringUtils; /* renamed from: com.yahoo.mobile.client.android.atom.io.k */ public class JsonRequestBuilder { /* renamed from: a */ public static final String f5756a = JsonRequestBuilder.class.getSimpleName(); /* renamed from: b */ private String f5757b; /* renamed from: c */ private String f5758c; /* renamed from: d */ private Response.Listener<String> f5759d; /* renamed from: e */ private Response.ErrorListener f5760e; /* renamed from: f */ private Map<String, String> f5761f; /* renamed from: g */ private RetryPolicy f5762g = new DefaultRetryPolicy(10000, 1, 1.0f); /* renamed from: h */ private int f5763h = 0; /* renamed from: a */ public JsonRequestBuilder mo9104a(Response.Listener<String> c0441t) { this.f5759d = c0441t; return this; } /* renamed from: a */ public JsonRequestBuilder mo9103a(Response.ErrorListener c0440s) { this.f5760e = c0440s; return this; } /* renamed from: a */ public JsonRequestBuilder mo9105a(String str) { this.f5757b = str; return this; } /* renamed from: b */ public JsonRequestBuilder mo9108b(String str) { this.f5758c = str; return this; } /* renamed from: a */ public JsonRequestBuilder mo9106a(Map<String, String> map) { this.f5761f = map; return this; } /* renamed from: a */ public JsonStringRequest mo9107a() { m8977b(); JsonStringRequest jsonStringRequest = new JsonStringRequest(this.f5763h, m8978c(), this.f5759d, this.f5760e); if (this.f5763h == 1) { jsonStringRequest.mo9109a(this.f5761f); } if (this.f5762g != null) { jsonStringRequest.setRetryPolicy(this.f5762g); } return jsonStringRequest; } /* renamed from: b */ private void m8977b() { if (this.f5757b == null) { throw new IllegalStateException("Builder must set authority."); } else if (this.f5759d == null) { throw new IllegalStateException("Builder must set listener."); } } /* renamed from: c */ private String m8978c() { Builder builder = new Builder(); builder.authority(this.f5757b).scheme("https"); if (StringUtils.isNotEmpty(this.f5758c)) { builder.appendEncodedPath(this.f5758c); } if (this.f5763h == 0 && this.f5761f != null && this.f5761f.size() > 0) { for (String str : this.f5761f.keySet()) { builder.appendQueryParameter(str, (String) this.f5761f.get(str)); } } return builder.build().toString(); } }
UTF-8
Java
3,002
java
JsonRequestBuilder.java
Java
[]
null
[]
package com.yahoo.mobile.client.android.atom.io; import android.net.Uri.Builder; import com.android.volley.Response; import com.android.volley.Response; import com.android.volley.DefaultRetryPolicy; import com.android.volley.RetryPolicy; import java.util.Map; import org.apache.commons.lang3.StringUtils; /* renamed from: com.yahoo.mobile.client.android.atom.io.k */ public class JsonRequestBuilder { /* renamed from: a */ public static final String f5756a = JsonRequestBuilder.class.getSimpleName(); /* renamed from: b */ private String f5757b; /* renamed from: c */ private String f5758c; /* renamed from: d */ private Response.Listener<String> f5759d; /* renamed from: e */ private Response.ErrorListener f5760e; /* renamed from: f */ private Map<String, String> f5761f; /* renamed from: g */ private RetryPolicy f5762g = new DefaultRetryPolicy(10000, 1, 1.0f); /* renamed from: h */ private int f5763h = 0; /* renamed from: a */ public JsonRequestBuilder mo9104a(Response.Listener<String> c0441t) { this.f5759d = c0441t; return this; } /* renamed from: a */ public JsonRequestBuilder mo9103a(Response.ErrorListener c0440s) { this.f5760e = c0440s; return this; } /* renamed from: a */ public JsonRequestBuilder mo9105a(String str) { this.f5757b = str; return this; } /* renamed from: b */ public JsonRequestBuilder mo9108b(String str) { this.f5758c = str; return this; } /* renamed from: a */ public JsonRequestBuilder mo9106a(Map<String, String> map) { this.f5761f = map; return this; } /* renamed from: a */ public JsonStringRequest mo9107a() { m8977b(); JsonStringRequest jsonStringRequest = new JsonStringRequest(this.f5763h, m8978c(), this.f5759d, this.f5760e); if (this.f5763h == 1) { jsonStringRequest.mo9109a(this.f5761f); } if (this.f5762g != null) { jsonStringRequest.setRetryPolicy(this.f5762g); } return jsonStringRequest; } /* renamed from: b */ private void m8977b() { if (this.f5757b == null) { throw new IllegalStateException("Builder must set authority."); } else if (this.f5759d == null) { throw new IllegalStateException("Builder must set listener."); } } /* renamed from: c */ private String m8978c() { Builder builder = new Builder(); builder.authority(this.f5757b).scheme("https"); if (StringUtils.isNotEmpty(this.f5758c)) { builder.appendEncodedPath(this.f5758c); } if (this.f5763h == 0 && this.f5761f != null && this.f5761f.size() > 0) { for (String str : this.f5761f.keySet()) { builder.appendQueryParameter(str, (String) this.f5761f.get(str)); } } return builder.build().toString(); } }
3,002
0.620253
0.555963
96
30.270834
23.064438
117
false
false
0
0
0
0
0
0
0.479167
false
false
4
33daef89f9976ade12430da804207703f270e0a0
36,404,142,806,743
7257d7f5ae4dc077930db07bef4749f7b52d8858
/src/SMS/DBInteface.java
7b9160b51ac86a00418976ef4cf30a14b6f1f684
[]
no_license
wattale/SMS
https://github.com/wattale/SMS
bf3f9eb67773592fa2fc0d83eb6c5484c911cd79
9dfcc91747b5785c12530c2e184b617ebc1ad4dc
refs/heads/master
2021-01-19T18:00:22.404000
2013-08-02T20:33:15
2013-08-02T20:33:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package SMS; /** * * @author Lasitha */ import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.sql.*; import java.util.Vector; import javax.imageio.ImageIO; public class DBInteface { public Vector getStudentRec(){ System.out.println("Database Interface is trying to get student Records... "); Vector studentRec = null; ResultSet resultSet; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); System.out.println("Got the connection.... to the data base.. "); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); resultSet = statement.executeQuery("select * from students order by Student_index ASC"); System.out.println("Got the result set.... "); studentRec = new Vector(); while (resultSet.next()) { System.out.println("putting... Students in to the vector... "); Student tmpStudent = new Student(resultSet.getString("Student_index"), resultSet.getString("Namewith_in"), resultSet.getString("FName"), resultSet.getString("DateofB"), resultSet.getString("Gender"), resultSet.getString("HomeADD"), resultSet.getString("Telephone"), null); studentRec.addElement(tmpStudent); System.out.println("put a student.. "); } return studentRec; } catch (Exception ex) { System.out.println("Got an Exceptiong while entering to the file.. ."); return studentRec; } } public boolean upDateInfo(Student student){ boolean upDated = false; try{ String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); //Statement stmt = connection.createStatement(); Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate("use StudentsManagement"); PreparedStatement PStmt = connection.prepareStatement("update students set Namewith_in = '"+student.getNameWithIn()+"', FName = '"+student.getFName()+"', DateofB = '"+student.getDateOfBirth()+"', Gender = '"+student.getGender()+"', HomeADD = '"+student.getHomeAddress()+"', Telephone = '"+student.getTelephone()+"' where Student_index ='"+student.getIndex()+"'"); PStmt.executeUpdate(); ResultSet tmp=stmt.executeQuery("select * from students where Student_index='"+student.getIndex()+"' for update"); if(tmp.first()){ tmp.updateBytes("photo", student.getImage()); tmp.updateRow(); }else{ System.out.println("not validddddddd"); } tmp.close(); upDated = true; }catch(Exception e){ System.out.println("UPDATE ERROR");} upDated = true; return upDated; } public boolean changePassWord(String index,String newPW){ boolean pWchanged = false; try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); PreparedStatement PStmt = connection.prepareStatement("update loginStdnts set Password = '"+newPW+"' where Student_index ='"+index+"'"); PStmt.executeUpdate(); pWchanged = true; }catch(Exception ex){ ex.printStackTrace(); } return pWchanged; } public LoginDetails login(String userName, String passWord){ LoginDetails details = new LoginDetails(false, ""); try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); ResultSet rs = statement.executeQuery("SELECT * from loginStdnts WHERE Student_index ='"+ userName+"'" + "AND Password ='" +passWord+"'"); if(rs.next()){ details= new LoginDetails(true,"student"); }else{ rs = statement.executeQuery("SELECT * from loginAdmin WHERE User_Name ='"+ userName+"'" + "AND Password ='" +passWord+"'"); if(rs.next()){ details = new LoginDetails(true,"admin"); } } }catch(Exception ex){ // ex.printStackTrace(); return details; } return details; } public boolean isStudent(String index){ boolean isIn = false; try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); ResultSet rs = statement.executeQuery("SELECT * from students WHERE Student_index ='"+index+"'"); if(rs.next()){ isIn = true; }else return false; }catch(Exception ex){ ex.printStackTrace(); } return isIn; } public boolean addStudent(String index, String nameWithIn, String fName, String dateOfBirth, String gender, String homeAdd, String telephone){ boolean isAdd = false; try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); System.out.println("Inside Add logic...."); if(!isStudent(index)){ System.out.println("Got student is not in the login table..."); PreparedStatement PStmt = connection.prepareStatement("insert into students values (?,?,?,?,?,?,?,?)"); System.out.println("setting a new sign up"); setNewSignUP(index, fName+"@sms", "student"); PStmt.setString(1, index); PStmt.setString(2, nameWithIn); PStmt.setString(3, fName); PStmt.setString(4, dateOfBirth); PStmt.setString(5, gender); PStmt.setString(6, homeAdd); PStmt.setString(7, telephone); PStmt.setBytes(8, selectPicture()); PStmt.executeUpdate(); isAdd = true; } } catch(Exception ex){ ex.printStackTrace(); } return isAdd; } public byte[] selectPicture(){ byte[] pic = null; try{ BufferedImage image = ImageIO.read(new File("smile.JPG")); pic = imageToBytes(image); }catch(Exception ex){ System.out.println("Select pic Exception... "); ex.printStackTrace(); } return pic; } public Student getStudent(String index){ Student student = new Student("","","","","","",""); try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); ResultSet rs = null; rs = statement.executeQuery("SELECT * from students WHERE Student_index ='"+index+"'" ); if(rs.next()){ student = new Student((String) rs.getString("Student_index"),(String) rs.getString("Namewith_in"),(String) rs.getString("FName"),(String) rs.getString("DateofB"),(String) rs.getString("Gender"),(String) rs.getString("HomeADD"),(String) rs.getString("Telephone"),rs.getBytes("photo")); }else{ student.setIsValid(false); } }catch(Exception ex){ ex.printStackTrace(); } return student; } public boolean setNewSignUP(String userName, String passWord, String type){ boolean isSignUP = false; if(type.equalsIgnoreCase("student")){ try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); ResultSet rs = null; rs = statement.executeQuery("SELECT * from loginStdnts WHERE Student_index ='"+ userName+"'" ); if(!rs.next()){ // System.out.println("Student is now being added..."); PreparedStatement PStmt = connection.prepareStatement("insert into loginStdnts values (?,?)"); PStmt.setString(1,userName); PStmt.setString(2,passWord); PStmt.executeUpdate(); isSignUP = true; } }catch(Exception ex){ ex.printStackTrace(); } }else{ try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); //System.out.println("Just about to add an admin ...."); ResultSet rs = null; rs = statement.executeQuery("SELECT * from loginAdmin WHERE User_Name ='"+ userName+"'" ); if(!rs.next()){ PreparedStatement PStmt = connection.prepareStatement("insert into loginAdmin values (?,?)"); PStmt.setString(1,userName); PStmt.setString(2,passWord); PStmt.executeUpdate(); //System.out.println("Successfully added admin..."); isSignUP = true; } }catch(Exception ex){ ex.printStackTrace(); } } return isSignUP; } public byte[] imageToBytes(BufferedImage img){ byte[] imageInByte = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try{ ImageIO.write( img, "jpg", baos ); baos.flush(); imageInByte = baos.toByteArray(); baos.close();} catch(Exception e){ } return imageInByte; } public BufferedImage bytesToImage(byte[] byteImage){ BufferedImage bImageFromConvert = null; InputStream in = new ByteArrayInputStream(byteImage); try{ bImageFromConvert = ImageIO.read(in); }catch(Exception e){ System.out.println("byte array error"); } return bImageFromConvert; } }
UTF-8
Java
12,662
java
DBInteface.java
Java
[ { "context": "n the editor.\n */\n\npackage SMS;\n\n/**\n *\n * @author Lasitha\n */\nimport java.awt.image.BufferedImage;\nimport j", "end": 140, "score": 0.9996079802513123, "start": 133, "tag": "NAME", "value": "Lasitha" }, { "context": "ed;\n }\n \n public LoginDetails login(String userName, String passWord){\n LoginDetails details = n", "end": 4283, "score": 0.9897834658622742, "start": 4275, "tag": "USERNAME", "value": "userName" }, { "context": "SELECT * from loginStdnts WHERE Student_index ='\"+ userName+\"'\" + \"AND Password ='\" +passWord+\"'\");\n ", "end": 4835, "score": 0.9946649074554443, "start": 4827, "tag": "USERNAME", "value": "userName" }, { "context": "dent_index ='\"+ userName+\"'\" + \"AND Password ='\" +passWord+\"'\");\n if(rs.next()){\n ", "end": 4865, "score": 0.9295171499252319, "start": 4861, "tag": "PASSWORD", "value": "pass" }, { "context": "ery(\"SELECT * from loginAdmin WHERE User_Name ='\"+ userName+\"'\" + \"AND Password ='\" +passWord+\"'\");\n ", "end": 5109, "score": 0.9928315877914429, "start": 5101, "tag": "USERNAME", "value": "userName" }, { "context": " User_Name ='\"+ userName+\"'\" + \"AND Password ='\" +passWord+\"'\");\n if(rs.next()){\n ", "end": 5139, "score": 0.5598502159118652, "start": 5135, "tag": "PASSWORD", "value": "pass" }, { "context": " \n \n \n public boolean setNewSignUP(String userName, String passWord, String type){\n boolean i", "end": 9499, "score": 0.9586677551269531, "start": 9491, "tag": "USERNAME", "value": "userName" }, { "context": "s (?,?)\");\n PStmt.setString(1,userName);\n PStmt.setString(2,passWord", "end": 10431, "score": 0.9913551211357117, "start": 10423, "tag": "USERNAME", "value": "userName" }, { "context": "ery(\"SELECT * from loginAdmin WHERE User_Name ='\"+ userName+\"'\" );\n if(!rs.next()){\n ", "end": 11279, "score": 0.9644284248352051, "start": 11271, "tag": "USERNAME", "value": "userName" }, { "context": "s (?,?)\");\n PStmt.setString(1,userName);\n PStmt.setString(2,passWord", "end": 11480, "score": 0.9797113537788391, "start": 11472, "tag": "USERNAME", "value": "userName" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package SMS; /** * * @author Lasitha */ import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.sql.*; import java.util.Vector; import javax.imageio.ImageIO; public class DBInteface { public Vector getStudentRec(){ System.out.println("Database Interface is trying to get student Records... "); Vector studentRec = null; ResultSet resultSet; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); System.out.println("Got the connection.... to the data base.. "); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); resultSet = statement.executeQuery("select * from students order by Student_index ASC"); System.out.println("Got the result set.... "); studentRec = new Vector(); while (resultSet.next()) { System.out.println("putting... Students in to the vector... "); Student tmpStudent = new Student(resultSet.getString("Student_index"), resultSet.getString("Namewith_in"), resultSet.getString("FName"), resultSet.getString("DateofB"), resultSet.getString("Gender"), resultSet.getString("HomeADD"), resultSet.getString("Telephone"), null); studentRec.addElement(tmpStudent); System.out.println("put a student.. "); } return studentRec; } catch (Exception ex) { System.out.println("Got an Exceptiong while entering to the file.. ."); return studentRec; } } public boolean upDateInfo(Student student){ boolean upDated = false; try{ String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); //Statement stmt = connection.createStatement(); Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate("use StudentsManagement"); PreparedStatement PStmt = connection.prepareStatement("update students set Namewith_in = '"+student.getNameWithIn()+"', FName = '"+student.getFName()+"', DateofB = '"+student.getDateOfBirth()+"', Gender = '"+student.getGender()+"', HomeADD = '"+student.getHomeAddress()+"', Telephone = '"+student.getTelephone()+"' where Student_index ='"+student.getIndex()+"'"); PStmt.executeUpdate(); ResultSet tmp=stmt.executeQuery("select * from students where Student_index='"+student.getIndex()+"' for update"); if(tmp.first()){ tmp.updateBytes("photo", student.getImage()); tmp.updateRow(); }else{ System.out.println("not validddddddd"); } tmp.close(); upDated = true; }catch(Exception e){ System.out.println("UPDATE ERROR");} upDated = true; return upDated; } public boolean changePassWord(String index,String newPW){ boolean pWchanged = false; try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); PreparedStatement PStmt = connection.prepareStatement("update loginStdnts set Password = '"+newPW+"' where Student_index ='"+index+"'"); PStmt.executeUpdate(); pWchanged = true; }catch(Exception ex){ ex.printStackTrace(); } return pWchanged; } public LoginDetails login(String userName, String passWord){ LoginDetails details = new LoginDetails(false, ""); try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); ResultSet rs = statement.executeQuery("SELECT * from loginStdnts WHERE Student_index ='"+ userName+"'" + "AND Password ='" +<PASSWORD>Word+"'"); if(rs.next()){ details= new LoginDetails(true,"student"); }else{ rs = statement.executeQuery("SELECT * from loginAdmin WHERE User_Name ='"+ userName+"'" + "AND Password ='" +<PASSWORD>Word+"'"); if(rs.next()){ details = new LoginDetails(true,"admin"); } } }catch(Exception ex){ // ex.printStackTrace(); return details; } return details; } public boolean isStudent(String index){ boolean isIn = false; try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); ResultSet rs = statement.executeQuery("SELECT * from students WHERE Student_index ='"+index+"'"); if(rs.next()){ isIn = true; }else return false; }catch(Exception ex){ ex.printStackTrace(); } return isIn; } public boolean addStudent(String index, String nameWithIn, String fName, String dateOfBirth, String gender, String homeAdd, String telephone){ boolean isAdd = false; try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); System.out.println("Inside Add logic...."); if(!isStudent(index)){ System.out.println("Got student is not in the login table..."); PreparedStatement PStmt = connection.prepareStatement("insert into students values (?,?,?,?,?,?,?,?)"); System.out.println("setting a new sign up"); setNewSignUP(index, fName+"@sms", "student"); PStmt.setString(1, index); PStmt.setString(2, nameWithIn); PStmt.setString(3, fName); PStmt.setString(4, dateOfBirth); PStmt.setString(5, gender); PStmt.setString(6, homeAdd); PStmt.setString(7, telephone); PStmt.setBytes(8, selectPicture()); PStmt.executeUpdate(); isAdd = true; } } catch(Exception ex){ ex.printStackTrace(); } return isAdd; } public byte[] selectPicture(){ byte[] pic = null; try{ BufferedImage image = ImageIO.read(new File("smile.JPG")); pic = imageToBytes(image); }catch(Exception ex){ System.out.println("Select pic Exception... "); ex.printStackTrace(); } return pic; } public Student getStudent(String index){ Student student = new Student("","","","","","",""); try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); ResultSet rs = null; rs = statement.executeQuery("SELECT * from students WHERE Student_index ='"+index+"'" ); if(rs.next()){ student = new Student((String) rs.getString("Student_index"),(String) rs.getString("Namewith_in"),(String) rs.getString("FName"),(String) rs.getString("DateofB"),(String) rs.getString("Gender"),(String) rs.getString("HomeADD"),(String) rs.getString("Telephone"),rs.getBytes("photo")); }else{ student.setIsValid(false); } }catch(Exception ex){ ex.printStackTrace(); } return student; } public boolean setNewSignUP(String userName, String passWord, String type){ boolean isSignUP = false; if(type.equalsIgnoreCase("student")){ try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); ResultSet rs = null; rs = statement.executeQuery("SELECT * from loginStdnts WHERE Student_index ='"+ userName+"'" ); if(!rs.next()){ // System.out.println("Student is now being added..."); PreparedStatement PStmt = connection.prepareStatement("insert into loginStdnts values (?,?)"); PStmt.setString(1,userName); PStmt.setString(2,passWord); PStmt.executeUpdate(); isSignUP = true; } }catch(Exception ex){ ex.printStackTrace(); } }else{ try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection connection = DriverManager.getConnection(url, "root", ""); Statement statement = connection.createStatement(); statement.executeUpdate("use StudentsManagement"); //System.out.println("Just about to add an admin ...."); ResultSet rs = null; rs = statement.executeQuery("SELECT * from loginAdmin WHERE User_Name ='"+ userName+"'" ); if(!rs.next()){ PreparedStatement PStmt = connection.prepareStatement("insert into loginAdmin values (?,?)"); PStmt.setString(1,userName); PStmt.setString(2,passWord); PStmt.executeUpdate(); //System.out.println("Successfully added admin..."); isSignUP = true; } }catch(Exception ex){ ex.printStackTrace(); } } return isSignUP; } public byte[] imageToBytes(BufferedImage img){ byte[] imageInByte = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try{ ImageIO.write( img, "jpg", baos ); baos.flush(); imageInByte = baos.toByteArray(); baos.close();} catch(Exception e){ } return imageInByte; } public BufferedImage bytesToImage(byte[] byteImage){ BufferedImage bImageFromConvert = null; InputStream in = new ByteArrayInputStream(byteImage); try{ bImageFromConvert = ImageIO.read(in); }catch(Exception e){ System.out.println("byte array error"); } return bImageFromConvert; } }
12,674
0.540278
0.536487
346
35.595375
39.737919
376
false
false
0
0
0
0
0
0
0.734104
false
false
4
649ae39b655011d0751d33387216fef5e0e0c787
23,433,341,634,990
3357386e1bc8b4550852a5ff7707dc66cf06598e
/pet-clinic-data/src/main/java/com/rabba007whizz/petclinic/services/PetTypeService.java
6e35a0a4caa3f63336a8d8d81b7e638e1bd947ab
[]
no_license
rabba007/raalam-pet-clinic
https://github.com/rabba007/raalam-pet-clinic
8c3b8a746cd08d278f1c484bf3cab18b2b5ad647
663bddd89eef50874e331dc33ceb40def771f418
refs/heads/master
2020-04-30T06:12:39.085000
2019-05-16T01:53:58
2019-05-16T01:53:58
176,645,403
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rabba007whizz.petclinic.services; import com.rabba007whizz.petclinic.model.PetType; public interface PetTypeService extends CrudService<PetType, Long> { }
UTF-8
Java
170
java
PetTypeService.java
Java
[]
null
[]
package com.rabba007whizz.petclinic.services; import com.rabba007whizz.petclinic.model.PetType; public interface PetTypeService extends CrudService<PetType, Long> { }
170
0.829412
0.794118
7
23.285715
27.400284
68
false
false
0
0
0
0
0
0
0.428571
false
false
4
e668b313abfdad4299ac885ded66df9e35eb7c81
34,445,637,739,710
a90f48b0dda9c88bb912f3c6e410a700c95690b5
/src/test/java/tests/RegistrationAndUploadLogoTest.java
31062be303aec9e18e7df22f4c8caf5001c2826b
[]
no_license
prafair/TestAssetTestNG
https://github.com/prafair/TestAssetTestNG
8f0c2fde020bd9b8e8edaeeeec8f20de5dea9929
a9bd77e7996ff5722abee8c1b3c93a9115b09e44
refs/heads/master
2020-04-19T16:49:09.469000
2019-05-09T13:39:50
2019-05-09T13:39:50
168,315,541
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tests; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.*; import pages.LogoPage; import pages.RegistrationPage; import java.awt.*; import static utils.GenerateEmailClass.gen_email; import static utils.newClickClass.retryingFindClick; /***************************************************************************** * Description: Tests for registration on http://iknow.travel using generated email * and upload logo picture of profile on that site. *******************************************************************************/ public class RegistrationAndUploadLogoTest { //-----------------------------------Variables----------------------------------- public static WebDriver driver; public static RegistrationPage ObjRegistrationPage; public static LogoPage ObjLogoPage; public String testURL = "http://iknow.travel"; //-----------------------------------Test Setup----------------------------------- @BeforeClass (description = "Test Setup: Open http://iknow.travel and go to registration page") public void setupTest () { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+ "\\src\\main\\resources\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.navigate().to(testURL); String title = driver.getTitle(); System.out.println("Page Title: " + title); Assert.assertEquals(title, "iknow.travel", "Title assertion is failed"); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='b-navbar__hamburger']"))); retryingFindClick(driver, By.xpath("//a[@class='b-navbar__hamburger']")); wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/login']"))); retryingFindClick(driver, By.xpath("//a[@href='/login']")); wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/registration']"))); retryingFindClick(driver, By.xpath("//a[@href='/registration']")); wait.until(ExpectedConditions.titleIs("Регистрация — iknow.travel")); ObjRegistrationPage = new RegistrationPage(driver); ObjLogoPage = new LogoPage(driver); } //-----------------------------------Tests----------------------------------- @Test (description = "Test for registration using generated email") public void registrationTest() { ObjRegistrationPage.enterGeneratedEmail(); ObjRegistrationPage.enterPassword(); ObjRegistrationPage.clickOnSubmitButton(); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.titleIs("iknow.travel")); wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//i[@class='br-icon-hamburger']"))); retryingFindClick(driver, By.xpath("//i[@class='br-icon-hamburger']")); wait.until(ExpectedConditions.elementToBeClickable(By.className("b-side-menu__side-menu-link"))); retryingFindClick(driver, By.className("b-side-menu__side-menu-link")); String actual_email = wait.until(ExpectedConditions.presenceOfElementLocated(By .xpath("//input[@placeholder='Ваш e-mail']"))) .getAttribute("value"); System.out.println("Actual Email: " + actual_email); System.out.println("Expected Email: " + gen_email); Assert.assertEquals(actual_email, gen_email, "E-mails don't match."); } @Test (description = "Test for upload logo") public void uploadLogoTest() throws InterruptedException, AWTException { WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Обложка и аватар"))); retryingFindClick(driver, By.linkText("Обложка и аватар")); wait.until(ExpectedConditions.elementToBeClickable(By.className("dz-default"))); retryingFindClick(driver, By.className("dz-default")); ObjLogoPage.uploadLogo(); ObjLogoPage.saveLogo(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".b-full-user__portrait"))); System.out.println("Logo is visible"); } //-----------------------------------Test Teardown----------------------------------- @AfterClass public void teardownTest (){ driver.quit(); } }
UTF-8
Java
4,695
java
RegistrationAndUploadLogoTest.java
Java
[]
null
[]
package tests; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.*; import pages.LogoPage; import pages.RegistrationPage; import java.awt.*; import static utils.GenerateEmailClass.gen_email; import static utils.newClickClass.retryingFindClick; /***************************************************************************** * Description: Tests for registration on http://iknow.travel using generated email * and upload logo picture of profile on that site. *******************************************************************************/ public class RegistrationAndUploadLogoTest { //-----------------------------------Variables----------------------------------- public static WebDriver driver; public static RegistrationPage ObjRegistrationPage; public static LogoPage ObjLogoPage; public String testURL = "http://iknow.travel"; //-----------------------------------Test Setup----------------------------------- @BeforeClass (description = "Test Setup: Open http://iknow.travel and go to registration page") public void setupTest () { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+ "\\src\\main\\resources\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.navigate().to(testURL); String title = driver.getTitle(); System.out.println("Page Title: " + title); Assert.assertEquals(title, "iknow.travel", "Title assertion is failed"); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='b-navbar__hamburger']"))); retryingFindClick(driver, By.xpath("//a[@class='b-navbar__hamburger']")); wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/login']"))); retryingFindClick(driver, By.xpath("//a[@href='/login']")); wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/registration']"))); retryingFindClick(driver, By.xpath("//a[@href='/registration']")); wait.until(ExpectedConditions.titleIs("Регистрация — iknow.travel")); ObjRegistrationPage = new RegistrationPage(driver); ObjLogoPage = new LogoPage(driver); } //-----------------------------------Tests----------------------------------- @Test (description = "Test for registration using generated email") public void registrationTest() { ObjRegistrationPage.enterGeneratedEmail(); ObjRegistrationPage.enterPassword(); ObjRegistrationPage.clickOnSubmitButton(); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.titleIs("iknow.travel")); wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//i[@class='br-icon-hamburger']"))); retryingFindClick(driver, By.xpath("//i[@class='br-icon-hamburger']")); wait.until(ExpectedConditions.elementToBeClickable(By.className("b-side-menu__side-menu-link"))); retryingFindClick(driver, By.className("b-side-menu__side-menu-link")); String actual_email = wait.until(ExpectedConditions.presenceOfElementLocated(By .xpath("//input[@placeholder='Ваш e-mail']"))) .getAttribute("value"); System.out.println("Actual Email: " + actual_email); System.out.println("Expected Email: " + gen_email); Assert.assertEquals(actual_email, gen_email, "E-mails don't match."); } @Test (description = "Test for upload logo") public void uploadLogoTest() throws InterruptedException, AWTException { WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Обложка и аватар"))); retryingFindClick(driver, By.linkText("Обложка и аватар")); wait.until(ExpectedConditions.elementToBeClickable(By.className("dz-default"))); retryingFindClick(driver, By.className("dz-default")); ObjLogoPage.uploadLogo(); ObjLogoPage.saveLogo(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".b-full-user__portrait"))); System.out.println("Logo is visible"); } //-----------------------------------Test Teardown----------------------------------- @AfterClass public void teardownTest (){ driver.quit(); } }
4,695
0.624597
0.623307
105
43.304764
33.394073
108
false
false
0
0
0
0
0
0
0.685714
false
false
4
e1a2058e9b304880fd180a915fa886a8367a1ca0
36,292,473,666,326
fc5669aef52689492318eee191cf6302084a0684
/src/dex/DexTypeIdList.java
9e3197e03ee2be71cb310b911d800a1dafa3fa79
[]
no_license
creativeNecessary/apk_shell_maker
https://github.com/creativeNecessary/apk_shell_maker
11443ce290ffe05fb4f6e8ef006083110031e195
cfc3ae5660da5404e3d043b5af9380d95f7e9d12
refs/heads/master
2020-03-24T00:05:22.664000
2018-07-25T10:14:08
2018-07-25T10:14:08
142,272,676
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dex; import util.ByteUtil; import util.FileUtil; import java.util.ArrayList; public class DexTypeIdList extends DexItem{ public static int ITEM_LENGTH = 4; private DexTypeIdList(DexHeader dexHeader) { super(dexHeader); originDataList = new ArrayList<>(); int start_off = dexHeader.getTypeIdsOff(); int size = dexHeader.getTypeIdsSize(); int length =size * ITEM_LENGTH; bytes = ByteUtil.getByteArray(getDexBytes(),start_off,length); for (int i=0 ;i< size ; i++){ int item_start = start_off + (i * ITEM_LENGTH); byte [] item = ByteUtil.getByteArray(getDexBytes(),item_start,ITEM_LENGTH); originDataList.add(new DexOriginData(item_start,ITEM_LENGTH,item)); } } public static DexTypeIdList init(DexHeader dexHeader) { return new DexTypeIdList(dexHeader); } }
UTF-8
Java
901
java
DexTypeIdList.java
Java
[]
null
[]
package dex; import util.ByteUtil; import util.FileUtil; import java.util.ArrayList; public class DexTypeIdList extends DexItem{ public static int ITEM_LENGTH = 4; private DexTypeIdList(DexHeader dexHeader) { super(dexHeader); originDataList = new ArrayList<>(); int start_off = dexHeader.getTypeIdsOff(); int size = dexHeader.getTypeIdsSize(); int length =size * ITEM_LENGTH; bytes = ByteUtil.getByteArray(getDexBytes(),start_off,length); for (int i=0 ;i< size ; i++){ int item_start = start_off + (i * ITEM_LENGTH); byte [] item = ByteUtil.getByteArray(getDexBytes(),item_start,ITEM_LENGTH); originDataList.add(new DexOriginData(item_start,ITEM_LENGTH,item)); } } public static DexTypeIdList init(DexHeader dexHeader) { return new DexTypeIdList(dexHeader); } }
901
0.648169
0.645949
33
26.30303
25.960909
87
false
false
0
0
0
0
0
0
0.69697
false
false
4
a4b569fdfa1f73674980febdf7a46f6bf758fc7b
31,525,060,017,377
56e1f1f65355a3d44f0683bc24ebb51108034253
/src/test/java/com/training/cleancode/e04/StackTest.java
e0ffdb906fc356d645ad10c0088a4ecdacf5d642
[]
no_license
arya-pish/clean-code
https://github.com/arya-pish/clean-code
3179899e09d027963af3383447b1f3b5a40bfc96
0bd86f93cd1b746fd2a6bfaa04f2228b80ca2e18
refs/heads/master
2021-09-12T22:09:00.952000
2018-04-21T13:58:40
2018-04-21T13:58:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.training.cleancode.e04; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * @author Arya Pishgah (pishgah@gamelectronics.com) 18/03/2018 */ public class StackTest { private Stack stack; @Before public void setUp() throws Exception { stack = StackImpl.newInstance(3); } @Test public void newlyStackIsEmpty() throws Exception { assertTrue(stack.isEmpty()); assertEquals(0, stack.size()); } @Test public void pushIntoStackIncreaseTheSizeOfStack() throws Exception { stack.push(1); assertEquals(1 , stack.size()); stack.push(4); assertEquals(2, stack.size()); } @Test public void popFromStackDecreaseTheSizeOfStack() throws Exception { stack.push(3); stack.push(8); assertEquals(2, stack.size()); stack.pop(); assertEquals(1, stack.size()); stack.pop(); assertEquals(0, stack.size()); } @Test public void pushOneAndTwo_popTwoAndOne() throws Exception { stack.push(1); stack.push(2); assertEquals(2, stack.pop()); assertEquals(1, stack.pop()); } @Test public void testTop() throws Exception { stack.push(4); assertEquals(4, stack.top()); stack.push(2); assertEquals(2, stack.top()); } @Test public void testFind() throws Exception { stack.push(3); stack.push(6); stack.push(45); find(45, 0); find(6, 1); find(3, 2); assertNull(stack.find(20)); } private void find(int element, int expectedIndex) { int index = stack.find(element); assertEquals(expectedIndex, index); } @Test public void findFromEmptyStack() throws Exception { assertNull(stack.find(1)); } @Test(expected = Stack.OverflowException.class) public void pushMoreThanStackCapacity_throwStackOverflowException() throws Exception { stack.push(1); stack.push(2); stack.push(5); stack.push(8); stack.push(23); } @Test(expected = Stack.UnderflowException.class) public void popFromEmptyStack_throwStackUnderflowException() throws Exception { stack.pop(); } @Test(expected = Stack.IllegalCapacityException.class) public void creatingStackWithNegativeCapacity_throwStackIllegalCapacityException() throws Exception { StackImpl.newInstance(-3); } @Test(expected = Stack.EmptyException.class) public void topFromEmptyStack() throws Exception { stack.top(); } public static class ImmutableStackTest { private Stack immutableStack; @Before public void setUp() { immutableStack = StackImpl.newInstance(0); } @Test public void immutableStackIsEmpty() throws Exception { assertTrue(immutableStack.isEmpty()); assertEquals(0, immutableStack.size()); } @Test public void find_returnNll() throws Exception { assertNull(immutableStack.find(3)); } @Test(expected = Stack.OverflowException.class) public void push_throwStackOverflowException() throws Exception { immutableStack.push(8); } @Test(expected = Stack.UnderflowException.class) public void pop_throwUnderflowException() throws Exception { immutableStack.pop(); } @Test(expected = Stack.EmptyException.class) public void top_throwEmptyException() throws Exception { immutableStack.top(); } } }
UTF-8
Java
3,780
java
StackTest.java
Java
[ { "context": "tatic org.junit.Assert.assertTrue;\n\n/**\n * @author Arya Pishgah (pishgah@gamelectronics.com) 18/03/2018\n */\npubli", "end": 245, "score": 0.9999028444290161, "start": 233, "tag": "NAME", "value": "Arya Pishgah" }, { "context": ".Assert.assertTrue;\n\n/**\n * @author Arya Pishgah (pishgah@gamelectronics.com) 18/03/2018\n */\npublic class StackTest {\n\n pri", "end": 273, "score": 0.9999321699142456, "start": 247, "tag": "EMAIL", "value": "pishgah@gamelectronics.com" } ]
null
[]
package com.training.cleancode.e04; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * @author <NAME> (<EMAIL>) 18/03/2018 */ public class StackTest { private Stack stack; @Before public void setUp() throws Exception { stack = StackImpl.newInstance(3); } @Test public void newlyStackIsEmpty() throws Exception { assertTrue(stack.isEmpty()); assertEquals(0, stack.size()); } @Test public void pushIntoStackIncreaseTheSizeOfStack() throws Exception { stack.push(1); assertEquals(1 , stack.size()); stack.push(4); assertEquals(2, stack.size()); } @Test public void popFromStackDecreaseTheSizeOfStack() throws Exception { stack.push(3); stack.push(8); assertEquals(2, stack.size()); stack.pop(); assertEquals(1, stack.size()); stack.pop(); assertEquals(0, stack.size()); } @Test public void pushOneAndTwo_popTwoAndOne() throws Exception { stack.push(1); stack.push(2); assertEquals(2, stack.pop()); assertEquals(1, stack.pop()); } @Test public void testTop() throws Exception { stack.push(4); assertEquals(4, stack.top()); stack.push(2); assertEquals(2, stack.top()); } @Test public void testFind() throws Exception { stack.push(3); stack.push(6); stack.push(45); find(45, 0); find(6, 1); find(3, 2); assertNull(stack.find(20)); } private void find(int element, int expectedIndex) { int index = stack.find(element); assertEquals(expectedIndex, index); } @Test public void findFromEmptyStack() throws Exception { assertNull(stack.find(1)); } @Test(expected = Stack.OverflowException.class) public void pushMoreThanStackCapacity_throwStackOverflowException() throws Exception { stack.push(1); stack.push(2); stack.push(5); stack.push(8); stack.push(23); } @Test(expected = Stack.UnderflowException.class) public void popFromEmptyStack_throwStackUnderflowException() throws Exception { stack.pop(); } @Test(expected = Stack.IllegalCapacityException.class) public void creatingStackWithNegativeCapacity_throwStackIllegalCapacityException() throws Exception { StackImpl.newInstance(-3); } @Test(expected = Stack.EmptyException.class) public void topFromEmptyStack() throws Exception { stack.top(); } public static class ImmutableStackTest { private Stack immutableStack; @Before public void setUp() { immutableStack = StackImpl.newInstance(0); } @Test public void immutableStackIsEmpty() throws Exception { assertTrue(immutableStack.isEmpty()); assertEquals(0, immutableStack.size()); } @Test public void find_returnNll() throws Exception { assertNull(immutableStack.find(3)); } @Test(expected = Stack.OverflowException.class) public void push_throwStackOverflowException() throws Exception { immutableStack.push(8); } @Test(expected = Stack.UnderflowException.class) public void pop_throwUnderflowException() throws Exception { immutableStack.pop(); } @Test(expected = Stack.EmptyException.class) public void top_throwEmptyException() throws Exception { immutableStack.top(); } } }
3,755
0.62037
0.606085
143
25.433567
22.664646
105
false
false
0
0
0
0
0
0
0.496504
false
false
4
8c2f6eb8a28dce53692c6eb714cce981c0f3ae8e
6,768,868,483,734
ab187ccedd471c653c8128828327aba77f3f6946
/src/main/java/com/robertx22/age_of_exile/saveclasses/gearitem/gear_bases/TooltipContext.java
9a14d852a85837ef1d2bee1b3c87f10aa8c9da03
[]
no_license
evstarMC/Age-of-Exile
https://github.com/evstarMC/Age-of-Exile
bdd04cf73058fe48fb0be8b16db7f12cb661fb7a
9a8b9d0d44e4860216e25e769fd9a46e046d86bb
refs/heads/master
2023-08-27T19:15:50.846000
2021-09-17T12:08:10
2021-09-17T12:08:10
357,961,872
0
0
null
true
2021-04-29T22:40:43
2021-04-14T15:54:42
2021-04-29T21:05:12
2021-04-29T22:40:42
6,487
0
0
0
Java
false
false
package com.robertx22.age_of_exile.saveclasses.gearitem.gear_bases; import com.robertx22.age_of_exile.capability.entity.EntityCap.UnitData; import net.minecraft.item.ItemStack; import net.minecraft.text.Text; import java.util.List; public class TooltipContext { public TooltipContext(ItemStack stack, List<Text> tooltip, UnitData data) { this.stack = stack; this.tooltip = tooltip; this.data = data; } public ItemStack stack; public List<Text> tooltip; public UnitData data; }
UTF-8
Java
527
java
TooltipContext.java
Java
[ { "context": "package com.robertx22.age_of_exile.saveclasses.gearitem.gear_bases;\n\nim", "end": 21, "score": 0.9418700933456421, "start": 12, "tag": "USERNAME", "value": "robertx22" }, { "context": "xile.saveclasses.gearitem.gear_bases;\n\nimport com.robertx22.age_of_exile.capability.entity.EntityCap.UnitData", "end": 89, "score": 0.970107913017273, "start": 80, "tag": "USERNAME", "value": "robertx22" } ]
null
[]
package com.robertx22.age_of_exile.saveclasses.gearitem.gear_bases; import com.robertx22.age_of_exile.capability.entity.EntityCap.UnitData; import net.minecraft.item.ItemStack; import net.minecraft.text.Text; import java.util.List; public class TooltipContext { public TooltipContext(ItemStack stack, List<Text> tooltip, UnitData data) { this.stack = stack; this.tooltip = tooltip; this.data = data; } public ItemStack stack; public List<Text> tooltip; public UnitData data; }
527
0.724858
0.717268
21
24.095238
23.660103
79
false
false
0
0
0
0
0
0
0.619048
false
false
4
4b61497db7883d886cc05e14fa5d40116532e690
15,831,249,499,046
2ecbb1dbcc55171921b462fd155969cb155b815c
/app/src/main/java/com/bawei/weekthreemn/di/presenter/IBannerPresenterImp.java
fe2ab0b46a3a5bcb9b1d65ab48db9aa29fd81a54
[]
no_license
wangshihao1/Weekthreemn
https://github.com/wangshihao1/Weekthreemn
2f1db3c9d6308bab0268a596ef826b96da806d0d
afaa0442870ba99418626d65e6230c2d2e9889bf
refs/heads/master
2020-05-05T09:49:27.386000
2019-04-07T04:41:22
2019-04-07T04:41:22
179,918,719
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bawei.weekthreemn.di.presenter; import com.bawei.weekthreemn.data.bean.BannerBean; import com.bawei.weekthreemn.di.contract.IBanner; import com.bawei.weekthreemn.di.model.IBannerModelmp; import java.lang.ref.SoftReference; public class IBannerPresenterImp implements IBanner.IBannerPresenter<IBanner.IBannerView> { private IBanner.IBannerModel bannerModel; private IBanner.IBannerView bannerView; private SoftReference<IBanner.IBannerView> reference; @Override public void atteachView(IBanner.IBannerView iBannerView) { this.bannerView = iBannerView; bannerModel = new IBannerModelmp(); reference = new SoftReference<>(bannerView); } @Override public void deatachView(IBanner.IBannerView iBannerView) { reference.clear(); } @Override public void responseBannerData() { bannerModel.requestBannerData(new IBanner.IBannerModel.CallBack() { @Override public void onCallBack(BannerBean bannerBean) { bannerView.showBannerData(bannerBean); } }); } }
UTF-8
Java
1,149
java
IBannerPresenterImp.java
Java
[]
null
[]
package com.bawei.weekthreemn.di.presenter; import com.bawei.weekthreemn.data.bean.BannerBean; import com.bawei.weekthreemn.di.contract.IBanner; import com.bawei.weekthreemn.di.model.IBannerModelmp; import java.lang.ref.SoftReference; public class IBannerPresenterImp implements IBanner.IBannerPresenter<IBanner.IBannerView> { private IBanner.IBannerModel bannerModel; private IBanner.IBannerView bannerView; private SoftReference<IBanner.IBannerView> reference; @Override public void atteachView(IBanner.IBannerView iBannerView) { this.bannerView = iBannerView; bannerModel = new IBannerModelmp(); reference = new SoftReference<>(bannerView); } @Override public void deatachView(IBanner.IBannerView iBannerView) { reference.clear(); } @Override public void responseBannerData() { bannerModel.requestBannerData(new IBanner.IBannerModel.CallBack() { @Override public void onCallBack(BannerBean bannerBean) { bannerView.showBannerData(bannerBean); } }); } }
1,149
0.689295
0.689295
37
30.054054
25.95104
91
false
false
0
0
0
0
0
0
0.378378
false
false
4
b6e63a96adae85d4a37887f34a085c7c7572aa5b
16,930,761,119,520
82aec38a4d8ec53eeabab07d031313ce39380cba
/src/main/java/ru/parsentev/task_020/Combine.java
dccbaf43b5c6d3473ccd21bef5fd504fe67b0c9d
[ "MIT" ]
permissive
ArchiGoodvin/course_test
https://github.com/ArchiGoodvin/course_test
9753596bd5ac43fcf2414738acc5c071d6d3a917
83db7515a4b07d2dbf3aa65053b439131cac1b03
refs/heads/master
2020-05-18T09:39:48.947000
2019-05-08T05:57:00
2019-05-08T05:57:00
184,332,330
0
0
null
true
2019-04-30T21:13:49
2019-04-30T21:13:49
2019-04-16T08:07:53
2017-07-19T13:36:07
87
0
0
0
null
false
false
package ru.parsentev.task_020; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.parsentev.task_001.Calculator; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Collections; import static org.slf4j.LoggerFactory.getLogger; /** * TODO: comment * * @author parsentev * @since 28.07.2016 */ public class Combine { private static final Logger log = getLogger(Combine.class); private static List<List<Integer>> list = new ArrayList<List<Integer>>(); private final int[] values; public Combine(final int[] values) { this.values = values; } public List<List<Integer>> generate() { List<Integer> valuesList = new ArrayList(Arrays.asList(values)); return generate(valuesList, 0); } static List<List<Integer>> generate(List<Integer> arr, int k) { for (int i = k; i < arr.size(); i++) { Collections.swap(arr, i, k); generate(arr, k + 1); Collections.swap(arr, k, i); } if (k == arr.size() - 1) { list.add(arr); } System.out.println(list); return list; } } /* public class Combine{ static void permute(java.util.List<Integer> arr, int k){ for(int i = k; i < arr.size(); i++){ java.util.Collections.swap(arr, i, k); permute(arr, k+1); java.util.Collections.swap(arr, k, i); } if (k == arr.size() -1){ System.out.println(java.util.Arrays.toString(arr.toArray())); } } public static void main(String[] args){ Combine.permute(java.util.Arrays.asList(1,2,3,4), 0); } }*/
UTF-8
Java
1,691
java
Combine.java
Java
[ { "context": "ory.getLogger;\n\n/**\n * TODO: comment\n *\n * @author parsentev\n * @since 28.07.2016\n */\npublic class Combine {\n ", "end": 332, "score": 0.9993142485618591, "start": 323, "tag": "USERNAME", "value": "parsentev" } ]
null
[]
package ru.parsentev.task_020; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.parsentev.task_001.Calculator; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Collections; import static org.slf4j.LoggerFactory.getLogger; /** * TODO: comment * * @author parsentev * @since 28.07.2016 */ public class Combine { private static final Logger log = getLogger(Combine.class); private static List<List<Integer>> list = new ArrayList<List<Integer>>(); private final int[] values; public Combine(final int[] values) { this.values = values; } public List<List<Integer>> generate() { List<Integer> valuesList = new ArrayList(Arrays.asList(values)); return generate(valuesList, 0); } static List<List<Integer>> generate(List<Integer> arr, int k) { for (int i = k; i < arr.size(); i++) { Collections.swap(arr, i, k); generate(arr, k + 1); Collections.swap(arr, k, i); } if (k == arr.size() - 1) { list.add(arr); } System.out.println(list); return list; } } /* public class Combine{ static void permute(java.util.List<Integer> arr, int k){ for(int i = k; i < arr.size(); i++){ java.util.Collections.swap(arr, i, k); permute(arr, k+1); java.util.Collections.swap(arr, k, i); } if (k == arr.size() -1){ System.out.println(java.util.Arrays.toString(arr.toArray())); } } public static void main(String[] args){ Combine.permute(java.util.Arrays.asList(1,2,3,4), 0); } }*/
1,691
0.594323
0.578356
66
24.621212
21.621935
77
false
false
0
0
0
0
0
0
0.712121
false
false
4
5e09d8e3f6051881d162cc60ef6bf2ca90b6dab4
34,162,169,893,913
834f51fb3c1bbe8a2c3a5e94f28f0fa6b1a0160b
/app/src/main/java/com/drumichiro/body_tapping_phone/FeatureExtractor.java
b7a25e20f59d9e1a265622bbd967ae59962bf5d8
[]
no_license
drumichiro/body-tapping-phone
https://github.com/drumichiro/body-tapping-phone
e5d1b206e4777b40e1271bbd41b10ec3ed198c45
49420ea876e88828ab961d2cfa2f4b02e3485d6b
refs/heads/master
2020-07-08T02:20:53.979000
2016-12-18T14:10:34
2016-12-18T14:23:36
74,029,447
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.drumichiro.body_tapping_phone; import junit.framework.Assert; import java.util.Arrays; /** * Created by drumichiro on 2016/11/12. */ public class FeatureExtractor { private final int features; private final int observations; private int position; private double weight; private double[][] buffer; public FeatureExtractor(int buffers, int observations) { Assert.assertTrue("The argument, observations, is not positive.", 0 < observations); this.observations = observations; features = observations * 2; Assert.assertTrue("The argument, observations, is too large.", 0 < features); Assert.assertTrue("The argument, buffers, is not positive.", 0 < buffers); buffer = new double[buffers][observations]; position = 0; weight = 1.0; } public int getFeatures() { return features; } public void setWeight(double weight) { this.weight = weight; } public void addObservation(double[] observation) { double[] targetBuffer = buffer[position]; Assert.assertNotNull("The argument, observation, is nullptr.", observation); Assert.assertTrue("The length of observation is different from initial length.", targetBuffer.length == observation.length); System.arraycopy(observation, 0, targetBuffer, 0, observation.length); position = (position + 1) % buffer.length; } public void extractFeature(double[] feature) { extractFeature(feature, 0); } public void extractFeature(double[] feature, int offset) { Assert.assertNotNull("The argument, feature, is nullptr.", feature); Assert.assertTrue("Offset is negative.", 0 <= offset); int boundary = observations + offset; Assert.assertTrue("The ending of feature is excess.", boundary + observations <= feature.length); Arrays.fill(feature, offset, boundary, 0.0); for (int i1=0; i1<buffer.length; ++i1) { for (int i2=0; i2<observations; ++i2) { feature[i2 + offset] += buffer[i1][i2]; } } // Assign negative values as a positive feature value. for (int i1=0; i1<observations; ++i1) { int positiveIndex = i1 + offset; int negativeIndex = positiveIndex + observations; feature[positiveIndex] *= weight; if (0.0 > feature[positiveIndex]) { feature[negativeIndex] = - feature[positiveIndex]; // Clear positive value. feature[positiveIndex] = 0.0; } else { // Clear negative value feature. feature[negativeIndex] = 0.0; } } } }
UTF-8
Java
2,786
java
FeatureExtractor.java
Java
[ { "context": "sert;\n\nimport java.util.Arrays;\n\n/**\n * Created by drumichiro on 2016/11/12.\n */\npublic class FeatureExtractor ", "end": 130, "score": 0.9994463920593262, "start": 120, "tag": "USERNAME", "value": "drumichiro" } ]
null
[]
package com.drumichiro.body_tapping_phone; import junit.framework.Assert; import java.util.Arrays; /** * Created by drumichiro on 2016/11/12. */ public class FeatureExtractor { private final int features; private final int observations; private int position; private double weight; private double[][] buffer; public FeatureExtractor(int buffers, int observations) { Assert.assertTrue("The argument, observations, is not positive.", 0 < observations); this.observations = observations; features = observations * 2; Assert.assertTrue("The argument, observations, is too large.", 0 < features); Assert.assertTrue("The argument, buffers, is not positive.", 0 < buffers); buffer = new double[buffers][observations]; position = 0; weight = 1.0; } public int getFeatures() { return features; } public void setWeight(double weight) { this.weight = weight; } public void addObservation(double[] observation) { double[] targetBuffer = buffer[position]; Assert.assertNotNull("The argument, observation, is nullptr.", observation); Assert.assertTrue("The length of observation is different from initial length.", targetBuffer.length == observation.length); System.arraycopy(observation, 0, targetBuffer, 0, observation.length); position = (position + 1) % buffer.length; } public void extractFeature(double[] feature) { extractFeature(feature, 0); } public void extractFeature(double[] feature, int offset) { Assert.assertNotNull("The argument, feature, is nullptr.", feature); Assert.assertTrue("Offset is negative.", 0 <= offset); int boundary = observations + offset; Assert.assertTrue("The ending of feature is excess.", boundary + observations <= feature.length); Arrays.fill(feature, offset, boundary, 0.0); for (int i1=0; i1<buffer.length; ++i1) { for (int i2=0; i2<observations; ++i2) { feature[i2 + offset] += buffer[i1][i2]; } } // Assign negative values as a positive feature value. for (int i1=0; i1<observations; ++i1) { int positiveIndex = i1 + offset; int negativeIndex = positiveIndex + observations; feature[positiveIndex] *= weight; if (0.0 > feature[positiveIndex]) { feature[negativeIndex] = - feature[positiveIndex]; // Clear positive value. feature[positiveIndex] = 0.0; } else { // Clear negative value feature. feature[negativeIndex] = 0.0; } } } }
2,786
0.60804
0.592247
79
34.265823
25.792114
92
false
false
0
0
0
0
0
0
0.886076
false
false
4
c082df4a191b97dae31c7236ca11828fd2d5b795
38,259,568,676,150
910e8e602249fea599998ac975538fe0c1c062ef
/src/com/gmail/pro100vetal07030401/Main.java
b297dfc14eed025ace517940cb2e4df83c04866b
[]
no_license
777-Vetal-777/JAVA_PRO_LESSON3_2
https://github.com/777-Vetal-777/JAVA_PRO_LESSON3_2
8494da6fcc92c1eafb499b77524f95df527a7357
f3ad386bb762d03dd78b45d484f56016941d8388
refs/heads/master
2020-09-09T18:40:17.579000
2019-11-13T19:54:55
2019-11-13T19:54:55
221,530,773
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gmail.pro100vetal07030401; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; public class Main { public static void main(String[] args) { Class<?> cls = TextContainer.class; if (!cls.isAnnotationPresent(SaveTo.class)){ return; } SaveTo saveTo = cls.getAnnotation(SaveTo.class); String path = saveTo.path(); try { Constructor<?> constructor = cls.getDeclaredConstructor(); constructor.setAccessible(true); TextContainer textContainer = (TextContainer) constructor.newInstance(); Method[] methods = cls.getDeclaredMethods(); for(Method method:methods){ if(Modifier.isPrivate(method.getModifiers())){ method.setAccessible(true); } if(method.isAnnotationPresent(Saver.class)){ method.invoke(textContainer,path); break; } } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
UTF-8
Java
1,500
java
Main.java
Java
[ { "context": "package com.gmail.pro100vetal07030401;\n\n\nimport java.lang.annotation.Annot", "end": 24, "score": 0.7668015956878662, "start": 18, "tag": "USERNAME", "value": "pro100" } ]
null
[]
package com.gmail.pro100vetal07030401; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; public class Main { public static void main(String[] args) { Class<?> cls = TextContainer.class; if (!cls.isAnnotationPresent(SaveTo.class)){ return; } SaveTo saveTo = cls.getAnnotation(SaveTo.class); String path = saveTo.path(); try { Constructor<?> constructor = cls.getDeclaredConstructor(); constructor.setAccessible(true); TextContainer textContainer = (TextContainer) constructor.newInstance(); Method[] methods = cls.getDeclaredMethods(); for(Method method:methods){ if(Modifier.isPrivate(method.getModifiers())){ method.setAccessible(true); } if(method.isAnnotationPresent(Saver.class)){ method.invoke(textContainer,path); break; } } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
1,500
0.598
0.590667
44
33.090908
20.269567
84
false
false
0
0
0
0
0
0
0.522727
false
false
4
6cef4073a1daaba6a43ce5a32e7f05aa48bf5c01
33,809,982,578,208
e7b7ff957c7a1b2d1002d89fbfa290ec33185c21
/example-apps/src/escola-src/escola/testes/testeArquivoTurmaEDisciplina.java
0217633b932f3bcea64086cbb4c5743610ca3601
[]
no_license
damorim/rwset
https://github.com/damorim/rwset
de3121caf36551b38e34c5b996bd1e91ae1e401e
65252f76efa10514337cdd6a361dd11b14714b20
refs/heads/master
2020-05-17T04:47:20.541000
2016-11-14T19:43:26
2016-11-14T19:43:26
9,355,925
1
10
null
false
2015-05-21T12:51:08
2013-04-10T21:02:24
2015-01-16T18:01:25
2015-01-16T18:01:25
35,275
0
11
9
Java
null
null
package escola.testes; import java.io.IOException; import java.util.Iterator; import escola.classesBase.*; import escola.dados.*; import escola.excecoes.RepositorioException; public class testeArquivoTurmaEDisciplina { /** * @param args */ public static void main(String[] args) { Repositorio<Pessoa> pessoas = new RepositorioArquivoPessoa(); Repositorio<Turma> turmas = new RepositorioArquivoTurma(); Repositorio<Disciplina> disc = new RepositorioArrayDisciplina(); Disciplina d = new Disciplina("turma", "ementz"); Disciplina d2 = new Disciplina("portugues", "ementa"); Disciplina d3 = new Disciplina("matematica", "ementa"); Disciplina d4 = new Disciplina("ingles", "ementa"); Turma t = new Turma("p5"); Turma t1 = new Turma("turma p"); Turma t2 = new Turma("turminha"); Turma t3 = new Turma("nomeee"); try { disc.inserir(d); disc.inserir(d2); disc.inserir(d3); disc.inserir(d4); turmas.inserir(t); turmas.inserir(t1); turmas.inserir(t2); turmas.inserir(t3); } catch (RepositorioException e) { System.out.println("rep excep"); } System.out.println("\niterator:\n"); Iterator<Turma> itt = new IteratorArquivoTurma("Turmas"); System.out.println(itt.hasNext()); while (itt.hasNext()) { System.out.println("entrou no hasnext"); System.out.println(itt.next().resumo()); } System.out.println("\niterator:\n"); Iterator<Disciplina> itd = disc.getIterator(); while (itd.hasNext()) { System.out.println(itd.next().resumo()); } } }
UTF-8
Java
1,529
java
testeArquivoTurmaEDisciplina.java
Java
[]
null
[]
package escola.testes; import java.io.IOException; import java.util.Iterator; import escola.classesBase.*; import escola.dados.*; import escola.excecoes.RepositorioException; public class testeArquivoTurmaEDisciplina { /** * @param args */ public static void main(String[] args) { Repositorio<Pessoa> pessoas = new RepositorioArquivoPessoa(); Repositorio<Turma> turmas = new RepositorioArquivoTurma(); Repositorio<Disciplina> disc = new RepositorioArrayDisciplina(); Disciplina d = new Disciplina("turma", "ementz"); Disciplina d2 = new Disciplina("portugues", "ementa"); Disciplina d3 = new Disciplina("matematica", "ementa"); Disciplina d4 = new Disciplina("ingles", "ementa"); Turma t = new Turma("p5"); Turma t1 = new Turma("turma p"); Turma t2 = new Turma("turminha"); Turma t3 = new Turma("nomeee"); try { disc.inserir(d); disc.inserir(d2); disc.inserir(d3); disc.inserir(d4); turmas.inserir(t); turmas.inserir(t1); turmas.inserir(t2); turmas.inserir(t3); } catch (RepositorioException e) { System.out.println("rep excep"); } System.out.println("\niterator:\n"); Iterator<Turma> itt = new IteratorArquivoTurma("Turmas"); System.out.println(itt.hasNext()); while (itt.hasNext()) { System.out.println("entrou no hasnext"); System.out.println(itt.next().resumo()); } System.out.println("\niterator:\n"); Iterator<Disciplina> itd = disc.getIterator(); while (itd.hasNext()) { System.out.println(itd.next().resumo()); } } }
1,529
0.686723
0.678221
63
23.269842
20.143301
66
false
false
0
0
0
0
0
0
1.984127
false
false
4
b175c749c388d83903861bbdb91ddd11dedb1647
33,809,982,579,517
1d11d02630949f18654d76ed8d5142520e559b22
/OnlineContributors/src/org/tolweb/tapestry/wrappers/CommonWrapper.java
0d348c732b0107c5dbd56e5da42f0cfac3a1f3ab
[]
no_license
tolweb/tolweb-app
https://github.com/tolweb/tolweb-app
ca588ff8f76377ffa2f680a3178351c46ea2e7ea
3a7b5c715f32f71d7033b18796d49a35b349db38
refs/heads/master
2021-01-02T14:46:52.512000
2012-03-31T19:22:24
2012-03-31T19:22:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.tolweb.tapestry.wrappers; import java.util.List; import org.apache.tapestry.IAsset; import org.apache.tapestry.annotations.Parameter; public abstract class CommonWrapper extends AbstractWrapper { @Parameter public abstract List<IAsset> getStylesheets(); }
UTF-8
Java
273
java
CommonWrapper.java
Java
[]
null
[]
package org.tolweb.tapestry.wrappers; import java.util.List; import org.apache.tapestry.IAsset; import org.apache.tapestry.annotations.Parameter; public abstract class CommonWrapper extends AbstractWrapper { @Parameter public abstract List<IAsset> getStylesheets(); }
273
0.81685
0.81685
11
23.818182
21.787477
61
false
false
0
0
0
0
0
0
0.636364
false
false
4