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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
33f420640670169013b59026d10fbacd3805e876 | 21,414,706,999,533 | a7b6d208b0dbace1a2daa926ed661d010d7e5e25 | /src/main/java/com/project/OnlineVotingSystem/model/RegisteredSocietyVoters.java | 457649b30322131027fa1793be53fad6f83e82d4 | []
| no_license | Jaibw/ovs | https://github.com/Jaibw/ovs | bd99bec39b15dc49b07614809da2f479ae0d164e | 0af7feca14eb36404bca3dd4d6de3009bb562cf0 | refs/heads/main | 2023-08-29T03:55:18.011000 | 2021-10-19T09:47:00 | 2021-10-19T09:47:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.project.OnlineVotingSystem.model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
@Entity(name = "Registered_Society_Voters")
public class RegisteredSocietyVoters {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String voterIdCardNo;
private String firstName;
private String lastName;
private String gender;
private String password;
private String reservationCategory;
private String mobileno;
private String emailId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "r_id")
private CooperativeSociety society;
private boolean castedVote;
public RegisteredSocietyVoters(int id, String voterIdCardNo, String firstName, String lastName, String gender,
String password, String reservationCategory, String mobileno, String emailId, CooperativeSociety society,
boolean castedVote) {
super();
this.id = id;
this.voterIdCardNo = voterIdCardNo;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.password = password;
this.reservationCategory = reservationCategory;
this.mobileno = mobileno;
this.emailId = emailId;
this.society = society;
this.castedVote = castedVote;
}
public RegisteredSocietyVoters() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVoterIdCardNo() {
return voterIdCardNo;
}
public void setVoterIdCardNo(String voterIdCardNo) {
this.voterIdCardNo = voterIdCardNo;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getReservationCategory() {
return reservationCategory;
}
public void setReservationCategory(String reservationCategory) {
this.reservationCategory = reservationCategory;
}
public String getMobileno() {
return mobileno;
}
public void setMobileno(String mobileno) {
this.mobileno = mobileno;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public CooperativeSociety getSociety() {
return society;
}
public void setSociety(CooperativeSociety society) {
this.society = society;
}
public boolean isCastedVote() {
return castedVote;
}
public void setCastedVote(boolean castedVote) {
this.castedVote = castedVote;
}
}
| UTF-8 | Java | 3,011 | java | RegisteredSocietyVoters.java | Java | [
{
"context": " private String voterIdCardNo;\n private String firstName;\n private String lastName;\n private String ",
"end": 524,
"score": 0.5757542252540588,
"start": 515,
"tag": "NAME",
"value": "firstName"
},
{
"context": ";\n private String firstName;\n private String lastName;\n private String gender;\n private String pa",
"end": 553,
"score": 0.9744781851768494,
"start": 545,
"tag": "NAME",
"value": "lastName"
},
{
"context": "SocietyVoters(int id, String voterIdCardNo, String firstName, String lastName, String gender,\n\t\t\tString passwo",
"end": 952,
"score": 0.9478127360343933,
"start": 943,
"tag": "NAME",
"value": "firstName"
},
{
"context": "id, String voterIdCardNo, String firstName, String lastName, String gender,\n\t\t\tString password, String reserv",
"end": 969,
"score": 0.9982629418373108,
"start": 961,
"tag": "NAME",
"value": "lastName"
},
{
"context": ".voterIdCardNo = voterIdCardNo;\n\t\tthis.firstName = firstName;\n\t\tthis.lastName = lastName;\n\t\tthis.gender = gend",
"end": 1214,
"score": 0.9992451667785645,
"start": 1205,
"tag": "NAME",
"value": "firstName"
},
{
"context": "o;\n\t\tthis.firstName = firstName;\n\t\tthis.lastName = lastName;\n\t\tthis.gender = gender;\n\t\tthis.password = passwo",
"end": 1242,
"score": 0.9993820786476135,
"start": 1234,
"tag": "NAME",
"value": "lastName"
},
{
"context": "astName;\n\t\tthis.gender = gender;\n\t\tthis.password = password;\n\t\tthis.reservationCategory = reservationCategory",
"end": 1294,
"score": 0.9988269209861755,
"start": 1286,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.project.OnlineVotingSystem.model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
@Entity(name = "Registered_Society_Voters")
public class RegisteredSocietyVoters {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String voterIdCardNo;
private String firstName;
private String lastName;
private String gender;
private String password;
private String reservationCategory;
private String mobileno;
private String emailId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "r_id")
private CooperativeSociety society;
private boolean castedVote;
public RegisteredSocietyVoters(int id, String voterIdCardNo, String firstName, String lastName, String gender,
String password, String reservationCategory, String mobileno, String emailId, CooperativeSociety society,
boolean castedVote) {
super();
this.id = id;
this.voterIdCardNo = voterIdCardNo;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.password = <PASSWORD>;
this.reservationCategory = reservationCategory;
this.mobileno = mobileno;
this.emailId = emailId;
this.society = society;
this.castedVote = castedVote;
}
public RegisteredSocietyVoters() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVoterIdCardNo() {
return voterIdCardNo;
}
public void setVoterIdCardNo(String voterIdCardNo) {
this.voterIdCardNo = voterIdCardNo;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getReservationCategory() {
return reservationCategory;
}
public void setReservationCategory(String reservationCategory) {
this.reservationCategory = reservationCategory;
}
public String getMobileno() {
return mobileno;
}
public void setMobileno(String mobileno) {
this.mobileno = mobileno;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public CooperativeSociety getSociety() {
return society;
}
public void setSociety(CooperativeSociety society) {
this.society = society;
}
public boolean isCastedVote() {
return castedVote;
}
public void setCastedVote(boolean castedVote) {
this.castedVote = castedVote;
}
}
| 3,013 | 0.741282 | 0.741282 | 127 | 22.708662 | 19.583099 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.559055 | false | false | 3 |
e6bd2b0f1cd782c0975fc2d832b7524b6b2fa8c9 | 3,805,341,037,106 | 251404d07c9d5eb6356e502d8216730acd2a3e03 | /app/src/main/java/app/lector/tortilleria_salida/model/Proveedores.java | a29386d9b35e1c477d4f445803ffbf2134ceb21f | []
| no_license | abel1313/proyectoTortilleriaAndroidStudio | https://github.com/abel1313/proyectoTortilleriaAndroidStudio | f8cd902cd4fd990fe8a8b4a13e9fc3f636f49f50 | 087eafe3ed76082947f6d96302ba84578f6da381 | refs/heads/master | 2023-05-04T09:13:40.056000 | 2021-05-26T02:19:44 | 2021-05-26T02:19:44 | 370,883,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.lector.tortilleria_salida.model;
import app.lector.tortilleria_salida.base.Base;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class Proveedores extends Base
{
private String nombreProveedor;
}
| UTF-8 | Java | 339 | java | Proveedores.java | Java | []
| null | []
| package app.lector.tortilleria_salida.model;
import app.lector.tortilleria_salida.base.Base;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class Proveedores extends Base
{
private String nombreProveedor;
}
| 339 | 0.828909 | 0.828909 | 16 | 20.1875 | 15.8083 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 3 |
be2400551e5de7a1c924e867d1d94f23ed0261e6 | 14,001,593,436,738 | 9b04be358a7a169ee360fe49ab590f3af3dd777c | /com/vmware/xclone/Xclones.java | 2864e188ef28d77d20380f7cf20ee246b1c21e3f | []
| no_license | powanjuanshu/Xclone | https://github.com/powanjuanshu/Xclone | 5c96c0f078fd8fd355252fc7c7045c32ee2c970f | 246be295a8505043f8ae1d12241751e5fb816df3 | refs/heads/master | 2020-03-13T12:23:55.601000 | 2013-08-02T05:53:41 | 2013-08-02T05:53:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vmware.xclone;
import com.vmware.xclone.algorithm.*;
import com.vmware.xclone.basicops.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;
/**
* <pre>
* Xclone
*
* Fastest VM Provision
*
* <b>Parameters:</b>
* url [required] : url of the web service.
* username [optional] : username for the authentication (default: root)
* password [optional] : password for the authentication (default: vmware)
* datacentername [optional] : name of the datacenter (default: Datacenter)
* resourcepool [optional] : name of the resource pool in the datacenter (default: cluster)
* vmname [required] : Name of the virtual machine
* cloneprefix [required] : prefix of the cloned virtual machine
* number [required] : the number of cloned virtual machines
* srchost [required] : the Ip of src host
* dsthosts [required] : the Ip of all dst hosts
* acceptlinked [optional] : Whether accept Linked clone (default: True)
* isOn [optional] : Whether Power on the VM after cloning (default: True)
* algthselect [optional] : select which algorithm to deploy the VMs [0 | 1 | 2| 3| ...] and default: 1
* opselect [optional] : select which operations (create(default) | start | stop | destroy)
* <b>Example:</b>
* Create example:
* <<
* "--url 10.117.4.228 --username root --password vmware "
* + "--datacentername Datacenter --vmname vm_clone --cloneprefix clone_ "
* + "--resourcepool cluster "
* + "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
* + "--ison false --algthselect 1"
* >>
* Stop VMs example:
* <<
* "--url 10.117.4.228 --username root --password vmware "
* + "--datacentername Datacenter --vmname vm_clone --cloneprefix clone_ "
* + "--resourcepool cluster "
* + "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
* + "--ison false --algthselect 1 --opselect stop"
* >>
* Destroy VMs example:
* <<
* "--url 10.117.4.228 --username root --password vmware "
* + "--datacentername Datacenter --vmname vm_clone --cloneprefix tttclone_ "
* + "--resourcepool cluster "
* + "--number 160 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
* + "--ison false --algthselect 1 --opselect destroy";
* >>
* </pre>
*/
public class Xclones {
private UserInterface ui;
public UserInterface getUi() {
return ui;
}
public void setUi(UserInterface ui) {
this.ui = ui;
}
public Xclones(UserInterface ui) {
this.setUi(ui);
}
public static void main(String[] args) {
// String inputString = "--url 10.117.5.254 --username root --password vmware "
// + "--datacentername Datacenter --vmname Xclone_temp --cloneprefix XXclone_ "
// + "--resourcepool Resources "
// + "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 "
// + "--srchost 10.117.4.140 --acceptlinked true "
// + "--ison false --algthselect 1";
// String[] Params = inputString.split("\\s+");
// UserInterface ui = UserInterface.getInstance(Params);
// StatusGet statusTask = new StatusGet(ui, 0, 100);
// statusTask.start();
// }
//}
try {
// private static CloningAlgorithms cAlgorithm;
String inputString = "--url 10.117.5.254 --username root --password vmware "
+ "--datacentername Datacenter --vmname xclone --cloneprefix SXclone_ "
+ "--resourcepool resource "
+ "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
+ "--ison on --algthselect 1";
// offString opselect: create | start | stop | destroy
String stopString = "--url 10.117.5.254 --username root --password vmware "
+ "--datacentername Datacenter --vmname vm_clone --cloneprefix clone_ "
+ "--resourcepool Resources "
+ "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
+ "--ison false --algthselect 1 --opselect stop";
String startString = "--url 10.117.5.254 --username root --password vmware "
+ "--datacentername Datacenter --vmname vm_clone --cloneprefix clone_ "
+ "--resourcepool cluster "
+ "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
+ "--ison false --algthselect 1 --opselect start";
String destroyString = "--url 10.117.5.254 --username root --password vmware "
+ "--datacentername Datacenter --vmname xclone --cloneprefix testclone_ "
+ "--resourcepool resource "
+ "--number 104 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
+ "--ison false --algthselect 1 --opselect destroy";
String[] Params = inputString.split("\\s+");
UserInterface ui = UserInterface.getInstance(Params);
String ops = ui.getOpselect();
int perNumDel = 6;
StatusGet statusTask = new StatusGet(ui, 0, 100);
statusTask.start();
long starttime = System.currentTimeMillis();
if (ops.equalsIgnoreCase("destroy")) {
int i = 0;
if(ui.getIsOn() == true)
{
int threadNum = (ui.getNumberOfVMs() + perNumDel - 1)
/ perNumDel;
CountDownLatch latch = new CountDownLatch(threadNum);
for (i = 0; i < ui.getNumberOfVMs(); i = i + perNumDel) {
PoweroffVM offTask = new PoweroffVM(ui.getVmClonePrefix(),
i, perNumDel);
offTask.start();
}
latch.wait();
}
for (i = 0; i < ui.getNumberOfVMs(); i = i + perNumDel) {
DeleteVM delTask = new DeleteVM(ui.getVmClonePrefix(), i,
perNumDel);
delTask.start();
}
} else if (ops.equalsIgnoreCase("stop")) {
int i = 0;
for (i = 0; i < ui.getNumberOfVMs(); i = i + perNumDel) {
PoweroffVM offTask = new PoweroffVM(ui.getVmClonePrefix(),
i, perNumDel);
offTask.start();
}
} else {
switch (ui.getAlgthSelect()) {
case 1:
TreeDeployVm deployVm = new TreeDeployVm(ui);
deployVm.DeployVmFromList();
break;
case 2:
SimpleDeploy sdeployVm = new SimpleDeploy(ui);
sdeployVm.run();
break;
default:
System.out.println("Stupid Boy, you Exceed our alg selection!");
}
}
long stoptime = System.currentTimeMillis();
System.out.printf("Total Time: %d\n", (stoptime-starttime)/60000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 6,903 | java | Xclones.java | Java | [
{
"context": "ional] : username for the authentication (default: root)\n * password [optional] : password for the ",
"end": 379,
"score": 0.8581567406654358,
"start": 375,
"tag": "USERNAME",
"value": "root"
},
{
"context": " << \n * \"--url 10.117.4.228 --username root --password vmware \"\n * \t\t \t\t+ ",
"end": 1400,
"score": 0.9997442364692688,
"start": 1388,
"tag": "IP_ADDRESS",
"value": "10.117.4.228"
},
{
"context": " \"--url 10.117.4.228 --username root --password vmware \"\n * \t\t \t\t+ \"--datacenternam",
"end": 1416,
"score": 0.9622241854667664,
"start": 1412,
"tag": "USERNAME",
"value": "root"
},
{
"context": " \"--url 10.117.4.228 --username root --password vmware \"\n * \t\t \t\t+ \"--datacentername Datacenter --vmn",
"end": 1434,
"score": 0.9847933650016785,
"start": 1428,
"tag": "PASSWORD",
"value": "vmware"
},
{
"context": "l cluster \"\n * \t\t \t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.7",
"end": 1608,
"score": 0.9997411966323853,
"start": 1597,
"tag": "IP_ADDRESS",
"value": "10.117.4.71"
},
{
"context": " * \t\t \t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14",
"end": 1621,
"score": 0.9997138381004333,
"start": 1609,
"tag": "IP_ADDRESS",
"value": "10.117.5.148"
},
{
"context": "\"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10",
"end": 1634,
"score": 0.9996860027313232,
"start": 1622,
"tag": "IP_ADDRESS",
"value": "10.117.7.125"
},
{
"context": " --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --",
"end": 1647,
"score": 0.9997064471244812,
"start": 1635,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "0.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked",
"end": 1659,
"score": 0.9996901154518127,
"start": 1648,
"tag": "IP_ADDRESS",
"value": "10.117.5.78"
},
{
"context": "0.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n * \t",
"end": 1671,
"score": 0.9994425177574158,
"start": 1660,
"tag": "IP_ADDRESS",
"value": "10.117.4.14"
},
{
"context": "25,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n * \t\t \t\t+ \"--ison false ",
"end": 1694,
"score": 0.9997442364692688,
"start": 1682,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": " VMs example:\n * <<\n * \"--url 10.117.4.228 --username root --password vmware \"\n * \t ",
"end": 1836,
"score": 0.9997534155845642,
"start": 1824,
"tag": "IP_ADDRESS",
"value": "10.117.4.228"
},
{
"context": " \"--url 10.117.4.228 --username root --password vmware \"\n * \t \t\t+ \"--datacente",
"end": 1852,
"score": 0.9975812435150146,
"start": 1848,
"tag": "USERNAME",
"value": "root"
},
{
"context": " \"--url 10.117.4.228 --username root --password vmware \"\n * \t \t\t+ \"--datacentername Datacenter -",
"end": 1870,
"score": 0.9654779434204102,
"start": 1864,
"tag": "PASSWORD",
"value": "vmware"
},
{
"context": "l cluster \"\n * \t\t \t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.7",
"end": 2048,
"score": 0.9997472167015076,
"start": 2037,
"tag": "IP_ADDRESS",
"value": "10.117.4.71"
},
{
"context": " * \t\t \t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14",
"end": 2061,
"score": 0.9997215270996094,
"start": 2049,
"tag": "IP_ADDRESS",
"value": "10.117.5.148"
},
{
"context": "\"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10",
"end": 2074,
"score": 0.9996991157531738,
"start": 2062,
"tag": "IP_ADDRESS",
"value": "10.117.7.125"
},
{
"context": " --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --",
"end": 2087,
"score": 0.9997296929359436,
"start": 2075,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "0.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked",
"end": 2099,
"score": 0.999717116355896,
"start": 2088,
"tag": "IP_ADDRESS",
"value": "10.117.5.78"
},
{
"context": "0.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n * \t",
"end": 2111,
"score": 0.9997133612632751,
"start": 2100,
"tag": "IP_ADDRESS",
"value": "10.117.4.14"
},
{
"context": "25,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n * \t\t \t\t+ \"--ison false ",
"end": 2134,
"score": 0.9997353553771973,
"start": 2122,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": " VMs example:\n * <<\n * \"--url 10.117.4.228 --username root --password vmware \"\n * \t\t \t\t+ ",
"end": 2295,
"score": 0.9997456669807434,
"start": 2283,
"tag": "IP_ADDRESS",
"value": "10.117.4.228"
},
{
"context": " \"--url 10.117.4.228 --username root --password vmware \"\n * \t\t \t\t+ \"--datacenternam",
"end": 2311,
"score": 0.9979813694953918,
"start": 2307,
"tag": "USERNAME",
"value": "root"
},
{
"context": " \"--url 10.117.4.228 --username root --password vmware \"\n * \t\t \t\t+ \"--datacentername Datacenter --vmn",
"end": 2329,
"score": 0.9694816470146179,
"start": 2323,
"tag": "PASSWORD",
"value": "vmware"
},
{
"context": "l cluster \"\n * \t\t \t\t+ \"--number 160 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.7",
"end": 2506,
"score": 0.9997435212135315,
"start": 2495,
"tag": "IP_ADDRESS",
"value": "10.117.4.71"
},
{
"context": " * \t\t \t\t+ \"--number 160 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14",
"end": 2519,
"score": 0.9997282028198242,
"start": 2507,
"tag": "IP_ADDRESS",
"value": "10.117.5.148"
},
{
"context": "\"--number 160 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10",
"end": 2532,
"score": 0.9997146129608154,
"start": 2520,
"tag": "IP_ADDRESS",
"value": "10.117.7.125"
},
{
"context": " --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --",
"end": 2545,
"score": 0.9997214674949646,
"start": 2533,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "0.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked",
"end": 2557,
"score": 0.9996930956840515,
"start": 2546,
"tag": "IP_ADDRESS",
"value": "10.117.5.78"
},
{
"context": "0.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n * \t",
"end": 2569,
"score": 0.9996601343154907,
"start": 2558,
"tag": "IP_ADDRESS",
"value": "10.117.4.14"
},
{
"context": "25,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n * \t\t \t\t+ \"--ison false ",
"end": 2592,
"score": 0.9997439980506897,
"start": 2580,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "(String[] args) {\n//\t\tString inputString = \"--url 10.117.5.254 --username root --password vmware \"\n//\t\t+ \"--data",
"end": 3003,
"score": 0.9997377395629883,
"start": 2991,
"tag": "IP_ADDRESS",
"value": "10.117.5.254"
},
{
"context": "tring inputString = \"--url 10.117.5.254 --username root --password vmware \"\n//\t\t+ \"--datacentername Datac",
"end": 3019,
"score": 0.995568037033081,
"start": 3015,
"tag": "USERNAME",
"value": "root"
},
{
"context": "g = \"--url 10.117.5.254 --username root --password vmware \"\n//\t\t+ \"--datacentername Datacenter --vmname Xcl",
"end": 3037,
"score": 0.9935212731361389,
"start": 3031,
"tag": "PASSWORD",
"value": "vmware"
},
{
"context": "cepool Resources \"\n//\t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.7",
"end": 3197,
"score": 0.999735414981842,
"start": 3186,
"tag": "IP_ADDRESS",
"value": "10.117.4.71"
},
{
"context": "rces \"\n//\t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14",
"end": 3210,
"score": 0.9997265934944153,
"start": 3198,
"tag": "IP_ADDRESS",
"value": "10.117.5.148"
},
{
"context": "\"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 \"\n//\t\t+ \"--s",
"end": 3223,
"score": 0.9997193813323975,
"start": 3211,
"tag": "IP_ADDRESS",
"value": "10.117.7.125"
},
{
"context": " --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 \"\n//\t\t+ \"--srchost 10.117",
"end": 3236,
"score": 0.9997335076332092,
"start": 3224,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "0.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 \"\n//\t\t+ \"--srchost 10.117.4.140 --acc",
"end": 3248,
"score": 0.9997192025184631,
"start": 3237,
"tag": "IP_ADDRESS",
"value": "10.117.5.78"
},
{
"context": "0.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 \"\n//\t\t+ \"--srchost 10.117.4.140 --acceptlinked tr",
"end": 3260,
"score": 0.9996974468231201,
"start": 3249,
"tag": "IP_ADDRESS",
"value": "10.117.4.14"
},
{
"context": ".4.140,10.117.5.78,10.117.4.14 \"\n//\t\t+ \"--srchost 10.117.4.140 --acceptlinked true \"\n//\t\t+ \"--ison false --algth",
"end": 3292,
"score": 0.9997413754463196,
"start": 3280,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "rithms cAlgorithm;\n\t\t\tString inputString = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--dat",
"end": 3649,
"score": 0.999731719493866,
"start": 3637,
"tag": "IP_ADDRESS",
"value": "10.117.5.254"
},
{
"context": "tring inputString = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--datacentername Data",
"end": 3665,
"score": 0.9964038133621216,
"start": 3661,
"tag": "USERNAME",
"value": "root"
},
{
"context": "g = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--datacentername Datacenter --vmname xc",
"end": 3683,
"score": 0.9900614023208618,
"start": 3677,
"tag": "PASSWORD",
"value": "vmware"
},
{
"context": "cepool resource \"\n\t\t\t\t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.7",
"end": 3840,
"score": 0.9997336864471436,
"start": 3829,
"tag": "IP_ADDRESS",
"value": "10.117.4.71"
},
{
"context": "rce \"\n\t\t\t\t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14",
"end": 3853,
"score": 0.9997228980064392,
"start": 3841,
"tag": "IP_ADDRESS",
"value": "10.117.5.148"
},
{
"context": "\"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10",
"end": 3866,
"score": 0.9997274875640869,
"start": 3854,
"tag": "IP_ADDRESS",
"value": "10.117.7.125"
},
{
"context": " --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --",
"end": 3879,
"score": 0.9997305870056152,
"start": 3867,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "0.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked",
"end": 3891,
"score": 0.9997255206108093,
"start": 3880,
"tag": "IP_ADDRESS",
"value": "10.117.5.78"
},
{
"context": "0.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n\t\t\t\t",
"end": 3903,
"score": 0.9997252821922302,
"start": 3892,
"tag": "IP_ADDRESS",
"value": "10.117.4.14"
},
{
"context": "25,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n\t\t\t\t\t+ \"--ison on --algthse",
"end": 3926,
"score": 0.999738872051239,
"start": 3914,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "rt | stop | destroy\n\t\t\tString stopString = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--dat",
"end": 4086,
"score": 0.9997259974479675,
"start": 4074,
"tag": "IP_ADDRESS",
"value": "10.117.5.254"
},
{
"context": "String stopString = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--datacentername Data",
"end": 4102,
"score": 0.9874905943870544,
"start": 4098,
"tag": "USERNAME",
"value": "root"
},
{
"context": "g = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--datacentername Datacenter --vmname vm",
"end": 4120,
"score": 0.9933993816375732,
"start": 4114,
"tag": "PASSWORD",
"value": "vmware"
},
{
"context": "epool Resources \"\n\t\t\t\t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.7",
"end": 4278,
"score": 0.9997050762176514,
"start": 4267,
"tag": "IP_ADDRESS",
"value": "10.117.4.71"
},
{
"context": "ces \"\n\t\t\t\t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14",
"end": 4291,
"score": 0.999717652797699,
"start": 4279,
"tag": "IP_ADDRESS",
"value": "10.117.5.148"
},
{
"context": "\"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10",
"end": 4304,
"score": 0.9997033476829529,
"start": 4292,
"tag": "IP_ADDRESS",
"value": "10.117.7.125"
},
{
"context": " --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --",
"end": 4317,
"score": 0.9997145533561707,
"start": 4305,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "0.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked",
"end": 4329,
"score": 0.9996752142906189,
"start": 4318,
"tag": "IP_ADDRESS",
"value": "10.117.5.78"
},
{
"context": "0.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n\t\t\t\t",
"end": 4341,
"score": 0.999294102191925,
"start": 4330,
"tag": "IP_ADDRESS",
"value": "10.117.4.14"
},
{
"context": "25,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n\t\t\t\t\t+ \"--ison false --algt",
"end": 4364,
"score": 0.9997369647026062,
"start": 4352,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "--opselect stop\";\n\n\t\t\tString startString = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--dat",
"end": 4486,
"score": 0.9997360706329346,
"start": 4474,
"tag": "IP_ADDRESS",
"value": "10.117.5.254"
},
{
"context": "tring startString = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--datacentername Data",
"end": 4502,
"score": 0.9920204281806946,
"start": 4498,
"tag": "USERNAME",
"value": "root"
},
{
"context": "g = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--datacentername Datacenter --vmname vm",
"end": 4520,
"score": 0.9938122034072876,
"start": 4514,
"tag": "PASSWORD",
"value": "vmware"
},
{
"context": "rcepool cluster \"\n\t\t\t\t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.7",
"end": 4676,
"score": 0.9997158646583557,
"start": 4665,
"tag": "IP_ADDRESS",
"value": "10.117.4.71"
},
{
"context": "ter \"\n\t\t\t\t\t+ \"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14",
"end": 4689,
"score": 0.999725341796875,
"start": 4677,
"tag": "IP_ADDRESS",
"value": "10.117.5.148"
},
{
"context": "\"--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10",
"end": 4702,
"score": 0.9997177720069885,
"start": 4690,
"tag": "IP_ADDRESS",
"value": "10.117.7.125"
},
{
"context": " --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --",
"end": 4715,
"score": 0.9996962547302246,
"start": 4703,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "0.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked",
"end": 4727,
"score": 0.9996675848960876,
"start": 4716,
"tag": "IP_ADDRESS",
"value": "10.117.5.78"
},
{
"context": "0.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n\t\t\t\t",
"end": 4739,
"score": 0.999363124370575,
"start": 4728,
"tag": "IP_ADDRESS",
"value": "10.117.4.14"
},
{
"context": "25,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n\t\t\t\t\t+ \"--ison false --algt",
"end": 4762,
"score": 0.9997236132621765,
"start": 4750,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "pselect start\";\n\n\t\t\tString destroyString = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--dat",
"end": 4887,
"score": 0.9997336268424988,
"start": 4875,
"tag": "IP_ADDRESS",
"value": "10.117.5.254"
},
{
"context": "ing destroyString = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--datacentername Data",
"end": 4903,
"score": 0.9947054982185364,
"start": 4899,
"tag": "USERNAME",
"value": "root"
},
{
"context": "g = \"--url 10.117.5.254 --username root --password vmware \"\n\t\t\t\t\t+ \"--datacentername Datacenter --vmname xc",
"end": 4921,
"score": 0.9936803579330444,
"start": 4915,
"tag": "PASSWORD",
"value": "vmware"
},
{
"context": "cepool resource \"\n\t\t\t\t\t+ \"--number 104 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.7",
"end": 5080,
"score": 0.9997239708900452,
"start": 5069,
"tag": "IP_ADDRESS",
"value": "10.117.4.71"
},
{
"context": "rce \"\n\t\t\t\t\t+ \"--number 104 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14",
"end": 5093,
"score": 0.999718189239502,
"start": 5081,
"tag": "IP_ADDRESS",
"value": "10.117.5.148"
},
{
"context": "\"--number 104 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10",
"end": 5106,
"score": 0.9997052550315857,
"start": 5094,
"tag": "IP_ADDRESS",
"value": "10.117.7.125"
},
{
"context": " --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --",
"end": 5119,
"score": 0.9997120499610901,
"start": 5107,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
},
{
"context": "0.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked",
"end": 5131,
"score": 0.9994060397148132,
"start": 5120,
"tag": "IP_ADDRESS",
"value": "10.117.5.78"
},
{
"context": "0.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n\t\t\t\t",
"end": 5143,
"score": 0.9997487664222717,
"start": 5132,
"tag": "IP_ADDRESS",
"value": "10.117.4.14"
},
{
"context": "25,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true \"\n\t\t\t\t\t+ \"--ison false --algt",
"end": 5166,
"score": 0.9997499585151672,
"start": 5154,
"tag": "IP_ADDRESS",
"value": "10.117.4.140"
}
]
| null | []
| package com.vmware.xclone;
import com.vmware.xclone.algorithm.*;
import com.vmware.xclone.basicops.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;
/**
* <pre>
* Xclone
*
* Fastest VM Provision
*
* <b>Parameters:</b>
* url [required] : url of the web service.
* username [optional] : username for the authentication (default: root)
* password [optional] : password for the authentication (default: vmware)
* datacentername [optional] : name of the datacenter (default: Datacenter)
* resourcepool [optional] : name of the resource pool in the datacenter (default: cluster)
* vmname [required] : Name of the virtual machine
* cloneprefix [required] : prefix of the cloned virtual machine
* number [required] : the number of cloned virtual machines
* srchost [required] : the Ip of src host
* dsthosts [required] : the Ip of all dst hosts
* acceptlinked [optional] : Whether accept Linked clone (default: True)
* isOn [optional] : Whether Power on the VM after cloning (default: True)
* algthselect [optional] : select which algorithm to deploy the VMs [0 | 1 | 2| 3| ...] and default: 1
* opselect [optional] : select which operations (create(default) | start | stop | destroy)
* <b>Example:</b>
* Create example:
* <<
* "--url 10.117.4.228 --username root --password <PASSWORD> "
* + "--datacentername Datacenter --vmname vm_clone --cloneprefix clone_ "
* + "--resourcepool cluster "
* + "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
* + "--ison false --algthselect 1"
* >>
* Stop VMs example:
* <<
* "--url 10.117.4.228 --username root --password <PASSWORD> "
* + "--datacentername Datacenter --vmname vm_clone --cloneprefix clone_ "
* + "--resourcepool cluster "
* + "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
* + "--ison false --algthselect 1 --opselect stop"
* >>
* Destroy VMs example:
* <<
* "--url 10.117.4.228 --username root --password <PASSWORD> "
* + "--datacentername Datacenter --vmname vm_clone --cloneprefix tttclone_ "
* + "--resourcepool cluster "
* + "--number 160 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
* + "--ison false --algthselect 1 --opselect destroy";
* >>
* </pre>
*/
public class Xclones {
private UserInterface ui;
public UserInterface getUi() {
return ui;
}
public void setUi(UserInterface ui) {
this.ui = ui;
}
public Xclones(UserInterface ui) {
this.setUi(ui);
}
public static void main(String[] args) {
// String inputString = "--url 10.117.5.254 --username root --password <PASSWORD> "
// + "--datacentername Datacenter --vmname Xclone_temp --cloneprefix XXclone_ "
// + "--resourcepool Resources "
// + "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 "
// + "--srchost 10.117.4.140 --acceptlinked true "
// + "--ison false --algthselect 1";
// String[] Params = inputString.split("\\s+");
// UserInterface ui = UserInterface.getInstance(Params);
// StatusGet statusTask = new StatusGet(ui, 0, 100);
// statusTask.start();
// }
//}
try {
// private static CloningAlgorithms cAlgorithm;
String inputString = "--url 10.117.5.254 --username root --password <PASSWORD> "
+ "--datacentername Datacenter --vmname xclone --cloneprefix SXclone_ "
+ "--resourcepool resource "
+ "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
+ "--ison on --algthselect 1";
// offString opselect: create | start | stop | destroy
String stopString = "--url 10.117.5.254 --username root --password <PASSWORD> "
+ "--datacentername Datacenter --vmname vm_clone --cloneprefix clone_ "
+ "--resourcepool Resources "
+ "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
+ "--ison false --algthselect 1 --opselect stop";
String startString = "--url 10.117.5.254 --username root --password <PASSWORD> "
+ "--datacentername Datacenter --vmname vm_clone --cloneprefix clone_ "
+ "--resourcepool cluster "
+ "--number 100 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
+ "--ison false --algthselect 1 --opselect start";
String destroyString = "--url 10.117.5.254 --username root --password <PASSWORD> "
+ "--datacentername Datacenter --vmname xclone --cloneprefix testclone_ "
+ "--resourcepool resource "
+ "--number 104 --dsthosts 10.117.4.71,10.117.5.148,10.117.7.125,10.117.4.140,10.117.5.78,10.117.4.14 --srchost 10.117.4.140 --acceptlinked true "
+ "--ison false --algthselect 1 --opselect destroy";
String[] Params = inputString.split("\\s+");
UserInterface ui = UserInterface.getInstance(Params);
String ops = ui.getOpselect();
int perNumDel = 6;
StatusGet statusTask = new StatusGet(ui, 0, 100);
statusTask.start();
long starttime = System.currentTimeMillis();
if (ops.equalsIgnoreCase("destroy")) {
int i = 0;
if(ui.getIsOn() == true)
{
int threadNum = (ui.getNumberOfVMs() + perNumDel - 1)
/ perNumDel;
CountDownLatch latch = new CountDownLatch(threadNum);
for (i = 0; i < ui.getNumberOfVMs(); i = i + perNumDel) {
PoweroffVM offTask = new PoweroffVM(ui.getVmClonePrefix(),
i, perNumDel);
offTask.start();
}
latch.wait();
}
for (i = 0; i < ui.getNumberOfVMs(); i = i + perNumDel) {
DeleteVM delTask = new DeleteVM(ui.getVmClonePrefix(), i,
perNumDel);
delTask.start();
}
} else if (ops.equalsIgnoreCase("stop")) {
int i = 0;
for (i = 0; i < ui.getNumberOfVMs(); i = i + perNumDel) {
PoweroffVM offTask = new PoweroffVM(ui.getVmClonePrefix(),
i, perNumDel);
offTask.start();
}
} else {
switch (ui.getAlgthSelect()) {
case 1:
TreeDeployVm deployVm = new TreeDeployVm(ui);
deployVm.DeployVmFromList();
break;
case 2:
SimpleDeploy sdeployVm = new SimpleDeploy(ui);
sdeployVm.run();
break;
default:
System.out.println("Stupid Boy, you Exceed our alg selection!");
}
}
long stoptime = System.currentTimeMillis();
System.out.printf("Total Time: %d\n", (stoptime-starttime)/60000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 6,935 | 0.630306 | 0.541793 | 167 | 40.335331 | 36.522591 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.125748 | false | false | 3 |
23014c80666756bc5d88c81b96d9a9e11339f604 | 14,654,428,462,117 | ccf82688f082e26cba5fc397c76c77cc007ab2e8 | /Mage.Tests/src/test/java/org/mage/test/cards/single/afc/ShareTheSpoilsTest.java | 8c6ab794249d8d127cc6c38611184e18c8504dba | [
"MIT"
]
| permissive | magefree/mage | https://github.com/magefree/mage | 3261a89320f586d698dd03ca759a7562829f247f | 5dba61244c738f4a184af0d256046312ce21d911 | refs/heads/master | 2023-09-03T15:55:36.650000 | 2023-09-03T03:53:12 | 2023-09-03T03:53:12 | 4,158,448 | 1,803 | 1,133 | MIT | false | 2023-09-14T20:18:55 | 2012-04-27T13:18:34 | 2023-09-11T18:25:38 | 2023-09-14T20:18:55 | 801,396 | 1,632 | 712 | 1,307 | Java | false | false | package org.mage.test.cards.single.afc;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestCommander4Players;
public class ShareTheSpoilsTest extends CardTestCommander4Players {
private static final String shareTheSpoils = "Share the Spoils";
/**
* When Share the Spoils enters the battlefield every player exiles one card.
*/
@Test
public void enterTheBattleField() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 2);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
setStopAt(1, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* When an opponent loses, their exiled cards are removed from the game and all other players exile a new card.
*/
@Test
public void nonOwnerLoses() {
setLife(playerD, 1);
addCard(Zone.BATTLEFIELD, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Banehound", 1);
attack(1, playerA, "Banehound", playerD);
setStopAt(1, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 0);
}
/**
* When an opponent loses, their exiled cards are removed from the game and all other players exile a new card.
*/
@Test
public void nonOwnerConcedes() {
addCard(Zone.BATTLEFIELD, playerA, shareTheSpoils);
concede(1, PhaseStep.PRECOMBAT_MAIN, playerD);
setStopAt(1, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 0);
}
/**
* When owner loses, no new cards should be exiled and owner's exiled cards are removed from the game.
*/
@Test
public void ownerConcedes() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 2);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
concede(1, PhaseStep.POSTCOMBAT_MAIN, playerA);
setStopAt(1, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, 0);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* When owner loses, no new cards should be exiled and owner's exiled cards are removed from the game.
*/
@Test
public void ownerLoses() {
setLife(playerA, 1);
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 2);
addCard(Zone.BATTLEFIELD, playerD, "Banehound", 1);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
attack(2, playerD, "Banehound", playerA);
setStopAt(2, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, 0);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* During your turn, you may cast A card from the cards exiled with share the spoils.
*/
@Test
public void canCastOnOwnTurn() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exiled when Tana is cast with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Tana, the Bloodsower", 1); // {2}{R}{G}
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Tana, the Bloodsower");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
setStopAt(1, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertPermanentCount(playerA, "Tana, the Bloodsower", 1);
assertExileCount(playerA, "Tana, the Bloodsower", 0);
assertExileCount(playerA, "Reliquary Tower", 1);
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* During your turn, you may play A land from the cards exiled with share the spoils.
*/
@Test
public void playLandOnOwnTurn() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exiled when Exotic Orchard is played with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Tana, the Bloodsower", 1); // {2}{R}{G}
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
playLand(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Exotic Orchard");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
setStopAt(1, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertPermanentCount(playerA, "Exotic Orchard", 1);
assertExileCount(playerA, "Exotic Orchard", 0);
assertExileCount(playerA, "Reliquary Tower", 1);
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* You cannot play a card or cast a spell when it's not your turn.
*/
@Test
public void cannotCastWhenNotYourTurn() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Lightning Bolt", 1); // {R}
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
addCard(Zone.LIBRARY, playerB, "Reliquary Tower");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
checkPlayableAbility("normal cast", 2, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Lightning Bolt", false);
checkPlayableAbility("before play", 2, PhaseStep.PRECOMBAT_MAIN, playerA, "Play Reliquary Tower", false);
setStopAt(2, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, "Lightning Bolt", 1);
assertExileCount(playerA, "Reliquary Tower", 0);
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
assertGraveyardCount(playerA, 0);
}
/**
* You may cast A spell or play A card, you cannot do both, or multiple of either.
*/
@Test
public void tryToCastOrPlayASecondCard() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exiled when card is played with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Lightning Bolt", 1); // {R}
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN);
playLand(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Exotic Orchard");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Abilities available after casting with Share the Spoils
checkPlayableAbility("Available Abilities", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Lightning Bolt", false);
setStopAt(1, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, "Exotic Orchard", 0);
assertExileCount(playerA, "Lightning Bolt", 1);
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* Ensure that the spending mana as if it were any color only works for cards exiled with Share the Spoils.
*/
@Test
public void checkManaSpendingForOtherExileSource() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.HAND, playerA, "Augury Raven");
addCard(Zone.BATTLEFIELD, playerA, "Prosper, Tome-Bound");
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
addCard(Zone.BATTLEFIELD, playerA, "Plains", 1);
// 3rd from the top, exile at end of turn with propser
addCard(Zone.LIBRARY, playerA, "Tana, the Bloodsower", 1); // {2}{R}{G}
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Ardenvale Tactician"); // Adventure part is "Dizzying Swoop"
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Foretell Augury Raven
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Foretell");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN);
// Try to cast Tana, you should not be able to since there isn't the {G} for it since she was exiled by Proser
checkPlayableAbility("normal cast", 5, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Tana, the Bloodsower", false);
// Try to activate the foretell on Augury Raven, but we can't since we don't have the {U} for it.
checkPlayableAbility("foretell creature cast", 5, PhaseStep.PRECOMBAT_MAIN, playerA, "Foretell {1}{U}", false);
// Cast an adventure card from hand
castSpell(5, PhaseStep.PRECOMBAT_MAIN, playerA, "Dizzying Swoop");
addTarget(playerA, "Prosper, Tome-Bound");
waitStackResolved(5, PhaseStep.PRECOMBAT_MAIN);
// Make sure the creature card can't be played from exile since there isn't the {W}{W} for it
checkPlayableAbility("creature cast", 5, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Ardenvale Tactician", false);
setStopAt(5, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
// 1 exiled with Share the Spoils
// 1 exiled Prosper (he only exiles one since we stop before the end step of playerA's second turn)
// 1 for the foretold Augury Raven
// 1 for the Dizzying Swoop Adventure
assertExileCount(playerA, 4);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* Make sure that the more difficult types cards work properly.
*/
@Test
public void checkDifficultCards() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exile Lovestruck Beast is cast
addCard(Zone.LIBRARY, playerA, "Ardenvale Tactician"); // Adventure, creature half {1}{W}{W}
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Lovestruck Beast"); // Adventure, adventure half "Heart's Desire" {G}
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Mountain");
// Modal dual face, cast front
addCard(Zone.LIBRARY, playerB, "Alrund, God of the Cosmos"); // Backside is "Hakka, Whispering Raven"
// Modal fual face, cast back
addCard(Zone.LIBRARY, playerC, "Esika, God of the Tree"); // Backside is "The Prismatic Bridge"
// Split card
addCard(Zone.LIBRARY, playerD, "Fire // Ice");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Cast the Adventure half of an Adventure card
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Heart's Desire");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Cast the Creature half of an Adventure card
castSpell(5, PhaseStep.PRECOMBAT_MAIN, playerA, "Ardenvale Tactician");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Cast split card
castSpell(9, PhaseStep.PRECOMBAT_MAIN, playerA, "Ice");
addTarget(playerA, "Mountain");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Cast front side of Modal dual face card
castSpell(13, PhaseStep.PRECOMBAT_MAIN, playerA, "Alrund, God of the Cosmos");
setChoice(playerA, "Land");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Cast back side of Modal dual face card
castSpell(17, PhaseStep.PRECOMBAT_MAIN, playerA, "The Prismatic Bridge");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
setStopAt(17, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
assertPermanentCount(playerA, "Ardenvale Tactician", 1);
assertExileCount(playerA, "Lovestruck Beast", 1);
// 1 from Share the Spoils exiling a card for ETB
// 1 from casting the Adventur half of a card (Heart's Desire) and leaving it in exile
// 1 from casting "Ice"
// 1 from casting "Alrund, God of the Cosmos"
// 1 from casting "The Prismatic Bridge
assertExileCount(playerA, 5);
// 0 since playerA cast their card and replaced it with one of their own
assertExileCount(playerB, 0);
// 0 since playerA cast their card and replaced it with one of their own
assertExileCount(playerC, 0);
// 0 since playerA cast their card and replaced it with one of their own
assertExileCount(playerD, 0);
// Ice is the only card that went in here
assertGraveyardCount(playerD, 1);
}
/**
* When Share the Spoils leaves the battlefield, the exiled cards are no longer playable.
*/
@Test
public void ensureCardsNotPlayable() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exiled when card is played with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Aether Helix", 1); // {3}{G}{U}
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
// Target in graveyard for Aether Helix
addCard(Zone.GRAVEYARD, playerA, "Aether Spellbomb");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Aether Helix");
addTarget(playerA, shareTheSpoils);
addTarget(playerA, "Aether Spellbomb");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
checkPlayableAbility("before play", 5, PhaseStep.PRECOMBAT_MAIN, playerA, "Play Exotic Orchard", false);
setStopAt(5, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, "Aether Helix", 0);
assertExileCount(playerA, "Exotic Orchard", 1);
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
assertGraveyardCount(playerA, 1);
}
/**
* When this share the spoils is destroyed and it is somehow recast, it will create a new pool of cards.
* The previous cards are no longer playable.
*/
@Test
public void checkDifferentCardPools() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 9);
// 3rd from the top, exiled when card is played with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Aether Helix", 1); // {3}{G}{U}
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
// Target in graveyard for Aether Helix
addCard(Zone.GRAVEYARD, playerA, "Aether Spellbomb");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Casting Aether Helix from exile with Share the spoils.
// Doing so exiles Exotic Orchard.
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Aether Helix");
addTarget(playerA, shareTheSpoils);
addTarget(playerA, "Aether Spellbomb");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Recast, exile a new set of cards
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Exotic Orchard was exile by the first Share the Spoils, so can't be cast again with the new one
checkPlayableAbility("before play", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Play Exotic Orchard", false);
setStopAt(1, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, "Aether Helix", 0);
assertExileCount(playerA, "Exotic Orchard", 1);
assertExileCount(playerA, 2);
assertExileCount(playerB, 2);
assertExileCount(playerC, 2);
assertExileCount(playerD, 2);
assertGraveyardCount(playerA, 1);
}
/**
* When a card exiled by Share the Spoils is played, another card is exiled.
* Check that this newly exiled card is correctly taken from the deck of the player who played the card,
* AND NOT from the controller of Share the Spoils.
*
* For https://github.com/magefree/mage/issues/9046
*/
@Test
public void checkExileFromCorrectDeck() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exiled when card is played with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Lightning Bolt", 1); // {R}
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN);
playLand(2, PhaseStep.PRECOMBAT_MAIN, playerD, "Exotic Orchard");
waitStackResolved(2, PhaseStep.PRECOMBAT_MAIN, playerD);
setStopAt(2, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertPermanentCount(playerD, "Exotic Orchard",1);
assertExileCount(playerA, 0); // playerA's Exotic Orchard was played by playerD
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 2); // 2nd card exiled when they played the Exotic Orchard
}
}
| UTF-8 | Java | 20,783 | java | ShareTheSpoilsTest.java | Java | [
{
"context": "ecute();\n\n assertPermanentCount(playerA, \"Tana, the Bloodsower\", 1);\n\n assertExileCount(p",
"end": 4854,
"score": 0.6184324622154236,
"start": 4851,
"tag": "NAME",
"value": "ana"
},
{
"context": "ast front\n addCard(Zone.LIBRARY, playerB, \"Alrund, God of the Cosmos\"); // Backside is \"Hakka, Whis",
"end": 12851,
"score": 0.9326881766319275,
"start": 12845,
"tag": "NAME",
"value": "Alrund"
},
{
"context": "cast back\n addCard(Zone.LIBRARY, playerC, \"Esika, God of the Tree\"); // Backside is \"The Prisma",
"end": 12995,
"score": 0.7702069878578186,
"start": 12993,
"tag": "NAME",
"value": "Es"
},
{
"context": "s is cast\n addCard(Zone.LIBRARY, playerA, \"Aether Helix\", 1); // {3}{G}{U}\n // Topmost, draw at be",
"end": 15875,
"score": 0.9349058866500854,
"start": 15863,
"tag": "NAME",
"value": "Aether Helix"
},
{
"context": "g of turn\n addCard(Zone.LIBRARY, playerA, \"Reliquary Tower\");\n\n // Target in graveyard fo",
"end": 15984,
"score": 0.6638281345367432,
"start": 15981,
"tag": "NAME",
"value": "Rel"
},
{
"context": "r Helix\n addCard(Zone.GRAVEYARD, playerA, \"Aether Spellbomb\");\n\n skipInitShuffling();\n\n castSpe",
"end": 16107,
"score": 0.8260458111763,
"start": 16091,
"tag": "NAME",
"value": "Aether Spellbomb"
},
{
"context": " castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, \"Aether Helix\");\n addTarget(playerA, shareTheSpoil",
"end": 16344,
"score": 0.7317403554916382,
"start": 16338,
"tag": "NAME",
"value": "Aether"
},
{
"context": "(1, PhaseStep.PRECOMBAT_MAIN, playerA, \"Aether Helix\");\n addTarget(playerA, shareTheSpoils);\n ",
"end": 16350,
"score": 0.530016303062439,
"start": 16348,
"tag": "NAME",
"value": "ix"
},
{
"context": "erA, shareTheSpoils);\n addTarget(playerA, \"Aether Spellbomb\");\n waitStackResolved(1, PhaseStep.PRECOMB",
"end": 16442,
"score": 0.7057979702949524,
"start": 16426,
"tag": "NAME",
"value": "Aether Spellbomb"
},
{
"context": " execute();\n\n assertExileCount(playerA, \"Aether Helix\", 0);\n assertExileCount(playerA, \"Exotic O",
"end": 16771,
"score": 0.92848140001297,
"start": 16759,
"tag": "NAME",
"value": "Aether Helix"
},
{
"context": "s is cast\n addCard(Zone.LIBRARY, playerA, \"Aether Helix\", 1); // {3}{G}{U}\n // Topmost, draw at be",
"end": 17632,
"score": 0.9886714220046997,
"start": 17620,
"tag": "NAME",
"value": "Aether Helix"
},
{
"context": "g of turn\n addCard(Zone.LIBRARY, playerA, \"Reliquary Tower\");\n\n // Target in graveyard for Aeth",
"end": 17747,
"score": 0.7046709060668945,
"start": 17738,
"tag": "NAME",
"value": "Reliquary"
},
{
"context": "r Helix\n addCard(Zone.GRAVEYARD, playerA, \"Aether Spellbomb\");\n\n skipInitShuffling();\n\n castSpe",
"end": 17864,
"score": 0.9642213582992554,
"start": 17848,
"tag": "NAME",
"value": "Aether Spellbomb"
},
{
"context": " castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, \"Aether Helix\");\n addTarget(playerA, shareTheSpoils);\n ",
"end": 18216,
"score": 0.9657716155052185,
"start": 18204,
"tag": "NAME",
"value": "Aether Helix"
},
{
"context": "erA, shareTheSpoils);\n addTarget(playerA, \"Aether Spellbomb\");\n waitStackResolved(1, PhaseStep.PRECOMB",
"end": 18308,
"score": 0.9720686078071594,
"start": 18292,
"tag": "NAME",
"value": "Aether Spellbomb"
},
{
"context": " execute();\n\n assertExileCount(playerA, \"Aether Helix\", 0);\n assertExileCount(playerA, \"Exotic O",
"end": 18926,
"score": 0.9939461946487427,
"start": 18914,
"tag": "NAME",
"value": "Aether Helix"
},
{
"context": " the Spoils.\n *\n * For https://github.com/magefree/mage/issues/9046\n */\n @Test\n public voi",
"end": 19491,
"score": 0.9995716214179993,
"start": 19483,
"tag": "USERNAME",
"value": "magefree"
}
]
| null | []
| package org.mage.test.cards.single.afc;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestCommander4Players;
public class ShareTheSpoilsTest extends CardTestCommander4Players {
private static final String shareTheSpoils = "Share the Spoils";
/**
* When Share the Spoils enters the battlefield every player exiles one card.
*/
@Test
public void enterTheBattleField() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 2);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
setStopAt(1, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* When an opponent loses, their exiled cards are removed from the game and all other players exile a new card.
*/
@Test
public void nonOwnerLoses() {
setLife(playerD, 1);
addCard(Zone.BATTLEFIELD, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Banehound", 1);
attack(1, playerA, "Banehound", playerD);
setStopAt(1, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 0);
}
/**
* When an opponent loses, their exiled cards are removed from the game and all other players exile a new card.
*/
@Test
public void nonOwnerConcedes() {
addCard(Zone.BATTLEFIELD, playerA, shareTheSpoils);
concede(1, PhaseStep.PRECOMBAT_MAIN, playerD);
setStopAt(1, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 0);
}
/**
* When owner loses, no new cards should be exiled and owner's exiled cards are removed from the game.
*/
@Test
public void ownerConcedes() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 2);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
concede(1, PhaseStep.POSTCOMBAT_MAIN, playerA);
setStopAt(1, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, 0);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* When owner loses, no new cards should be exiled and owner's exiled cards are removed from the game.
*/
@Test
public void ownerLoses() {
setLife(playerA, 1);
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 2);
addCard(Zone.BATTLEFIELD, playerD, "Banehound", 1);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
attack(2, playerD, "Banehound", playerA);
setStopAt(2, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, 0);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* During your turn, you may cast A card from the cards exiled with share the spoils.
*/
@Test
public void canCastOnOwnTurn() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exiled when Tana is cast with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Tana, the Bloodsower", 1); // {2}{R}{G}
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Tana, the Bloodsower");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
setStopAt(1, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertPermanentCount(playerA, "Tana, the Bloodsower", 1);
assertExileCount(playerA, "Tana, the Bloodsower", 0);
assertExileCount(playerA, "Reliquary Tower", 1);
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* During your turn, you may play A land from the cards exiled with share the spoils.
*/
@Test
public void playLandOnOwnTurn() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exiled when Exotic Orchard is played with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Tana, the Bloodsower", 1); // {2}{R}{G}
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
playLand(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Exotic Orchard");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
setStopAt(1, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertPermanentCount(playerA, "Exotic Orchard", 1);
assertExileCount(playerA, "Exotic Orchard", 0);
assertExileCount(playerA, "Reliquary Tower", 1);
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* You cannot play a card or cast a spell when it's not your turn.
*/
@Test
public void cannotCastWhenNotYourTurn() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Lightning Bolt", 1); // {R}
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
addCard(Zone.LIBRARY, playerB, "Reliquary Tower");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
checkPlayableAbility("normal cast", 2, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Lightning Bolt", false);
checkPlayableAbility("before play", 2, PhaseStep.PRECOMBAT_MAIN, playerA, "Play Reliquary Tower", false);
setStopAt(2, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, "Lightning Bolt", 1);
assertExileCount(playerA, "Reliquary Tower", 0);
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
assertGraveyardCount(playerA, 0);
}
/**
* You may cast A spell or play A card, you cannot do both, or multiple of either.
*/
@Test
public void tryToCastOrPlayASecondCard() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exiled when card is played with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Lightning Bolt", 1); // {R}
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN);
playLand(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Exotic Orchard");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Abilities available after casting with Share the Spoils
checkPlayableAbility("Available Abilities", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Lightning Bolt", false);
setStopAt(1, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, "Exotic Orchard", 0);
assertExileCount(playerA, "Lightning Bolt", 1);
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* Ensure that the spending mana as if it were any color only works for cards exiled with Share the Spoils.
*/
@Test
public void checkManaSpendingForOtherExileSource() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.HAND, playerA, "Augury Raven");
addCard(Zone.BATTLEFIELD, playerA, "Prosper, Tome-Bound");
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
addCard(Zone.BATTLEFIELD, playerA, "Plains", 1);
// 3rd from the top, exile at end of turn with propser
addCard(Zone.LIBRARY, playerA, "Tana, the Bloodsower", 1); // {2}{R}{G}
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Ardenvale Tactician"); // Adventure part is "Dizzying Swoop"
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Foretell Augury Raven
activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Foretell");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN);
// Try to cast Tana, you should not be able to since there isn't the {G} for it since she was exiled by Proser
checkPlayableAbility("normal cast", 5, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Tana, the Bloodsower", false);
// Try to activate the foretell on Augury Raven, but we can't since we don't have the {U} for it.
checkPlayableAbility("foretell creature cast", 5, PhaseStep.PRECOMBAT_MAIN, playerA, "Foretell {1}{U}", false);
// Cast an adventure card from hand
castSpell(5, PhaseStep.PRECOMBAT_MAIN, playerA, "Dizzying Swoop");
addTarget(playerA, "Prosper, Tome-Bound");
waitStackResolved(5, PhaseStep.PRECOMBAT_MAIN);
// Make sure the creature card can't be played from exile since there isn't the {W}{W} for it
checkPlayableAbility("creature cast", 5, PhaseStep.PRECOMBAT_MAIN, playerA, "Cast Ardenvale Tactician", false);
setStopAt(5, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
// 1 exiled with Share the Spoils
// 1 exiled Prosper (he only exiles one since we stop before the end step of playerA's second turn)
// 1 for the foretold Augury Raven
// 1 for the Dizzying Swoop Adventure
assertExileCount(playerA, 4);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
}
/**
* Make sure that the more difficult types cards work properly.
*/
@Test
public void checkDifficultCards() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exile Lovestruck Beast is cast
addCard(Zone.LIBRARY, playerA, "Ardenvale Tactician"); // Adventure, creature half {1}{W}{W}
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Lovestruck Beast"); // Adventure, adventure half "Heart's Desire" {G}
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Mountain");
// Modal dual face, cast front
addCard(Zone.LIBRARY, playerB, "Alrund, God of the Cosmos"); // Backside is "Hakka, Whispering Raven"
// Modal fual face, cast back
addCard(Zone.LIBRARY, playerC, "Esika, God of the Tree"); // Backside is "The Prismatic Bridge"
// Split card
addCard(Zone.LIBRARY, playerD, "Fire // Ice");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Cast the Adventure half of an Adventure card
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Heart's Desire");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Cast the Creature half of an Adventure card
castSpell(5, PhaseStep.PRECOMBAT_MAIN, playerA, "Ardenvale Tactician");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Cast split card
castSpell(9, PhaseStep.PRECOMBAT_MAIN, playerA, "Ice");
addTarget(playerA, "Mountain");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Cast front side of Modal dual face card
castSpell(13, PhaseStep.PRECOMBAT_MAIN, playerA, "Alrund, God of the Cosmos");
setChoice(playerA, "Land");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Cast back side of Modal dual face card
castSpell(17, PhaseStep.PRECOMBAT_MAIN, playerA, "The Prismatic Bridge");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
setStopAt(17, PhaseStep.POSTCOMBAT_MAIN);
setStrictChooseMode(true);
execute();
assertPermanentCount(playerA, "Ardenvale Tactician", 1);
assertExileCount(playerA, "Lovestruck Beast", 1);
// 1 from Share the Spoils exiling a card for ETB
// 1 from casting the Adventur half of a card (Heart's Desire) and leaving it in exile
// 1 from casting "Ice"
// 1 from casting "Alrund, God of the Cosmos"
// 1 from casting "The Prismatic Bridge
assertExileCount(playerA, 5);
// 0 since playerA cast their card and replaced it with one of their own
assertExileCount(playerB, 0);
// 0 since playerA cast their card and replaced it with one of their own
assertExileCount(playerC, 0);
// 0 since playerA cast their card and replaced it with one of their own
assertExileCount(playerD, 0);
// Ice is the only card that went in here
assertGraveyardCount(playerD, 1);
}
/**
* When Share the Spoils leaves the battlefield, the exiled cards are no longer playable.
*/
@Test
public void ensureCardsNotPlayable() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exiled when card is played with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "<NAME>", 1); // {3}{G}{U}
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
// Target in graveyard for Aether Helix
addCard(Zone.GRAVEYARD, playerA, "<NAME>");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Aether Helix");
addTarget(playerA, shareTheSpoils);
addTarget(playerA, "<NAME>");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
checkPlayableAbility("before play", 5, PhaseStep.PRECOMBAT_MAIN, playerA, "Play Exotic Orchard", false);
setStopAt(5, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, "<NAME>", 0);
assertExileCount(playerA, "Exotic Orchard", 1);
assertExileCount(playerA, 1);
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 1);
assertGraveyardCount(playerA, 1);
}
/**
* When this share the spoils is destroyed and it is somehow recast, it will create a new pool of cards.
* The previous cards are no longer playable.
*/
@Test
public void checkDifferentCardPools() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 9);
// 3rd from the top, exiled when card is played with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "<NAME>", 1); // {3}{G}{U}
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
// Target in graveyard for Aether Helix
addCard(Zone.GRAVEYARD, playerA, "<NAME>");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Casting Aether Helix from exile with Share the spoils.
// Doing so exiles Exotic Orchard.
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "<NAME>");
addTarget(playerA, shareTheSpoils);
addTarget(playerA, "<NAME>");
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Recast, exile a new set of cards
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN, playerA);
// Exotic Orchard was exile by the first Share the Spoils, so can't be cast again with the new one
checkPlayableAbility("before play", 1, PhaseStep.PRECOMBAT_MAIN, playerA, "Play Exotic Orchard", false);
setStopAt(1, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertExileCount(playerA, "<NAME>", 0);
assertExileCount(playerA, "Exotic Orchard", 1);
assertExileCount(playerA, 2);
assertExileCount(playerB, 2);
assertExileCount(playerC, 2);
assertExileCount(playerD, 2);
assertGraveyardCount(playerA, 1);
}
/**
* When a card exiled by Share the Spoils is played, another card is exiled.
* Check that this newly exiled card is correctly taken from the deck of the player who played the card,
* AND NOT from the controller of Share the Spoils.
*
* For https://github.com/magefree/mage/issues/9046
*/
@Test
public void checkExileFromCorrectDeck() {
addCard(Zone.HAND, playerA, shareTheSpoils);
addCard(Zone.BATTLEFIELD, playerA, "Mountain", 8);
// 3rd from the top, exiled when card is played with Share the Spoils
addCard(Zone.LIBRARY, playerA, "Lightning Bolt", 1); // {R}
// 2nd from the top, exile when Share the Spoils is cast
addCard(Zone.LIBRARY, playerA, "Exotic Orchard");
// Topmost, draw at beginning of turn
addCard(Zone.LIBRARY, playerA, "Reliquary Tower");
skipInitShuffling();
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, shareTheSpoils);
waitStackResolved(1, PhaseStep.PRECOMBAT_MAIN);
playLand(2, PhaseStep.PRECOMBAT_MAIN, playerD, "Exotic Orchard");
waitStackResolved(2, PhaseStep.PRECOMBAT_MAIN, playerD);
setStopAt(2, PhaseStep.END_TURN);
setStrictChooseMode(true);
execute();
assertPermanentCount(playerD, "Exotic Orchard",1);
assertExileCount(playerA, 0); // playerA's Exotic Orchard was played by playerD
assertExileCount(playerB, 1);
assertExileCount(playerC, 1);
assertExileCount(playerD, 2); // 2nd card exiled when they played the Exotic Orchard
}
}
| 20,713 | 0.654477 | 0.643603 | 544 | 37.204044 | 30.692329 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.419118 | false | false | 3 |
735c763fd6f942d2acd5fa1b9027025cb0023e21 | 2,259,152,816,058 | 72150eedfc69e42d2546817c021649d279318dee | /core/src/com/soccer/states/ClientState.java | acb5995704340abe767137a027920dcf7b18d413 | []
| no_license | savigny001/ButtonSoccer | https://github.com/savigny001/ButtonSoccer | f8a09c357141bd52783b7fb12a242d2b1e0efb83 | 6159f80b01c93c6e54314eec15294f3e175f916c | refs/heads/master | 2021-06-25T14:53:41.180000 | 2017-09-11T15:15:56 | 2017-09-11T15:15:56 | 103,150,337 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.soccer.states;
import com.soccer.pojo.TeamSide;
import java.util.List;
public class ClientState {
public StateType stateType;
public List<Integer> playerNumbers;
public TeamSide teamSide;
public Integer numberOfPlaceing, placedPlayers;
public ClientState() {
}
}
| UTF-8 | Java | 304 | java | ClientState.java | Java | []
| null | []
| package com.soccer.states;
import com.soccer.pojo.TeamSide;
import java.util.List;
public class ClientState {
public StateType stateType;
public List<Integer> playerNumbers;
public TeamSide teamSide;
public Integer numberOfPlaceing, placedPlayers;
public ClientState() {
}
}
| 304 | 0.736842 | 0.736842 | 16 | 18 | 16.397408 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
c279b4e3deb3efc4a42e36887410a1e32b2a4a35 | 5,171,140,647,461 | b9096391f4c0ed556b95b8de26f5c84f672fffef | /src/com/practice/concurrency/NotSafetySolution3.java | 7dd1883e6ac4d2cb23530ecdedff94fa780da0e6 | []
| no_license | 123CLOUD123/mixed-learning | https://github.com/123CLOUD123/mixed-learning | 110406bb850e340bc9c1af6536f12c3e8553ba95 | 40a281e27b123735906a863b9c9c189425fa8677 | refs/heads/master | 2023-06-28T07:06:43.487000 | 2021-07-23T03:22:53 | 2021-07-23T03:22:53 | 195,952,664 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.practice.concurrency;
/**
* 多线程共享可变变量时,可通过ThreadLocal来实现线程安全,ThreadLocal类通过为每个线程创建一个与该线程相关联
* 的ThreadLocalMap来存储线程要访问的变量,这样的方式改杜绝了共享的行为,改成线程封闭的方式来访问变量,变量不
* 被共享了,也就一定是线程安全的了
* @author Cloud
*
*/
public class NotSafetySolution3 {
// private static Long count;
private static ThreadLocal<Long> countHolder = new ThreadLocal<Long>() {
public Long initValue() {
return 0L;
}
};
public static void changeCount() {
countHolder.set(countHolder.get() + 1);
}
}
| UTF-8 | Java | 696 | java | NotSafetySolution3.java | Java | [
{
"context": ",改成线程封闭的方式来访问变量,变量不\n * 被共享了,也就一定是线程安全的了\n * @author Cloud\n *\n */\npublic class NotSafetySolution3 {\n\n//\tpriv",
"end": 206,
"score": 0.8106845617294312,
"start": 201,
"tag": "USERNAME",
"value": "Cloud"
}
]
| null | []
| package com.practice.concurrency;
/**
* 多线程共享可变变量时,可通过ThreadLocal来实现线程安全,ThreadLocal类通过为每个线程创建一个与该线程相关联
* 的ThreadLocalMap来存储线程要访问的变量,这样的方式改杜绝了共享的行为,改成线程封闭的方式来访问变量,变量不
* 被共享了,也就一定是线程安全的了
* @author Cloud
*
*/
public class NotSafetySolution3 {
// private static Long count;
private static ThreadLocal<Long> countHolder = new ThreadLocal<Long>() {
public Long initValue() {
return 0L;
}
};
public static void changeCount() {
countHolder.set(countHolder.get() + 1);
}
}
| 696 | 0.742857 | 0.736735 | 23 | 20.304348 | 22.514603 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.913043 | false | false | 3 |
201305943e494393e51610e31ac16b8d34c4c9b4 | 26,792,006,061,884 | 568ba7c192addffbed427f0bd99dbdae3df5a80e | /src/main/java/monero/wallet/model/MoneroMessageSignatureType.java | f8ffdb46aaede3e6e819c7c715c0812d372d0e19 | [
"MIT",
"Apache-2.0"
]
| permissive | woodser/monero-wallet-java | https://github.com/woodser/monero-wallet-java | 97896665716ac1237822fb3cbb7119c668d0b671 | 913827fc76a92f2e0d38222f244c7be5561cbbee | refs/heads/master | 2021-01-19T11:02:25.232000 | 2021-01-15T19:46:04 | 2021-01-15T19:46:04 | 87,889,947 | 16 | 13 | null | null | null | null | null | null | null | null | null | null | null | null | null | package monero.wallet.model;
/**
* Enumerate message signature types.
*/
public enum MoneroMessageSignatureType {
SIGN_WITH_SPEND_KEY,
SIGN_WITH_VIEW_KEY
}
| UTF-8 | Java | 163 | java | MoneroMessageSignatureType.java | Java | []
| null | []
| package monero.wallet.model;
/**
* Enumerate message signature types.
*/
public enum MoneroMessageSignatureType {
SIGN_WITH_SPEND_KEY,
SIGN_WITH_VIEW_KEY
}
| 163 | 0.742331 | 0.742331 | 9 | 17.111111 | 14.984766 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 3 |
9774349a36e02858368119f1f2c896e5b5d58b74 | 4,896,262,777,562 | 5c84ba11bc3f34016a06d8f084b6385ed4d13acc | /app/src/main/java/com/google/qllm/View/Employee/EmployeeAddActivity.java | 7e48505fd1561c2bfa5aed6038e02dfa05e35912 | []
| no_license | zbotvnz/QLLM | https://github.com/zbotvnz/QLLM | c1c3d2338e5a09a15dd7f10b4f2383a0363b5055 | d987a03ace29320325ffa5215dc5da3e6c080f9d | refs/heads/master | 2020-03-05T20:57:31.245000 | 2017-07-08T04:11:44 | 2017-07-08T04:11:44 | 93,628,802 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.qllm.View.Employee;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.google.qllm.Object.Employee;
import com.google.qllm.Presenter.CheckNetwork.PresenterCheckNetwork;
import com.google.qllm.R;
import com.google.qllm.View.CheckNetwork.ViewCheckNetwork;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
public class EmployeeAddActivity extends AppCompatActivity implements ViewCheckNetwork {
private PresenterCheckNetwork checkNetwork;
private String title;
private String id;
private String fullname,phone,status;
private ProgressDialog pdLoading;
private int REQUEST_ID_IMAGE_CAPTURE = 1;//camera code request
private int REQUEST_IMAGE_PICK = 2;//Pick Image from gallery
private EditText edtFullnameEmployeeAdd,
edtPhoneEmployeeAdd;
private SwitchCompat switchStatusEmployeeAdd;
private Button btnAddEmployeeAdd,
btnCannelEmployeeAdd;
private TextInputLayout tilFullnameEmployeeAdd,
tilPhoneEmployeeAdd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//screen portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// status bar color
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
Window window=getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
window.setStatusBarColor(ContextCompat.getColor(this,R.color.Black));
}
//
setContentView(R.layout.activity_employee_add);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarEmployeeAdd);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
title=getIntent().getStringExtra("Title");
setTitle(title);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Init();
}
private void Init()
{
pdLoading=new ProgressDialog(this);
edtFullnameEmployeeAdd= (EditText) findViewById(R.id.edtFullnameEmployeeAdd);
edtPhoneEmployeeAdd= (EditText) findViewById(R.id.edtPhoneEmployeeAdd);
switchStatusEmployeeAdd = (SwitchCompat) findViewById(R.id.switchStatusEmployeeAdd);
btnAddEmployeeAdd= (Button) findViewById(R.id.btnAddEmployeeAdd);
btnCannelEmployeeAdd= (Button) findViewById(R.id.btnCannelEmployeeAdd);
tilFullnameEmployeeAdd= (TextInputLayout) findViewById(R.id.tilFullnameEmployeeAdd);
tilPhoneEmployeeAdd= (TextInputLayout) findViewById(R.id.tilPhoneEmployeeAdd);
if(title.equals("Sửa Nhân Viên"))
{
id=getIntent().getStringExtra("ID");
fullname=getIntent().getStringExtra("Fullname");
phone=getIntent().getStringExtra("Phone");
status=getIntent().getStringExtra("Status");
edtFullnameEmployeeAdd.setText(fullname);
if(phone.equals("Chưa Cập Nhật")==false) {
edtPhoneEmployeeAdd.setText(phone);
}
if(status.equals("Đang làm việc"))
{
switchStatusEmployeeAdd.setChecked(true);
}
else
{
switchStatusEmployeeAdd.setChecked(false);
}
btnAddEmployeeAdd.setText("Lưu");
}
checkNetwork=new PresenterCheckNetwork(this,getApplicationContext());
btnAddEmployeeAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String fullname=edtFullnameEmployeeAdd.getText().toString();
if(fullname.equals("")||fullname==null)
{
tilFullnameEmployeeAdd.setError("Họ tên không được để trống");
}
else
{
tilFullnameEmployeeAdd.setError(null);
checkNetwork.receiveHandleCheckNetwork();
}
}
});
btnCannelEmployeeAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public void onNetworkConnectionFailed() {
AlertDialog.Builder dialog=new AlertDialog.Builder(getApplicationContext());
dialog.setTitle("Lỗi mạng");
dialog.setMessage("Không có kết nối Internet, Vui lòng kiểm tra lại");
dialog.setCancelable(false);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
@Override
public void onNetworkConnectionSuccess() {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
pdLoading.setMessage("Đang xử lý...");
pdLoading.setCanceledOnTouchOutside(false);
pdLoading.setCancelable(false);
pdLoading.show();
addEmployee();
}
});
}
private void addEmployee()
{
final String fullname=edtFullnameEmployeeAdd.getText().toString();
final String avatar="";
final String phone=edtPhoneEmployeeAdd.getText().toString();
final Boolean status=switchStatusEmployeeAdd.isChecked();
DatabaseReference root= FirebaseDatabase.getInstance().getReference();
if(title.equals("Thêm Nhân Viên"))
{
Employee employee=new Employee(fullname,phone,avatar,status);
root.child("Employee").push().setValue(employee);
pdLoading.dismiss();
finish();
}
else
{
Employee employee=new Employee(fullname,phone,avatar,status);
root.child("Employee").child(id).setValue(employee);
pdLoading.dismiss();
finish();
}
}
}
| UTF-8 | Java | 7,942 | java | EmployeeAddActivity.java | Java | []
| null | []
| package com.google.qllm.View.Employee;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.google.qllm.Object.Employee;
import com.google.qllm.Presenter.CheckNetwork.PresenterCheckNetwork;
import com.google.qllm.R;
import com.google.qllm.View.CheckNetwork.ViewCheckNetwork;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
public class EmployeeAddActivity extends AppCompatActivity implements ViewCheckNetwork {
private PresenterCheckNetwork checkNetwork;
private String title;
private String id;
private String fullname,phone,status;
private ProgressDialog pdLoading;
private int REQUEST_ID_IMAGE_CAPTURE = 1;//camera code request
private int REQUEST_IMAGE_PICK = 2;//Pick Image from gallery
private EditText edtFullnameEmployeeAdd,
edtPhoneEmployeeAdd;
private SwitchCompat switchStatusEmployeeAdd;
private Button btnAddEmployeeAdd,
btnCannelEmployeeAdd;
private TextInputLayout tilFullnameEmployeeAdd,
tilPhoneEmployeeAdd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//screen portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// status bar color
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
Window window=getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
window.setStatusBarColor(ContextCompat.getColor(this,R.color.Black));
}
//
setContentView(R.layout.activity_employee_add);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarEmployeeAdd);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
title=getIntent().getStringExtra("Title");
setTitle(title);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Init();
}
private void Init()
{
pdLoading=new ProgressDialog(this);
edtFullnameEmployeeAdd= (EditText) findViewById(R.id.edtFullnameEmployeeAdd);
edtPhoneEmployeeAdd= (EditText) findViewById(R.id.edtPhoneEmployeeAdd);
switchStatusEmployeeAdd = (SwitchCompat) findViewById(R.id.switchStatusEmployeeAdd);
btnAddEmployeeAdd= (Button) findViewById(R.id.btnAddEmployeeAdd);
btnCannelEmployeeAdd= (Button) findViewById(R.id.btnCannelEmployeeAdd);
tilFullnameEmployeeAdd= (TextInputLayout) findViewById(R.id.tilFullnameEmployeeAdd);
tilPhoneEmployeeAdd= (TextInputLayout) findViewById(R.id.tilPhoneEmployeeAdd);
if(title.equals("Sửa Nhân Viên"))
{
id=getIntent().getStringExtra("ID");
fullname=getIntent().getStringExtra("Fullname");
phone=getIntent().getStringExtra("Phone");
status=getIntent().getStringExtra("Status");
edtFullnameEmployeeAdd.setText(fullname);
if(phone.equals("Chưa Cập Nhật")==false) {
edtPhoneEmployeeAdd.setText(phone);
}
if(status.equals("Đang làm việc"))
{
switchStatusEmployeeAdd.setChecked(true);
}
else
{
switchStatusEmployeeAdd.setChecked(false);
}
btnAddEmployeeAdd.setText("Lưu");
}
checkNetwork=new PresenterCheckNetwork(this,getApplicationContext());
btnAddEmployeeAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String fullname=edtFullnameEmployeeAdd.getText().toString();
if(fullname.equals("")||fullname==null)
{
tilFullnameEmployeeAdd.setError("Họ tên không được để trống");
}
else
{
tilFullnameEmployeeAdd.setError(null);
checkNetwork.receiveHandleCheckNetwork();
}
}
});
btnCannelEmployeeAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public void onNetworkConnectionFailed() {
AlertDialog.Builder dialog=new AlertDialog.Builder(getApplicationContext());
dialog.setTitle("Lỗi mạng");
dialog.setMessage("Không có kết nối Internet, Vui lòng kiểm tra lại");
dialog.setCancelable(false);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
@Override
public void onNetworkConnectionSuccess() {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
pdLoading.setMessage("Đang xử lý...");
pdLoading.setCanceledOnTouchOutside(false);
pdLoading.setCancelable(false);
pdLoading.show();
addEmployee();
}
});
}
private void addEmployee()
{
final String fullname=edtFullnameEmployeeAdd.getText().toString();
final String avatar="";
final String phone=edtPhoneEmployeeAdd.getText().toString();
final Boolean status=switchStatusEmployeeAdd.isChecked();
DatabaseReference root= FirebaseDatabase.getInstance().getReference();
if(title.equals("Thêm Nhân Viên"))
{
Employee employee=new Employee(fullname,phone,avatar,status);
root.child("Employee").push().setValue(employee);
pdLoading.dismiss();
finish();
}
else
{
Employee employee=new Employee(fullname,phone,avatar,status);
root.child("Employee").child(id).setValue(employee);
pdLoading.dismiss();
finish();
}
}
}
| 7,942 | 0.663246 | 0.662232 | 221 | 34.714931 | 25.388123 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.624434 | false | false | 3 |
6d78464638febb15b993695f3da2c82827603abb | 31,344,671,394,853 | 6ed88b3dd16688c55d2bcf7dd94153d3a3783977 | /src/kr/co/programers/javastudy2/StringBufferExam.java | 588b7599e3a56e2646c247b74a8adad01682acd7 | []
| no_license | jbh2507/Hello-world | https://github.com/jbh2507/Hello-world | 95f81423569a11eb37bb5b7a15988666dae2233e | 43a1f93eb0922088bb73a651f623b9bf054ef490 | refs/heads/master | 2020-04-11T19:53:10.607000 | 2019-08-05T08:13:01 | 2019-08-05T08:13:01 | 162,051,345 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.co.programers.javastudy2;
public class StringBufferExam {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
sb.append("hello ");
sb.append("world");
String str = sb.toString();
System.out.println(str);
StringBuffer sb2 = new StringBuffer();
StringBuffer sb3 = sb2.append("hello"); // sb2에 "hello"를 붙여 sb2로 선언
if(sb2 == sb3) {
System.out.println("sb2 == sb3");
}
// StringBuffer은 메소드를 통해 수정할 경우 String과는 다르게 레퍼런스 자체가 변조된다.
// 따라서 15행에 sb3를 선언하며 .append(); 메소드를 사용하며 sb2 또한 값이 변조되어 sb2 == sb3가 true를 반환하는 것이다.
String str2 = new StringBuffer().append("hello ").append("world").toString();
// StringBuffer가 기본적으로 가지고있는 메소드들은 대부분 자기 자신(this)를 반환함
// 따라서 자기자신을 리턴하여 계속 자신의 메소드를 호출하여 사용하는 메소드 체이닝(Method Chaining)을 사용할 수 있음(위의 예처럼)
System.out.println(str2); // sysout: hello world
}
}
| UTF-8 | Java | 1,184 | java | StringBufferExam.java | Java | []
| null | []
| package kr.co.programers.javastudy2;
public class StringBufferExam {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
sb.append("hello ");
sb.append("world");
String str = sb.toString();
System.out.println(str);
StringBuffer sb2 = new StringBuffer();
StringBuffer sb3 = sb2.append("hello"); // sb2에 "hello"를 붙여 sb2로 선언
if(sb2 == sb3) {
System.out.println("sb2 == sb3");
}
// StringBuffer은 메소드를 통해 수정할 경우 String과는 다르게 레퍼런스 자체가 변조된다.
// 따라서 15행에 sb3를 선언하며 .append(); 메소드를 사용하며 sb2 또한 값이 변조되어 sb2 == sb3가 true를 반환하는 것이다.
String str2 = new StringBuffer().append("hello ").append("world").toString();
// StringBuffer가 기본적으로 가지고있는 메소드들은 대부분 자기 자신(this)를 반환함
// 따라서 자기자신을 리턴하여 계속 자신의 메소드를 호출하여 사용하는 메소드 체이닝(Method Chaining)을 사용할 수 있음(위의 예처럼)
System.out.println(str2); // sysout: hello world
}
}
| 1,184 | 0.65625 | 0.636161 | 27 | 31.185184 | 27.279129 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.148148 | false | false | 3 |
5be4bd0e1a731a8f3464ba721876f671283e7de7 | 8,598,524,533,050 | 61cf3109eaf4561e071d93f9daf0d3cf9155ca9f | /src/com/rbt/service/ICategoryService.java | 928cc0a5cbdbce2eaa48c09b304db1933ff72747 | []
| no_license | haoouwen/epf | https://github.com/haoouwen/epf | b620fe05c93db178a122cfef778d31c036a2a822 | abe0f1ed564f33dcf766591c5f9b04ce2b5e8094 | refs/heads/master | 2021-01-19T13:46:10.278000 | 2017-08-20T10:40:12 | 2017-08-20T10:40:12 | 100,859,509 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Package:com.rbt.servie
* FileName: ICategoryService.java
*/
package com.rbt.service;
import java.util.List;
import java.util.Map;
import com.rbt.model.Category;
/**
* @function 功能 分类信息表Service层业务接口实现类
* @author 创建人 LJQ
* @date 创建日期 Tue Jul 12 13:04:58 CST 2014
*/
public interface ICategoryService extends IGenericService<Category,String>{
/**
* @MethodDescribe 方法描述 根据地区查找数据
* @author 创建人 CYC
* @date 创建日期 Nov 21, 2014 2:52:04 PM
*/
public List getAreaCategoryList(Map map);
/**
* @MethodDescribe 方法描述 根据地区查找数据
* @author 创建人 CYC
* @date 创建日期 Nov 21, 2014 2:52:04 PM
*/
public List getTwoAreaCategoryList(Map map);
/**
* @MethodDescribe 方法描述 建立分类表索引数据
* @author 创建人 LJQ
* @date 创建日期 Aug 26, 2014 2:52:04 PM
*/
public List getCategoryIndexList(Map map);
/**
* @MethodDescribe 方法描述 前台查找相应的分类
* @author 创建人 LJQ
* @date 创建日期 Aug 29, 2014 5:46:42 PM
*/
public List getWebCategroyList(Map map);
/**
* @MethodDescribe 方法描述 获取所有地区信息
* @author 创建人 HXK
* @date 创建日期 2014-08-31
*/
public List getAll();
/**
* 方法描述:分类是否显示批量修改
* @param interrule
*/
public void updateDisplay(final List list);
/**
* 方法描述:获取特殊的cat_id集合
* @param interrule
*/
public List getDeleteList(Map map);
/**
* @MethodDescribe 方法描述 创建一个递归方法用于批量删除
* @author 创建人 LJQ
* @date 创建日期 Jul 15, 2014 4:33:29 PM
*/
public boolean Recursive(String id);
/**
* @author : LHY
* @Method Description : 递归调用删除数据
*/
public void recuDelete(String id);
/**
* 方法描述:删除分类信息表信息
*
* @return
* @throws Exception
*/
public boolean catdelete(String ids);
/**
* @Method Description :删除分类前,先判断是否已经有商品绑定了,如果没有可以删除,否则不让删除
* @author: HXK
* @date : May 29, 2014 6:16:07 PM
* @param
* @return bool true可以删除,false不能删除
*/
public boolean categoryGoods(String cat_id,String model_type);
/**
* @Method Description :导出分类
* @author: HXK
* @date : Sep 1, 2015 6:18:31 PM
* @param
* @return return_type
*/
public void exportCatExcel() throws Exception ;
}
| UTF-8 | Java | 2,570 | java | ICategoryService.java | Java | [
{
"context": " @function 功能 分类信息表Service层业务接口实现类\n * @author 创建人 LJQ\n * @date 创建日期 Tue Jul 12 13:04:58 CST 2014\n */\n\n",
"end": 237,
"score": 0.9646440744400024,
"start": 234,
"tag": "USERNAME",
"value": "LJQ"
},
{
"context": "@MethodDescribe 方法描述 根据地区查找数据 \n\t * @author 创建人 CYC\n\t * @date 创建日期 Nov 21, 2014 2:52:04 PM\n\t */\n\tpu",
"end": 428,
"score": 0.9974838495254517,
"start": 425,
"tag": "USERNAME",
"value": "CYC"
},
{
"context": "@MethodDescribe 方法描述 根据地区查找数据 \n\t * @author 创建人 CYC\n\t * @date 创建日期 Nov 21, 2014 2:52:04 PM\n\t */\n\tpu",
"end": 581,
"score": 0.9958577156066895,
"start": 578,
"tag": "USERNAME",
"value": "CYC"
},
{
"context": "MethodDescribe 方法描述 建立分类表索引数据 \n\t * @author 创建人 LJQ\n\t * @date 创建日期 Aug 26, 2014 2:52:04 PM\n\t */\n\tpu",
"end": 738,
"score": 0.9827569723129272,
"start": 735,
"tag": "USERNAME",
"value": "LJQ"
},
{
"context": "@MethodDescribe 方法描述 前台查找相应的分类\n\t * @author 创建人 LJQ\n\t * @date 创建日期 Aug 29, 2014 5:46:42 PM\n\t */\n ",
"end": 894,
"score": 0.9764738082885742,
"start": 891,
"tag": "USERNAME",
"value": "LJQ"
},
{
"context": "* @MethodDescribe 方法描述 获取所有地区信息\n\t * @author 创建人 HXK\n\t * @date 创建日期 2014-08-31\n\t */\n public List ",
"end": 1055,
"score": 0.9974671006202698,
"start": 1052,
"tag": "USERNAME",
"value": "HXK"
},
{
"context": "MethodDescribe 方法描述 创建一个递归方法用于批量删除\n\t * @author 创建人 LJQ\n\t * @date 创建日期 Jul 15, 2014 4:33:29 PM\n\t */\n\tpubl",
"end": 1371,
"score": 0.9967199563980103,
"start": 1368,
"tag": "USERNAME",
"value": "LJQ"
},
{
"context": "c boolean Recursive(String id);\n\t/**\n\t * @author : LHY\n\t * @Method Description : 递归调用删除数据\n\t */\n\tpublic v",
"end": 1476,
"score": 0.9993533492088318,
"start": 1473,
"tag": "USERNAME",
"value": "LHY"
},
{
"context": " :删除分类前,先判断是否已经有商品绑定了,如果没有可以删除,否则不让删除\n\t * @author: HXK\n\t * @date : May 29, 2014 6:16:07 PM\n\t * @param \n\t",
"end": 1744,
"score": 0.9995361566543579,
"start": 1741,
"tag": "USERNAME",
"value": "HXK"
},
{
"context": " /**\n\t * @Method Description :导出分类\n\t * @author: HXK\n\t * @date : Sep 1, 2015 6:18:31 PM\n\t * @param \n\t ",
"end": 1956,
"score": 0.9995142221450806,
"start": 1953,
"tag": "USERNAME",
"value": "HXK"
}
]
| null | []
| /*
* Package:com.rbt.servie
* FileName: ICategoryService.java
*/
package com.rbt.service;
import java.util.List;
import java.util.Map;
import com.rbt.model.Category;
/**
* @function 功能 分类信息表Service层业务接口实现类
* @author 创建人 LJQ
* @date 创建日期 Tue Jul 12 13:04:58 CST 2014
*/
public interface ICategoryService extends IGenericService<Category,String>{
/**
* @MethodDescribe 方法描述 根据地区查找数据
* @author 创建人 CYC
* @date 创建日期 Nov 21, 2014 2:52:04 PM
*/
public List getAreaCategoryList(Map map);
/**
* @MethodDescribe 方法描述 根据地区查找数据
* @author 创建人 CYC
* @date 创建日期 Nov 21, 2014 2:52:04 PM
*/
public List getTwoAreaCategoryList(Map map);
/**
* @MethodDescribe 方法描述 建立分类表索引数据
* @author 创建人 LJQ
* @date 创建日期 Aug 26, 2014 2:52:04 PM
*/
public List getCategoryIndexList(Map map);
/**
* @MethodDescribe 方法描述 前台查找相应的分类
* @author 创建人 LJQ
* @date 创建日期 Aug 29, 2014 5:46:42 PM
*/
public List getWebCategroyList(Map map);
/**
* @MethodDescribe 方法描述 获取所有地区信息
* @author 创建人 HXK
* @date 创建日期 2014-08-31
*/
public List getAll();
/**
* 方法描述:分类是否显示批量修改
* @param interrule
*/
public void updateDisplay(final List list);
/**
* 方法描述:获取特殊的cat_id集合
* @param interrule
*/
public List getDeleteList(Map map);
/**
* @MethodDescribe 方法描述 创建一个递归方法用于批量删除
* @author 创建人 LJQ
* @date 创建日期 Jul 15, 2014 4:33:29 PM
*/
public boolean Recursive(String id);
/**
* @author : LHY
* @Method Description : 递归调用删除数据
*/
public void recuDelete(String id);
/**
* 方法描述:删除分类信息表信息
*
* @return
* @throws Exception
*/
public boolean catdelete(String ids);
/**
* @Method Description :删除分类前,先判断是否已经有商品绑定了,如果没有可以删除,否则不让删除
* @author: HXK
* @date : May 29, 2014 6:16:07 PM
* @param
* @return bool true可以删除,false不能删除
*/
public boolean categoryGoods(String cat_id,String model_type);
/**
* @Method Description :导出分类
* @author: HXK
* @date : Sep 1, 2015 6:18:31 PM
* @param
* @return return_type
*/
public void exportCatExcel() throws Exception ;
}
| 2,570 | 0.645115 | 0.599138 | 99 | 20.080809 | 17.078356 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.969697 | false | false | 3 |
ea1f9ae3d44619ba9bea4b2f6d1cd7c036c20573 | 1,056,562,021,977 | 085f608ed990313c41a79cada58dd9a842342af2 | /src/Main/Java/Controllers/SignIn.java | 37ea505d72c5886b889f287afa83705075bb1b6d | []
| no_license | cjs26888/CSC202 | https://github.com/cjs26888/CSC202 | 6d50a3f1c8403259f59bf9aa835b7b5fdd2a0404 | fb2b47dd3c3c7b4124618ba0e84074bf69b010b1 | refs/heads/master | 2021-01-25T08:01:44.911000 | 2017-07-27T03:20:21 | 2017-07-27T03:20:21 | 93,704,700 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Main.Java.Controllers;
import Main.Java.Classes.User;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
/**
* Created by Biggus on 6/2/2017.
*/
public class SignIn implements Initializable
{
@FXML
TextField User;
@FXML
PasswordField Pass;
@FXML
Label passLBL;
Stage stage;
public void signin() throws IOException
{
Stage stage = new Stage();
Paint red = Color.RED;
User UseMe = Start.getUser(User.getText());
System.out.println(UseMe.toString());
if (UseMe.getpWord().equals(Pass.getText()))
{
Stage temp = (Stage) Pass.getScene().getWindow();
temp.close();
Parent message = FXMLLoader.load(getClass().getResource("/Main/Resources/View/PopUp.fxml"));
Scene Message = new Scene(message);
stage.setScene(Message);
stage.show();
}
else
{
passLBL.setVisible(true);
passLBL.setText("Your password is incorrect");
passLBL.setTextFill(red);
}
/*
else
{
passLBL.setVisible(true);
passLBL.setText("Your Username does not match our system");
passLBL.setTextFill(red);
}
*/
}
public void back() throws IOException {
Stage temp = (Stage) Pass.getScene().getWindow();
temp.close();
stage = new Stage();
Parent message = FXMLLoader.load(getClass().getResource("/Main/Resources/View/Main.fxml"));
Scene Message = new Scene(message);
stage.setScene(Message);
stage.show();
}
@Override
public void initialize(URL location, ResourceBundle resources)
{
}
}
| UTF-8 | Java | 2,248 | java | SignIn.java | Java | [
{
"context": "rt java.util.ResourceBundle;\r\n\r\n/**\r\n * Created by Biggus on 6/2/2017.\r\n */\r\npublic class SignIn implements",
"end": 546,
"score": 0.7274026870727539,
"start": 540,
"tag": "USERNAME",
"value": "Biggus"
}
]
| null | []
| package Main.Java.Controllers;
import Main.Java.Classes.User;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
/**
* Created by Biggus on 6/2/2017.
*/
public class SignIn implements Initializable
{
@FXML
TextField User;
@FXML
PasswordField Pass;
@FXML
Label passLBL;
Stage stage;
public void signin() throws IOException
{
Stage stage = new Stage();
Paint red = Color.RED;
User UseMe = Start.getUser(User.getText());
System.out.println(UseMe.toString());
if (UseMe.getpWord().equals(Pass.getText()))
{
Stage temp = (Stage) Pass.getScene().getWindow();
temp.close();
Parent message = FXMLLoader.load(getClass().getResource("/Main/Resources/View/PopUp.fxml"));
Scene Message = new Scene(message);
stage.setScene(Message);
stage.show();
}
else
{
passLBL.setVisible(true);
passLBL.setText("Your password is incorrect");
passLBL.setTextFill(red);
}
/*
else
{
passLBL.setVisible(true);
passLBL.setText("Your Username does not match our system");
passLBL.setTextFill(red);
}
*/
}
public void back() throws IOException {
Stage temp = (Stage) Pass.getScene().getWindow();
temp.close();
stage = new Stage();
Parent message = FXMLLoader.load(getClass().getResource("/Main/Resources/View/Main.fxml"));
Scene Message = new Scene(message);
stage.setScene(Message);
stage.show();
}
@Override
public void initialize(URL location, ResourceBundle resources)
{
}
}
| 2,248 | 0.589413 | 0.586744 | 82 | 25.414635 | 21.129652 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536585 | false | false | 3 |
86207b6f897609b5975e05c89f7e7e2ea5b076ec | 27,745,488,790,891 | e3d1d592c2e87207a5b72d98d0a28191f5e7cbe7 | /xianghaapp/src/main/java/com/example/xianghaapp/util/BitMapCallBack.java | 5b9a23a4ea957c523e74c5c604abc70943a75b6e | [
"Apache-2.0"
]
| permissive | hgwxr/AndroidBasic | https://github.com/hgwxr/AndroidBasic | 3aaadbe7b4a898c055469f826841a3ef34951c91 | a74f7f77836d1855e6a636bd9509f24b395cb526 | refs/heads/master | 2021-01-09T20:07:34.618000 | 2016-08-20T08:28:59 | 2016-08-20T08:28:59 | 65,815,332 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.xianghaapp.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import com.example.xianghaapp.model.base.BaseModel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by Administrator on 2016/8/10.
*/
public class BitMapCallBack implements BaseModel.OnLoadCompleteListener{
private ImageView imageView;
public BitMapCallBack(ImageView imageView) {
this.imageView = imageView;
}
@Override
public void onLoadComplete(byte[] bs, String PATH) {
if (bs!=null) {
String tag = (String) imageView.getTag();
if (bs.length != 0 && tag != null && tag.equals(PATH)) {
FileOutputStream fos = null;
try {
Bitmap image = BitmapFactory.decodeByteArray(bs, 0, bs.length);
imageView.setImageBitmap(image);
File externalCacheDir = imageView.getContext().getExternalCacheDir();
File file=new File(externalCacheDir,PATH.replaceAll("/","")+".jpg");
fos = new FileOutputStream(file);
//1
// image.compress(Bitmap.CompressFormat.JPEG,100,fos);
//2
fos.write(bs,0,bs.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (fos!=null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
| UTF-8 | Java | 1,855 | java | BitMapCallBack.java | Java | []
| null | []
| package com.example.xianghaapp.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import com.example.xianghaapp.model.base.BaseModel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by Administrator on 2016/8/10.
*/
public class BitMapCallBack implements BaseModel.OnLoadCompleteListener{
private ImageView imageView;
public BitMapCallBack(ImageView imageView) {
this.imageView = imageView;
}
@Override
public void onLoadComplete(byte[] bs, String PATH) {
if (bs!=null) {
String tag = (String) imageView.getTag();
if (bs.length != 0 && tag != null && tag.equals(PATH)) {
FileOutputStream fos = null;
try {
Bitmap image = BitmapFactory.decodeByteArray(bs, 0, bs.length);
imageView.setImageBitmap(image);
File externalCacheDir = imageView.getContext().getExternalCacheDir();
File file=new File(externalCacheDir,PATH.replaceAll("/","")+".jpg");
fos = new FileOutputStream(file);
//1
// image.compress(Bitmap.CompressFormat.JPEG,100,fos);
//2
fos.write(bs,0,bs.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (fos!=null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
| 1,855 | 0.538544 | 0.530458 | 60 | 29.916666 | 23.681421 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55 | false | false | 3 |
ada08bf760a9f4a3ae89d4f7598933146b2713d7 | 29,076,928,662,592 | 5dc5d34a7414660b003b7737e23cb4f85b12477f | /app/src/main/java/com/example/administrator/im/ui/fragment/local/TypeFileFrag.java | 802b76efab540518e632057e93584f9272783f18 | []
| no_license | SmallBearBeast/IM | https://github.com/SmallBearBeast/IM | 279e790fb1f348daf6e00291359c9bf559470359 | de2107d2654bc38c96a2b7a0d16db622915fc972 | refs/heads/master | 2020-03-06T15:50:19.408000 | 2018-11-20T04:14:57 | 2018-11-20T04:14:57 | 126,962,849 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.administrator.im.ui.fragment.local;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.example.administrator.im.R;
import com.example.administrator.im.frame.dagger.component.FragCom;
import com.example.administrator.im.ui.adapter.TypeFileAdapter;
import com.example.administrator.im.ui.fragment.BaseFrag;
import com.example.administrator.im.util.MediaUtil;
import com.example.administrator.im.util.MyUtil;
import javax.inject.Inject;
import butterknife.BindView;
/**
* Created by Administrator on 2018/2/12.
*/
public class TypeFileFrag extends BaseFrag {
private static final String TAG = "TypeFileFrag";
@BindView(R.id.rv_file_container)
RecyclerView rvFileContainer;
@Inject
public TypeFileAdapter adapter;
@Inject
public MediaUtil mediaUtil;
@Override
protected void init() {
super.init();
MyUtil.initRecyclerView(rvFileContainer, getActivity());
rvFileContainer.setAdapter(adapter);
}
@Override
protected int layoutId() {
return R.layout.frag_type_file;
}
@Override
protected void inject(FragCom fragCom) {
fragCom.inject(this);
}
@Override
public void onStop() {
super.onStop();
adapter.stopEventBus();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser)
adapter.startEventBus();
else if(adapter.isStartEventBus())
adapter.stopEventBus();
}
@Override
public void onPause() {
super.onPause();
}
}
| UTF-8 | Java | 1,664 | java | TypeFileFrag.java | Java | [
{
"context": ";\n\nimport butterknife.BindView;\n\n/**\n * Created by Administrator on 2018/2/12.\n */\n\npublic class TypeFileFrag exte",
"end": 551,
"score": 0.616343080997467,
"start": 538,
"tag": "NAME",
"value": "Administrator"
}
]
| null | []
| package com.example.administrator.im.ui.fragment.local;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.example.administrator.im.R;
import com.example.administrator.im.frame.dagger.component.FragCom;
import com.example.administrator.im.ui.adapter.TypeFileAdapter;
import com.example.administrator.im.ui.fragment.BaseFrag;
import com.example.administrator.im.util.MediaUtil;
import com.example.administrator.im.util.MyUtil;
import javax.inject.Inject;
import butterknife.BindView;
/**
* Created by Administrator on 2018/2/12.
*/
public class TypeFileFrag extends BaseFrag {
private static final String TAG = "TypeFileFrag";
@BindView(R.id.rv_file_container)
RecyclerView rvFileContainer;
@Inject
public TypeFileAdapter adapter;
@Inject
public MediaUtil mediaUtil;
@Override
protected void init() {
super.init();
MyUtil.initRecyclerView(rvFileContainer, getActivity());
rvFileContainer.setAdapter(adapter);
}
@Override
protected int layoutId() {
return R.layout.frag_type_file;
}
@Override
protected void inject(FragCom fragCom) {
fragCom.inject(this);
}
@Override
public void onStop() {
super.onStop();
adapter.stopEventBus();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser)
adapter.startEventBus();
else if(adapter.isStartEventBus())
adapter.stopEventBus();
}
@Override
public void onPause() {
super.onPause();
}
}
| 1,664 | 0.694111 | 0.689303 | 69 | 23.115942 | 20.150547 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false | 3 |
3526ea73a6b83c7ed43cdbb2fd359cf9f996edd5 | 12,549,894,496,954 | 747487b1c13f53e9a1f0564df888624c0b1bc1f4 | /src/main/java/com/lojaunit/services/ClienteService.java | f2cdbb99aff6612770de9750751825aa760ceb46 | []
| no_license | rasjuliocesar/UnitWorkWeb-LojaUnit-SpringBoot | https://github.com/rasjuliocesar/UnitWorkWeb-LojaUnit-SpringBoot | f73c70bbb2f3aa2a39ffe0afc89a11b2b218ea74 | 1023a4aabdb37e50825beea6f762c715197f44b0 | refs/heads/master | 2023-01-12T23:26:55.484000 | 2020-11-17T23:49:36 | 2020-11-17T23:49:36 | 308,899,496 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lojaunit.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lojaunit.entities.Cliente;
import com.lojaunit.repository.ClienteRepository;
@Service
public class ClienteService {
@Autowired
private ClienteRepository clienteRepository;
public List<Cliente> findAll(){
return clienteRepository.findAll();
}
public Cliente findById(Long id) {
Optional<Cliente> cliente = clienteRepository.findById(id);
return cliente.get();
}
public Cliente insert(Cliente cliente) {
return clienteRepository.save(cliente);
}
public void delete(Long id) {
clienteRepository.deleteById(id);
}
public Cliente update(Long id, Cliente cliente) {
Cliente cli = clienteRepository.getOne(id);
updateData(cli, cliente);
return clienteRepository.save(cli);
}
private void updateData(Cliente cli, Cliente cliente) {
cli.setCpf(cliente.getCpf());
cli.setNome(cliente.getNome());
cli.setEmail(cliente.getEmail());
cli.setDataNascimento(cliente.getDataNascimento());
cli.setSexo(cliente.getSexo());
cli.setNomeSocial(cliente.getNomeSocial());
cli.setApelido(cliente.getApelido());
cli.setTelefone(cliente.getTelefone());
}
}
| UTF-8 | Java | 1,294 | java | ClienteService.java | Java | []
| null | []
| package com.lojaunit.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lojaunit.entities.Cliente;
import com.lojaunit.repository.ClienteRepository;
@Service
public class ClienteService {
@Autowired
private ClienteRepository clienteRepository;
public List<Cliente> findAll(){
return clienteRepository.findAll();
}
public Cliente findById(Long id) {
Optional<Cliente> cliente = clienteRepository.findById(id);
return cliente.get();
}
public Cliente insert(Cliente cliente) {
return clienteRepository.save(cliente);
}
public void delete(Long id) {
clienteRepository.deleteById(id);
}
public Cliente update(Long id, Cliente cliente) {
Cliente cli = clienteRepository.getOne(id);
updateData(cli, cliente);
return clienteRepository.save(cli);
}
private void updateData(Cliente cli, Cliente cliente) {
cli.setCpf(cliente.getCpf());
cli.setNome(cliente.getNome());
cli.setEmail(cliente.getEmail());
cli.setDataNascimento(cliente.getDataNascimento());
cli.setSexo(cliente.getSexo());
cli.setNomeSocial(cliente.getNomeSocial());
cli.setApelido(cliente.getApelido());
cli.setTelefone(cliente.getTelefone());
}
}
| 1,294 | 0.765842 | 0.765842 | 51 | 24.372549 | 19.847418 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.529412 | false | false | 3 |
a9a8098fe6fcda49cc8976a577a4fec4e878d357 | 17,738,214,977,988 | e7736dd4e3bb2820bad1e9e13ae783bde0a7fba5 | /app/src/main/java/com/huejie/osmdroid/project/recordbook/bookfragment/InterchangeRecordBookFragment.java | 11a4b10916569dd5265b4f7023a007cfc88e34b8 | []
| no_license | g327659406/osmdroid | https://github.com/g327659406/osmdroid | c8a6b49d8f3e618858d551defa306ea8652db537 | 372cd57dfc06ddee3ddb70873638d2039403d331 | refs/heads/master | 2021-01-14T21:00:50.852000 | 2020-02-24T14:31:15 | 2020-02-24T14:31:15 | 242,757,999 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.huejie.osmdroid.project.recordbook.bookfragment;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.blankj.utilcode.utils.FileUtils;
import com.huejie.osmdroid.R;
import com.huejie.osmdroid.app.AppContext;
import com.huejie.osmdroid.model.CommonRecordBookMedia;
import com.huejie.osmdroid.model.books.BookSimple;
import com.huejie.osmdroid.model.books.InterchangeRecordBook;
import com.huejie.osmdroid.project.recordbook.activity.PaintActivity;
import com.huejie.osmdroid.util.Config;
import com.huejie.osmdroid.util.DBUtil;
import com.huejie.osmdroid.util.DictUtil;
import com.huejie.osmdroid.util.Util;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.litepal.LitePal;
import org.osmdroid.util.LocationUtils;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import static android.app.Activity.RESULT_OK;
/**
* 互通式立交外业调查记录簿
*/
public class InterchangeRecordBookFragment extends BookBaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private BookSimple bookSimple;
private String projectName;
@OnClick(R.id.tv_currentSituation)
public void currentSituation() {
Util.showPopwindow(getActivity(), tv_currentSituation, DictUtil.getDictLabels(getActivity(), DictUtil.CROSS_ROAD_LEVEL), "");
}
@OnClick(R.id.tv_planning)
public void planning() {
Util.showPopwindow(getActivity(), tv_planning, DictUtil.getDictLabels(getActivity(), DictUtil.CROSS_ROAD_LEVEL), "");
}
@BindView(R.id.et_ljmc)
EditText et_ljmc;
@BindView(R.id.et_jczh)
EditText et_jczh;
@BindView(R.id.et_qdzh)
EditText et_qdzh;
@BindView(R.id.et_zdzh)
EditText et_zdzh;
@BindView(R.id.et_jcmc)
EditText et_jcmc;
@BindView(R.id.et_crossAngle)
EditText et_crossAngle;
//被交叉道路等级 现状
@BindView(R.id.tv_currentSituation)
CheckedTextView tv_currentSituation;
//被交叉道路等级 规划
@BindView(R.id.tv_planning)
CheckedTextView tv_planning;
@BindView(R.id.et_widthSituation)
EditText et_widthSituation;
@BindView(R.id.et_widthPlanning)
EditText et_widthPlanning;
@BindView(R.id.et_headroom)
EditText et_headroom;
@BindView(R.id.et_designHeight)
EditText et_designHeight;
@BindView(R.id.et_centralCoordinate)
EditText et_centralCoordinate;
@BindView(R.id.et_clht)
EditText et_clht;
@BindView(R.id.et_now_describe)
EditText et_now_describe;
@BindView(R.id.iv_dmsyt)
ImageView iv_dmsyt;
@BindView(R.id.tv_dmsyt)
TextView tv_dmsyt;
@BindView(R.id.et_situationDescription)
EditText et_situationDescription;
@BindView(R.id.et_kzys)
EditText et_kzys;
@BindView(R.id.et_sggc)
EditText et_sggc;
@BindView(R.id.iv_fajt)
ImageView iv_fajt;
@BindView(R.id.tv_fajt)
TextView tv_fajt;
//断面示意图片选择
@OnClick(R.id.iv_dmsyt_load)
public void dmLoadFile() {
GalleryFinal.openGalleryMuti(100, 1, new GalleryFinal.OnHanlderResultCallback() {
@Override
public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
String photoPath = resultList.get(0).getPhotoPath();
Intent intent_paint = new Intent(getActivity(), PaintActivity.class);
intent_paint.putExtra("mediaPath", photoPath);
intent_paint.putExtra("projectId", bookSimple.projectId + "");
startActivityForResult(intent_paint, 100);
}
@Override
public void onHanlderFailure(int requestCode, String errorMsg) {
}
});
}
//断面示意图片新建
@OnClick(R.id.iv_dmsyt_add)
public void dmAddFile() {
startActivityForResult(new Intent(getActivity(), PaintActivity.class).putExtra("projectId", bookSimple.projectId + ""), 100);
}
//选择示意图片
@OnClick(R.id.iv_fajt_load)
public void faLoadFile() {
GalleryFinal.openGalleryMuti(100, 1, new GalleryFinal.OnHanlderResultCallback() {
@Override
public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
String photoPath = resultList.get(0).getPhotoPath();
Intent intent_paint = new Intent(getActivity(), PaintActivity.class);
intent_paint.putExtra("projectId", bookSimple.projectId + "");
intent_paint.putExtra("mediaPath", photoPath);
startActivityForResult(intent_paint, 101);
}
@Override
public void onHanlderFailure(int requestCode, String errorMsg) {
}
});
}
//创建示意图片
@OnClick(R.id.iv_fajt_add)
public void faAddFile() {
Intent intent_paint = new Intent(getActivity(), PaintActivity.class);
intent_paint.putExtra("projectId", bookSimple.projectId + "");
startActivityForResult(intent_paint, 101);
}
public InterchangeRecordBookFragment() {
// Required empty public constructor
}
public static InterchangeRecordBookFragment newInstance(BookSimple param1, String param2) {
InterchangeRecordBookFragment fragment = new InterchangeRecordBookFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
bookSimple = (BookSimple) getArguments().getSerializable(ARG_PARAM1);
projectName = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_interchange_recordbook, container, false);
}
private InterchangeRecordBook book;
private CommonRecordBookMedia mediaCrossSectionDiagram;
private CommonRecordBookMedia mediaPlanePositionDiagram;
int cType;
int pType;
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
ButterKnife.bind(this, view);
book = LitePal.find(InterchangeRecordBook.class, bookSimple.id);
et_ljmc.setText(book.name);
et_jczh.setText(book.crossStake);
et_qdzh.setText(book.startStake);
et_zdzh.setText(book.endStake);
et_jcmc.setText(book.intersectName);
et_crossAngle.setText(Util.valueString(book.crossAngle));
tv_currentSituation.setText("现状:" + DictUtil.getDictLabelByCode(getActivity(), DictUtil.CROSS_ROAD_LEVEL, book.intersectNowLevel));
tv_planning.setText("规划:" + DictUtil.getDictLabelByCode(getActivity(), DictUtil.CROSS_ROAD_LEVEL, book.intersectPlanLevel));
et_widthSituation.setText(Util.valueString(book.intersectNowWidth) );
et_widthPlanning.setText(Util.valueString(book.intersectPlanWidth ));
et_headroom.setText(Util.valueString(book.headroom) );
et_designHeight.setText(Util.valueString(book.designHigh) );
et_centralCoordinate.setText(Util.valueString(book.centerElevation) );
et_clht.setText(book.initialForm);
et_now_describe.setText(book.nowDescribe);
et_situationDescription.setText(book.trafficSituation);
et_kzys.setText(book.topographyFactor);
et_sggc.setText(book.projectDescription);
cType = (int) DictUtil.getBookMediaCode(getActivity(), DictUtil.MEDIA_TYPE, DictUtil.LABEL_RECORD_BOOK_MEDIA_DMSYT);
pType = (int) DictUtil.getBookMediaCode(getActivity(), DictUtil.MEDIA_TYPE, DictUtil.LABEL_RECORD_BOOK_MEDIA_FAJT);
DBUtil.useExtraDbByProjectName(getActivity(), projectName);
//获取横断面示意图
mediaCrossSectionDiagram = LitePal.where("record_book_id = ? and record_book_type_id = ? and media_type = ?", book.id + "", book.recordBookTypeId + "", cType + "").findFirst(CommonRecordBookMedia.class);
if (null != mediaCrossSectionDiagram && !TextUtils.isEmpty(mediaCrossSectionDiagram.mediaPath)) {
iv_dmsyt.setVisibility(View.VISIBLE);
tv_dmsyt.setVisibility(View.GONE);
ImageLoader.getInstance().displayImage("file://" + Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaCrossSectionDiagram.mediaPath, iv_dmsyt);
} else {
iv_dmsyt.setVisibility(View.GONE);
tv_dmsyt.setVisibility(View.VISIBLE);
}
mediaPlanePositionDiagram = LitePal.where("record_book_id = ? and record_book_type_id = ? and media_type = ?", book.id + "", book.recordBookTypeId + "", pType + "").findFirst(CommonRecordBookMedia.class);
if (null != mediaPlanePositionDiagram && !TextUtils.isEmpty(mediaPlanePositionDiagram.mediaPath)) {
iv_fajt.setVisibility(View.VISIBLE);
tv_fajt.setVisibility(View.GONE);
ImageLoader.getInstance().displayImage("file://" + Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaPlanePositionDiagram.mediaPath, iv_fajt);
} else {
iv_fajt.setVisibility(View.GONE);
tv_fajt.setVisibility(View.VISIBLE);
}
iv_dmsyt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(getActivity(), PaintActivity.class).putExtra("projectId", bookSimple.projectId + "").putExtra("mediaPath", Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaCrossSectionDiagram.mediaPath), 100);
}
});
iv_dmsyt.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(getActivity()).setMessage("确定删除该图片吗?").setTitle("警告").setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
FileUtils.deleteFile(Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaCrossSectionDiagram.mediaPath);
mediaCrossSectionDiagram.delete();
tv_dmsyt.setVisibility(View.VISIBLE);
iv_dmsyt.setVisibility(View.INVISIBLE);
}
}).create();
dialog.show();
return false;
}
});
iv_fajt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(getActivity(), PaintActivity.class).putExtra("projectId", bookSimple.projectId + "").putExtra("mediaPath", Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaPlanePositionDiagram.mediaPath), 101);
}
});
iv_fajt.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(getActivity()).setMessage("确定删除该图片吗?").setTitle("警告").setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
FileUtils.deleteFile(Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaPlanePositionDiagram.mediaPath);
mediaPlanePositionDiagram.delete();
tv_fajt.setVisibility(View.VISIBLE);
iv_fajt.setVisibility(View.GONE);
}
}).create();
dialog.show();
return false;
}
});
}
@Override
public BookSimple getBookContent() {
book.name = et_ljmc.getText().toString().trim();
book.crossStake = et_jczh.getText().toString().trim();
book.startStake = et_qdzh.getText().toString().trim();
book.endStake = et_zdzh.getText().toString().trim();
book.intersectName = et_jcmc.getText().toString().trim();
book.crossAngle = Util.valueInteger(et_crossAngle.getText().toString().trim());
if (tv_currentSituation.getTag() != null) {
book.intersectNowLevel = (int) DictUtil.getDictCodeByLabel(getActivity(), DictUtil.CROSS_ROAD_LEVEL, tv_currentSituation.getTag().toString());
}
if (tv_planning.getTag() != null) {
book.intersectPlanLevel = (int) DictUtil.getDictCodeByLabel(getActivity(), DictUtil.CROSS_ROAD_LEVEL, tv_planning.getTag().toString());
}
book.intersectNowWidth = Util.valueDouble(et_widthSituation.getText().toString().trim());
book.intersectPlanWidth = Util.valueDouble(et_widthPlanning.getText().toString().trim());
book.headroom = Util.valueDouble(et_headroom.getText().toString().trim());
book.designHigh = Util.valueDouble(et_designHeight.getText().toString().trim());
book.centerElevation = Util.valueDouble(et_centralCoordinate.getText().toString().trim());
book.initialForm = et_clht.getText().toString().trim();
book.nowDescribe = et_now_describe.getText().toString().trim();
book.trafficSituation = et_situationDescription.getText().toString().trim();
book.topographyFactor = et_kzys.getText().toString().trim();
book.projectDescription = et_sggc.getText().toString().trim();
return book;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && null != data) {
String picPath = data.getStringExtra("mediaPath");
if (requestCode == 100) {
//挡土墙
iv_dmsyt.setVisibility(View.VISIBLE);
tv_dmsyt.setVisibility(View.GONE);
ImageLoader.getInstance().displayImage("file://" + picPath, iv_dmsyt);
//保存示意图
if (null == mediaCrossSectionDiagram) {
mediaCrossSectionDiagram = new CommonRecordBookMedia();
mediaCrossSectionDiagram.recordBookId = book.id;
mediaCrossSectionDiagram.recordBookTypeId = book.recordBookTypeId;
mediaCrossSectionDiagram.mediaType = cType;
}
mediaCrossSectionDiagram.mediaPath = Util.getStoreUrl(getActivity(), picPath);
mediaCrossSectionDiagram.mediaName = FileUtils.getFileName(mediaCrossSectionDiagram.mediaPath);
mediaCrossSectionDiagram.extension = FileUtils.getFileExtension(mediaCrossSectionDiagram.mediaPath);
mediaCrossSectionDiagram.dateTimeOriginal = Util.getFromatDate(System.currentTimeMillis(), Util.Y_M_D_H_M_S);
Location location = LocationUtils.getLastKnownLocation((LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE));
if (null != location) {
mediaCrossSectionDiagram.gpsLatitude = location.getLatitude() + "";
mediaCrossSectionDiagram.gpsLongitude = location.getLongitude() + "";
mediaCrossSectionDiagram.gpsAltitude = location.getAltitude() + "";
}
mediaCrossSectionDiagram.size = FileUtils.getFileLength(picPath);
DBUtil.useExtraDbByProjectName(getActivity(), projectName);
mediaCrossSectionDiagram.saveOrUpdate("record_book_id = ? and record_book_type_id = ? and media_type = ?", mediaCrossSectionDiagram.recordBookId + "", mediaCrossSectionDiagram.recordBookTypeId + "", mediaCrossSectionDiagram.mediaType + "");
} else if (requestCode == 101) {
iv_fajt.setVisibility(View.VISIBLE);
tv_fajt.setVisibility(View.GONE);
ImageLoader.getInstance().displayImage("file://" + picPath, iv_fajt);
if (null == mediaPlanePositionDiagram) {
mediaPlanePositionDiagram = new CommonRecordBookMedia();
mediaPlanePositionDiagram.recordBookId = book.id;
mediaPlanePositionDiagram.recordBookTypeId = book.recordBookTypeId;
mediaPlanePositionDiagram.mediaType = pType;
}
mediaPlanePositionDiagram.mediaPath = Util.getStoreUrl(getActivity(), picPath);
mediaPlanePositionDiagram.mediaName = FileUtils.getFileName(mediaPlanePositionDiagram.mediaPath);
mediaPlanePositionDiagram.extension = FileUtils.getFileExtension(mediaPlanePositionDiagram.mediaPath);
mediaPlanePositionDiagram.dateTimeOriginal = Util.getFromatDate(System.currentTimeMillis(), Util.Y_M_D_H_M_S);
Location location = LocationUtils.getLastKnownLocation((LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE));
if (null != location) {
mediaPlanePositionDiagram.gpsLatitude = location.getLatitude() + "";
mediaPlanePositionDiagram.gpsLongitude = location.getLongitude() + "";
mediaPlanePositionDiagram.gpsAltitude = location.getAltitude() + "";
}
mediaPlanePositionDiagram.size = FileUtils.getFileLength(picPath);
DBUtil.useExtraDbByProjectName(getActivity(), projectName);
mediaPlanePositionDiagram.saveOrUpdate("record_book_id = ? and record_book_type_id = ? and media_type = ?", mediaPlanePositionDiagram.recordBookId + "", mediaPlanePositionDiagram.recordBookTypeId + "", mediaPlanePositionDiagram.mediaType + "");
}
}
}
}
| UTF-8 | Java | 19,453 | java | InterchangeRecordBookFragment.java | Java | []
| null | []
| package com.huejie.osmdroid.project.recordbook.bookfragment;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.blankj.utilcode.utils.FileUtils;
import com.huejie.osmdroid.R;
import com.huejie.osmdroid.app.AppContext;
import com.huejie.osmdroid.model.CommonRecordBookMedia;
import com.huejie.osmdroid.model.books.BookSimple;
import com.huejie.osmdroid.model.books.InterchangeRecordBook;
import com.huejie.osmdroid.project.recordbook.activity.PaintActivity;
import com.huejie.osmdroid.util.Config;
import com.huejie.osmdroid.util.DBUtil;
import com.huejie.osmdroid.util.DictUtil;
import com.huejie.osmdroid.util.Util;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.litepal.LitePal;
import org.osmdroid.util.LocationUtils;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import static android.app.Activity.RESULT_OK;
/**
* 互通式立交外业调查记录簿
*/
public class InterchangeRecordBookFragment extends BookBaseFragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private BookSimple bookSimple;
private String projectName;
@OnClick(R.id.tv_currentSituation)
public void currentSituation() {
Util.showPopwindow(getActivity(), tv_currentSituation, DictUtil.getDictLabels(getActivity(), DictUtil.CROSS_ROAD_LEVEL), "");
}
@OnClick(R.id.tv_planning)
public void planning() {
Util.showPopwindow(getActivity(), tv_planning, DictUtil.getDictLabels(getActivity(), DictUtil.CROSS_ROAD_LEVEL), "");
}
@BindView(R.id.et_ljmc)
EditText et_ljmc;
@BindView(R.id.et_jczh)
EditText et_jczh;
@BindView(R.id.et_qdzh)
EditText et_qdzh;
@BindView(R.id.et_zdzh)
EditText et_zdzh;
@BindView(R.id.et_jcmc)
EditText et_jcmc;
@BindView(R.id.et_crossAngle)
EditText et_crossAngle;
//被交叉道路等级 现状
@BindView(R.id.tv_currentSituation)
CheckedTextView tv_currentSituation;
//被交叉道路等级 规划
@BindView(R.id.tv_planning)
CheckedTextView tv_planning;
@BindView(R.id.et_widthSituation)
EditText et_widthSituation;
@BindView(R.id.et_widthPlanning)
EditText et_widthPlanning;
@BindView(R.id.et_headroom)
EditText et_headroom;
@BindView(R.id.et_designHeight)
EditText et_designHeight;
@BindView(R.id.et_centralCoordinate)
EditText et_centralCoordinate;
@BindView(R.id.et_clht)
EditText et_clht;
@BindView(R.id.et_now_describe)
EditText et_now_describe;
@BindView(R.id.iv_dmsyt)
ImageView iv_dmsyt;
@BindView(R.id.tv_dmsyt)
TextView tv_dmsyt;
@BindView(R.id.et_situationDescription)
EditText et_situationDescription;
@BindView(R.id.et_kzys)
EditText et_kzys;
@BindView(R.id.et_sggc)
EditText et_sggc;
@BindView(R.id.iv_fajt)
ImageView iv_fajt;
@BindView(R.id.tv_fajt)
TextView tv_fajt;
//断面示意图片选择
@OnClick(R.id.iv_dmsyt_load)
public void dmLoadFile() {
GalleryFinal.openGalleryMuti(100, 1, new GalleryFinal.OnHanlderResultCallback() {
@Override
public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
String photoPath = resultList.get(0).getPhotoPath();
Intent intent_paint = new Intent(getActivity(), PaintActivity.class);
intent_paint.putExtra("mediaPath", photoPath);
intent_paint.putExtra("projectId", bookSimple.projectId + "");
startActivityForResult(intent_paint, 100);
}
@Override
public void onHanlderFailure(int requestCode, String errorMsg) {
}
});
}
//断面示意图片新建
@OnClick(R.id.iv_dmsyt_add)
public void dmAddFile() {
startActivityForResult(new Intent(getActivity(), PaintActivity.class).putExtra("projectId", bookSimple.projectId + ""), 100);
}
//选择示意图片
@OnClick(R.id.iv_fajt_load)
public void faLoadFile() {
GalleryFinal.openGalleryMuti(100, 1, new GalleryFinal.OnHanlderResultCallback() {
@Override
public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
String photoPath = resultList.get(0).getPhotoPath();
Intent intent_paint = new Intent(getActivity(), PaintActivity.class);
intent_paint.putExtra("projectId", bookSimple.projectId + "");
intent_paint.putExtra("mediaPath", photoPath);
startActivityForResult(intent_paint, 101);
}
@Override
public void onHanlderFailure(int requestCode, String errorMsg) {
}
});
}
//创建示意图片
@OnClick(R.id.iv_fajt_add)
public void faAddFile() {
Intent intent_paint = new Intent(getActivity(), PaintActivity.class);
intent_paint.putExtra("projectId", bookSimple.projectId + "");
startActivityForResult(intent_paint, 101);
}
public InterchangeRecordBookFragment() {
// Required empty public constructor
}
public static InterchangeRecordBookFragment newInstance(BookSimple param1, String param2) {
InterchangeRecordBookFragment fragment = new InterchangeRecordBookFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
bookSimple = (BookSimple) getArguments().getSerializable(ARG_PARAM1);
projectName = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_interchange_recordbook, container, false);
}
private InterchangeRecordBook book;
private CommonRecordBookMedia mediaCrossSectionDiagram;
private CommonRecordBookMedia mediaPlanePositionDiagram;
int cType;
int pType;
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
ButterKnife.bind(this, view);
book = LitePal.find(InterchangeRecordBook.class, bookSimple.id);
et_ljmc.setText(book.name);
et_jczh.setText(book.crossStake);
et_qdzh.setText(book.startStake);
et_zdzh.setText(book.endStake);
et_jcmc.setText(book.intersectName);
et_crossAngle.setText(Util.valueString(book.crossAngle));
tv_currentSituation.setText("现状:" + DictUtil.getDictLabelByCode(getActivity(), DictUtil.CROSS_ROAD_LEVEL, book.intersectNowLevel));
tv_planning.setText("规划:" + DictUtil.getDictLabelByCode(getActivity(), DictUtil.CROSS_ROAD_LEVEL, book.intersectPlanLevel));
et_widthSituation.setText(Util.valueString(book.intersectNowWidth) );
et_widthPlanning.setText(Util.valueString(book.intersectPlanWidth ));
et_headroom.setText(Util.valueString(book.headroom) );
et_designHeight.setText(Util.valueString(book.designHigh) );
et_centralCoordinate.setText(Util.valueString(book.centerElevation) );
et_clht.setText(book.initialForm);
et_now_describe.setText(book.nowDescribe);
et_situationDescription.setText(book.trafficSituation);
et_kzys.setText(book.topographyFactor);
et_sggc.setText(book.projectDescription);
cType = (int) DictUtil.getBookMediaCode(getActivity(), DictUtil.MEDIA_TYPE, DictUtil.LABEL_RECORD_BOOK_MEDIA_DMSYT);
pType = (int) DictUtil.getBookMediaCode(getActivity(), DictUtil.MEDIA_TYPE, DictUtil.LABEL_RECORD_BOOK_MEDIA_FAJT);
DBUtil.useExtraDbByProjectName(getActivity(), projectName);
//获取横断面示意图
mediaCrossSectionDiagram = LitePal.where("record_book_id = ? and record_book_type_id = ? and media_type = ?", book.id + "", book.recordBookTypeId + "", cType + "").findFirst(CommonRecordBookMedia.class);
if (null != mediaCrossSectionDiagram && !TextUtils.isEmpty(mediaCrossSectionDiagram.mediaPath)) {
iv_dmsyt.setVisibility(View.VISIBLE);
tv_dmsyt.setVisibility(View.GONE);
ImageLoader.getInstance().displayImage("file://" + Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaCrossSectionDiagram.mediaPath, iv_dmsyt);
} else {
iv_dmsyt.setVisibility(View.GONE);
tv_dmsyt.setVisibility(View.VISIBLE);
}
mediaPlanePositionDiagram = LitePal.where("record_book_id = ? and record_book_type_id = ? and media_type = ?", book.id + "", book.recordBookTypeId + "", pType + "").findFirst(CommonRecordBookMedia.class);
if (null != mediaPlanePositionDiagram && !TextUtils.isEmpty(mediaPlanePositionDiagram.mediaPath)) {
iv_fajt.setVisibility(View.VISIBLE);
tv_fajt.setVisibility(View.GONE);
ImageLoader.getInstance().displayImage("file://" + Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaPlanePositionDiagram.mediaPath, iv_fajt);
} else {
iv_fajt.setVisibility(View.GONE);
tv_fajt.setVisibility(View.VISIBLE);
}
iv_dmsyt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(getActivity(), PaintActivity.class).putExtra("projectId", bookSimple.projectId + "").putExtra("mediaPath", Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaCrossSectionDiagram.mediaPath), 100);
}
});
iv_dmsyt.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(getActivity()).setMessage("确定删除该图片吗?").setTitle("警告").setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
FileUtils.deleteFile(Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaCrossSectionDiagram.mediaPath);
mediaCrossSectionDiagram.delete();
tv_dmsyt.setVisibility(View.VISIBLE);
iv_dmsyt.setVisibility(View.INVISIBLE);
}
}).create();
dialog.show();
return false;
}
});
iv_fajt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(getActivity(), PaintActivity.class).putExtra("projectId", bookSimple.projectId + "").putExtra("mediaPath", Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaPlanePositionDiagram.mediaPath), 101);
}
});
iv_fajt.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog dialog = new AlertDialog.Builder(getActivity()).setMessage("确定删除该图片吗?").setTitle("警告").setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
FileUtils.deleteFile(Util.getProjectsPath(getActivity(), AppContext.sp.getString(Config.SP.CURRENT_WORK_DIR)) + mediaPlanePositionDiagram.mediaPath);
mediaPlanePositionDiagram.delete();
tv_fajt.setVisibility(View.VISIBLE);
iv_fajt.setVisibility(View.GONE);
}
}).create();
dialog.show();
return false;
}
});
}
@Override
public BookSimple getBookContent() {
book.name = et_ljmc.getText().toString().trim();
book.crossStake = et_jczh.getText().toString().trim();
book.startStake = et_qdzh.getText().toString().trim();
book.endStake = et_zdzh.getText().toString().trim();
book.intersectName = et_jcmc.getText().toString().trim();
book.crossAngle = Util.valueInteger(et_crossAngle.getText().toString().trim());
if (tv_currentSituation.getTag() != null) {
book.intersectNowLevel = (int) DictUtil.getDictCodeByLabel(getActivity(), DictUtil.CROSS_ROAD_LEVEL, tv_currentSituation.getTag().toString());
}
if (tv_planning.getTag() != null) {
book.intersectPlanLevel = (int) DictUtil.getDictCodeByLabel(getActivity(), DictUtil.CROSS_ROAD_LEVEL, tv_planning.getTag().toString());
}
book.intersectNowWidth = Util.valueDouble(et_widthSituation.getText().toString().trim());
book.intersectPlanWidth = Util.valueDouble(et_widthPlanning.getText().toString().trim());
book.headroom = Util.valueDouble(et_headroom.getText().toString().trim());
book.designHigh = Util.valueDouble(et_designHeight.getText().toString().trim());
book.centerElevation = Util.valueDouble(et_centralCoordinate.getText().toString().trim());
book.initialForm = et_clht.getText().toString().trim();
book.nowDescribe = et_now_describe.getText().toString().trim();
book.trafficSituation = et_situationDescription.getText().toString().trim();
book.topographyFactor = et_kzys.getText().toString().trim();
book.projectDescription = et_sggc.getText().toString().trim();
return book;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && null != data) {
String picPath = data.getStringExtra("mediaPath");
if (requestCode == 100) {
//挡土墙
iv_dmsyt.setVisibility(View.VISIBLE);
tv_dmsyt.setVisibility(View.GONE);
ImageLoader.getInstance().displayImage("file://" + picPath, iv_dmsyt);
//保存示意图
if (null == mediaCrossSectionDiagram) {
mediaCrossSectionDiagram = new CommonRecordBookMedia();
mediaCrossSectionDiagram.recordBookId = book.id;
mediaCrossSectionDiagram.recordBookTypeId = book.recordBookTypeId;
mediaCrossSectionDiagram.mediaType = cType;
}
mediaCrossSectionDiagram.mediaPath = Util.getStoreUrl(getActivity(), picPath);
mediaCrossSectionDiagram.mediaName = FileUtils.getFileName(mediaCrossSectionDiagram.mediaPath);
mediaCrossSectionDiagram.extension = FileUtils.getFileExtension(mediaCrossSectionDiagram.mediaPath);
mediaCrossSectionDiagram.dateTimeOriginal = Util.getFromatDate(System.currentTimeMillis(), Util.Y_M_D_H_M_S);
Location location = LocationUtils.getLastKnownLocation((LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE));
if (null != location) {
mediaCrossSectionDiagram.gpsLatitude = location.getLatitude() + "";
mediaCrossSectionDiagram.gpsLongitude = location.getLongitude() + "";
mediaCrossSectionDiagram.gpsAltitude = location.getAltitude() + "";
}
mediaCrossSectionDiagram.size = FileUtils.getFileLength(picPath);
DBUtil.useExtraDbByProjectName(getActivity(), projectName);
mediaCrossSectionDiagram.saveOrUpdate("record_book_id = ? and record_book_type_id = ? and media_type = ?", mediaCrossSectionDiagram.recordBookId + "", mediaCrossSectionDiagram.recordBookTypeId + "", mediaCrossSectionDiagram.mediaType + "");
} else if (requestCode == 101) {
iv_fajt.setVisibility(View.VISIBLE);
tv_fajt.setVisibility(View.GONE);
ImageLoader.getInstance().displayImage("file://" + picPath, iv_fajt);
if (null == mediaPlanePositionDiagram) {
mediaPlanePositionDiagram = new CommonRecordBookMedia();
mediaPlanePositionDiagram.recordBookId = book.id;
mediaPlanePositionDiagram.recordBookTypeId = book.recordBookTypeId;
mediaPlanePositionDiagram.mediaType = pType;
}
mediaPlanePositionDiagram.mediaPath = Util.getStoreUrl(getActivity(), picPath);
mediaPlanePositionDiagram.mediaName = FileUtils.getFileName(mediaPlanePositionDiagram.mediaPath);
mediaPlanePositionDiagram.extension = FileUtils.getFileExtension(mediaPlanePositionDiagram.mediaPath);
mediaPlanePositionDiagram.dateTimeOriginal = Util.getFromatDate(System.currentTimeMillis(), Util.Y_M_D_H_M_S);
Location location = LocationUtils.getLastKnownLocation((LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE));
if (null != location) {
mediaPlanePositionDiagram.gpsLatitude = location.getLatitude() + "";
mediaPlanePositionDiagram.gpsLongitude = location.getLongitude() + "";
mediaPlanePositionDiagram.gpsAltitude = location.getAltitude() + "";
}
mediaPlanePositionDiagram.size = FileUtils.getFileLength(picPath);
DBUtil.useExtraDbByProjectName(getActivity(), projectName);
mediaPlanePositionDiagram.saveOrUpdate("record_book_id = ? and record_book_type_id = ? and media_type = ?", mediaPlanePositionDiagram.recordBookId + "", mediaPlanePositionDiagram.recordBookTypeId + "", mediaPlanePositionDiagram.mediaType + "");
}
}
}
}
| 19,453 | 0.663755 | 0.661259 | 411 | 45.79562 | 44.917301 | 291 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.756691 | false | false | 3 |
0e7c9f5412b5544393f20dcfb12a3ec34ed4e972 | 20,856,361,238,334 | 30b2eba9a7b563509fff637e10b8879c10657a76 | /web/box-admin/src/main/java/com/boxamazing/admin/QueryController.java | 0b5ae9725c1ee1eeca9e772ab6b911d92ffa7a55 | []
| no_license | hecj/box | https://github.com/hecj/box | 73f60c11c293cac4a66b9b0b33ba79ff5aadfc2d | e59cc1cceb238b1a6d5b35ae8a98b68b7da5918f | refs/heads/master | 2020-09-24T06:11:08.248000 | 2016-08-25T05:55:48 | 2016-08-25T05:55:48 | 66,528,932 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.boxamazing.admin;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.boxamazing.common.BaseController;
import com.boxamazing.common.FileUtil;
import com.boxamazing.common.LOG;
import com.boxamazing.common.interceptor.UserUtil;
import com.boxamazing.service.dbs.model.Dbs;
import com.boxamazing.service.q.model.Q;
import com.boxamazing.service.qh.model.Qh;
import com.boxamazing.service.qo.model.Qo;
import com.boxamazing.service.r.model.R;
import com.boxamazing.service.u.model.PUser;
import com.boxamazing.service.util.DBSUTIL;
import com.boxamazing.util.DateUtil;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
/**
* 信息查询
*/
public class QueryController extends BaseController {
public void getStaticUrl() throws FileNotFoundException, IOException {
Long id = getParaToLong("id");
Qh qh = Qh.dao.findById(id);
Long qid = qh.getLong("qid");
PUser u = UserUtil.getU(getSession());
R r = R.findFirstRByRid(u.get("rid"));
String qs = r.get("qs");
qs = "," + qs + ",";
String wp = getWebPath();
String pf = new File(wp).getParent();
File file = new File(pf, qh.getStr("url"));
if (!file.exists()) {
setAttr("msg", "执行结果未找到,或未执行完成,如有疑问,请联系技术支持!!");
renderJson();
} else {
if (qs.contains("," + qid + ",")) {
String jsonText = FileUtil.readFile(file, "UTF-8");
renderJson(jsonText);
} else {
setAttr("msg", "您无权查询该统计内容!!");
renderJson();
}
}
// setAttr("qol",qol);
}
/**
* 进入通用查询页面
*/
public void index() {
PUser u = UserUtil.getU(getSession());
try {
R r = R.findFirstRByRid(u.get("role_id"));
String qs = r.get("qs");
List<Q> ql = Q.findQListByTypeStatIds(0, 0, qs, "clc", "desc");
setAttr("ql", ql);
} catch (Exception e) {
LOG.error(e.getMessage());
e.printStackTrace();
}
render("index.ftl");
}
public void statics() {
PUser u = UserUtil.getU(getSession());
R r = R.findFirstRByRid(u.get("rid"));
String qs = r.get("qs");
List<Q> ql = Q.findQListByTypeStatIds(1, 0, qs, "clc", "desc");
List<Qo> qol = Qo.findQoListByQids(qs);
setAttr("ql", ql);
// setAttr("qol",qol);
render("statics.ftl");
}
/**
* 统计查询
*/
public void staticex() {
Date dt = new Date();
Long id = getParaToLong("id");
String sx = getPara("sx");
Q q = Q.dao.findById(id);
setAttr("q", "q");
Long qhid = null;
ArrayList<String> whereps = new ArrayList<String>();
if (q != null) {
String sql = q.get("sql");
List<String> sql_fs = Arrays.asList(DBSUTIL.getFields(sql).split(
","));
setAttr("sql_fs", sql_fs);
Long dbid = q.getLong("dbid");
if (dbid == null || dbid <= 0) {
setAttr("msg", "当前查询配置的数据源不存在!");
} else {
Dbs dbs = Dbs.dao.findById(dbid);
if (dbs == null) {
setAttr("msg", "当前查询配置的数据源不存在!");
} else {
Config c = DBSUTIL.getDb(dbs);
if (c != null) {
String[] sxz = sx.split(",");
for (String key : sxz) {
whereps.add(getPara("where." + key));
}
String pms = JsonKit.toJson(whereps);// 参数
int i = q.getInt("ms");
if (i <= 0) {// 不限制
} else {
List<Qh> ql = Qh.findQhByQidPmsDt(id, pms, System.currentTimeMillis() / 1000 - i * 60);
if (ql.size() > 0) {
setAttr("msg", i
+ "分钟内已有用户执行过相同的统计,查询常见者限定统计时间不得小于" + i
+ "分钟请查看他的查询历史!");
renderJson();
return;
}
}
{// 先记录执行历史
Integer clc = q.getInt("clc");
if (clc == null) {
clc = 0;
}
try {
q.set("clc", clc + 1);
q.update();
Qh qh = new Qh();
qh.set("qid", id);
qh.set("dt", dt);
qh.set("pms", pms);
qh.set("t", 1);
qh.save();
qhid = qh.getLong("id");
} catch (Exception e) {
e.printStackTrace();
}
}
String url = null;
List<Record> q_rl = null;
try {
List<Qo> qol = Qo.dao.find(
"select * from qo where qid=?", id);
setAttr("qol", qol);
q_rl = onlyEx(whereps, sql, dbs, id);
url = rendHtmlAndEx(q_rl, id, sql_fs, qol);
System.out.println("shengchengurl:" + url);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
Qh qh = Qh.dao.findById(qhid);
qh.set("edt", new Date());
qh.set("url", url);
qh.update();
} catch (Exception e) {
e.printStackTrace();
}
}
// Object q_rl =
// DBSUTIL.invokeMeth("query",Db.use(DBSUTIL.COMMON+dbs.getLong("id")),
// sql, whereps);
setAttr("q_rl", q_rl);
} else {
setAttr("msg", "数据源配置出错!");
LOG.info(dbid + "数据源配置出错!");
}
}
}
} else {
setAttr("msg", "当前查询的对象不存在!");
}
renderJson();
// render("ex_res.ftl");
}
/**
* 生成静态统计文件
*
* @param whereps
* @param sql
* @param dbs
* @param id
* @return
* @throws ParseException
*/
private List<Record> onlyEx(ArrayList<String> whereps, String sql, Dbs dbs,
Long id) {
// 执行最终查询结果 限制最多查100条
List<Record> q_rl = Db.use(DBSUTIL.COMMON + dbs.getLong("id")).find(
sql + " limit 0,100", whereps.toArray());
return q_rl;
}
/**
* 生成静态统计文件
*
* @param whereps
* @param sql
* @param dbs
* @param id
* @param qol
* @param sql_fs
* @return
* @throws ParseException
* @throws IOException
*/
private String rendHtmlAndEx(List<Record> q_rl, Long id,
List<String> sql_fs, List<Qo> qol) throws ParseException,
IOException {
// 执行最终查询结果 限制最多查100条
Map<String, Object> content = new HashMap<String, Object>();
content.put("sql_fs", sql_fs);
content.put("qol", qol);
content.put("q_rl", q_rl);
String json = JsonKit.toJson(content);
String wp = getWebPath();
String jsonpath = "querystatic/genstatics/";
String filep = jsonpath + DateUtil.currDate("yyyy年MM月dd日HH时mm分ss秒SSS")
+ "查询" + id + ".json";
String pf = new File(wp).getParent();
File f = new File(pf, filep);
FileUtil.createFile(f);
f.createNewFile();
FileUtil.writeTo(json, f, "UTF-8");
return filep;
}
private String getWebPath() {
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
if (classLoader == null) {
classLoader = ClassLoader.getSystemClassLoader();
}
java.net.URL url = classLoader.getResource("");
String ROOT_CLASS_PATH = url.getPath() + "/";
File rootFile = new File(ROOT_CLASS_PATH);
String WEB_INFO_DIRECTORY_PATH = rootFile.getParent() + "/";
File webInfoDir = new File(WEB_INFO_DIRECTORY_PATH);
String SERVLET_CONTEXT_PATH = webInfoDir.getParent() + "/";
return SERVLET_CONTEXT_PATH;
}
/**
* 通用查询
*/
public void ex() {
Date dt = new Date();
Long id = getParaToLong("id");
String sx = getPara("sx");
Q q = Q.dao.findById(id);
setAttr("q", "q");
String pms = "[]";
ArrayList<String> whereps = new ArrayList<String>();
if (q != null) {
String sql = q.get("sql");
setAttr("sql_fs", Arrays.asList(DBSUTIL.getFields(sql).split(",")));
Long dbid = q.getLong("dbid");
if (dbid == null || dbid <= 0) {
setAttr("msg", "当前查询配置的数据源不存在!");
} else {
Dbs dbs = Dbs.dao.findById(dbid);
if (dbs == null) {
setAttr("msg", "当前查询配置的数据源不存在!");
} else {
Config c = DBSUTIL.getDb(dbs);
if (c != null) {
String[] sxz = sx.split(",");
for (String key : sxz) {
whereps.add(getPara("where." + key));
}
pms = JsonKit.toJson(whereps);
int i = q.getInt("ms");
if (i <= 0) {// 不限制
} else {
List<Qh> ql = Qh.findQhByQidPmsDt(
id, pms,System.currentTimeMillis() / 1000 - i * 60);
if (ql.size() > 0) {
setAttr("msg", i
+ "分钟内已有用户执行过相同的查询,查询创建者限制查询间隔不得小于" + i
+ "分钟!");
renderJson();
return;
}
}
List<Record> q_rl = onlyEx(whereps, sql, dbs, id);
// Object q_rl =
// DBSUTIL.invokeMeth("query",Db.use(DBSUTIL.COMMON+dbs.getLong("id")),
// sql, whereps);
setAttr("q_rl", q_rl);
} else {
setAttr("msg", "数据源配置出错!");
LOG.info(dbid + "数据源配置出错!");
}
}
}
} else {
setAttr("msg", "当前查询的对象不存在!");
}
List<Qo> qol = Qo.findQoListByQid(id);
setAttr("qol", qol);
Integer clc = q.getInt("clc");
if (clc == null) {
clc = 0;
}
try {
q.set("clc", clc + 1);
q.update();
Qh qh = new Qh();
qh.set("qid", id);
qh.set("dt", dt);
qh.set("pms", pms);
qh.set("t", 0);
qh.set("edt", new Date());
Map hm = new HashMap<String, String>();
hm.put("q_rl", getAttr("q_rl"));
hm.put("qol", qol);
hm.put("sql_fs", getAttr("sql_fs"));
String rs = JsonKit.toJson(hm);
if (rs.length() <= 4000) {
qh.set("url", rs);
} else {
qh.set("url", "内容超过4000不予存储");
}
qh.save();
} catch (Exception e) {
e.printStackTrace();
}
renderJson();
// render("ex_res.ftl");
}
public void his() {
Long id = getParaToLong("qid");
setAttr("qid", id);
Page<Qh> qhl = Qh.dao.paginate(getParaToInt("page", 1), 10, "select *",
"from qh where qid=? order by id desc", id);
setAttr("pg", qhl);
render("his.ftl");
}
public void prewhere() {
Long id = getParaToLong("id");
List<Qo> qol = Qo.findQoListByQid(id);
setAttr("qol", qol);
renderJson();
}
//
// public void add() {
// List<R> rl = R.dao.find("select * from r order by id desc");
// setAttr("rl", rl);
// }
//
// @Before(UValidator.class)
// public void save() {
// getModel(U.class).save();
// redirect("/u");
// }
//
// public void edit() {
// setAttr("u", U.dao.findById(getParaToInt()));
// List<R> rl = R.dao.find("select * from r order by id desc");
// setAttr("rl", rl);
// }
//
// @Before(UValidator.class)
// public void update() {
// getModel(U.class).update();
// redirect("/u");
// }
//
// public void delete() {
// U.dao.deleteById(getParaToInt());
// redirect("/u");
// }
//
// public void deleteByIds() {
// U.dao.deleteByIds(getParaValues("id"));
// redirect("/u");
// }
@Override
public String getMn() {
return "信息查询";
}
}
| UTF-8 | Java | 11,592 | java | QueryController.java | Java | []
| null | []
| package com.boxamazing.admin;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.boxamazing.common.BaseController;
import com.boxamazing.common.FileUtil;
import com.boxamazing.common.LOG;
import com.boxamazing.common.interceptor.UserUtil;
import com.boxamazing.service.dbs.model.Dbs;
import com.boxamazing.service.q.model.Q;
import com.boxamazing.service.qh.model.Qh;
import com.boxamazing.service.qo.model.Qo;
import com.boxamazing.service.r.model.R;
import com.boxamazing.service.u.model.PUser;
import com.boxamazing.service.util.DBSUTIL;
import com.boxamazing.util.DateUtil;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
/**
* 信息查询
*/
public class QueryController extends BaseController {
public void getStaticUrl() throws FileNotFoundException, IOException {
Long id = getParaToLong("id");
Qh qh = Qh.dao.findById(id);
Long qid = qh.getLong("qid");
PUser u = UserUtil.getU(getSession());
R r = R.findFirstRByRid(u.get("rid"));
String qs = r.get("qs");
qs = "," + qs + ",";
String wp = getWebPath();
String pf = new File(wp).getParent();
File file = new File(pf, qh.getStr("url"));
if (!file.exists()) {
setAttr("msg", "执行结果未找到,或未执行完成,如有疑问,请联系技术支持!!");
renderJson();
} else {
if (qs.contains("," + qid + ",")) {
String jsonText = FileUtil.readFile(file, "UTF-8");
renderJson(jsonText);
} else {
setAttr("msg", "您无权查询该统计内容!!");
renderJson();
}
}
// setAttr("qol",qol);
}
/**
* 进入通用查询页面
*/
public void index() {
PUser u = UserUtil.getU(getSession());
try {
R r = R.findFirstRByRid(u.get("role_id"));
String qs = r.get("qs");
List<Q> ql = Q.findQListByTypeStatIds(0, 0, qs, "clc", "desc");
setAttr("ql", ql);
} catch (Exception e) {
LOG.error(e.getMessage());
e.printStackTrace();
}
render("index.ftl");
}
public void statics() {
PUser u = UserUtil.getU(getSession());
R r = R.findFirstRByRid(u.get("rid"));
String qs = r.get("qs");
List<Q> ql = Q.findQListByTypeStatIds(1, 0, qs, "clc", "desc");
List<Qo> qol = Qo.findQoListByQids(qs);
setAttr("ql", ql);
// setAttr("qol",qol);
render("statics.ftl");
}
/**
* 统计查询
*/
public void staticex() {
Date dt = new Date();
Long id = getParaToLong("id");
String sx = getPara("sx");
Q q = Q.dao.findById(id);
setAttr("q", "q");
Long qhid = null;
ArrayList<String> whereps = new ArrayList<String>();
if (q != null) {
String sql = q.get("sql");
List<String> sql_fs = Arrays.asList(DBSUTIL.getFields(sql).split(
","));
setAttr("sql_fs", sql_fs);
Long dbid = q.getLong("dbid");
if (dbid == null || dbid <= 0) {
setAttr("msg", "当前查询配置的数据源不存在!");
} else {
Dbs dbs = Dbs.dao.findById(dbid);
if (dbs == null) {
setAttr("msg", "当前查询配置的数据源不存在!");
} else {
Config c = DBSUTIL.getDb(dbs);
if (c != null) {
String[] sxz = sx.split(",");
for (String key : sxz) {
whereps.add(getPara("where." + key));
}
String pms = JsonKit.toJson(whereps);// 参数
int i = q.getInt("ms");
if (i <= 0) {// 不限制
} else {
List<Qh> ql = Qh.findQhByQidPmsDt(id, pms, System.currentTimeMillis() / 1000 - i * 60);
if (ql.size() > 0) {
setAttr("msg", i
+ "分钟内已有用户执行过相同的统计,查询常见者限定统计时间不得小于" + i
+ "分钟请查看他的查询历史!");
renderJson();
return;
}
}
{// 先记录执行历史
Integer clc = q.getInt("clc");
if (clc == null) {
clc = 0;
}
try {
q.set("clc", clc + 1);
q.update();
Qh qh = new Qh();
qh.set("qid", id);
qh.set("dt", dt);
qh.set("pms", pms);
qh.set("t", 1);
qh.save();
qhid = qh.getLong("id");
} catch (Exception e) {
e.printStackTrace();
}
}
String url = null;
List<Record> q_rl = null;
try {
List<Qo> qol = Qo.dao.find(
"select * from qo where qid=?", id);
setAttr("qol", qol);
q_rl = onlyEx(whereps, sql, dbs, id);
url = rendHtmlAndEx(q_rl, id, sql_fs, qol);
System.out.println("shengchengurl:" + url);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
Qh qh = Qh.dao.findById(qhid);
qh.set("edt", new Date());
qh.set("url", url);
qh.update();
} catch (Exception e) {
e.printStackTrace();
}
}
// Object q_rl =
// DBSUTIL.invokeMeth("query",Db.use(DBSUTIL.COMMON+dbs.getLong("id")),
// sql, whereps);
setAttr("q_rl", q_rl);
} else {
setAttr("msg", "数据源配置出错!");
LOG.info(dbid + "数据源配置出错!");
}
}
}
} else {
setAttr("msg", "当前查询的对象不存在!");
}
renderJson();
// render("ex_res.ftl");
}
/**
* 生成静态统计文件
*
* @param whereps
* @param sql
* @param dbs
* @param id
* @return
* @throws ParseException
*/
private List<Record> onlyEx(ArrayList<String> whereps, String sql, Dbs dbs,
Long id) {
// 执行最终查询结果 限制最多查100条
List<Record> q_rl = Db.use(DBSUTIL.COMMON + dbs.getLong("id")).find(
sql + " limit 0,100", whereps.toArray());
return q_rl;
}
/**
* 生成静态统计文件
*
* @param whereps
* @param sql
* @param dbs
* @param id
* @param qol
* @param sql_fs
* @return
* @throws ParseException
* @throws IOException
*/
private String rendHtmlAndEx(List<Record> q_rl, Long id,
List<String> sql_fs, List<Qo> qol) throws ParseException,
IOException {
// 执行最终查询结果 限制最多查100条
Map<String, Object> content = new HashMap<String, Object>();
content.put("sql_fs", sql_fs);
content.put("qol", qol);
content.put("q_rl", q_rl);
String json = JsonKit.toJson(content);
String wp = getWebPath();
String jsonpath = "querystatic/genstatics/";
String filep = jsonpath + DateUtil.currDate("yyyy年MM月dd日HH时mm分ss秒SSS")
+ "查询" + id + ".json";
String pf = new File(wp).getParent();
File f = new File(pf, filep);
FileUtil.createFile(f);
f.createNewFile();
FileUtil.writeTo(json, f, "UTF-8");
return filep;
}
private String getWebPath() {
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
if (classLoader == null) {
classLoader = ClassLoader.getSystemClassLoader();
}
java.net.URL url = classLoader.getResource("");
String ROOT_CLASS_PATH = url.getPath() + "/";
File rootFile = new File(ROOT_CLASS_PATH);
String WEB_INFO_DIRECTORY_PATH = rootFile.getParent() + "/";
File webInfoDir = new File(WEB_INFO_DIRECTORY_PATH);
String SERVLET_CONTEXT_PATH = webInfoDir.getParent() + "/";
return SERVLET_CONTEXT_PATH;
}
/**
* 通用查询
*/
public void ex() {
Date dt = new Date();
Long id = getParaToLong("id");
String sx = getPara("sx");
Q q = Q.dao.findById(id);
setAttr("q", "q");
String pms = "[]";
ArrayList<String> whereps = new ArrayList<String>();
if (q != null) {
String sql = q.get("sql");
setAttr("sql_fs", Arrays.asList(DBSUTIL.getFields(sql).split(",")));
Long dbid = q.getLong("dbid");
if (dbid == null || dbid <= 0) {
setAttr("msg", "当前查询配置的数据源不存在!");
} else {
Dbs dbs = Dbs.dao.findById(dbid);
if (dbs == null) {
setAttr("msg", "当前查询配置的数据源不存在!");
} else {
Config c = DBSUTIL.getDb(dbs);
if (c != null) {
String[] sxz = sx.split(",");
for (String key : sxz) {
whereps.add(getPara("where." + key));
}
pms = JsonKit.toJson(whereps);
int i = q.getInt("ms");
if (i <= 0) {// 不限制
} else {
List<Qh> ql = Qh.findQhByQidPmsDt(
id, pms,System.currentTimeMillis() / 1000 - i * 60);
if (ql.size() > 0) {
setAttr("msg", i
+ "分钟内已有用户执行过相同的查询,查询创建者限制查询间隔不得小于" + i
+ "分钟!");
renderJson();
return;
}
}
List<Record> q_rl = onlyEx(whereps, sql, dbs, id);
// Object q_rl =
// DBSUTIL.invokeMeth("query",Db.use(DBSUTIL.COMMON+dbs.getLong("id")),
// sql, whereps);
setAttr("q_rl", q_rl);
} else {
setAttr("msg", "数据源配置出错!");
LOG.info(dbid + "数据源配置出错!");
}
}
}
} else {
setAttr("msg", "当前查询的对象不存在!");
}
List<Qo> qol = Qo.findQoListByQid(id);
setAttr("qol", qol);
Integer clc = q.getInt("clc");
if (clc == null) {
clc = 0;
}
try {
q.set("clc", clc + 1);
q.update();
Qh qh = new Qh();
qh.set("qid", id);
qh.set("dt", dt);
qh.set("pms", pms);
qh.set("t", 0);
qh.set("edt", new Date());
Map hm = new HashMap<String, String>();
hm.put("q_rl", getAttr("q_rl"));
hm.put("qol", qol);
hm.put("sql_fs", getAttr("sql_fs"));
String rs = JsonKit.toJson(hm);
if (rs.length() <= 4000) {
qh.set("url", rs);
} else {
qh.set("url", "内容超过4000不予存储");
}
qh.save();
} catch (Exception e) {
e.printStackTrace();
}
renderJson();
// render("ex_res.ftl");
}
public void his() {
Long id = getParaToLong("qid");
setAttr("qid", id);
Page<Qh> qhl = Qh.dao.paginate(getParaToInt("page", 1), 10, "select *",
"from qh where qid=? order by id desc", id);
setAttr("pg", qhl);
render("his.ftl");
}
public void prewhere() {
Long id = getParaToLong("id");
List<Qo> qol = Qo.findQoListByQid(id);
setAttr("qol", qol);
renderJson();
}
//
// public void add() {
// List<R> rl = R.dao.find("select * from r order by id desc");
// setAttr("rl", rl);
// }
//
// @Before(UValidator.class)
// public void save() {
// getModel(U.class).save();
// redirect("/u");
// }
//
// public void edit() {
// setAttr("u", U.dao.findById(getParaToInt()));
// List<R> rl = R.dao.find("select * from r order by id desc");
// setAttr("rl", rl);
// }
//
// @Before(UValidator.class)
// public void update() {
// getModel(U.class).update();
// redirect("/u");
// }
//
// public void delete() {
// U.dao.deleteById(getParaToInt());
// redirect("/u");
// }
//
// public void deleteByIds() {
// U.dao.deleteByIds(getParaValues("id"));
// redirect("/u");
// }
@Override
public String getMn() {
return "信息查询";
}
}
| 11,592 | 0.552708 | 0.548058 | 450 | 22.368889 | 17.73288 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.402222 | false | false | 3 |
f0c7fcdbebd5c2b71a6aa4087cada5f9f6354769 | 10,668,698,829,996 | e91e1d9338e8fa5d306cda8391e708ae17a9d21c | /src/assessment/PilesEqualHeight.java | c6d1ce5ffc144c5c97a1e72228480b622c5a242f | []
| no_license | sagacioussid02/AlgorithmicExperiments | https://github.com/sagacioussid02/AlgorithmicExperiments | 8c3203e163e14d29bfc3f8556eeb5e54a43ae4bb | 5023fcfcce0a38ec72bf9b6f14e997fc9e0268f9 | refs/heads/master | 2022-03-25T17:16:36.737000 | 2019-11-25T04:19:20 | 2019-11-25T04:19:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package assessment;
import java.util.Arrays;
public class PilesEqualHeight {
public static void main(String[] args) {
int[] arr = {5,4,3,3,2,1};
System.out.println(minNoOfStepsToEqualHeight(arr));
}
private static int minNoOfStepsToEqualHeight(int[] arr) {
int length = arr.length;
int moves = 0;
int maxIndex = 0;
while(maxIndex<length) {
//get the max index of the largest element
//where the next element is different
maxIndex = getMaxIndex(arr);
//replace the maximum number with its next number
//which is just lower than the maximum number
if(maxIndex!=length-1) {
arr[maxIndex] = arr[++maxIndex];
moves++;
} else {
break;
}
Arrays.stream(arr).forEach(System.out::print);
System.out.println("\n");
}
return moves;
}
//method to return the min number in a sorted array
private static int getMaxIndex(int[] arr) {
int maxIndex=0;
//loop from the first element
//loop till the length of array
//check if the next number is same
//increment the index
while(maxIndex<(arr.length-1)&&arr[maxIndex]==arr[maxIndex+1]) {
maxIndex++;
}
return maxIndex;
}
}
| UTF-8 | Java | 1,144 | java | PilesEqualHeight.java | Java | []
| null | []
| package assessment;
import java.util.Arrays;
public class PilesEqualHeight {
public static void main(String[] args) {
int[] arr = {5,4,3,3,2,1};
System.out.println(minNoOfStepsToEqualHeight(arr));
}
private static int minNoOfStepsToEqualHeight(int[] arr) {
int length = arr.length;
int moves = 0;
int maxIndex = 0;
while(maxIndex<length) {
//get the max index of the largest element
//where the next element is different
maxIndex = getMaxIndex(arr);
//replace the maximum number with its next number
//which is just lower than the maximum number
if(maxIndex!=length-1) {
arr[maxIndex] = arr[++maxIndex];
moves++;
} else {
break;
}
Arrays.stream(arr).forEach(System.out::print);
System.out.println("\n");
}
return moves;
}
//method to return the min number in a sorted array
private static int getMaxIndex(int[] arr) {
int maxIndex=0;
//loop from the first element
//loop till the length of array
//check if the next number is same
//increment the index
while(maxIndex<(arr.length-1)&&arr[maxIndex]==arr[maxIndex+1]) {
maxIndex++;
}
return maxIndex;
}
}
| 1,144 | 0.678322 | 0.667832 | 47 | 23.340425 | 18.515406 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.255319 | false | false | 3 |
30d91cb7f8b3ae799158961dc57000e4d70fd0f4 | 360,777,264,383 | b95c91d08b3c9120267c46ea47e9c18ca8a893c4 | /src/main/java/org/fanlychie/commons/web/spring/servlet/SimpleHandlerInterceptor.java | f4eea44926e3487fff674ef521af00b033eb7c81 | []
| no_license | fanlychie/commons-web | https://github.com/fanlychie/commons-web | 1af710852bc1426c32f760b3195b9d471052eabe | e9d9226828eb21f3063301d372293f2a81ecda2a | refs/heads/master | 2021-01-14T08:30:30.620000 | 2018-07-10T03:19:32 | 2018-07-10T03:19:32 | 81,961,860 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.fanlychie.commons.web.spring.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 简单的处理器拦截
* <p>
* 可以通过 RequestContext 和 ResponseContext 获取请求相关的上下文变量
* <p>
* Created by fanlychie on 2017/2/15.
*/
public class SimpleHandlerInterceptor extends ServletHandlerInterceptor {
@Override
public boolean handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
} | UTF-8 | Java | 558 | java | SimpleHandlerInterceptor.java | Java | [
{
"context": " ResponseContext 获取请求相关的上下文变量\n * <p>\n * Created by fanlychie on 2017/2/15.\n */\npublic class SimpleHandlerInter",
"end": 252,
"score": 0.9996021389961243,
"start": 243,
"tag": "USERNAME",
"value": "fanlychie"
}
]
| null | []
| package org.fanlychie.commons.web.spring.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 简单的处理器拦截
* <p>
* 可以通过 RequestContext 和 ResponseContext 获取请求相关的上下文变量
* <p>
* Created by fanlychie on 2017/2/15.
*/
public class SimpleHandlerInterceptor extends ServletHandlerInterceptor {
@Override
public boolean handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
} | 558 | 0.767717 | 0.753937 | 20 | 24.450001 | 30.678127 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 3 |
b44b22f1dd169c22dad8b800b8a93080997d55c7 | 15,882,789,094,484 | f332df8db8d18768b281320d67d94c17971d5c1b | /src/main/java/net/namiha/favoritelist/account/AccountDao.java | 4b09b56a5654b4765467dadccf6ccfd0762a4852 | []
| no_license | namiha/favorite-list | https://github.com/namiha/favorite-list | cb40a38e4df2b28a5199bbdcec59441726cdaff9 | 8557000189bd172c7e6d165dab75159735b83b39 | refs/heads/master | 2018-12-27T21:53:33.926000 | 2018-10-25T14:07:43 | 2018-10-25T14:09:14 | 94,161,181 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.namiha.favoritelist.account;
import net.namiha.favoritelist.account.entity.Account;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.JpaRepository;
@Profile(value = { "test", "development", "production" })
public interface AccountDao extends JpaRepository<Account, Long> {
Account findById(String id);
}
| UTF-8 | Java | 377 | java | AccountDao.java | Java | []
| null | []
| package net.namiha.favoritelist.account;
import net.namiha.favoritelist.account.entity.Account;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.JpaRepository;
@Profile(value = { "test", "development", "production" })
public interface AccountDao extends JpaRepository<Account, Long> {
Account findById(String id);
}
| 377 | 0.795756 | 0.795756 | 12 | 30.416666 | 26.896276 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 3 |
60134e8d8abf115eff6b11ef13ef7e13bc8bb9e3 | 3,264,175,146,717 | 812a2a9bb78e3e2080393d74a21a4701035c54f1 | /com/afk/script/api/InteractableObject.java | d3529d664b8f8c56049851d13a0d579943485fec | []
| no_license | luckruns0ut/AFK | https://github.com/luckruns0ut/AFK | 15050820059af95db76de6a51795b3962af23a77 | 34a78cf568cff859915ab5108fb59c895d7714ee | refs/heads/master | 2015-07-21T15:04:09 | 2015-05-02T15:24:53 | 2015-05-02T15:24:53 | 30,939,931 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.afk.script.api;
import com.afk.inject.interfaces.IInteractableObject;
import com.afk.inject.interfaces.IRenderableNode;
/**
* Created by luckruns0ut on 27/02/15.
*/
public class InteractableObject extends GameObject {
private IInteractableObject accessor;
public InteractableObject(IInteractableObject accessor, Tile tile) {
super(tile);
this.accessor = accessor;
}
@Override
public int getId() {
return (accessor.getHash() >> 14) & 0x7FFF;
}
@Override
public int getHash() {
return accessor.getHash();
}
@Override
public int getPlane() {
return accessor.getPlane();
}
@Override
public int getRelativeX() {
return accessor.getRelativeX();
}
@Override
public int getRelativeY() {
return accessor.getRelativeY();
}
@Override
public IRenderableNode getPrimaryRenderableNode() {
return accessor.getRenderableNode();
}
public IInteractableObject getAccessor() {
return accessor;
}
}
| UTF-8 | Java | 1,066 | java | InteractableObject.java | Java | [
{
"context": "ect.interfaces.IRenderableNode;\n\n/**\n * Created by luckruns0ut on 27/02/15.\n */\npublic class InteractableObject ",
"end": 163,
"score": 0.9995865821838379,
"start": 152,
"tag": "USERNAME",
"value": "luckruns0ut"
}
]
| null | []
| package com.afk.script.api;
import com.afk.inject.interfaces.IInteractableObject;
import com.afk.inject.interfaces.IRenderableNode;
/**
* Created by luckruns0ut on 27/02/15.
*/
public class InteractableObject extends GameObject {
private IInteractableObject accessor;
public InteractableObject(IInteractableObject accessor, Tile tile) {
super(tile);
this.accessor = accessor;
}
@Override
public int getId() {
return (accessor.getHash() >> 14) & 0x7FFF;
}
@Override
public int getHash() {
return accessor.getHash();
}
@Override
public int getPlane() {
return accessor.getPlane();
}
@Override
public int getRelativeX() {
return accessor.getRelativeX();
}
@Override
public int getRelativeY() {
return accessor.getRelativeY();
}
@Override
public IRenderableNode getPrimaryRenderableNode() {
return accessor.getRenderableNode();
}
public IInteractableObject getAccessor() {
return accessor;
}
}
| 1,066 | 0.65197 | 0.641651 | 50 | 20.32 | 19.291904 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.28 | false | false | 3 |
edccbdb3632a0524fa01d33742119fb6028724ba | 29,575,144,837,415 | 67c5b23611ef65d7e0fa451e0043aa76a2472452 | /Mall/app/src/main/java/com/giveu/shoppingmall/model/bean/response/ListInstalmentResponse.java | 9b4ddd7d1f415577ca926139247e04a8066d007a | []
| no_license | dengjiaping/mall_new | https://github.com/dengjiaping/mall_new | bcb60ae80a9dfd52fe66cf97a9cffd372f6123af | 811c1988e602d166d3cb2f35b0e92bd1e1695a89 | refs/heads/master | 2021-07-12T17:07:37.727000 | 2017-10-16T10:40:51 | 2017-10-16T10:40:51 | 110,532,195 | 0 | 1 | null | true | 2017-11-13T10:11:44 | 2017-11-13T10:11:44 | 2017-10-16T10:38:47 | 2017-10-16T10:42:27 | 12,894 | 0 | 0 | 0 | null | false | null | package com.giveu.shoppingmall.model.bean.response;
import com.android.volley.mynet.BaseBean;
import java.util.List;
/**
* Created by 513419 on 2017/7/4.
*/
public class ListInstalmentResponse extends BaseBean<ListInstalmentResponse> {
public List<Instalment> instalmentList;
public static class Instalment {
/**
* amount : 58377
* dueDate : 测试内容i708
* num : 85106
* payStatus : 测试内容5904
*/
public String amount;
public String dueDate;
public int num;
public String payStatus;
}
}
| UTF-8 | Java | 603 | java | ListInstalmentResponse.java | Java | [
{
"context": "eBean;\n\nimport java.util.List;\n\n/**\n * Created by 513419 on 2017/7/4.\n */\n\npublic class ListInstalmentResp",
"end": 144,
"score": 0.9954569339752197,
"start": 138,
"tag": "USERNAME",
"value": "513419"
}
]
| null | []
| package com.giveu.shoppingmall.model.bean.response;
import com.android.volley.mynet.BaseBean;
import java.util.List;
/**
* Created by 513419 on 2017/7/4.
*/
public class ListInstalmentResponse extends BaseBean<ListInstalmentResponse> {
public List<Instalment> instalmentList;
public static class Instalment {
/**
* amount : 58377
* dueDate : 测试内容i708
* num : 85106
* payStatus : 测试内容5904
*/
public String amount;
public String dueDate;
public int num;
public String payStatus;
}
}
| 603 | 0.633731 | 0.584327 | 28 | 19.964285 | 19.286343 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 3 |
221c72e46e641ba4aa1a1e7b6fbc0cef5c4895c4 | 438,086,664,845 | 5f12149620ba37f106eec5b132bfcb5b4f1e9f6c | /src/main/java/com/pramode/xmlops/OpsApp.java | 38817c19a48b8f0fe874255a0ace384789d6f8ca | []
| no_license | pramode2009/xmlops | https://github.com/pramode2009/xmlops | 7226771a6db8a59e2b51abe183dfcd3e6f0c1306 | 62d98be5f767a403fadc3f3ab58a114edb4c46d8 | refs/heads/master | 2020-03-23T02:10:25.262000 | 2018-07-15T06:02:49 | 2018-07-15T06:02:49 | 140,960,376 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pramode.xmlops;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
// @RestController -- > Return string json as ressponse
// @Controller -- > Return view (static html and files ) as ressponse
@Controller
@SpringBootApplication
public class OpsApp
{
public static void main(String[] args) {
SpringApplication.run(OpsApp.class, args);
}
@GetMapping("/")
// @RequestMapping(method=RequestMethod.GET,value="/")
String home() {
return "index.html";
}
}
| UTF-8 | Java | 946 | java | OpsApp.java | Java | []
| null | []
| package com.pramode.xmlops;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
// @RestController -- > Return string json as ressponse
// @Controller -- > Return view (static html and files ) as ressponse
@Controller
@SpringBootApplication
public class OpsApp
{
public static void main(String[] args) {
SpringApplication.run(OpsApp.class, args);
}
@GetMapping("/")
// @RequestMapping(method=RequestMethod.GET,value="/")
String home() {
return "index.html";
}
}
| 946 | 0.738901 | 0.738901 | 35 | 24.914286 | 25.223993 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.885714 | false | false | 5 |
a02e457a8e76e66101660a8f684c00ccd3adb697 | 3,882,650,443,093 | 44e8064828f9397257d585c1511749108944fa0e | /src/test/java/ex31/karvonenTableGenTest.java | 330fa8335e80b43f498411c8f65c915ba1355ddf | []
| no_license | tsehaiB/boucaud-cop3330-assingment2 | https://github.com/tsehaiB/boucaud-cop3330-assingment2 | 2e283e5dbbe7d6f477c26faf023fb3cec8d087f9 | 19e0d41c7419362c2199227334c8424e1511b115 | refs/heads/master | 2023-05-27T10:33:17.502000 | 2021-06-14T03:43:35 | 2021-06-14T03:43:35 | 376,683,759 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* UCF COP3330 Summer 2021 Assignment 2 Solution
* Copyright 2021 Tsehai Boucaud
*/
package ex31;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class karvonenTableGenTest {
@Test
void tableGen_returns_table_given_age_and_HR() {
//given
karvonenTableGen table = new karvonenTableGen();
//when
String expected = "Intensity |Rate \n" +
"55% |138.15 bpm\n" +
"60% |144.8 bpm\n" +
"65% |151.45 bpm\n" +
"70% |158.1 bpm\n" +
"75% |164.75 bpm\n" +
"80% |171.4 bpm\n" +
"85% |178.05 bpm\n" +
"90% |184.7 bpm\n" +
"95% |191.35 bpm";
String actual = table.tableGen(22, 65);
//then
assertEquals(expected, actual);
}
@Test
void calculate_returns_171_given_22_65_80() {
//given
karvonenTableGen table = new karvonenTableGen();
//when
double expected = 171.4;
double actual = table.calculate(22, 65, 80);
//then
assertEquals(expected, actual);
}
} | UTF-8 | Java | 1,255 | java | karvonenTableGenTest.java | Java | [
{
"context": "mmer 2021 Assignment 2 Solution\n * Copyright 2021 Tsehai Boucaud\n */\n\npackage ex31;\n\nimport org.junit.jupiter.api.",
"end": 86,
"score": 0.9998764395713806,
"start": 72,
"tag": "NAME",
"value": "Tsehai Boucaud"
}
]
| null | []
| /*
* UCF COP3330 Summer 2021 Assignment 2 Solution
* Copyright 2021 <NAME>
*/
package ex31;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class karvonenTableGenTest {
@Test
void tableGen_returns_table_given_age_and_HR() {
//given
karvonenTableGen table = new karvonenTableGen();
//when
String expected = "Intensity |Rate \n" +
"55% |138.15 bpm\n" +
"60% |144.8 bpm\n" +
"65% |151.45 bpm\n" +
"70% |158.1 bpm\n" +
"75% |164.75 bpm\n" +
"80% |171.4 bpm\n" +
"85% |178.05 bpm\n" +
"90% |184.7 bpm\n" +
"95% |191.35 bpm";
String actual = table.tableGen(22, 65);
//then
assertEquals(expected, actual);
}
@Test
void calculate_returns_171_given_22_65_80() {
//given
karvonenTableGen table = new karvonenTableGen();
//when
double expected = 171.4;
double actual = table.calculate(22, 65, 80);
//then
assertEquals(expected, actual);
}
} | 1,247 | 0.483665 | 0.406375 | 47 | 25.723404 | 20.651827 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.553191 | false | false | 5 |
e04b0264c1b143379ab76aa8815e9f80a7b06649 | 5,394,478,932,791 | e16a29a4d29958b12a9f1223ee9355bf5c4bce0c | /jbehave-core/src/test/java/org/jbehave/core/embedder/ConcurrencyBehaviour.java | 4aa6f3ff77ce6e6c38f232d0db9f941fc1b7cdc0 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
]
| permissive | JSlain/jbehave-core | https://github.com/JSlain/jbehave-core | 5ecea59b759b0eacc5d6622fe9ee4f6fb8d08858 | baeae8a62890ce230587d2d8bce6b081e42ff5a6 | refs/heads/master | 2021-01-18T06:20:51.755000 | 2013-11-04T04:31:47 | 2013-11-04T04:31:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jbehave.core.embedder;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.jbehave.core.annotations.When;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.embedder.Embedder.RunningEmbeddablesFailed;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.jbehave.core.io.CodeLocations.codeLocationFromClass;
import static org.jbehave.core.reporters.Format.CONSOLE;
import static org.jbehave.core.reporters.Format.HTML;
import static org.jbehave.core.reporters.Format.XML;
public class ConcurrencyBehaviour {
@Test(expected=RunningEmbeddablesFailed.class)
public void shouldAllowStoriesToBeCancelled() {
Embedder embedder = new Embedder();
embedder.embedderControls().useStoryTimeoutInSecs(1);
embedder.runAsEmbeddables(asList(ThreadsStories.class.getName()));
}
public static class ThreadsStories extends JUnitStories {
@Override
public Configuration configuration() {
return new MostUsefulConfiguration().useStoryLoader(new LoadFromClasspath(this.getClass()))
.useStoryReporterBuilder(new StoryReporterBuilder().withFormats(CONSOLE, HTML, XML));
}
@Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new ThreadsSteps());
}
@Override
protected List<String> storyPaths() {
return new StoryFinder().findPaths(codeLocationFromClass(this.getClass()), "**/*.story", "");
}
}
public static class ThreadsSteps {
@When("$name counts to $n Mississippi")
public void whenSomeoneCountsMississippis(String name, AtomicInteger n) throws InterruptedException {
long start = System.currentTimeMillis();
System.out.println(name + " starts counting to " + n);
for (int i = 0; i < n.intValue(); i++) {
System.out.println(name + " says " + i + " Mississippi (" + (System.currentTimeMillis() - start)
+ " millis)");
TimeUnit.SECONDS.sleep(1);
}
}
}
}
| UTF-8 | Java | 2,595 | java | ConcurrencyBehaviour.java | Java | []
| null | []
| package org.jbehave.core.embedder;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.jbehave.core.annotations.When;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.embedder.Embedder.RunningEmbeddablesFailed;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.jbehave.core.io.CodeLocations.codeLocationFromClass;
import static org.jbehave.core.reporters.Format.CONSOLE;
import static org.jbehave.core.reporters.Format.HTML;
import static org.jbehave.core.reporters.Format.XML;
public class ConcurrencyBehaviour {
@Test(expected=RunningEmbeddablesFailed.class)
public void shouldAllowStoriesToBeCancelled() {
Embedder embedder = new Embedder();
embedder.embedderControls().useStoryTimeoutInSecs(1);
embedder.runAsEmbeddables(asList(ThreadsStories.class.getName()));
}
public static class ThreadsStories extends JUnitStories {
@Override
public Configuration configuration() {
return new MostUsefulConfiguration().useStoryLoader(new LoadFromClasspath(this.getClass()))
.useStoryReporterBuilder(new StoryReporterBuilder().withFormats(CONSOLE, HTML, XML));
}
@Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new ThreadsSteps());
}
@Override
protected List<String> storyPaths() {
return new StoryFinder().findPaths(codeLocationFromClass(this.getClass()), "**/*.story", "");
}
}
public static class ThreadsSteps {
@When("$name counts to $n Mississippi")
public void whenSomeoneCountsMississippis(String name, AtomicInteger n) throws InterruptedException {
long start = System.currentTimeMillis();
System.out.println(name + " starts counting to " + n);
for (int i = 0; i < n.intValue(); i++) {
System.out.println(name + " says " + i + " Mississippi (" + (System.currentTimeMillis() - start)
+ " millis)");
TimeUnit.SECONDS.sleep(1);
}
}
}
}
| 2,595 | 0.706358 | 0.705202 | 68 | 37.161766 | 30.530415 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.558824 | false | false | 5 |
56981d3a0f48a015d9d171a7ec714be487ed16bb | 9,603,546,880,123 | 107c5d818fc996e11b9bb1524c63d271d47a6eb4 | /src/emsTest/MemberTest.java | ee766e5de7dc38a7e6850695f94989f86df7e953 | []
| no_license | Ironolife/CS3343_Project | https://github.com/Ironolife/CS3343_Project | e89add817b5bc34bcf404eeeba6726129b350663 | c6db818a3621d72ef5ab7186ff7fe472306a7f76 | refs/heads/master | 2020-03-31T02:06:42.870000 | 2018-12-08T08:36:01 | 2018-12-08T08:36:01 | 151,808,676 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package emsTest;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
import ems.Coupon;
import ems.Member;
public class MemberTest {
@Test
public void testAddBalance() {
Member testMember = new Member("testId", "password", "name", 20, "hkid");
testMember.addBalance(500);
assertEquals(testMember.getBalance(), 500, 0.01);
}
//Stub required
@Test
public void testSubtractBalanceSuccess() {
Member testMember = new Member("testId", "password", "name", 20, "hkid");
testMember.addBalance(500);
boolean testSuccess = testMember.substractBalance(300);
assertTrue(testSuccess);
}
@Test
public void testSubtractBalanceFail() {
Member testMember = new Member("testId", "password", "name", 20, "hkid");
boolean testFail = testMember.substractBalance(300);
assertFalse(testFail);
}
@Test
public void testGetName() {
Member testMember = new Member("testId", "password", "name", 20, "hkid");
assertEquals("name", testMember.getName());
}
@Test
public void testGetDiscount() {
Member testMember = new Member("testId", "password", "name", 20, "hkid");
double errorMargin = 0.0001;
assertEquals(0.95, testMember.getDiscount(), errorMargin);
}
}
| UTF-8 | Java | 1,228 | java | MemberTest.java | Java | [
{
"context": "e() {\n\t\tMember testMember = new Member(\"testId\", \"password\", \"name\", 20, \"hkid\");\n\t\ttestMember.addBalance(50",
"end": 260,
"score": 0.9944061636924744,
"start": 252,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "s() {\n\t\tMember testMember = new Member(\"testId\", \"password\", \"name\", 20, \"hkid\");\n\t\ttestMember.addBalance(50",
"end": 493,
"score": 0.8439294695854187,
"start": 485,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "l() {\n\t\tMember testMember = new Member(\"testId\", \"password\", \"name\", 20, \"hkid\");\n\t\tboolean testFail = testM",
"end": 737,
"score": 0.8228407502174377,
"start": 729,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "e() {\n\t\tMember testMember = new Member(\"testId\", \"password\", \"name\", 20, \"hkid\");\n\t\tassertEquals(\"name\", tes",
"end": 934,
"score": 0.9738625884056091,
"start": 926,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "t() {\n\t\tMember testMember = new Member(\"testId\", \"password\", \"name\", 20, \"hkid\");\n\t\tdouble errorMargin = 0.0",
"end": 1101,
"score": 0.9967111945152283,
"start": 1093,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package emsTest;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
import ems.Coupon;
import ems.Member;
public class MemberTest {
@Test
public void testAddBalance() {
Member testMember = new Member("testId", "<PASSWORD>", "name", 20, "hkid");
testMember.addBalance(500);
assertEquals(testMember.getBalance(), 500, 0.01);
}
//Stub required
@Test
public void testSubtractBalanceSuccess() {
Member testMember = new Member("testId", "<PASSWORD>", "name", 20, "hkid");
testMember.addBalance(500);
boolean testSuccess = testMember.substractBalance(300);
assertTrue(testSuccess);
}
@Test
public void testSubtractBalanceFail() {
Member testMember = new Member("testId", "<PASSWORD>", "name", 20, "hkid");
boolean testFail = testMember.substractBalance(300);
assertFalse(testFail);
}
@Test
public void testGetName() {
Member testMember = new Member("testId", "<PASSWORD>", "name", 20, "hkid");
assertEquals("name", testMember.getName());
}
@Test
public void testGetDiscount() {
Member testMember = new Member("testId", "<PASSWORD>", "name", 20, "hkid");
double errorMargin = 0.0001;
assertEquals(0.95, testMember.getDiscount(), errorMargin);
}
}
| 1,238 | 0.704397 | 0.675081 | 50 | 23.559999 | 24.128954 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 5 |
16cb0eb4ff0869f1b86f66f1301c56fb595e8c41 | 14,594,298,876,808 | 8420daa42123ffacd22545ff4700809a6e64b445 | /src/main/java/services/ReaderTestProgramsFromKonzept.java | bc360e9d0a6f72e95ec438f71cc0f539fde24123 | []
| no_license | oleksii-smolenskyi/assistantengineer | https://github.com/oleksii-smolenskyi/assistantengineer | 8fd13cfb131e47ac235bfc0600796d379bae0f75 | bfc0de9fa6f1e5cd9b33dbc24673d2b1d052d719 | refs/heads/master | 2021-01-15T02:44:51.002000 | 2020-02-24T22:06:22 | 2020-02-24T22:06:22 | 242,851,622 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package services;
import models.Progressable;
import java.io.File;
import java.io.IOException;
public class ReaderTestProgramsFromKonzept implements Progressable {
private int ready = 0;
@Override
public synchronized int getReady() {
return 0;
}
@Override
public synchronized boolean isReady() {
return false;
}
IOException stopException;
@Override
public synchronized IOException getStopException() {
return stopException;
}
private File fileKonzept;
public ReaderTestProgramsFromKonzept(File fileKonzept) throws IOException {
if(fileKonzept.toString().endsWith(".xlsx")) {
throw new IOException("Не підтримуваний формат файлу " + fileKonzept);
}
this.fileKonzept = fileKonzept;
}
private String statusMessage;
@Override
public String getStatusMessage() {
return statusMessage;
}
}
| UTF-8 | Java | 959 | java | ReaderTestProgramsFromKonzept.java | Java | []
| null | []
| package services;
import models.Progressable;
import java.io.File;
import java.io.IOException;
public class ReaderTestProgramsFromKonzept implements Progressable {
private int ready = 0;
@Override
public synchronized int getReady() {
return 0;
}
@Override
public synchronized boolean isReady() {
return false;
}
IOException stopException;
@Override
public synchronized IOException getStopException() {
return stopException;
}
private File fileKonzept;
public ReaderTestProgramsFromKonzept(File fileKonzept) throws IOException {
if(fileKonzept.toString().endsWith(".xlsx")) {
throw new IOException("Не підтримуваний формат файлу " + fileKonzept);
}
this.fileKonzept = fileKonzept;
}
private String statusMessage;
@Override
public String getStatusMessage() {
return statusMessage;
}
}
| 959 | 0.677385 | 0.675241 | 42 | 21.214285 | 21.876858 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 5 |
aaf18e1a9cff209546beeae84e6e1cbe2eb2db78 | 14,817,637,178,980 | ae12996324ff89489ded4c10163f7ff9919d080b | /LeetCodePractice/src/dp/MaximumLengthOfPairChain.java | cf3384f1539863710d98f51a1862c6ca2df82ea7 | []
| no_license | DeanHe/Practice | https://github.com/DeanHe/Practice | 31f1f2522f3e7a35dc57f6c1ae74487ad044e2df | 3230cda09ad345f71bb1537cb66124ec051de3a5 | refs/heads/master | 2023-07-05T20:31:33.033000 | 2023-07-01T18:02:32 | 2023-07-01T18:02:32 | 149,399,927 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dp;
import java.util.Arrays;
/*
You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.
A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.
Return the length longest chain which can be formed.
You do not need to use up all the given intervals. You can select pairs in any order.
Example 1:
Input: pairs = [[1,2],[2,3],[3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4].
Example 2:
Input: pairs = [[1,2],[7,8],[4,5]]
Output: 3
Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].
Constraints:
n == pairs.length
1 <= n <= 1000
-1000 <= lefti < righti < 1000
analysis:
DP: TC(N ^ 2)
Greedy TC(N log N)
*/
public class MaximumLengthOfPairChain {
public int findLongestChain(int[][] pairs) {
int res = 0;
Arrays.sort(pairs, (a, b) -> a[1] - b[1]);
int end = Integer.MIN_VALUE;
for(int[] pair : pairs){
if(end < pair[0]){
end = pair[1];
res++;
}
}
return res;
}
public int findLongestChainDP(int[][] pairs) {
int len = pairs.length;
Arrays.sort(pairs, (a, b) -> a[0] - b[0]);
// dp[i] means longest chain size ended with pair[i]
int[] dp = new int[len];
Arrays.fill(dp, 1);
for(int i = 0; i < len; i++){
for(int j = 0; j < i; j++){
if(pairs[j][1] < pairs[i][0]){
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return dp[pairs.length - 1];
}
}
| UTF-8 | Java | 1,560 | java | MaximumLengthOfPairChain.java | Java | []
| null | []
| package dp;
import java.util.Arrays;
/*
You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.
A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.
Return the length longest chain which can be formed.
You do not need to use up all the given intervals. You can select pairs in any order.
Example 1:
Input: pairs = [[1,2],[2,3],[3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4].
Example 2:
Input: pairs = [[1,2],[7,8],[4,5]]
Output: 3
Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].
Constraints:
n == pairs.length
1 <= n <= 1000
-1000 <= lefti < righti < 1000
analysis:
DP: TC(N ^ 2)
Greedy TC(N log N)
*/
public class MaximumLengthOfPairChain {
public int findLongestChain(int[][] pairs) {
int res = 0;
Arrays.sort(pairs, (a, b) -> a[1] - b[1]);
int end = Integer.MIN_VALUE;
for(int[] pair : pairs){
if(end < pair[0]){
end = pair[1];
res++;
}
}
return res;
}
public int findLongestChainDP(int[][] pairs) {
int len = pairs.length;
Arrays.sort(pairs, (a, b) -> a[0] - b[0]);
// dp[i] means longest chain size ended with pair[i]
int[] dp = new int[len];
Arrays.fill(dp, 1);
for(int i = 0; i < len; i++){
for(int j = 0; j < i; j++){
if(pairs[j][1] < pairs[i][0]){
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return dp[pairs.length - 1];
}
}
| 1,560 | 0.545513 | 0.509615 | 67 | 21.283583 | 23.070175 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.283582 | false | false | 5 |
396130e58b15d926390eb2af977063c45cf2df00 | 31,533,649,897,754 | 4427f04d2c44ad4d9968c09a16bc8491cc6e18d0 | /src/main/java/propertyFiles/popupsElements/AddEventPopup.java | 3bc1705ae81f633de05b45d313eb3c5bc3b399d6 | []
| no_license | ArtemDiranov/GLD | https://github.com/ArtemDiranov/GLD | 1d0f2e58d895cf750c63aaeb66f413daa30b5daa | 817b7adef2344e7822da5d50e0259160080d345e | refs/heads/master | 2018-12-08T20:25:17.981000 | 2018-11-05T13:21:27 | 2018-11-05T13:21:27 | 60,362,968 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package propertyFiles.popupsElements;
import com.codeborne.selenide.ElementsCollection;
import com.codeborne.selenide.SelenideElement;
import static com.codeborne.selenide.Condition.attribute;
import static com.codeborne.selenide.Selectors.byXpath;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;
public class AddEventPopup {
public static SelenideElement budget_FirstPopupTitle() {
return $(".popup-header.lato.fontSize20");
}
public static void testPopupEventLinesInfo(int box, int span, String lineText) {
(popupEventInfo().get(box)).
$$("span").
get(span).
shouldHave(attribute("innerText", lineText));
}
public static void selectEvent_in_popup(int eventIndx) {
$$(".iconWithText-text.undefined.lato16.color-ashBrown-600").
get(eventIndx).
click();
}
public static ElementsCollection popupEventInfo() {
return $$(".popup.popup-container .iconWithText .iconWithText-text");
}
}
| UTF-8 | Java | 1,085 | java | AddEventPopup.java | Java | []
| null | []
| package propertyFiles.popupsElements;
import com.codeborne.selenide.ElementsCollection;
import com.codeborne.selenide.SelenideElement;
import static com.codeborne.selenide.Condition.attribute;
import static com.codeborne.selenide.Selectors.byXpath;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;
public class AddEventPopup {
public static SelenideElement budget_FirstPopupTitle() {
return $(".popup-header.lato.fontSize20");
}
public static void testPopupEventLinesInfo(int box, int span, String lineText) {
(popupEventInfo().get(box)).
$$("span").
get(span).
shouldHave(attribute("innerText", lineText));
}
public static void selectEvent_in_popup(int eventIndx) {
$$(".iconWithText-text.undefined.lato16.color-ashBrown-600").
get(eventIndx).
click();
}
public static ElementsCollection popupEventInfo() {
return $$(".popup.popup-container .iconWithText .iconWithText-text");
}
}
| 1,085 | 0.682028 | 0.675576 | 35 | 30 | 26.554525 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 5 |
b70c36f326717df73c85896ab3314de61d0097a9 | 10,239,202,046,468 | 3bb8b3cf01b1b476504d0d99e19beced1f8530e7 | /occurrence-download/src/main/java/org/gbif/occurrence/download/file/dwca/DwcaDownloadAggregator.java | a0aa32eb241fa37e09e63ce02bc752445e403f77 | [
"Apache-2.0"
]
| permissive | timrobertson100/occurrence | https://github.com/timrobertson100/occurrence | 9953bfdadd3b330471773280ce1cc2bb858629db | 82c0aebcc2fa67f9c3af202b22e7388cd1a65eb3 | refs/heads/master | 2022-02-21T04:58:53.892000 | 2022-01-28T12:53:02 | 2022-01-28T12:53:02 | 186,794,230 | 0 | 0 | null | true | 2019-05-15T09:29:49 | 2019-05-15T09:29:49 | 2019-04-15T13:23:53 | 2019-05-14T12:25:47 | 9,137 | 0 | 0 | 0 | null | false | false | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gbif.occurrence.download.file.dwca;
import org.gbif.api.service.registry.OccurrenceDownloadService;
import org.gbif.occurrence.download.file.DownloadAggregator;
import org.gbif.occurrence.download.file.DownloadJobConfiguration;
import org.gbif.occurrence.download.file.Result;
import org.gbif.occurrence.download.file.common.DatasetUsagesCollector;
import org.gbif.occurrence.download.file.common.DownloadFileUtils;
import org.gbif.occurrence.download.util.HeadersFileUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Throwables;
/**
* Aggregates partials results of files and combine then into the output zip file.
*/
public class DwcaDownloadAggregator implements DownloadAggregator {
private static final Logger LOG = LoggerFactory.getLogger(DwcaDownloadAggregator.class);
// Service that persist dataset usage information
private final OccurrenceDownloadService occurrenceDownloadService;
private final DownloadJobConfiguration configuration;
/**
* Utility method that creates a file, if the files exists it is deleted.
*/
private static void createFile(String outFile) {
try {
File file = new File(outFile);
if (file.exists()) {
file.delete();
}
file.createNewFile();
} catch (IOException e) {
LOG.error("Error creating file", e);
throw Throwables.propagate(e);
}
}
/**
* Appends the result files to the output file.
*/
private static void appendResult(Result result, OutputStream interpretedFileWriter, OutputStream verbatimFileWriter,
OutputStream multimediaFileWriter) throws IOException {
DownloadFileUtils.appendAndDelete(result.getDownloadFileWork().getJobDataFileName()
+ TableSuffixes.INTERPRETED_SUFFIX, interpretedFileWriter);
DownloadFileUtils.appendAndDelete(result.getDownloadFileWork().getJobDataFileName() + TableSuffixes.VERBATIM_SUFFIX,
verbatimFileWriter);
DownloadFileUtils.appendAndDelete(result.getDownloadFileWork().getJobDataFileName()
+ TableSuffixes.MULTIMEDIA_SUFFIX, multimediaFileWriter);
}
public DwcaDownloadAggregator(DownloadJobConfiguration configuration,
OccurrenceDownloadService occurrenceDownloadService) {
this.occurrenceDownloadService = occurrenceDownloadService;
this.configuration = configuration;
}
public void init() {
createFile(configuration.getInterpretedDataFileName());
createFile(configuration.getVerbatimDataFileName());
createFile(configuration.getMultimediaDataFileName());
}
/**
* Collects the results of each job.
* Iterates over the list of futures to collect individual results.
*/
@Override
public void aggregate(List<Result> results) {
init();
try (
FileOutputStream interpretedFileWriter = new FileOutputStream(configuration.getInterpretedDataFileName(), true);
FileOutputStream verbatimFileWriter = new FileOutputStream(configuration.getVerbatimDataFileName(), true);
FileOutputStream multimediaFileWriter = new FileOutputStream(configuration.getMultimediaDataFileName(), true)) {
HeadersFileUtil.appendInterpretedHeaders(interpretedFileWriter);
HeadersFileUtil.appendVerbatimHeaders(verbatimFileWriter);
HeadersFileUtil.appendMultimediaHeaders(multimediaFileWriter);
if (!results.isEmpty()) {
// Results are sorted to respect the original ordering
Collections.sort(results);
DatasetUsagesCollector datasetUsagesCollector = new DatasetUsagesCollector();
for (Result result : results) {
datasetUsagesCollector.sumUsages(result.getDatasetUsages());
appendResult(result, interpretedFileWriter, verbatimFileWriter, multimediaFileWriter);
}
CitationsFileWriter.createCitationFile(datasetUsagesCollector.getDatasetUsages(),
configuration.getCitationDataFileName(),
occurrenceDownloadService,
configuration.getDownloadKey());
}
//Creates the DwcA zip file
DwcaArchiveBuilder.buildArchive(configuration);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
| UTF-8 | Java | 5,141 | java | DwcaDownloadAggregator.java | Java | []
| null | []
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gbif.occurrence.download.file.dwca;
import org.gbif.api.service.registry.OccurrenceDownloadService;
import org.gbif.occurrence.download.file.DownloadAggregator;
import org.gbif.occurrence.download.file.DownloadJobConfiguration;
import org.gbif.occurrence.download.file.Result;
import org.gbif.occurrence.download.file.common.DatasetUsagesCollector;
import org.gbif.occurrence.download.file.common.DownloadFileUtils;
import org.gbif.occurrence.download.util.HeadersFileUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Throwables;
/**
* Aggregates partials results of files and combine then into the output zip file.
*/
public class DwcaDownloadAggregator implements DownloadAggregator {
private static final Logger LOG = LoggerFactory.getLogger(DwcaDownloadAggregator.class);
// Service that persist dataset usage information
private final OccurrenceDownloadService occurrenceDownloadService;
private final DownloadJobConfiguration configuration;
/**
* Utility method that creates a file, if the files exists it is deleted.
*/
private static void createFile(String outFile) {
try {
File file = new File(outFile);
if (file.exists()) {
file.delete();
}
file.createNewFile();
} catch (IOException e) {
LOG.error("Error creating file", e);
throw Throwables.propagate(e);
}
}
/**
* Appends the result files to the output file.
*/
private static void appendResult(Result result, OutputStream interpretedFileWriter, OutputStream verbatimFileWriter,
OutputStream multimediaFileWriter) throws IOException {
DownloadFileUtils.appendAndDelete(result.getDownloadFileWork().getJobDataFileName()
+ TableSuffixes.INTERPRETED_SUFFIX, interpretedFileWriter);
DownloadFileUtils.appendAndDelete(result.getDownloadFileWork().getJobDataFileName() + TableSuffixes.VERBATIM_SUFFIX,
verbatimFileWriter);
DownloadFileUtils.appendAndDelete(result.getDownloadFileWork().getJobDataFileName()
+ TableSuffixes.MULTIMEDIA_SUFFIX, multimediaFileWriter);
}
public DwcaDownloadAggregator(DownloadJobConfiguration configuration,
OccurrenceDownloadService occurrenceDownloadService) {
this.occurrenceDownloadService = occurrenceDownloadService;
this.configuration = configuration;
}
public void init() {
createFile(configuration.getInterpretedDataFileName());
createFile(configuration.getVerbatimDataFileName());
createFile(configuration.getMultimediaDataFileName());
}
/**
* Collects the results of each job.
* Iterates over the list of futures to collect individual results.
*/
@Override
public void aggregate(List<Result> results) {
init();
try (
FileOutputStream interpretedFileWriter = new FileOutputStream(configuration.getInterpretedDataFileName(), true);
FileOutputStream verbatimFileWriter = new FileOutputStream(configuration.getVerbatimDataFileName(), true);
FileOutputStream multimediaFileWriter = new FileOutputStream(configuration.getMultimediaDataFileName(), true)) {
HeadersFileUtil.appendInterpretedHeaders(interpretedFileWriter);
HeadersFileUtil.appendVerbatimHeaders(verbatimFileWriter);
HeadersFileUtil.appendMultimediaHeaders(multimediaFileWriter);
if (!results.isEmpty()) {
// Results are sorted to respect the original ordering
Collections.sort(results);
DatasetUsagesCollector datasetUsagesCollector = new DatasetUsagesCollector();
for (Result result : results) {
datasetUsagesCollector.sumUsages(result.getDatasetUsages());
appendResult(result, interpretedFileWriter, verbatimFileWriter, multimediaFileWriter);
}
CitationsFileWriter.createCitationFile(datasetUsagesCollector.getDatasetUsages(),
configuration.getCitationDataFileName(),
occurrenceDownloadService,
configuration.getDownloadKey());
}
//Creates the DwcA zip file
DwcaArchiveBuilder.buildArchive(configuration);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
| 5,141 | 0.722233 | 0.721066 | 126 | 39.801586 | 33.939026 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.547619 | false | false | 5 |
6d43f462cd8224e34d54fc3f566f4ec1a84b6358 | 17,111,149,718,760 | 59230541861812443ea8c2940dc7aae0304367ef | /src/main/java/com/iancaffey/jcc/io/WriterStrategy.java | 03190ae52daa43954295451bb8cd6e7f36c49d89 | [
"MIT"
]
| permissive | iitc/jcc | https://github.com/iitc/jcc | 392132b865fd73dc0af7264fc632d2aceabc6c50 | e3ec367260a1b8c483e6918446678ecbac25b894 | refs/heads/master | 2018-02-18T22:36:30.505000 | 2017-01-08T19:37:38 | 2017-01-08T19:37:38 | 55,537,924 | 7 | 1 | null | false | 2016-05-12T03:33:48 | 2016-04-05T19:09:44 | 2016-05-04T20:01:38 | 2016-05-12T03:33:48 | 100 | 4 | 1 | 1 | Java | null | null | package com.iancaffey.jcc.io;
/**
* WriterStrategy
*
* @author Ian Caffey
* @since 1.0
*/
public enum WriterStrategy {
SINGLE_QUOTED_STRING,
DOUBLE_QUOTED_STRING
}
| UTF-8 | Java | 178 | java | WriterStrategy.java | Java | [
{
"context": "affey.jcc.io;\n\n/**\n * WriterStrategy\n *\n * @author Ian Caffey\n * @since 1.0\n */\npublic enum WriterStrategy {\n ",
"end": 77,
"score": 0.9998599886894226,
"start": 67,
"tag": "NAME",
"value": "Ian Caffey"
}
]
| null | []
| package com.iancaffey.jcc.io;
/**
* WriterStrategy
*
* @author <NAME>
* @since 1.0
*/
public enum WriterStrategy {
SINGLE_QUOTED_STRING,
DOUBLE_QUOTED_STRING
}
| 174 | 0.674157 | 0.662921 | 12 | 13.833333 | 10.998737 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 5 |
954d99ef84b1349a6dc0b1aa22af3691ea0ffd5c | 5,394,478,936,087 | e8ffba684a1c9edd7029e2d70b111bd305f2f4d7 | /src/main/java/ru.iaulitin.transactions/tx_required/batch1/demo2/package-info.java | e33cd05109f5ab6b374a763c71fb05c017550f89 | []
| no_license | Mobilnik/game-of-transactions | https://github.com/Mobilnik/game-of-transactions | b475321c8bbb12457bcc0d2130537cd79bc72453 | 5247363e28a622220675bb6976790c50605b8435 | refs/heads/master | 2020-08-05T23:49:08.350000 | 2019-10-08T09:17:36 | 2019-10-08T09:17:36 | 212,760,794 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.iaulitin.transactions.tx_required.batch1.demo2;
/**
* Demo 2:
* <p>
* 1. No exceptions inserted by a developer to be thrown.
* <p>
* 2. a. UserController#demo is marked as @Transactional
* <p>
* <p>
* Result:
* <p>
* Log:
* r.i.t.t.b.demo2.rest.Controller_req_1_2 : TX ID: 1766be27
* r.i.t.t.b.demo2.service.Service_req_1_2 : TX ID: 1766be27
* r.i.t.t.b.demo2.dao.UserDao_req_1_2 : TX ID: 1766be27
* r.i.t.t.b.demo2.dao.UserDao_req_1_2 : Updated user: User(id=2, name=BORIS, balance=900)
* r.i.t.t.b.demo2.dao.UserDao_req_1_2 : TX ID: 1766be27
* r.i.t.t.b.demo2.dao.UserDao_req_1_2 : Updated user: User(id=1, name=ANTON, balance=600)
* r.i.t.t.b.d.d.TransferHistoryDao_req_1_2 : TX ID: 1766be27
* r.i.t.t.b.d.d.TransferHistoryDao_req_1_2 : Created transfer history: TransferHistory(senderId=2, receiverId=1, amount=100)
* <p>
* Database:
* 	Users:(1,600,ANTON), (2,900,BORIS)
* 	TransferHistory: (2,1,100)
* <p>
* Conclusion:
* Everything executed in a single TX. Logs and DB state correlate.
* <p>
* <p>
* <p>
*
* II. And now we add an exception
* Result:
* Log:
* r.i.t.t.b.w.d.rest.Controller_req_1_3 : No TX provided
* r.i.t.t.b.w.d.service.Service_req_1_3 : TX ID: 493aefd8
* r.i.t.t.b.w.demo3.dao.UserDao_req_1_3 : TX ID: 493aefd8
* r.i.t.t.b.w.demo3.dao.UserDao_req_1_3 : Updated user: User(id=2, name=BORIS, balance=900)
* r.i.t.t.b.w.demo3.dao.UserDao_req_1_3 : TX ID: 493aefd8
* r.i.t.t.b.w.demo3.dao.UserDao_req_1_3 : Updated user: User(id=1, name=ANTON, balance=600)
* <p>
*
* Exception:
* java.lang.RuntimeException: Exception between user update and history create
*
* <p>
* Database:
* 	Users:(1,500,ANTON), (2,1000,BORIS)
* 	TransferHistory: %empty%
* <p>
*
* Conclusion:
* The transaction is consistent
*/ | UTF-8 | Java | 1,838 | java | package-info.java | Java | [
{
"context": "rDao_req_1_2 : Updated user: User(id=2, name=BORIS, balance=900)\n * r.i.t.t.b.demo2.dao.UserDao_req_",
"end": 511,
"score": 0.9132518768310547,
"start": 506,
"tag": "NAME",
"value": "BORIS"
},
{
"context": "rDao_req_1_2 : Updated user: User(id=1, name=ANTON, balance=600)\n * r.i.t.t.b.d.d.TransferHistoryDao",
"end": 669,
"score": 0.9463863372802734,
"start": 664,
"tag": "NAME",
"value": "ANTON"
},
{
"context": "serDao_req_1_3 : Updated user: User(id=2, name=BORIS, balance=900)\n * r.i.t.t.b.w.demo3.dao.UserDao_re",
"end": 1402,
"score": 0.5951324105262756,
"start": 1397,
"tag": "USERNAME",
"value": "BORIS"
},
{
"context": "serDao_req_1_3 : Updated user: User(id=1, name=ANTON, balance=600)\n * <p>\n *\n * Exception:\n * java.lan",
"end": 1560,
"score": 0.7752155661582947,
"start": 1555,
"tag": "NAME",
"value": "ANTON"
},
{
"context": "create\n *\n * <p>\n * Database:\n * 	Users:(1,500,ANTON), (2,1000,BORIS)\n * 	TransferHistory: %empty",
"end": 1725,
"score": 0.623340904712677,
"start": 1722,
"tag": "USERNAME",
"value": "ANT"
},
{
"context": "ate\n *\n * <p>\n * Database:\n * 	Users:(1,500,ANTON), (2,1000,BORIS)\n * 	TransferHistory: %empty%\n",
"end": 1727,
"score": 0.5247902274131775,
"start": 1725,
"tag": "NAME",
"value": "ON"
}
]
| null | []
| package ru.iaulitin.transactions.tx_required.batch1.demo2;
/**
* Demo 2:
* <p>
* 1. No exceptions inserted by a developer to be thrown.
* <p>
* 2. a. UserController#demo is marked as @Transactional
* <p>
* <p>
* Result:
* <p>
* Log:
* r.i.t.t.b.demo2.rest.Controller_req_1_2 : TX ID: 1766be27
* r.i.t.t.b.demo2.service.Service_req_1_2 : TX ID: 1766be27
* r.i.t.t.b.demo2.dao.UserDao_req_1_2 : TX ID: 1766be27
* r.i.t.t.b.demo2.dao.UserDao_req_1_2 : Updated user: User(id=2, name=BORIS, balance=900)
* r.i.t.t.b.demo2.dao.UserDao_req_1_2 : TX ID: 1766be27
* r.i.t.t.b.demo2.dao.UserDao_req_1_2 : Updated user: User(id=1, name=ANTON, balance=600)
* r.i.t.t.b.d.d.TransferHistoryDao_req_1_2 : TX ID: 1766be27
* r.i.t.t.b.d.d.TransferHistoryDao_req_1_2 : Created transfer history: TransferHistory(senderId=2, receiverId=1, amount=100)
* <p>
* Database:
* 	Users:(1,600,ANTON), (2,900,BORIS)
* 	TransferHistory: (2,1,100)
* <p>
* Conclusion:
* Everything executed in a single TX. Logs and DB state correlate.
* <p>
* <p>
* <p>
*
* II. And now we add an exception
* Result:
* Log:
* r.i.t.t.b.w.d.rest.Controller_req_1_3 : No TX provided
* r.i.t.t.b.w.d.service.Service_req_1_3 : TX ID: 493aefd8
* r.i.t.t.b.w.demo3.dao.UserDao_req_1_3 : TX ID: 493aefd8
* r.i.t.t.b.w.demo3.dao.UserDao_req_1_3 : Updated user: User(id=2, name=BORIS, balance=900)
* r.i.t.t.b.w.demo3.dao.UserDao_req_1_3 : TX ID: 493aefd8
* r.i.t.t.b.w.demo3.dao.UserDao_req_1_3 : Updated user: User(id=1, name=ANTON, balance=600)
* <p>
*
* Exception:
* java.lang.RuntimeException: Exception between user update and history create
*
* <p>
* Database:
* 	Users:(1,500,ANTON), (2,1000,BORIS)
* 	TransferHistory: %empty%
* <p>
*
* Conclusion:
* The transaction is consistent
*/ | 1,838 | 0.63765 | 0.565832 | 55 | 32.436363 | 32.22916 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490909 | false | false | 5 |
26eeb06e95a73c1608ba9524e320f3636d508ccf | 20,804,821,596,575 | f8a14fec331ec56dd7e070fc032604117f155085 | /gameserver/src/main/java/ru/l2/gameserver/taskmanager/AiTaskManager.java | fb5022c184206a03ba84543fb0559cf5e5183a6a | []
| no_license | OFRF/BladeRush | https://github.com/OFRF/BladeRush | c2f06d050a1f2d79a9b50567b9f1152d6d755149 | 87329d131c0fcc8417ed15479298fdb90bc8f1d2 | refs/heads/master | 2023-03-25T13:51:04.404000 | 2020-05-04T14:37:23 | 2020-05-04T14:37:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.l2.gameserver.taskmanager;
import ru.l2.commons.threading.RunnableImpl;
import ru.l2.commons.threading.SteppingRunnableQueueManager;
import ru.l2.commons.util.Rnd;
import ru.l2.gameserver.Config;
import ru.l2.gameserver.ThreadPoolManager;
public class AiTaskManager extends SteppingRunnableQueueManager {
private static final long TICK = 250L;
private static final AiTaskManager[] _instances = new AiTaskManager[Config.AI_TASK_MANAGER_COUNT];
private static int randomizer;
static {
for (int i = 0; i < _instances.length; ++i) {
_instances[i] = new AiTaskManager();
}
}
private AiTaskManager() {
super(TICK);
ThreadPoolManager.getInstance().scheduleAtFixedRate(this, Rnd.get(TICK), TICK);
ThreadPoolManager.getInstance().scheduleAtFixedRate(new RunnableImpl() {
@Override
public void runImpl() {
purge();
}
}, 60000L, 60000L);
}
public static AiTaskManager getInstance() {
return _instances[randomizer++ & _instances.length - 1];
}
public CharSequence getStats(final int num) {
return _instances[num].getStats();
}
}
| UTF-8 | Java | 1,206 | java | AiTaskManager.java | Java | []
| null | []
| package ru.l2.gameserver.taskmanager;
import ru.l2.commons.threading.RunnableImpl;
import ru.l2.commons.threading.SteppingRunnableQueueManager;
import ru.l2.commons.util.Rnd;
import ru.l2.gameserver.Config;
import ru.l2.gameserver.ThreadPoolManager;
public class AiTaskManager extends SteppingRunnableQueueManager {
private static final long TICK = 250L;
private static final AiTaskManager[] _instances = new AiTaskManager[Config.AI_TASK_MANAGER_COUNT];
private static int randomizer;
static {
for (int i = 0; i < _instances.length; ++i) {
_instances[i] = new AiTaskManager();
}
}
private AiTaskManager() {
super(TICK);
ThreadPoolManager.getInstance().scheduleAtFixedRate(this, Rnd.get(TICK), TICK);
ThreadPoolManager.getInstance().scheduleAtFixedRate(new RunnableImpl() {
@Override
public void runImpl() {
purge();
}
}, 60000L, 60000L);
}
public static AiTaskManager getInstance() {
return _instances[randomizer++ & _instances.length - 1];
}
public CharSequence getStats(final int num) {
return _instances[num].getStats();
}
}
| 1,206 | 0.664179 | 0.646766 | 38 | 30.736841 | 26.376509 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 5 |
0f4a80626e4e21c41852e70aba0718406605ae64 | 25,804,163,528,792 | 54ab6c6172eb0137788cf3963ec98d1e41948527 | /hr-base/hr-soap-service/src/main/java/com/studerb/hr/ws/TimeServiceImp.java | be009d713cd7512579c3f01d5e62847d2de310af | []
| no_license | duchien85/springapps | https://github.com/duchien85/springapps | 471cb6bba09345f82d19e084d922a3b4b06da108 | 0b99b465710a661b644c2475c22cd53409914756 | refs/heads/master | 2016-09-06T00:56:38.045000 | 2011-01-14T07:24:53 | 2011-01-14T07:24:53 | 37,699,235 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.studerb.hr.ws;
import java.util.Date;
import javax.jws.WebService;
@WebService(endpointInterface = "com.studerb.hr.ws.TimerService")
public class TimeServiceImp implements TimerService {
@Override
public Long getTimeAsElapsed() {
return new Date().getTime();
}
@Override
public String getTimeAsString() {
Date d = new Date();
return d.toString();
}
}
| UTF-8 | Java | 417 | java | TimeServiceImp.java | Java | []
| null | []
| package com.studerb.hr.ws;
import java.util.Date;
import javax.jws.WebService;
@WebService(endpointInterface = "com.studerb.hr.ws.TimerService")
public class TimeServiceImp implements TimerService {
@Override
public Long getTimeAsElapsed() {
return new Date().getTime();
}
@Override
public String getTimeAsString() {
Date d = new Date();
return d.toString();
}
}
| 417 | 0.669065 | 0.669065 | 21 | 18.857143 | 18.808018 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 5 |
ce7113ef8418b638f41dc18f9db76963e14cdd33 | 29,987,461,678,612 | 3c96c66ea03dac354cacc1bd860f73394846fc17 | /src/main/java/domain/user/sales_representative/SalesRepresentative.java | 19be3089d1e1d86be9ae54ddb960492ec42621c4 | []
| no_license | Dyrhoi/dat2sem-fog | https://github.com/Dyrhoi/dat2sem-fog | 7cf7e079f253208e3f1f1659edbb4c1bcd8a203b | 20c2e745c9a10239a30c9ebc859a31570abc2657 | refs/heads/master | 2023-02-09T03:34:38.448000 | 2021-01-05T21:20:41 | 2021-01-05T21:20:41 | 315,322,682 | 0 | 0 | null | false | 2021-01-05T21:20:42 | 2020-11-23T13:23:17 | 2021-01-05T20:40:15 | 2021-01-05T21:20:42 | 18,658 | 0 | 0 | 0 | Java | false | false | package domain.user.sales_representative;
import domain.user.User;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
public class SalesRepresentative extends User {
private static final int PASSWORD_ITTERATIONS = 65536;
private static final int PASSWORD_LENGTH = 256; //32 bytes
private static final SecretKeyFactory PASSWORD_FACTORY;
static {
SecretKeyFactory factory = null;
try {
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
} catch (NoSuchAlgorithmException e){
e.printStackTrace();
}
PASSWORD_FACTORY = factory;
}
public static byte[] generateSalt(){
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return salt;
}
public static byte[] calculateSecret(byte[] salt, String password){
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt,
PASSWORD_ITTERATIONS,
PASSWORD_LENGTH);
try {
return PASSWORD_FACTORY.generateSecret(spec).getEncoded();
} catch (InvalidKeySpecException e){
throw new RuntimeException(e);
}
}
public static int getPasswordItterations() {
return PASSWORD_ITTERATIONS;
}
public static int getPasswordLength() {
return PASSWORD_LENGTH;
}
public static SecretKeyFactory getPasswordFactory() {
return PASSWORD_FACTORY;
}
private final byte[] salt;
private final byte[] secret;
public SalesRepresentative(int id, String firstname, String lastname, String email, String phone, Address address, byte[] salt, byte[] secret) {
super(id, firstname, lastname, email, phone, address, Type.SALES_REPRESENTATIVE);
this.salt = salt;
this.secret = secret;
}
public boolean isPasswordCorrect(String password) {
return Arrays.equals(this.secret, calculateSecret(salt, password));
}
public byte[] getSalt() {
return salt;
}
public byte[] getSecret() {
return secret;
}
} | UTF-8 | Java | 2,333 | java | SalesRepresentative.java | Java | []
| null | []
| package domain.user.sales_representative;
import domain.user.User;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
public class SalesRepresentative extends User {
private static final int PASSWORD_ITTERATIONS = 65536;
private static final int PASSWORD_LENGTH = 256; //32 bytes
private static final SecretKeyFactory PASSWORD_FACTORY;
static {
SecretKeyFactory factory = null;
try {
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
} catch (NoSuchAlgorithmException e){
e.printStackTrace();
}
PASSWORD_FACTORY = factory;
}
public static byte[] generateSalt(){
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return salt;
}
public static byte[] calculateSecret(byte[] salt, String password){
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt,
PASSWORD_ITTERATIONS,
PASSWORD_LENGTH);
try {
return PASSWORD_FACTORY.generateSecret(spec).getEncoded();
} catch (InvalidKeySpecException e){
throw new RuntimeException(e);
}
}
public static int getPasswordItterations() {
return PASSWORD_ITTERATIONS;
}
public static int getPasswordLength() {
return PASSWORD_LENGTH;
}
public static SecretKeyFactory getPasswordFactory() {
return PASSWORD_FACTORY;
}
private final byte[] salt;
private final byte[] secret;
public SalesRepresentative(int id, String firstname, String lastname, String email, String phone, Address address, byte[] salt, byte[] secret) {
super(id, firstname, lastname, email, phone, address, Type.SALES_REPRESENTATIVE);
this.salt = salt;
this.secret = secret;
}
public boolean isPasswordCorrect(String password) {
return Arrays.equals(this.secret, calculateSecret(salt, password));
}
public byte[] getSalt() {
return salt;
}
public byte[] getSecret() {
return secret;
}
} | 2,333 | 0.665667 | 0.659666 | 79 | 28.544304 | 26.496618 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.670886 | false | false | 5 |
5eb01bf16396e6e5ec18d67c41489322c191acb6 | 3,848,290,722,426 | 0e83b482e2532685e7df64ad65ed5e6f326d3102 | /SeleniumTest1/src/testSuites/CpbNew.java | 52c407cc7925e814fb94cd56e36e953b74c952fa | []
| no_license | monkeygithub1/wjhWork | https://github.com/monkeygithub1/wjhWork | beb12d1c8aaedf55f4a5207a05a36f025f86ee41 | 89f50475941f92479621082b6f2cc7aaf13fca01 | refs/heads/master | 2020-03-30T06:06:37.769000 | 2019-03-26T08:49:11 | 2019-03-26T08:49:11 | 150,839,789 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package testSuites;
import org.testng.annotations.Test;
import framework.BrowserEngine;
import pageObjects.PMIS_Page;
import pageObjects.PMIS_YiFangHeTong_Page;
import org.testng.annotations.BeforeClass;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterClass;
/*
* 乙方合同
* 书面
* 普通部门(创新业务部)
* 工程建设
* 一次性通过
*/
public class CpbNew {
WebDriver driver;
String username = "13910623294";
String username_fawu = "18602634891";//法务
String username_sc = "18602270056";
String username_dept = "13752506056";//创新业务部
String username_sybzjl = "13612194369";
String username_sybdsz = "15522219091";
String passwd = "qw";
String cpb_name = "自动化乙方合同1";
String cpb_money = "1000";
String cpb_dept = "创新业务部";
String cpb_time = "1";
String cpb_xingzhi = "书面";
String cpb_type = "工程建设";
String cpb_jia = "国网";
String cpb_yi = "天津市万贸科技有限公司";
String proj_name="甲方合同专用项目1";
String cpb_descript = "备注非必填";
String cpb_moneyIn_bili = "10:0";
String cpb_moneyIn_date1 = "2018-02-01";
String cpb_invoiceOut_bili = "10:0";
String cpb_invoiceOut_date1 = "2018-03-01";
@BeforeClass
public void setUp() throws IOException {
BrowserEngine browserEngine = new BrowserEngine();
browserEngine.initConfigData();
driver = browserEngine.getBrowser();
}
@Test
public void applyNewcpb() throws InterruptedException {
PMIS_Page pmis = PageFactory.initElements(driver, PMIS_Page.class);
PMIS_YiFangHeTong_Page pmis_cpb = PageFactory.initElements(driver, PMIS_YiFangHeTong_Page.class);
Thread.sleep(1000);
pmis.login(username, passwd);
Thread.sleep(1000);
pmis_cpb.applyNewCpb(cpb_name, cpb_money, cpb_dept, cpb_time, cpb_xingzhi, cpb_type, cpb_jia, cpb_yi, proj_name, cpb_descript,
cpb_moneyIn_bili, cpb_moneyIn_date1, cpb_invoiceOut_bili, cpb_invoiceOut_date1);
}
//@Test(priority=1)//法务审批
// public void shenpi_fawu() throws InterruptedException{
// PMIS_Page pmis = PageFactory.initElements(driver, PMIS_Page.class);
// pmis.loginSwitch(username_fawu, passwd);
// PMIS_JiaFangHeTong_Page pmis_cpb = PageFactory.initElements(driver, PMIS_JiaFangHeTong_Page.class);
// pmis_cpb.cpbSpAgree("OK");
// }
@AfterClass
public void afterClass() {
}
} | GB18030 | Java | 2,464 | java | CpbNew.java | Java | [
{
"context": "s CpbNew {\n\tWebDriver driver;\n\tString username = \"13910623294\";\n\tString username_fawu = \"18602634891\";//法务\n\tStr",
"end": 490,
"score": 0.9012166857719421,
"start": 479,
"tag": "USERNAME",
"value": "13910623294"
},
{
"context": "String username = \"13910623294\";\n\tString username_fawu = \"18602634891\";//法务\n\tString username_sc = \"18602",
"end": 514,
"score": 0.8991709351539612,
"start": 510,
"tag": "USERNAME",
"value": "fawu"
},
{
"context": "sername = \"13910623294\";\n\tString username_fawu = \"18602634891\";//法务\n\tString username_sc = \"18602270056\";\n\tStrin",
"end": 529,
"score": 0.8587122559547424,
"start": 518,
"tag": "USERNAME",
"value": "18602634891"
},
{
"context": "fawu = \"18602634891\";//法务\n\tString username_sc = \"18602270056\";\n\tString username_dept = \"13752506056\";",
"end": 561,
"score": 0.550020158290863,
"start": 560,
"tag": "USERNAME",
"value": "8"
},
{
"context": "ame_dept = \"13752506056\";//创新业务部\n\tString username_sybzjl = \"13612194369\";\n\tString username_sybdsz = \"15522",
"end": 642,
"score": 0.9320003986358643,
"start": 636,
"tag": "USERNAME",
"value": "sybzjl"
},
{
"context": "username_sybzjl = \"13612194369\";\n\tString username_sybdsz = \"15522219091\";\n\tString passwd = \"qw\";\n\tString c",
"end": 683,
"score": 0.9042357802391052,
"start": 677,
"tag": "USERNAME",
"value": "sybdsz"
},
{
"context": "ybzjl = \"13612194369\";\n\tString username_sybdsz = \"15522219091\";\n\tString passwd = \"qw\";\n\tString cpb_name = \"自动化乙",
"end": 698,
"score": 0.7242456078529358,
"start": 687,
"tag": "PASSWORD",
"value": "15522219091"
},
{
"context": "sername_sybdsz = \"15522219091\";\n\tString passwd = \"qw\";\n\tString cpb_name = \"自动化乙方合同1\";\n\tString cpb_mone",
"end": 721,
"score": 0.999218225479126,
"start": 719,
"tag": "PASSWORD",
"value": "qw"
},
{
"context": ", PMIS_Page.class);\n//\t\tpmis.loginSwitch(username_fawu, passwd);\n//\t\tPMIS_JiaFangHeTong_Page pmis_cpb = ",
"end": 2101,
"score": 0.9970709681510925,
"start": 2097,
"tag": "USERNAME",
"value": "fawu"
}
]
| null | []
| package testSuites;
import org.testng.annotations.Test;
import framework.BrowserEngine;
import pageObjects.PMIS_Page;
import pageObjects.PMIS_YiFangHeTong_Page;
import org.testng.annotations.BeforeClass;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterClass;
/*
* 乙方合同
* 书面
* 普通部门(创新业务部)
* 工程建设
* 一次性通过
*/
public class CpbNew {
WebDriver driver;
String username = "13910623294";
String username_fawu = "18602634891";//法务
String username_sc = "18602270056";
String username_dept = "13752506056";//创新业务部
String username_sybzjl = "13612194369";
String username_sybdsz = "<PASSWORD>";
String passwd = "qw";
String cpb_name = "自动化乙方合同1";
String cpb_money = "1000";
String cpb_dept = "创新业务部";
String cpb_time = "1";
String cpb_xingzhi = "书面";
String cpb_type = "工程建设";
String cpb_jia = "国网";
String cpb_yi = "天津市万贸科技有限公司";
String proj_name="甲方合同专用项目1";
String cpb_descript = "备注非必填";
String cpb_moneyIn_bili = "10:0";
String cpb_moneyIn_date1 = "2018-02-01";
String cpb_invoiceOut_bili = "10:0";
String cpb_invoiceOut_date1 = "2018-03-01";
@BeforeClass
public void setUp() throws IOException {
BrowserEngine browserEngine = new BrowserEngine();
browserEngine.initConfigData();
driver = browserEngine.getBrowser();
}
@Test
public void applyNewcpb() throws InterruptedException {
PMIS_Page pmis = PageFactory.initElements(driver, PMIS_Page.class);
PMIS_YiFangHeTong_Page pmis_cpb = PageFactory.initElements(driver, PMIS_YiFangHeTong_Page.class);
Thread.sleep(1000);
pmis.login(username, passwd);
Thread.sleep(1000);
pmis_cpb.applyNewCpb(cpb_name, cpb_money, cpb_dept, cpb_time, cpb_xingzhi, cpb_type, cpb_jia, cpb_yi, proj_name, cpb_descript,
cpb_moneyIn_bili, cpb_moneyIn_date1, cpb_invoiceOut_bili, cpb_invoiceOut_date1);
}
//@Test(priority=1)//法务审批
// public void shenpi_fawu() throws InterruptedException{
// PMIS_Page pmis = PageFactory.initElements(driver, PMIS_Page.class);
// pmis.loginSwitch(username_fawu, passwd);
// PMIS_JiaFangHeTong_Page pmis_cpb = PageFactory.initElements(driver, PMIS_JiaFangHeTong_Page.class);
// pmis_cpb.cpbSpAgree("OK");
// }
@AfterClass
public void afterClass() {
}
} | 2,463 | 0.726325 | 0.679409 | 77 | 28.90909 | 25.09058 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.714286 | false | false | 5 |
70fd033fb26107854fbcb1a7e1ef5d1846392758 | 31,233,002,197,525 | b4bd222493afe3f2b3a6c77323083ec5762eb3dc | /app/src/test/java/com/example/szachy/WiezaTest.java | 545ae38ddf1525937735acd59d45791d91082fa7 | []
| no_license | Michal314-p/Android_szachy | https://github.com/Michal314-p/Android_szachy | b4b94a1c7e123e3aa28218192aa94ba25c30c141 | 92da6a88f029909e3906529a1924f07a1c780fb6 | refs/heads/main | 2023-03-27T14:06:23.756000 | 2021-03-28T14:06:57 | 2021-03-28T14:06:57 | 351,450,416 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.szachy;
import com.example.szachy.Figury.Wieza;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public class WiezaTest
{
private String[][] szachownica_testowa = {{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","wc","xx","wb","xx","xx","xx"}};
private int xp=7;
private int yp=4;
private int xk=7;
private int yk=7;
private String gracz="b";
private String przeciwnik="c";
@Test
public void sprawdz_wieze()
{
String [][] kopia;
kopia=kopiuj(szachownica_testowa);
kopia[7][4]="xx";
Wieza wieza = new Wieza();
System.out.println(wieza.sprawdz_ruch_wiezy(szachownica_testowa,xp,yp,xk,yk,gracz,przeciwnik));
for(int i=0;i<szachownica_testowa.length;i++)
{
for(int j=0;j<szachownica_testowa.length;j++)
{
System.out.print(szachownica_testowa[i][j]);
}
System.out.println();
}
}
public String[][] kopiuj(String[][] szachownica)
{
String [][] kopia = new String[8][8];
for(int i=0;i<szachownica.length;i++)
{
for(int j=0;j<szachownica.length;j++)
{
kopia[i][j]=szachownica[i][j];
}
}
return kopia;
}
}
| UTF-8 | Java | 1,693 | java | WiezaTest.java | Java | []
| null | []
| package com.example.szachy;
import com.example.szachy.Figury.Wieza;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public class WiezaTest
{
private String[][] szachownica_testowa = {{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","xx","xx","xx","xx","xx","xx"},
{"xx","xx","wc","xx","wb","xx","xx","xx"}};
private int xp=7;
private int yp=4;
private int xk=7;
private int yk=7;
private String gracz="b";
private String przeciwnik="c";
@Test
public void sprawdz_wieze()
{
String [][] kopia;
kopia=kopiuj(szachownica_testowa);
kopia[7][4]="xx";
Wieza wieza = new Wieza();
System.out.println(wieza.sprawdz_ruch_wiezy(szachownica_testowa,xp,yp,xk,yk,gracz,przeciwnik));
for(int i=0;i<szachownica_testowa.length;i++)
{
for(int j=0;j<szachownica_testowa.length;j++)
{
System.out.print(szachownica_testowa[i][j]);
}
System.out.println();
}
}
public String[][] kopiuj(String[][] szachownica)
{
String [][] kopia = new String[8][8];
for(int i=0;i<szachownica.length;i++)
{
for(int j=0;j<szachownica.length;j++)
{
kopia[i][j]=szachownica[i][j];
}
}
return kopia;
}
}
| 1,693 | 0.494389 | 0.487301 | 60 | 27.216667 | 23.361002 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.65 | false | false | 5 |
4861efe9fbdf1dc60fabd911099c881803e53d33 | 26,233,660,269,015 | 12d954bcb8c678c420bca4962501a2207b9bf178 | /app/src/main/java/zsj/com/oyk255/example/ouyiku/v1/NineDetailActivity.java | 4eb752281eecb12ceea394d983179cc69367978d | []
| no_license | zsj6102/oyk2.5.5 | https://github.com/zsj6102/oyk2.5.5 | be7b2e1011cca9162e049781022f49452083119b | 3128758331ee26c851fd24e67d1054d8ca826734 | refs/heads/master | 2021-01-23T11:21:10.203000 | 2017-06-08T10:07:54 | 2017-06-08T10:07:54 | 93,131,888 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package zsj.com.oyk255.example.ouyiku.v1;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.android.volley.VolleyError;
import zsj.com.oyk255.R;
import zsj.com.oyk255.example.ouyiku.detail.popwindow.Share_pop;
import zsj.com.oyk255.example.ouyiku.fragment.DetailGoodsinfoFragment;
import zsj.com.oyk255.example.ouyiku.huodong.HuoDongDetail;
import zsj.com.oyk255.example.ouyiku.huodong.HuoDongDetailData;
import zsj.com.oyk255.example.ouyiku.huodong.MContent;
import zsj.com.oyk255.example.ouyiku.huodong.Status;
import zsj.com.oyk255.example.ouyiku.utils.Constant;
import zsj.com.oyk255.example.ouyiku.utils.PhotoUtil;
import zsj.com.oyk255.example.ouyiku.view.AspectRatioImageView;
import zsj.com.oyk255.example.ouyiku.view.CustomViewPager;
import zsj.com.oyk255.example.ouyiku.view.ViewpageIndicator;
import zsj.com.oyk255.example.ouyiku.view.ZProgressHUD;
import zsj.com.oyk255.suiyuchen.HTTPUtils;
import zsj.com.oyk255.suiyuchen.UILUtils;
import zsj.com.oyk255.suiyuchen.VolleyListener;
import com.google.gson.Gson;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.message.PushAgent;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class NineDetailActivity extends FragmentActivity implements OnClickListener{
private ListView mListView;
private CustomViewPager mLunBoPager;
private ViewpageIndicator viewpageIndicator;
InputMethodManager im;
int[] mImgRes=new int[]{R.mipmap.logo,R.mipmap.logo,R.mipmap.logo,R.mipmap.logo};
private String productId;
private SharedPreferences sp;
private String userid;//用户id
private String token;//用户token
private TextView mTitle;
private TextView mAttr;
private TextView mTime;
private TextView mNewPrice;
private TextView mOldPrice;
private TextView mSku;
private TextView mZhekou;
// ArrayList<String> mLunboData=new ArrayList<String>();//轮播图片
private String zeronine;
ArrayList<MContent> mGraphicData=new ArrayList<MContent>();//图文详情
ArrayList<String> mBannerData=new ArrayList<String>();
private IWXAPI api;
private static final String APP_ID="wx246edc55db723ecb";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nine_detail);
PushAgent.getInstance(this).onAppStart();
im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (savedInstanceState == null) {
overridePendingTransition(R.anim.push_from_right,R.anim.push_to_left);
}
api = WXAPIFactory.createWXAPI(this, APP_ID, false);
api.registerApp(APP_ID);
Intent intent = getIntent();
productId = intent.getStringExtra("productId");
sp = getSharedPreferences("userdata", 0);
userid = sp.getString("userid", "");
token = sp.getString("token", "");
zeronine = intent.getStringExtra("zeronine");
initUI();
initData();
}
private String fproId;
private String isbuy;
private String title;
@Override
protected void onStart() {
sp = getSharedPreferences("userdata", 0);
userid = sp.getString("userid", "");
token = sp.getString("token", "");
super.onStart();
}
private void initData() {
final ZProgressHUD progressHUD = ZProgressHUD.getInstance(this);
progressHUD.setMessage("加载中");
progressHUD.setSpinnerType(ZProgressHUD.SIMPLE_ROUND_SPINNER );
progressHUD.show();
String url= Constant.URL.NineDetailURL;
HashMap<String, String> map=new HashMap<String, String>();
map.put("product_id", productId);
map.put("user_id", userid);
HTTPUtils.post(this, url, map, new VolleyListener() {
@Override
public void onResponse(String arg0) {
Gson gson = new Gson();
progressHUD.dismiss();
HuoDongDetail fromJson = gson.fromJson(arg0, HuoDongDetail.class);
Status status = fromJson.getStatus();
String succeed = status.getSucceed();
if(succeed.equals("1")){
HuoDongDetailData data = fromJson.getData();
List<MContent> mContent = data.getMContent();
mGraphicData.addAll(mContent);
List<String> productImage = data.getProductImage();
mBannerData.addAll(productImage);
title = data.getTitle();
String marketprice = data.getMarketprice();
String currprice = data.getCurrprice();
String stock = data.getStock();
String attr = data.getAttr();
String ltime = data.getLtime();
fproId = data.getFproId();
isbuy = data.getIsbuy();
Log.e("isbuy", isbuy);
mTitle.setText(title);
mAttr.setText(attr);
mNewPrice.setText("¥"+currprice);
mOldPrice.setText("¥"+marketprice);
mSku.setText("库存:"+stock);
recLen = Integer.valueOf(ltime);
timer.schedule(task, 1000, 1000);
float i = Float.parseFloat(marketprice);
float i2 = Float.parseFloat(currprice);
float f=i2/i;
float b = (float)(Math.round(f*100))/100;
float b2=b*10;
mZhekou.setText(b2+"折");
FragmentManager fragmentManager = getSupportFragmentManager();
mLunBoPager.setOnPageChangeListener(new ViewPageChangedListener());
mLunBoPager.setAdapter(new ViewPageAdapter(fragmentManager));
mListView.setAdapter(new GraphicAdaptr());
}
}
@Override
public void onErrorResponse(VolleyError arg0) {
progressHUD.dismiss();
}
});
}
private int recLen ;
Timer timer = new Timer();
private void initUI() {
findViewById(R.id.ninedetail_back).setOnClickListener(this);
View mShare = findViewById(R.id.ninedetail_share);
mShare.setOnClickListener(this);
mListView = (ListView) findViewById(R.id.ninedetaillistview);
TextView mBuy = (TextView) findViewById(R.id.ninedetail_buy);
mBuy.setOnClickListener(this);
View topView = getLayoutInflater().inflate(R.layout.nine_detail_topview, null);
mLunBoPager = (CustomViewPager) topView.findViewById(R.id.detail_lunbo);
viewpageIndicator = (ViewpageIndicator) topView.findViewById(R.id.viewpageIndicator2);
mTitle = (TextView) topView.findViewById(R.id.detai_name);
mAttr = (TextView) topView.findViewById(R.id.detail_attr);
mTime = (TextView) topView.findViewById(R.id.detail_daojishi);
mNewPrice = (TextView) topView.findViewById(R.id.detail_newprice);
mOldPrice = (TextView) topView.findViewById(R.id.detail_oldprice);
mOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
mSku = (TextView) topView.findViewById(R.id.detail_sku);
mZhekou = (TextView) topView.findViewById(R.id.detail_zhekou);
if(zeronine.equals("zero")){
mTime.setVisibility(View.GONE);
mSku.setVisibility(View.GONE);
mZhekou.setVisibility(View.GONE);
mShare.setVisibility(View.INVISIBLE);
}
mListView.addHeaderView(topView);
share_pop = new Share_pop(this);
}
class ViewPageChangedListener implements OnPageChangeListener{
@Override
public void onPageScrolled(int position, float arg1, int arg2) {
position%=mBannerData.size();
viewpageIndicator.move(position, arg1,mBannerData.size());
}
@Override
public void onPageSelected(int arg0) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
}
class ViewPageAdapter extends FragmentPagerAdapter{
public ViewPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
int index= position %mImgRes.length;
if(mBannerData.size()==0){
DetailGoodsinfoFragment bannerItemFragment = new DetailGoodsinfoFragment(index, mImgRes[index]);
return bannerItemFragment;
}else{
String bannerDatum = mBannerData.get(index);
DetailGoodsinfoFragment bannerItemFragment2 = new DetailGoodsinfoFragment(index, bannerDatum);
return bannerItemFragment2;
}
}
@Override
public int getCount() {
//TODO
return mBannerData.size();
}
}
class GraphicAdaptr extends BaseAdapter{
@Override
public int getCount() {
return mGraphicData.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@SuppressLint("ViewHolder")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View layout =null;
ViewHolder holder;
if(convertView==null){
layout=getLayoutInflater().inflate(R.layout.graphic_item, null);
holder=new ViewHolder();
holder.mGraphic_img = (AspectRatioImageView) layout.findViewById(R.id.graphic_img);
layout.setTag(holder);
}else{
layout=convertView;
holder = (ViewHolder) layout.getTag();
}
MContent mContent = mGraphicData.get(position);
String url = mContent.getUrl();
UILUtils.displayImageNoAnim(url, holder.mGraphic_img);
return layout;
}
}
class ViewHolder{
AspectRatioImageView mGraphic_img;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ninedetail_back:
finish();
break;
case R.id.ninedetail_share:
share_pop.showAtLocation(findViewById(R.id.ninedetaillayout), Gravity.CENTER, 0, 0);
share_pop.view.findViewById(R.id.iv_share_wx3).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
api.registerApp(APP_ID);
api.sendReq(createReq(false));
}
});
share_pop.view.findViewById(R.id.iv_share_pyq3).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
api.registerApp(APP_ID);
api.sendReq(createReq(true));
}
});
break;
case R.id.ninedetail_buy:
if(!userid.equals("")){
if(isbuy.equals("0")){
Toast.makeText(NineDetailActivity.this, "已购买过此商品", Toast.LENGTH_SHORT).show();
} else if(isbuy.equals("2")){
Toast.makeText(NineDetailActivity.this, "没有库存了", Toast.LENGTH_SHORT).show();
} else if(isbuy.equals("1")){
Intent intent = new Intent(NineDetailActivity.this, ConfirmOrder9and0Activity.class);
intent.putExtra("productId", productId);
startActivity(intent);
} else if(isbuy.equals("3")){
Toast.makeText(NineDetailActivity.this, "活动未开始", Toast.LENGTH_SHORT).show();
}
else if(isbuy.equals("4")){
Toast.makeText(NineDetailActivity.this, "活动已结束", Toast.LENGTH_SHORT).show();
}
}else{
startActivity(new Intent(this, LoginActivity.class));
}
break;
default:
break;
}
}
//时间戳转换
public String times(long time) {
SimpleDateFormat sdr = new SimpleDateFormat("dd天HH时mm分ss秒");
String times = sdr.format(new Date(time * 1000L));
return times;
}
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() { // UI thread
@Override
public void run() {
recLen--;
String times = times(recLen);
mTime.setText("剩余:"+times);
if(recLen < 0){
timer.cancel();
}
}
});
}
};
private Share_pop share_pop;
public SendMessageToWX.Req createReq(boolean timeLine) {
String ArticleUrl="http://ouyiku.com/jiubuy/view?pid="+productId;
String title2 = title;
WXWebpageObject webpage = new WXWebpageObject();
webpage.webpageUrl = ArticleUrl;
WXMediaMessage msg = new WXMediaMessage(webpage);
// String title = title2;
msg.description = title2;
// msg.title = title;
Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.tubiao3);
msg.thumbData = PhotoUtil.bmpToByteArray(thumb, true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = msg;
// req.scene = SendMessageToWX.Req.WXSceneSession;
req.scene = timeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
return req;
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
@Override
public void finish() {
hideSoftInput();
super.finish();
overridePendingTransition(R.anim.push_from_left, R.anim.push_to_right);
}
protected void hideSoftInput() {
View view = getCurrentFocus();
if(view != null) {
IBinder binder = view.getWindowToken();
if(binder != null) {
im.hideSoftInputFromWindow(binder, 0);
}
}
}
}
| UTF-8 | Java | 13,732 | java | NineDetailActivity.java | Java | []
| null | []
| package zsj.com.oyk255.example.ouyiku.v1;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.android.volley.VolleyError;
import zsj.com.oyk255.R;
import zsj.com.oyk255.example.ouyiku.detail.popwindow.Share_pop;
import zsj.com.oyk255.example.ouyiku.fragment.DetailGoodsinfoFragment;
import zsj.com.oyk255.example.ouyiku.huodong.HuoDongDetail;
import zsj.com.oyk255.example.ouyiku.huodong.HuoDongDetailData;
import zsj.com.oyk255.example.ouyiku.huodong.MContent;
import zsj.com.oyk255.example.ouyiku.huodong.Status;
import zsj.com.oyk255.example.ouyiku.utils.Constant;
import zsj.com.oyk255.example.ouyiku.utils.PhotoUtil;
import zsj.com.oyk255.example.ouyiku.view.AspectRatioImageView;
import zsj.com.oyk255.example.ouyiku.view.CustomViewPager;
import zsj.com.oyk255.example.ouyiku.view.ViewpageIndicator;
import zsj.com.oyk255.example.ouyiku.view.ZProgressHUD;
import zsj.com.oyk255.suiyuchen.HTTPUtils;
import zsj.com.oyk255.suiyuchen.UILUtils;
import zsj.com.oyk255.suiyuchen.VolleyListener;
import com.google.gson.Gson;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.message.PushAgent;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class NineDetailActivity extends FragmentActivity implements OnClickListener{
private ListView mListView;
private CustomViewPager mLunBoPager;
private ViewpageIndicator viewpageIndicator;
InputMethodManager im;
int[] mImgRes=new int[]{R.mipmap.logo,R.mipmap.logo,R.mipmap.logo,R.mipmap.logo};
private String productId;
private SharedPreferences sp;
private String userid;//用户id
private String token;//用户token
private TextView mTitle;
private TextView mAttr;
private TextView mTime;
private TextView mNewPrice;
private TextView mOldPrice;
private TextView mSku;
private TextView mZhekou;
// ArrayList<String> mLunboData=new ArrayList<String>();//轮播图片
private String zeronine;
ArrayList<MContent> mGraphicData=new ArrayList<MContent>();//图文详情
ArrayList<String> mBannerData=new ArrayList<String>();
private IWXAPI api;
private static final String APP_ID="wx246edc55db723ecb";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nine_detail);
PushAgent.getInstance(this).onAppStart();
im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (savedInstanceState == null) {
overridePendingTransition(R.anim.push_from_right,R.anim.push_to_left);
}
api = WXAPIFactory.createWXAPI(this, APP_ID, false);
api.registerApp(APP_ID);
Intent intent = getIntent();
productId = intent.getStringExtra("productId");
sp = getSharedPreferences("userdata", 0);
userid = sp.getString("userid", "");
token = sp.getString("token", "");
zeronine = intent.getStringExtra("zeronine");
initUI();
initData();
}
private String fproId;
private String isbuy;
private String title;
@Override
protected void onStart() {
sp = getSharedPreferences("userdata", 0);
userid = sp.getString("userid", "");
token = sp.getString("token", "");
super.onStart();
}
private void initData() {
final ZProgressHUD progressHUD = ZProgressHUD.getInstance(this);
progressHUD.setMessage("加载中");
progressHUD.setSpinnerType(ZProgressHUD.SIMPLE_ROUND_SPINNER );
progressHUD.show();
String url= Constant.URL.NineDetailURL;
HashMap<String, String> map=new HashMap<String, String>();
map.put("product_id", productId);
map.put("user_id", userid);
HTTPUtils.post(this, url, map, new VolleyListener() {
@Override
public void onResponse(String arg0) {
Gson gson = new Gson();
progressHUD.dismiss();
HuoDongDetail fromJson = gson.fromJson(arg0, HuoDongDetail.class);
Status status = fromJson.getStatus();
String succeed = status.getSucceed();
if(succeed.equals("1")){
HuoDongDetailData data = fromJson.getData();
List<MContent> mContent = data.getMContent();
mGraphicData.addAll(mContent);
List<String> productImage = data.getProductImage();
mBannerData.addAll(productImage);
title = data.getTitle();
String marketprice = data.getMarketprice();
String currprice = data.getCurrprice();
String stock = data.getStock();
String attr = data.getAttr();
String ltime = data.getLtime();
fproId = data.getFproId();
isbuy = data.getIsbuy();
Log.e("isbuy", isbuy);
mTitle.setText(title);
mAttr.setText(attr);
mNewPrice.setText("¥"+currprice);
mOldPrice.setText("¥"+marketprice);
mSku.setText("库存:"+stock);
recLen = Integer.valueOf(ltime);
timer.schedule(task, 1000, 1000);
float i = Float.parseFloat(marketprice);
float i2 = Float.parseFloat(currprice);
float f=i2/i;
float b = (float)(Math.round(f*100))/100;
float b2=b*10;
mZhekou.setText(b2+"折");
FragmentManager fragmentManager = getSupportFragmentManager();
mLunBoPager.setOnPageChangeListener(new ViewPageChangedListener());
mLunBoPager.setAdapter(new ViewPageAdapter(fragmentManager));
mListView.setAdapter(new GraphicAdaptr());
}
}
@Override
public void onErrorResponse(VolleyError arg0) {
progressHUD.dismiss();
}
});
}
private int recLen ;
Timer timer = new Timer();
private void initUI() {
findViewById(R.id.ninedetail_back).setOnClickListener(this);
View mShare = findViewById(R.id.ninedetail_share);
mShare.setOnClickListener(this);
mListView = (ListView) findViewById(R.id.ninedetaillistview);
TextView mBuy = (TextView) findViewById(R.id.ninedetail_buy);
mBuy.setOnClickListener(this);
View topView = getLayoutInflater().inflate(R.layout.nine_detail_topview, null);
mLunBoPager = (CustomViewPager) topView.findViewById(R.id.detail_lunbo);
viewpageIndicator = (ViewpageIndicator) topView.findViewById(R.id.viewpageIndicator2);
mTitle = (TextView) topView.findViewById(R.id.detai_name);
mAttr = (TextView) topView.findViewById(R.id.detail_attr);
mTime = (TextView) topView.findViewById(R.id.detail_daojishi);
mNewPrice = (TextView) topView.findViewById(R.id.detail_newprice);
mOldPrice = (TextView) topView.findViewById(R.id.detail_oldprice);
mOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
mSku = (TextView) topView.findViewById(R.id.detail_sku);
mZhekou = (TextView) topView.findViewById(R.id.detail_zhekou);
if(zeronine.equals("zero")){
mTime.setVisibility(View.GONE);
mSku.setVisibility(View.GONE);
mZhekou.setVisibility(View.GONE);
mShare.setVisibility(View.INVISIBLE);
}
mListView.addHeaderView(topView);
share_pop = new Share_pop(this);
}
class ViewPageChangedListener implements OnPageChangeListener{
@Override
public void onPageScrolled(int position, float arg1, int arg2) {
position%=mBannerData.size();
viewpageIndicator.move(position, arg1,mBannerData.size());
}
@Override
public void onPageSelected(int arg0) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
}
class ViewPageAdapter extends FragmentPagerAdapter{
public ViewPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
int index= position %mImgRes.length;
if(mBannerData.size()==0){
DetailGoodsinfoFragment bannerItemFragment = new DetailGoodsinfoFragment(index, mImgRes[index]);
return bannerItemFragment;
}else{
String bannerDatum = mBannerData.get(index);
DetailGoodsinfoFragment bannerItemFragment2 = new DetailGoodsinfoFragment(index, bannerDatum);
return bannerItemFragment2;
}
}
@Override
public int getCount() {
//TODO
return mBannerData.size();
}
}
class GraphicAdaptr extends BaseAdapter{
@Override
public int getCount() {
return mGraphicData.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@SuppressLint("ViewHolder")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View layout =null;
ViewHolder holder;
if(convertView==null){
layout=getLayoutInflater().inflate(R.layout.graphic_item, null);
holder=new ViewHolder();
holder.mGraphic_img = (AspectRatioImageView) layout.findViewById(R.id.graphic_img);
layout.setTag(holder);
}else{
layout=convertView;
holder = (ViewHolder) layout.getTag();
}
MContent mContent = mGraphicData.get(position);
String url = mContent.getUrl();
UILUtils.displayImageNoAnim(url, holder.mGraphic_img);
return layout;
}
}
class ViewHolder{
AspectRatioImageView mGraphic_img;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ninedetail_back:
finish();
break;
case R.id.ninedetail_share:
share_pop.showAtLocation(findViewById(R.id.ninedetaillayout), Gravity.CENTER, 0, 0);
share_pop.view.findViewById(R.id.iv_share_wx3).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
api.registerApp(APP_ID);
api.sendReq(createReq(false));
}
});
share_pop.view.findViewById(R.id.iv_share_pyq3).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
api.registerApp(APP_ID);
api.sendReq(createReq(true));
}
});
break;
case R.id.ninedetail_buy:
if(!userid.equals("")){
if(isbuy.equals("0")){
Toast.makeText(NineDetailActivity.this, "已购买过此商品", Toast.LENGTH_SHORT).show();
} else if(isbuy.equals("2")){
Toast.makeText(NineDetailActivity.this, "没有库存了", Toast.LENGTH_SHORT).show();
} else if(isbuy.equals("1")){
Intent intent = new Intent(NineDetailActivity.this, ConfirmOrder9and0Activity.class);
intent.putExtra("productId", productId);
startActivity(intent);
} else if(isbuy.equals("3")){
Toast.makeText(NineDetailActivity.this, "活动未开始", Toast.LENGTH_SHORT).show();
}
else if(isbuy.equals("4")){
Toast.makeText(NineDetailActivity.this, "活动已结束", Toast.LENGTH_SHORT).show();
}
}else{
startActivity(new Intent(this, LoginActivity.class));
}
break;
default:
break;
}
}
//时间戳转换
public String times(long time) {
SimpleDateFormat sdr = new SimpleDateFormat("dd天HH时mm分ss秒");
String times = sdr.format(new Date(time * 1000L));
return times;
}
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() { // UI thread
@Override
public void run() {
recLen--;
String times = times(recLen);
mTime.setText("剩余:"+times);
if(recLen < 0){
timer.cancel();
}
}
});
}
};
private Share_pop share_pop;
public SendMessageToWX.Req createReq(boolean timeLine) {
String ArticleUrl="http://ouyiku.com/jiubuy/view?pid="+productId;
String title2 = title;
WXWebpageObject webpage = new WXWebpageObject();
webpage.webpageUrl = ArticleUrl;
WXMediaMessage msg = new WXMediaMessage(webpage);
// String title = title2;
msg.description = title2;
// msg.title = title;
Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.tubiao3);
msg.thumbData = PhotoUtil.bmpToByteArray(thumb, true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = msg;
// req.scene = SendMessageToWX.Req.WXSceneSession;
req.scene = timeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
return req;
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
@Override
public void finish() {
hideSoftInput();
super.finish();
overridePendingTransition(R.anim.push_from_left, R.anim.push_to_right);
}
protected void hideSoftInput() {
View view = getCurrentFocus();
if(view != null) {
IBinder binder = view.getWindowToken();
if(binder != null) {
im.hideSoftInputFromWindow(binder, 0);
}
}
}
}
| 13,732 | 0.709263 | 0.700308 | 453 | 29.075056 | 23.758881 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.679912 | false | false | 5 |
68f4892e911a9b9e0a6e841744ed7f8303104678 | 6,640,019,465,174 | 772d00094f3c86fd5b0dfdff5986ce73cb4f6ada | /src/com/Sts/Framework/UI/DataTransfer/StsDirectoryBrowserFileTransferPanel.java | de1e2e85cd0e22671387ac9187352735e1b60735 | []
| no_license | tlasseter/gcs | https://github.com/tlasseter/gcs | 52ccfe32c836caca3c53daf0387e0d64a2b6f140 | 7538bb2272c4a3caee43be212f3e8a7ccf091b43 | refs/heads/master | 2021-03-27T20:47:48.844000 | 2014-09-25T18:58:31 | 2014-09-25T18:58:31 | 24,471,103 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.Sts.Framework.UI.DataTransfer;
import com.Sts.Framework.IO.FilenameFilters.*;
import com.Sts.Framework.IO.*;
import com.Sts.Framework.UI.*;
import java.io.*;
import java.util.*;
/**
* Copyright: Copyright (c) 2011
* Author: Tom Lasseter
* Date: 9/20/11
*/
public class StsDirectoryBrowserFileTransferPanel extends StsDirectoryBrowserObjectsTransferPanel
{
FolderFilter filter = new FolderFilter();
StsAbstractFilenameFilter masterFileFilter;
StsAbstractFilenameFilter subFilesFilter;
StsAbstractFilenameFilter fileFilter;
StsAbstractFilenameFilter folderFilter;
public StsDirectoryBrowserFileTransferPanel(String currentDirectory, StsObjectTransferListener listener,
StsAbstractFilenameFilter masterFileFilter, StsAbstractFilenameFilter subFilesFilter, StsAbstractFilenameFilter folderFilter, int width, int height)
{
super.initialize("Test Directory Objects Panel", currentDirectory, listener, width, height);
this.masterFileFilter = masterFileFilter;
this.subFilesFilter = subFilesFilter;
this.folderFilter = folderFilter;
fileFilter = StsFilenameFilter.addFilters(masterFileFilter, new StsAbstractFilenameFilter[] { subFilesFilter, folderFilter });
}
public Object[] getAvailableObjects()
{
if(directory == null) return null;
File directoryFile = new File(directory);
File[] files = directoryFile.listFiles(); // fileFilter
if(files == null) return new StsFile[0];
HashMap<String, StsSubFileSet> subFileSets = new HashMap<String, StsSubFileSet>();
for(File file : files)
{
try
{
if(file.isDirectory())
{
StsFile masterFile = masterFileFromFolder(file);
if(masterFile != null)
{
String name = masterFile.name;
StsSubFileSet existingSet = subFileSets.get(name);
if(existingSet != null)
{
StsMessageFiles.errorMessage(this, "getAvailableObjects", "A deviation survey already exists for " + masterFileFilter.name);
continue;
}
StsSubFileSet subFileSet = new StsSubFileSet();
subFileSet.setMasterFile(masterFile);
subFileSet.isDirectory = true;
subFileSets.put(name, subFileSet);
}
}
else // not a directory, add this file as either masterFile or subFile to new or existing subFileSet
{
StsFile stsFile = StsFile.constructor(file.toPath());
if(stsFile == null) continue;
masterFileFilter.parseFile(stsFile);
String name = masterFileFilter.name;
if(masterFileFilter.groupOk()) // this is a masterFile
{
StsSubFileSet existingSet = subFileSets.get(name);
if(existingSet != null)
{
StsMessageFiles.errorMessage(this, "getAvailableObjects", "A deviation survey already exists for " + masterFileFilter.name);
continue;
}
StsSubFileSet subFileSet = new StsSubFileSet();
subFileSet.setMasterFile(stsFile);
subFileSets.put(name, subFileSet);
}
else // this is a subFile
{
StsSubFileSet subFileSet = subFileSets.get(name);
if(subFileSet == null)
{
subFileSet = new StsSubFileSet();
subFileSets.put(name, subFileSet);
}
subFileSet.addSubFile(stsFile);
}
}
}
catch(Exception e) { }
}
StsSubFileSet[] values = subFileSets.values().toArray(new StsSubFileSet[0]);
Arrays.sort(values);
return values;
}
private StsFile masterFileFromFolder(File folder)
{
File[] files = folder.listFiles(masterFileFilter);
if(files == null || files.length == 0) return null;
if(files.length > 1)
{
StsMessageFiles.errorMessage("More than one deviation survey file found in folder " + folder.getPath());
return null;
}
if(!folderFilter.parseFile(folder)) return null;
String folderName = masterFileFilter.name;
StsFile masterFile = StsFile.constructor(files[0].toPath());
if(masterFile == null) return null;
masterFileFilter.parseFile(masterFile);
if(folderName.equals(masterFileFilter.name))
return masterFile;
else
return null;
}
public Object[] initializeAvailableObjects()
{
return getAvailableObjects();
}
class FolderFilter implements FilenameFilter
{
FolderFilter() { }
public boolean accept(File file) { return file.isDirectory(); }
public boolean accept(File file, String filename) { return file.isDirectory(); }
}
}
| UTF-8 | Java | 4,350 | java | StsDirectoryBrowserFileTransferPanel.java | Java | [
{
"context": "\n\n/**\n * Copyright: Copyright (c) 2011\n * Author: Tom Lasseter\n * Date: 9/20/11\n */\npublic class StsDirectoryBro",
"end": 254,
"score": 0.9998541474342346,
"start": 242,
"tag": "NAME",
"value": "Tom Lasseter"
}
]
| null | []
| package com.Sts.Framework.UI.DataTransfer;
import com.Sts.Framework.IO.FilenameFilters.*;
import com.Sts.Framework.IO.*;
import com.Sts.Framework.UI.*;
import java.io.*;
import java.util.*;
/**
* Copyright: Copyright (c) 2011
* Author: <NAME>
* Date: 9/20/11
*/
public class StsDirectoryBrowserFileTransferPanel extends StsDirectoryBrowserObjectsTransferPanel
{
FolderFilter filter = new FolderFilter();
StsAbstractFilenameFilter masterFileFilter;
StsAbstractFilenameFilter subFilesFilter;
StsAbstractFilenameFilter fileFilter;
StsAbstractFilenameFilter folderFilter;
public StsDirectoryBrowserFileTransferPanel(String currentDirectory, StsObjectTransferListener listener,
StsAbstractFilenameFilter masterFileFilter, StsAbstractFilenameFilter subFilesFilter, StsAbstractFilenameFilter folderFilter, int width, int height)
{
super.initialize("Test Directory Objects Panel", currentDirectory, listener, width, height);
this.masterFileFilter = masterFileFilter;
this.subFilesFilter = subFilesFilter;
this.folderFilter = folderFilter;
fileFilter = StsFilenameFilter.addFilters(masterFileFilter, new StsAbstractFilenameFilter[] { subFilesFilter, folderFilter });
}
public Object[] getAvailableObjects()
{
if(directory == null) return null;
File directoryFile = new File(directory);
File[] files = directoryFile.listFiles(); // fileFilter
if(files == null) return new StsFile[0];
HashMap<String, StsSubFileSet> subFileSets = new HashMap<String, StsSubFileSet>();
for(File file : files)
{
try
{
if(file.isDirectory())
{
StsFile masterFile = masterFileFromFolder(file);
if(masterFile != null)
{
String name = masterFile.name;
StsSubFileSet existingSet = subFileSets.get(name);
if(existingSet != null)
{
StsMessageFiles.errorMessage(this, "getAvailableObjects", "A deviation survey already exists for " + masterFileFilter.name);
continue;
}
StsSubFileSet subFileSet = new StsSubFileSet();
subFileSet.setMasterFile(masterFile);
subFileSet.isDirectory = true;
subFileSets.put(name, subFileSet);
}
}
else // not a directory, add this file as either masterFile or subFile to new or existing subFileSet
{
StsFile stsFile = StsFile.constructor(file.toPath());
if(stsFile == null) continue;
masterFileFilter.parseFile(stsFile);
String name = masterFileFilter.name;
if(masterFileFilter.groupOk()) // this is a masterFile
{
StsSubFileSet existingSet = subFileSets.get(name);
if(existingSet != null)
{
StsMessageFiles.errorMessage(this, "getAvailableObjects", "A deviation survey already exists for " + masterFileFilter.name);
continue;
}
StsSubFileSet subFileSet = new StsSubFileSet();
subFileSet.setMasterFile(stsFile);
subFileSets.put(name, subFileSet);
}
else // this is a subFile
{
StsSubFileSet subFileSet = subFileSets.get(name);
if(subFileSet == null)
{
subFileSet = new StsSubFileSet();
subFileSets.put(name, subFileSet);
}
subFileSet.addSubFile(stsFile);
}
}
}
catch(Exception e) { }
}
StsSubFileSet[] values = subFileSets.values().toArray(new StsSubFileSet[0]);
Arrays.sort(values);
return values;
}
private StsFile masterFileFromFolder(File folder)
{
File[] files = folder.listFiles(masterFileFilter);
if(files == null || files.length == 0) return null;
if(files.length > 1)
{
StsMessageFiles.errorMessage("More than one deviation survey file found in folder " + folder.getPath());
return null;
}
if(!folderFilter.parseFile(folder)) return null;
String folderName = masterFileFilter.name;
StsFile masterFile = StsFile.constructor(files[0].toPath());
if(masterFile == null) return null;
masterFileFilter.parseFile(masterFile);
if(folderName.equals(masterFileFilter.name))
return masterFile;
else
return null;
}
public Object[] initializeAvailableObjects()
{
return getAvailableObjects();
}
class FolderFilter implements FilenameFilter
{
FolderFilter() { }
public boolean accept(File file) { return file.isDirectory(); }
public boolean accept(File file, String filename) { return file.isDirectory(); }
}
}
| 4,344 | 0.710345 | 0.707126 | 132 | 31.954546 | 31.602135 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.431818 | false | false | 5 |
9088373fa453a999bd886d5ce5f60cb7d13e0e18 | 16,088,947,517,090 | bee68f06a082a0a5d94e089cabf995d7a6436634 | /src/main/java/com/example/exception/work/IllegalArgumentException.java | 14853090eafc67f0b98eb36ff4ff9b6ae2c8d4dc | []
| no_license | swgswg/springboot2 | https://github.com/swgswg/springboot2 | af47820806a0bd98c3f3e46bbdaa943ea5125650 | 91ad08046d3ec12b31026b81a2aea0d23fb53ed9 | refs/heads/main | 2023-03-07T22:45:05.760000 | 2021-03-02T01:59:31 | 2021-03-02T01:59:31 | 330,205,312 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.exception.work;
import com.example.constant.ErrorCode;
import com.example.exception.ApiException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
/**
* @author song
* 参数不合法
*/
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class IllegalArgumentException extends ApiException {
ErrorCode errorCode = ErrorCode.ILLEGAL_ARGUMENT;
public IllegalArgumentException(String message) {
super(message);
}
public IllegalArgumentException(ErrorCode errorCode) {
super(errorCode);
}
public IllegalArgumentException(ErrorCode errorCode, String message) {
super(errorCode, message);
}
}
| UTF-8 | Java | 800 | java | IllegalArgumentException.java | Java | [
{
"context": "g.springframework.http.HttpStatus;\n\n/**\n * @author song\n * 参数不合法\n */\n@Data\n@NoArgsConstructor\n@EqualsAndH",
"end": 303,
"score": 0.9962146878242493,
"start": 299,
"tag": "USERNAME",
"value": "song"
}
]
| null | []
| package com.example.exception.work;
import com.example.constant.ErrorCode;
import com.example.exception.ApiException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
/**
* @author song
* 参数不合法
*/
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class IllegalArgumentException extends ApiException {
ErrorCode errorCode = ErrorCode.ILLEGAL_ARGUMENT;
public IllegalArgumentException(String message) {
super(message);
}
public IllegalArgumentException(ErrorCode errorCode) {
super(errorCode);
}
public IllegalArgumentException(ErrorCode errorCode, String message) {
super(errorCode, message);
}
}
| 800 | 0.763291 | 0.763291 | 32 | 23.6875 | 21.080853 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 5 |
d036567ef6673f93ffbb7b6f6c06d43a25459747 | 21,732,534,545,051 | 7558893556bd914f18e9a12d13926b05b513b50a | /src/main/java/ru/settletale/math/Ray.java | 00cfd7f41d1063921f9f75e53c54884ad2be29b5 | []
| no_license | fewizz/SettleTale | https://github.com/fewizz/SettleTale | 4e7c84dddccf0d8a48a53b79147993a2dbbc27c1 | c08bb9c5763358436c6ce08ee0e34b448df826e2 | refs/heads/master | 2021-01-11T04:32:53.049000 | 2017-08-22T20:42:16 | 2017-08-22T20:42:16 | 71,170,204 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.settletale.math;
public class Ray {
}
| UTF-8 | Java | 51 | java | Ray.java | Java | []
| null | []
| package ru.settletale.math;
public class Ray {
}
| 51 | 0.72549 | 0.72549 | 5 | 9.2 | 11.232097 | 27 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 5 |
0c773be37234a114d157d13dea28eb92448801be | 12,721,693,154,576 | 538561c542664e198761e8184c8779b54dcc392d | /belajar-java-thread/src/test/java/ekomuliyo/com/thread/DeadlockTest.java | acfe907dd850f67520fb50f570c5279c3878691e | []
| no_license | ekomuliyo/Java | https://github.com/ekomuliyo/Java | 7ffb61821f37b30edfde702d6b49a86505306b4f | 69573733237229f81f20fddb8b992dd410fd069a | refs/heads/master | 2022-06-28T18:06:40.809000 | 2022-02-23T10:01:38 | 2022-02-23T10:01:38 | 236,895,638 | 1 | 0 | null | false | 2022-06-21T04:15:20 | 2020-01-29T03:31:07 | 2021-12-04T10:13:47 | 2022-06-21T04:15:20 | 689 | 1 | 0 | 3 | Java | false | false | package ekomuliyo.com.thread;
import org.junit.jupiter.api.Test;
public class DeadlockTest {
@Test
void transfer() throws InterruptedException {
var balance1 = new Balance(1_000_000L);
var balance2 = new Balance(1_000_000L);
var thread1 = new Thread(() -> {
try {
Balance.transfer(balance1, balance2, 500_000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
var thread2 = new Thread(() -> {
try {
Balance.transfer(balance2, balance1, 500_000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("Balance 1 : " + balance1.getValue());
System.out.println("Balance 2 : " + balance2.getValue());
}
}
| UTF-8 | Java | 961 | java | DeadlockTest.java | Java | []
| null | []
| package ekomuliyo.com.thread;
import org.junit.jupiter.api.Test;
public class DeadlockTest {
@Test
void transfer() throws InterruptedException {
var balance1 = new Balance(1_000_000L);
var balance2 = new Balance(1_000_000L);
var thread1 = new Thread(() -> {
try {
Balance.transfer(balance1, balance2, 500_000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
var thread2 = new Thread(() -> {
try {
Balance.transfer(balance2, balance1, 500_000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("Balance 1 : " + balance1.getValue());
System.out.println("Balance 2 : " + balance2.getValue());
}
}
| 961 | 0.526535 | 0.48283 | 37 | 24.972973 | 21.025707 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540541 | false | false | 5 |
b4eefdbd27b42f65220af503c521c4b127edcdc4 | 15,333,033,273,585 | 5e87b6ecb1cf1a172cbffd22b734c10b726db3cc | /extensions/entitystore-javaspaces/src/main/java/org/qi4j/library/spaces/javaspaces/JavaSpacesClientMixin.java | 13d03bb3eb68aebcd1a580160a97ce4f384f22dc | []
| no_license | fb71/qi4j-sandbox | https://github.com/fb71/qi4j-sandbox | ddf2fd43751538d0fb00f229463e18e2afdda768 | 4e87398b3a98a08817f74e7e918ae4964ce57f68 | refs/heads/master | 2021-01-15T23:27:10.837000 | 2010-12-12T15:16:01 | 2010-12-12T15:16:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2008 Niclas Hedhman.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qi4j.library.spaces.javaspaces;
import net.jini.config.ConfigurationException;
import net.jini.config.ConfigurationFile;
import net.jini.core.entry.UnusableEntryException;
import net.jini.core.lease.LeaseDeniedException;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.core.transaction.Transaction;
import net.jini.core.transaction.TransactionException;
import net.jini.core.transaction.TransactionFactory;
import net.jini.core.transaction.server.TransactionManager;
import net.jini.discovery.DiscoveryEvent;
import net.jini.discovery.DiscoveryListener;
import net.jini.discovery.DiscoveryManagement;
import net.jini.discovery.LookupDiscoveryManager;
import net.jini.lookup.LookupCache;
import net.jini.lookup.ServiceDiscoveryEvent;
import net.jini.lookup.ServiceDiscoveryListener;
import net.jini.lookup.ServiceDiscoveryManager;
import net.jini.space.JavaSpace05;
import net.jini.space.MatchSet;
import org.qi4j.api.configuration.Configuration;
import org.qi4j.api.injection.scope.This;
import org.qi4j.api.service.Activatable;
import org.qi4j.library.spaces.Space;
import org.qi4j.library.spaces.SpaceException;
import org.qi4j.library.spaces.SpaceTransaction;
import java.io.*;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;
import java.util.StringTokenizer;
public class JavaSpacesClientMixin
implements Space, Activatable
{
@This private Configuration<JavaSpacesClientConfiguration> my;
private ServiceHolder<JavaSpace05> spaceService;
private ServiceHolder<TransactionManager> transactionService;
private StackThreadLocal<TransactionProxy> transactionStack;
public JavaSpacesClientMixin()
{
transactionStack = new StackThreadLocal<TransactionProxy>();
}
public void write( String id, String entry )
{
synchronized( this )
{
if( spaceService.service != null )
{
try
{
StorageEntry storageEntry = new StorageEntry( id, entry );
spaceService.service.write( storageEntry, currentTransaction(), 6000 );
}
catch( TransactionException e )
{
e.printStackTrace(); // Can not happen without own transaction.
}
catch( RemoteException e )
{
throw new SpaceException( "Remote problems: " + e.getMessage(), e );
}
}
}
}
public Serializable take( String id, long timeout )
{
synchronized( this )
{
if( spaceService.service != null )
{
try
{
StorageEntry entry = (StorageEntry) spaceService.service.take( new StorageEntry( id, null ), currentTransaction(), 6000 );
if( entry == null )
{
return null;
}
return entry.data();
}
catch( TransactionException e )
{
e.printStackTrace(); // Can not happen without own transaction.
}
catch( RemoteException e )
{
throw new SpaceException( "Remote problems: " + e.getMessage(), e );
}
catch( UnusableEntryException e )
{
e.printStackTrace();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
return null;
}
public String takeIfExists( String id )
{
synchronized( this )
{
if( spaceService.service != null )
{
try
{
StorageEntry entry = (StorageEntry) spaceService.service.takeIfExists( new StorageEntry( id, null ), currentTransaction(), 6000 );
if( entry == null )
{
return null;
}
return entry.data();
}
catch( TransactionException e )
{
e.printStackTrace(); // Can not happen without own transaction.
}
catch( RemoteException e )
{
throw new SpaceException( "Remote problems: " + e.getMessage(), e );
}
catch( UnusableEntryException e )
{
e.printStackTrace();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
return null;
}
}
public Serializable read( String id, long timeout )
{
synchronized( this )
{
if( spaceService.service != null )
{
try
{
StorageEntry entry = (StorageEntry) spaceService.service.read( new StorageEntry( id, null ), currentTransaction(), timeout );
if( entry == null )
{
return null;
}
return entry.data();
}
catch( TransactionException e )
{
e.printStackTrace(); // Can not happen without own transaction.
}
catch( RemoteException e )
{
throw new SpaceException( "Remote problems: " + e.getMessage(), e );
}
catch( UnusableEntryException e )
{
e.printStackTrace();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
return null;
}
public String readIfExists( String id )
{
synchronized( this )
{
if( spaceService.service != null )
{
try
{
StorageEntry entry = (StorageEntry) spaceService.service.readIfExists( new StorageEntry( id, null ), currentTransaction(), 6000 );
if( entry == null )
{
return null;
}
return entry.data();
}
catch( TransactionException e )
{
e.printStackTrace(); // Can not happen without own transaction.
}
catch( RemoteException e )
{
throw new SpaceException( "Remote problems: " + e.getMessage(), e );
}
catch( UnusableEntryException e )
{
e.printStackTrace();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
return null;
}
public SpaceTransaction newTransaction()
{
synchronized( this )
{
if( transactionService.service != null )
{
try
{
Transaction.Created created = TransactionFactory.create( transactionService.service, 60000 );
Transaction transaction = created.transaction;
System.out.println( "NEW: " + transaction );
TransactionProxy transactionProxy = new TransactionProxy( transaction, this );
transactionStack.get().push( transactionProxy );
return transactionProxy;
}
catch( LeaseDeniedException e )
{
e.printStackTrace();
}
catch( RemoteException e )
{
e.printStackTrace();
}
}
return new NullTransactionProxy();
}
}
public boolean isReady()
{
return spaceService.service != null && transactionService.service != null;
}
public void activate()
throws Exception
{
String groupConfig = my.configuration().groups().get();
System.out.println( "GROUPS: " + groupConfig );
String[] groups = convert( groupConfig );
spaceService = initializeLookup( groups, JavaSpace05.class );
transactionService = initializeLookup( groups, TransactionManager.class );
}
private String[] convert( String data )
{
if( data == null )
{
return new String[0];
}
StringTokenizer st = new StringTokenizer( data, ",", false );
ArrayList<String> result = new ArrayList<String>();
while( st.hasMoreTokens() )
{
String item = st.nextToken().trim();
result.add( item );
}
String[] retVal = new String[result.size()];
return result.toArray( retVal );
}
public void passivate()
throws Exception
{
spaceService.lookupCache.terminate();
transactionService.lookupCache.terminate();
}
static <T> ServiceHolder<T> initializeLookup( String[] groups, Class<T> type )
throws IOException
{
ClassLoader classloader = JavaSpacesClientMixin.class.getClassLoader();
InputStream in = JavaSpacesClientMixin.class.getResourceAsStream( "jini.config" );
Reader reader = new InputStreamReader( in );
String[] options = new String[0];
DiscoveryManagement dm = null;
try
{
net.jini.config.Configuration config = new ConfigurationFile( reader, options, classloader );
dm = new LookupDiscoveryManager( groups, null, null, config );
}
catch( ConfigurationException e )
{
e.printStackTrace();
}
ServiceDiscoveryManager sdm = new ServiceDiscoveryManager( dm, null );
Class[] types = new Class[]{ type };
ServiceTemplate template = new ServiceTemplate( null, types, null );
LookupCache lookupCache = sdm.createLookupCache( template, null, null );
return new ServiceHolder<T>( dm, lookupCache );
}
Transaction currentTransaction()
{
Stack<TransactionProxy> curStack = transactionStack.get();
if( curStack.size() == 0 )
{
System.err.println( "WARNING: Transaction is null." );
return null;
}
TransactionProxy proxy = curStack.peek();
if( proxy == null )
{
System.err.println( "WARNING: Transaction is null." );
return null;
}
else if( proxy.transaction == null )
{
System.err.println( "WARNING: Transaction is null." );
}
Transaction transaction = proxy.transaction;
System.out.println( "LOOKUP: " + transaction );
return transaction;
}
void removeTransaction( TransactionProxy transaction )
{
Stack<TransactionProxy> curStack = transactionStack.get();
curStack.remove( transaction );
}
public Iterator<String> iterator()
{
ArrayList templates = new ArrayList();
templates.add( new StorageEntry(null, null) );
try
{
Transaction txn = currentTransaction();
MatchSet matchSet = spaceService.service.contents( templates, txn, 60000, 1000 );
return new EntryIterator( matchSet );
}
catch( TransactionException e )
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
catch( RemoteException e )
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return null;
}
static class ServiceHolder<T>
implements DiscoveryListener
{
private DiscoveryManagement dm;
private LookupCache lookupCache;
T service;
public ServiceHolder( DiscoveryManagement dm, LookupCache lookupCache )
{
this.dm = dm;
this.lookupCache = lookupCache;
this.dm.addDiscoveryListener( this );
lookupCache.addListener( new ServiceDiscoveryListener()
{
public void serviceAdded( ServiceDiscoveryEvent event )
{
System.out.println( "Service Added: " + event );
service = (T) event.getPostEventServiceItem().service;
}
public void serviceRemoved( ServiceDiscoveryEvent event )
{
System.out.println( "Service Removed: " + event );
service = null;
}
public void serviceChanged( ServiceDiscoveryEvent event )
{
System.out.println( "Service Changed: " + event );
}
} );
}
public void dispose()
{
dm.removeDiscoveryListener( this );
}
public void discovered( DiscoveryEvent e )
{
System.out.println( "Discovered: " + e.getGroups() );
}
public void discarded( DiscoveryEvent e )
{
System.out.println( "Discarded: " + e.getGroups() );
}
}
private static class EntryIterator
implements Iterator<String>
{
private MatchSet matchSet;
private StorageEntry nextEntry;
public EntryIterator( MatchSet matchSet )
{
this.matchSet = matchSet;
try
{
nextEntry = getNext( matchSet );
}
catch( RemoteException e )
{
e.printStackTrace();
}
catch( UnusableEntryException e )
{
e.printStackTrace();
}
}
private StorageEntry getNext( MatchSet matchSet )
throws RemoteException, UnusableEntryException
{
StorageEntry storageEntry = (StorageEntry) matchSet.next();
return storageEntry;
}
public boolean hasNext()
{
return nextEntry != null;
}
public String next()
{
String result = nextEntry.data();
try
{
nextEntry = getNext( matchSet );
}
catch( RemoteException e )
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
catch( UnusableEntryException e )
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return result;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
}
| UTF-8 | Java | 15,830 | java | JavaSpacesClientMixin.java | Java | [
{
"context": "/*\n * Copyright 2008 Niclas Hedhman.\n *\n * Licensed under the Apache License, Vers",
"end": 35,
"score": 0.9998640418052673,
"start": 21,
"tag": "NAME",
"value": "Niclas Hedhman"
}
]
| null | []
| /*
* Copyright 2008 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.qi4j.library.spaces.javaspaces;
import net.jini.config.ConfigurationException;
import net.jini.config.ConfigurationFile;
import net.jini.core.entry.UnusableEntryException;
import net.jini.core.lease.LeaseDeniedException;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.core.transaction.Transaction;
import net.jini.core.transaction.TransactionException;
import net.jini.core.transaction.TransactionFactory;
import net.jini.core.transaction.server.TransactionManager;
import net.jini.discovery.DiscoveryEvent;
import net.jini.discovery.DiscoveryListener;
import net.jini.discovery.DiscoveryManagement;
import net.jini.discovery.LookupDiscoveryManager;
import net.jini.lookup.LookupCache;
import net.jini.lookup.ServiceDiscoveryEvent;
import net.jini.lookup.ServiceDiscoveryListener;
import net.jini.lookup.ServiceDiscoveryManager;
import net.jini.space.JavaSpace05;
import net.jini.space.MatchSet;
import org.qi4j.api.configuration.Configuration;
import org.qi4j.api.injection.scope.This;
import org.qi4j.api.service.Activatable;
import org.qi4j.library.spaces.Space;
import org.qi4j.library.spaces.SpaceException;
import org.qi4j.library.spaces.SpaceTransaction;
import java.io.*;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;
import java.util.StringTokenizer;
public class JavaSpacesClientMixin
implements Space, Activatable
{
@This private Configuration<JavaSpacesClientConfiguration> my;
private ServiceHolder<JavaSpace05> spaceService;
private ServiceHolder<TransactionManager> transactionService;
private StackThreadLocal<TransactionProxy> transactionStack;
public JavaSpacesClientMixin()
{
transactionStack = new StackThreadLocal<TransactionProxy>();
}
public void write( String id, String entry )
{
synchronized( this )
{
if( spaceService.service != null )
{
try
{
StorageEntry storageEntry = new StorageEntry( id, entry );
spaceService.service.write( storageEntry, currentTransaction(), 6000 );
}
catch( TransactionException e )
{
e.printStackTrace(); // Can not happen without own transaction.
}
catch( RemoteException e )
{
throw new SpaceException( "Remote problems: " + e.getMessage(), e );
}
}
}
}
public Serializable take( String id, long timeout )
{
synchronized( this )
{
if( spaceService.service != null )
{
try
{
StorageEntry entry = (StorageEntry) spaceService.service.take( new StorageEntry( id, null ), currentTransaction(), 6000 );
if( entry == null )
{
return null;
}
return entry.data();
}
catch( TransactionException e )
{
e.printStackTrace(); // Can not happen without own transaction.
}
catch( RemoteException e )
{
throw new SpaceException( "Remote problems: " + e.getMessage(), e );
}
catch( UnusableEntryException e )
{
e.printStackTrace();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
return null;
}
public String takeIfExists( String id )
{
synchronized( this )
{
if( spaceService.service != null )
{
try
{
StorageEntry entry = (StorageEntry) spaceService.service.takeIfExists( new StorageEntry( id, null ), currentTransaction(), 6000 );
if( entry == null )
{
return null;
}
return entry.data();
}
catch( TransactionException e )
{
e.printStackTrace(); // Can not happen without own transaction.
}
catch( RemoteException e )
{
throw new SpaceException( "Remote problems: " + e.getMessage(), e );
}
catch( UnusableEntryException e )
{
e.printStackTrace();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
return null;
}
}
public Serializable read( String id, long timeout )
{
synchronized( this )
{
if( spaceService.service != null )
{
try
{
StorageEntry entry = (StorageEntry) spaceService.service.read( new StorageEntry( id, null ), currentTransaction(), timeout );
if( entry == null )
{
return null;
}
return entry.data();
}
catch( TransactionException e )
{
e.printStackTrace(); // Can not happen without own transaction.
}
catch( RemoteException e )
{
throw new SpaceException( "Remote problems: " + e.getMessage(), e );
}
catch( UnusableEntryException e )
{
e.printStackTrace();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
return null;
}
public String readIfExists( String id )
{
synchronized( this )
{
if( spaceService.service != null )
{
try
{
StorageEntry entry = (StorageEntry) spaceService.service.readIfExists( new StorageEntry( id, null ), currentTransaction(), 6000 );
if( entry == null )
{
return null;
}
return entry.data();
}
catch( TransactionException e )
{
e.printStackTrace(); // Can not happen without own transaction.
}
catch( RemoteException e )
{
throw new SpaceException( "Remote problems: " + e.getMessage(), e );
}
catch( UnusableEntryException e )
{
e.printStackTrace();
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
}
return null;
}
public SpaceTransaction newTransaction()
{
synchronized( this )
{
if( transactionService.service != null )
{
try
{
Transaction.Created created = TransactionFactory.create( transactionService.service, 60000 );
Transaction transaction = created.transaction;
System.out.println( "NEW: " + transaction );
TransactionProxy transactionProxy = new TransactionProxy( transaction, this );
transactionStack.get().push( transactionProxy );
return transactionProxy;
}
catch( LeaseDeniedException e )
{
e.printStackTrace();
}
catch( RemoteException e )
{
e.printStackTrace();
}
}
return new NullTransactionProxy();
}
}
public boolean isReady()
{
return spaceService.service != null && transactionService.service != null;
}
public void activate()
throws Exception
{
String groupConfig = my.configuration().groups().get();
System.out.println( "GROUPS: " + groupConfig );
String[] groups = convert( groupConfig );
spaceService = initializeLookup( groups, JavaSpace05.class );
transactionService = initializeLookup( groups, TransactionManager.class );
}
private String[] convert( String data )
{
if( data == null )
{
return new String[0];
}
StringTokenizer st = new StringTokenizer( data, ",", false );
ArrayList<String> result = new ArrayList<String>();
while( st.hasMoreTokens() )
{
String item = st.nextToken().trim();
result.add( item );
}
String[] retVal = new String[result.size()];
return result.toArray( retVal );
}
public void passivate()
throws Exception
{
spaceService.lookupCache.terminate();
transactionService.lookupCache.terminate();
}
static <T> ServiceHolder<T> initializeLookup( String[] groups, Class<T> type )
throws IOException
{
ClassLoader classloader = JavaSpacesClientMixin.class.getClassLoader();
InputStream in = JavaSpacesClientMixin.class.getResourceAsStream( "jini.config" );
Reader reader = new InputStreamReader( in );
String[] options = new String[0];
DiscoveryManagement dm = null;
try
{
net.jini.config.Configuration config = new ConfigurationFile( reader, options, classloader );
dm = new LookupDiscoveryManager( groups, null, null, config );
}
catch( ConfigurationException e )
{
e.printStackTrace();
}
ServiceDiscoveryManager sdm = new ServiceDiscoveryManager( dm, null );
Class[] types = new Class[]{ type };
ServiceTemplate template = new ServiceTemplate( null, types, null );
LookupCache lookupCache = sdm.createLookupCache( template, null, null );
return new ServiceHolder<T>( dm, lookupCache );
}
Transaction currentTransaction()
{
Stack<TransactionProxy> curStack = transactionStack.get();
if( curStack.size() == 0 )
{
System.err.println( "WARNING: Transaction is null." );
return null;
}
TransactionProxy proxy = curStack.peek();
if( proxy == null )
{
System.err.println( "WARNING: Transaction is null." );
return null;
}
else if( proxy.transaction == null )
{
System.err.println( "WARNING: Transaction is null." );
}
Transaction transaction = proxy.transaction;
System.out.println( "LOOKUP: " + transaction );
return transaction;
}
void removeTransaction( TransactionProxy transaction )
{
Stack<TransactionProxy> curStack = transactionStack.get();
curStack.remove( transaction );
}
public Iterator<String> iterator()
{
ArrayList templates = new ArrayList();
templates.add( new StorageEntry(null, null) );
try
{
Transaction txn = currentTransaction();
MatchSet matchSet = spaceService.service.contents( templates, txn, 60000, 1000 );
return new EntryIterator( matchSet );
}
catch( TransactionException e )
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
catch( RemoteException e )
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return null;
}
static class ServiceHolder<T>
implements DiscoveryListener
{
private DiscoveryManagement dm;
private LookupCache lookupCache;
T service;
public ServiceHolder( DiscoveryManagement dm, LookupCache lookupCache )
{
this.dm = dm;
this.lookupCache = lookupCache;
this.dm.addDiscoveryListener( this );
lookupCache.addListener( new ServiceDiscoveryListener()
{
public void serviceAdded( ServiceDiscoveryEvent event )
{
System.out.println( "Service Added: " + event );
service = (T) event.getPostEventServiceItem().service;
}
public void serviceRemoved( ServiceDiscoveryEvent event )
{
System.out.println( "Service Removed: " + event );
service = null;
}
public void serviceChanged( ServiceDiscoveryEvent event )
{
System.out.println( "Service Changed: " + event );
}
} );
}
public void dispose()
{
dm.removeDiscoveryListener( this );
}
public void discovered( DiscoveryEvent e )
{
System.out.println( "Discovered: " + e.getGroups() );
}
public void discarded( DiscoveryEvent e )
{
System.out.println( "Discarded: " + e.getGroups() );
}
}
private static class EntryIterator
implements Iterator<String>
{
private MatchSet matchSet;
private StorageEntry nextEntry;
public EntryIterator( MatchSet matchSet )
{
this.matchSet = matchSet;
try
{
nextEntry = getNext( matchSet );
}
catch( RemoteException e )
{
e.printStackTrace();
}
catch( UnusableEntryException e )
{
e.printStackTrace();
}
}
private StorageEntry getNext( MatchSet matchSet )
throws RemoteException, UnusableEntryException
{
StorageEntry storageEntry = (StorageEntry) matchSet.next();
return storageEntry;
}
public boolean hasNext()
{
return nextEntry != null;
}
public String next()
{
String result = nextEntry.data();
try
{
nextEntry = getNext( matchSet );
}
catch( RemoteException e )
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
catch( UnusableEntryException e )
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return result;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
}
| 15,822 | 0.532533 | 0.529122 | 483 | 31.774326 | 26.678921 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459627 | false | false | 5 |
0e1e6591bd4c15d7e8358eb4430f59c670f24359 | 29,678,224,039,085 | 7e7341775f9a648aedcb9977efdf45e33759f391 | /app/src/main/java/cn/ubia/interfaceManager/ZigbeeInfoCallBackInterface.java | eecdc4f6091d2f94d74c135c07d772efdfaa2533 | []
| no_license | ybbxk119/ubell-test | https://github.com/ybbxk119/ubell-test | c8da13231055d4126098ef8e3f620b4f62ea9c2a | de434ef2b936e8ca71e4df5dfe2f44b900c9f009 | refs/heads/master | 2020-03-27T17:14:23.356000 | 2018-08-31T07:06:50 | 2018-08-31T07:06:50 | 146,838,134 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.ubia.interfaceManager;
import cn.ubia.bean.ZigbeeInfo;
/**
* @author dftx
*
*/
public interface ZigbeeInfoCallBackInterface {
void ZigbeeInfocallback(ZigbeeInfo mZigbeeInfo );
}
| UTF-8 | Java | 206 | java | ZigbeeInfoCallBackInterface.java | Java | [
{
"context": "mport cn.ubia.bean.ZigbeeInfo;\n\n \n \n/**\n * @author dftx\n *\n */\npublic interface ZigbeeInfoCallBackInterfa",
"end": 91,
"score": 0.999678373336792,
"start": 87,
"tag": "USERNAME",
"value": "dftx"
}
]
| null | []
| package cn.ubia.interfaceManager;
import cn.ubia.bean.ZigbeeInfo;
/**
* @author dftx
*
*/
public interface ZigbeeInfoCallBackInterface {
void ZigbeeInfocallback(ZigbeeInfo mZigbeeInfo );
}
| 206 | 0.728155 | 0.728155 | 15 | 12.733334 | 17.879101 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.266667 | false | false | 5 |
f5328a62913150de77692fdec881222beb1a1401 | 4,887,672,810,880 | 250af2b1f3f6dd945ca5e9a968f8f5fb153918fe | /sdk/src/main/java/com/jxtii/solr/utils/HandleEntity.java | f0b0bcd0b3ac03ed75175108231879c2ded43d94 | []
| no_license | milkbrother1988/SolrSearch | https://github.com/milkbrother1988/SolrSearch | c7b62015aabf890b7e1bb229b7ccc8d9229dc8a6 | dd0be951e7914c57296c332df4d8a400cc9fff87 | refs/heads/master | 2021-12-22T15:55:52.372000 | 2017-10-16T13:48:03 | 2017-10-16T13:48:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jxtii.solr.utils;
import com.jxtii.solr.annotation.FieldType;
import com.jxtii.solr.annotation.SolrField;
import com.jxtii.solr.entity.SolrContent;
import org.joda.time.JodaTimePermission;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 将实体转换成统一类型
* @date 17/7/8.
* @author guolf
*/
public class HandleEntity<T> {
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public SolrContent getContent(Class<?> cls) {
SolrContent content = new SolrContent();
Map map = new HashMap<>();
while (cls != null) {
Field[] fs = cls.getDeclaredFields();
for (Field f : fs) {
SolrField solrField = f.getAnnotation(SolrField.class);
if (solrField != null) {
if (solrField.type() == FieldType.NORMAL) {
Object value = Reflections.invokeGetter(getData(), f.getName());
if(f.getType() == Date.class){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
map.put(f.getName(), simpleDateFormat.format(value));
} else {
map.put(f.getName(), value);
}
} else if (solrField.type() == FieldType.PRIMARY) {
String value = Reflections.invokeGetter(getData(), f.getName()) + "";
content.setId(value);
} else if (solrField.type() == FieldType.FILE) {
String value = Reflections.invokeGetter(getData(), f.getName()) + "";
content.setFilePath(value);
}
}
}
cls = cls.getSuperclass();
}
content.setData(map);
return content;
}
}
| UTF-8 | Java | 2,058 | java | HandleEntity.java | Java | [
{
"context": "ap;\n\n/**\n * 将实体转换成统一类型\n * @date 17/7/8.\n * @author guolf\n */\npublic class HandleEntity<T> {\n\n private T",
"end": 393,
"score": 0.9996446371078491,
"start": 388,
"tag": "USERNAME",
"value": "guolf"
}
]
| null | []
| package com.jxtii.solr.utils;
import com.jxtii.solr.annotation.FieldType;
import com.jxtii.solr.annotation.SolrField;
import com.jxtii.solr.entity.SolrContent;
import org.joda.time.JodaTimePermission;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 将实体转换成统一类型
* @date 17/7/8.
* @author guolf
*/
public class HandleEntity<T> {
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public SolrContent getContent(Class<?> cls) {
SolrContent content = new SolrContent();
Map map = new HashMap<>();
while (cls != null) {
Field[] fs = cls.getDeclaredFields();
for (Field f : fs) {
SolrField solrField = f.getAnnotation(SolrField.class);
if (solrField != null) {
if (solrField.type() == FieldType.NORMAL) {
Object value = Reflections.invokeGetter(getData(), f.getName());
if(f.getType() == Date.class){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
map.put(f.getName(), simpleDateFormat.format(value));
} else {
map.put(f.getName(), value);
}
} else if (solrField.type() == FieldType.PRIMARY) {
String value = Reflections.invokeGetter(getData(), f.getName()) + "";
content.setId(value);
} else if (solrField.type() == FieldType.FILE) {
String value = Reflections.invokeGetter(getData(), f.getName()) + "";
content.setFilePath(value);
}
}
}
cls = cls.getSuperclass();
}
content.setData(map);
return content;
}
}
| 2,058 | 0.52895 | 0.526987 | 61 | 32.409836 | 26.217487 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540984 | false | false | 5 |
182e32a16165d13d06b966c50e5c489793e5f77a | 3,350,074,519,398 | 945aefa06c668939423aa38ce0f3f07b8baea68d | /sc_consumer_order_hystrix/src/main/java/com/meijindeng/service/OrderHystrixService.java | 12062336e2a24639f48a5b30099af2d881304d2e | []
| no_license | meijindeng/springcloud_learning | https://github.com/meijindeng/springcloud_learning | 666e00f33caa648d15b303fce9c0ffffc4eaa39b | b17fb64993167b47ed8521d0d7687281d9a6f12f | refs/heads/master | 2023-07-17T02:39:20.441000 | 2021-09-10T02:40:58 | 2021-09-10T02:40:58 | 403,526,698 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.meijindeng.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @description: OrderHystrixService
* @Author: dengmeijin
* @Date: 2021/9/8 10:01
*/
@Component
@FeignClient(value = "SC-PROVIDER-PAYMENT-HYSTRIX")
public interface OrderHystrixService {
/**
* 正常访问
* @param id
* @return
*/
@GetMapping("/payment/hystrix/ok/{id}")
String paymentInfo_OK(@PathVariable("id") Integer id);
/**
* 超时访问
* @param id
* @return
*/
@GetMapping("/payment/hystrix/timeout/{id}")
String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}
| UTF-8 | Java | 810 | java | OrderHystrixService.java | Java | [
{
"context": "*\n * @description: OrderHystrixService\n * @Author: dengmeijin\n * @Date: 2021/9/8 10:01\n */\n@Component\n@FeignCli",
"end": 322,
"score": 0.9994824528694153,
"start": 312,
"tag": "USERNAME",
"value": "dengmeijin"
}
]
| null | []
| package com.meijindeng.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @description: OrderHystrixService
* @Author: dengmeijin
* @Date: 2021/9/8 10:01
*/
@Component
@FeignClient(value = "SC-PROVIDER-PAYMENT-HYSTRIX")
public interface OrderHystrixService {
/**
* 正常访问
* @param id
* @return
*/
@GetMapping("/payment/hystrix/ok/{id}")
String paymentInfo_OK(@PathVariable("id") Integer id);
/**
* 超时访问
* @param id
* @return
*/
@GetMapping("/payment/hystrix/timeout/{id}")
String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}
| 810 | 0.692695 | 0.680101 | 32 | 23.8125 | 21.255054 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.21875 | false | false | 5 |
3636823d671ab8e2fc671b74ee57b7fcf8ac30b8 | 22,892,175,712,035 | 680d0cdf2207f8e5c5bf9e91df1ff6dac1285254 | /src/test/java/org/giiwa/dao/XTest.java | 048ea2eb7b00aca7766e5f84f67b2ff31248cd22 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | giiwa/giiwa | https://github.com/giiwa/giiwa | e16a90ab566c4bf8ad31ef15f2226a1364447705 | b57a063ebe07a2a6f82f6c2902ad2cdae0343390 | refs/heads/master | 2023-03-10T17:44:28.802000 | 2022-10-28T06:59:36 | 2022-10-28T06:59:36 | 61,117,349 | 62 | 26 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.giiwa.dao;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.giiwa.engine.JS;
import org.giiwa.json.JSON;
import org.giiwa.task.Task;
import org.junit.Test;
public class XTest {
@Test
public void test() {
String s = "a-c";
char[] ss = X.range2(s, "-");
System.out.println(Arrays.toString(ss));
System.out.println(X.toLong("9700262001", -1));
}
@Test
public void testTo() {
double d = 6.462212122;
System.out.println(X.toFloat(d, 0));
}
@Test
public void testClone() {
JSON j1 = JSON.create();
j1.append("a", JSON.create().append("b", 1));
JSON j2 = X.clone(j1);
Task t1 = new Task() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void onExecute() {
// TODO Auto-generated method stub
}
};
JSON j4 = j1.append("_task", t1);
JSON j3 = X.clone(j4);
System.out.println("j1=" + j1);
System.out.println("j2=" + j2);
System.out.println("j3=" + j3.get("_task"));
System.out.println("j4=" + j4);
System.out.println("t1=" + t1);
Task t2 = X.clone(t1);
System.out.println("t2=" + t2);
}
@Test
public void testToLong() {
String d = "1.63E+12";
System.out.println(X.toLong(X.toDouble(d)));
}
@Test
public void isSame() {
byte[] s1 = new byte[] { 78, 94, 115, -92, -59, 125, 89, -116, 127, 25, -66, 108, 88, -11, 71, -9, -34, -5,
-110, 54 };
byte[] s2 = new byte[] { 78, 94, 115, -92, -59, 125, 89, -116, 127, 25, -66, 108, 88, -11, 71, -9, -34, -5,
-110, 54 };
System.out.println(X.isSame(s1, s2));
}
@Test
public void testToLong1() {
double d = 11.5;
System.out.println(X.toLong(d));
}
@Test
public void testInt() {
String s = "1212131122122222122212";
System.out.println(X.toInt(s, 0));
}
@Test
public void testAsList() {
try {
String js = "var l1=[1,2,3,[1,2]];l1;";
Object o = JS.run(js);
System.out.println(o.getClass());
List l2 = X.asList(o, e1 -> e1);
System.out.println(l2.size());
} catch (Exception e) {
e.printStackTrace();
}
// X.asList(o, e1->e1);
}
@Test
public void testIsSame() {
List<String> l1 = new ArrayList<String>();
List<String> l2 = new ArrayList<String>();
l1.add("a");
l1.add("b");
l2.add("b");
l2.add("a");
System.out.println(X.isSame(l1, l2));
}
@Test
public void testSize() {
String s = "4g";
System.out.println(X.inst.size(s));
}
}
| UTF-8 | Java | 2,435 | java | XTest.java | Java | []
| null | []
| package org.giiwa.dao;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.giiwa.engine.JS;
import org.giiwa.json.JSON;
import org.giiwa.task.Task;
import org.junit.Test;
public class XTest {
@Test
public void test() {
String s = "a-c";
char[] ss = X.range2(s, "-");
System.out.println(Arrays.toString(ss));
System.out.println(X.toLong("9700262001", -1));
}
@Test
public void testTo() {
double d = 6.462212122;
System.out.println(X.toFloat(d, 0));
}
@Test
public void testClone() {
JSON j1 = JSON.create();
j1.append("a", JSON.create().append("b", 1));
JSON j2 = X.clone(j1);
Task t1 = new Task() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void onExecute() {
// TODO Auto-generated method stub
}
};
JSON j4 = j1.append("_task", t1);
JSON j3 = X.clone(j4);
System.out.println("j1=" + j1);
System.out.println("j2=" + j2);
System.out.println("j3=" + j3.get("_task"));
System.out.println("j4=" + j4);
System.out.println("t1=" + t1);
Task t2 = X.clone(t1);
System.out.println("t2=" + t2);
}
@Test
public void testToLong() {
String d = "1.63E+12";
System.out.println(X.toLong(X.toDouble(d)));
}
@Test
public void isSame() {
byte[] s1 = new byte[] { 78, 94, 115, -92, -59, 125, 89, -116, 127, 25, -66, 108, 88, -11, 71, -9, -34, -5,
-110, 54 };
byte[] s2 = new byte[] { 78, 94, 115, -92, -59, 125, 89, -116, 127, 25, -66, 108, 88, -11, 71, -9, -34, -5,
-110, 54 };
System.out.println(X.isSame(s1, s2));
}
@Test
public void testToLong1() {
double d = 11.5;
System.out.println(X.toLong(d));
}
@Test
public void testInt() {
String s = "1212131122122222122212";
System.out.println(X.toInt(s, 0));
}
@Test
public void testAsList() {
try {
String js = "var l1=[1,2,3,[1,2]];l1;";
Object o = JS.run(js);
System.out.println(o.getClass());
List l2 = X.asList(o, e1 -> e1);
System.out.println(l2.size());
} catch (Exception e) {
e.printStackTrace();
}
// X.asList(o, e1->e1);
}
@Test
public void testIsSame() {
List<String> l1 = new ArrayList<String>();
List<String> l2 = new ArrayList<String>();
l1.add("a");
l1.add("b");
l2.add("b");
l2.add("a");
System.out.println(X.isSame(l1, l2));
}
@Test
public void testSize() {
String s = "4g";
System.out.println(X.inst.size(s));
}
}
| 2,435 | 0.589733 | 0.509651 | 137 | 16.773722 | 18.813721 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.992701 | false | false | 5 |
804cd78f634ecb79dce262d42af89ccfc5414bf7 | 9,663,676,441,777 | 7ad31a709dbd3da156a81c72e587b93d6fbeae0b | /src/Day327baozhuang/HelloWorld1.java | 2e23d1ffff020140473ad82f02e7fb8dabde35ce | []
| no_license | kzr1998/javaweb-practice | https://github.com/kzr1998/javaweb-practice | 64fd42ba4c4a73d7fbf4dbbb95239f230ada8e27 | 6ea5d405fbb2d111c533bfa9a23ca2631014ba66 | refs/heads/master | 2020-04-28T05:05:27.067000 | 2019-05-04T14:11:00 | 2019-05-04T14:11:00 | 175,006,823 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Day327baozhuang;
public class HelloWorld1 {
public static void main(String[] args) {
//定义float类型变量,赋值为88.99
float f1 =88.99f;
//将基本类型转换为字符串
String s=Float.toString(f1);
s+=20;
//打印输出
System.out.println("f1转换为String型后与整数20的求和结果为:"+s);
//定义String类型变量,赋值为"188.55"
String str = "188.55";
// 将字符串转换为基本类型double
Double b=Double.parseDouble(str);
b+=20;
//打印输出
System.out.println("str转换为double型后与整数20的求和结果为"+b);
}
}
| UTF-8 | Java | 687 | java | HelloWorld1.java | Java | []
| null | []
| package Day327baozhuang;
public class HelloWorld1 {
public static void main(String[] args) {
//定义float类型变量,赋值为88.99
float f1 =88.99f;
//将基本类型转换为字符串
String s=Float.toString(f1);
s+=20;
//打印输出
System.out.println("f1转换为String型后与整数20的求和结果为:"+s);
//定义String类型变量,赋值为"188.55"
String str = "188.55";
// 将字符串转换为基本类型double
Double b=Double.parseDouble(str);
b+=20;
//打印输出
System.out.println("str转换为double型后与整数20的求和结果为"+b);
}
}
| 687 | 0.589792 | 0.52741 | 20 | 25.450001 | 15.441746 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 5 |
d9be19c552dcdc8d95809da64be04958d8399d5f | 14,224,931,716,451 | cd1bbfeb61bff4659763847ffc5f44d9c704fa80 | /PokerClient/PokerClient/src/actions/SmallBlind.java | 5de093c728f3b92cd555d7154edc2213ddf3cde4 | [
"MIT"
]
| permissive | Rita96/Progetto-J | https://github.com/Rita96/Progetto-J | e0575a2aa03f6ef6900f4f9c1cf32b492bf44da3 | d8eec35644dbee4a0f59f32874b6bc3ff7d2e05c | refs/heads/master | 2021-04-06T05:42:16.737000 | 2017-07-12T16:16:17 | 2017-07-12T16:16:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package actions;
/**
* Classe che rappresenta il piccolo buio
*/
public class SmallBlind extends Action {
/**
* Costruttore della classe SmallBlind
* @param amount valore del piccolo buio
*/
public SmallBlind(int amount) {
super("Small Blind", "paga small blind", amount);
this.actionType = ActionSet.SMALL_BLIND;
}
}
| UTF-8 | Java | 365 | java | SmallBlind.java | Java | []
| null | []
| package actions;
/**
* Classe che rappresenta il piccolo buio
*/
public class SmallBlind extends Action {
/**
* Costruttore della classe SmallBlind
* @param amount valore del piccolo buio
*/
public SmallBlind(int amount) {
super("Small Blind", "paga small blind", amount);
this.actionType = ActionSet.SMALL_BLIND;
}
}
| 365 | 0.649315 | 0.649315 | 16 | 21.8125 | 20.224424 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 5 |
94cd4dd4da41ec7d3eca85ab177c3c0117c2cc15 | 22,196,391,016,680 | 3ad1de95897807b78de0d1411448a621e7c57858 | /springboot/todolist/src/main/java/com/nkanyang/todolist/TodoListService.java | d417fb8c58abeec196ce141081a45b658ebc9758 | []
| no_license | nkanyang/java | https://github.com/nkanyang/java | faeadfa958c932aa02e03be81f9cd8d4ed948f50 | 0ed2954a7be0d2cffeaf0b7248b1510068648e2c | refs/heads/master | 2022-12-15T19:34:21.910000 | 2020-08-23T09:06:51 | 2020-08-23T09:06:51 | 265,101,007 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nkanyang.todolist;
import com.nkanyang.todolist.model.TodoItem;
import com.nkanyang.todolist.model.TodoListDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class TodoListService {
@Autowired
private TodoListRepository todoListRepository;
public TodoListDto getAllItems() {
TodoListDto todoList = new TodoListDto();
List<TodoItem> list = (List<TodoItem>)todoListRepository.findAll();
todoList.setTodoItemList(list);
return todoList;
}
public TodoListDto getItems(boolean isDone) {
TodoListDto todoList = new TodoListDto();
List<TodoItem> list = null;
if(isDone) {
list = todoListRepository.findByDoneTrue();
}
else{
list = todoListRepository.findByDoneFalse();
}
todoList.setTodoItemList(list);
return todoList;
}
public TodoItem addTodoItem(TodoItem todoItem) {
todoListRepository.save(todoItem);
return todoItem;
}
public void updateTodoItem(TodoItem todoItem) {
todoListRepository.save(todoItem);
}
public void deleteTodoItem(TodoItem todoItem) {
todoListRepository.delete(todoItem);
}
}
| UTF-8 | Java | 1,343 | java | TodoListService.java | Java | []
| null | []
| package com.nkanyang.todolist;
import com.nkanyang.todolist.model.TodoItem;
import com.nkanyang.todolist.model.TodoListDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class TodoListService {
@Autowired
private TodoListRepository todoListRepository;
public TodoListDto getAllItems() {
TodoListDto todoList = new TodoListDto();
List<TodoItem> list = (List<TodoItem>)todoListRepository.findAll();
todoList.setTodoItemList(list);
return todoList;
}
public TodoListDto getItems(boolean isDone) {
TodoListDto todoList = new TodoListDto();
List<TodoItem> list = null;
if(isDone) {
list = todoListRepository.findByDoneTrue();
}
else{
list = todoListRepository.findByDoneFalse();
}
todoList.setTodoItemList(list);
return todoList;
}
public TodoItem addTodoItem(TodoItem todoItem) {
todoListRepository.save(todoItem);
return todoItem;
}
public void updateTodoItem(TodoItem todoItem) {
todoListRepository.save(todoItem);
}
public void deleteTodoItem(TodoItem todoItem) {
todoListRepository.delete(todoItem);
}
}
| 1,343 | 0.689501 | 0.689501 | 49 | 26.408163 | 21.31007 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44898 | false | false | 5 |
b32bff89302ed1ed947c056bcf132cbc605b5cd8 | 28,071,906,273,484 | a23f622b604a5cc95a43bcccf3ae858d6c04b7f1 | /src/main/java/diamond/cms/server/mvc/aspect/CommentEmailNoticeAspect.java | 1e4a81947ab065fb502e7678aa6a436a04e784f6 | []
| no_license | soulhez/cms-admin-end | https://github.com/soulhez/cms-admin-end | a6f5459fbe9b923bbbc479f020684f97ea7aeef4 | 40689458c9cce66818636be5effc47213098b960 | refs/heads/master | 2022-02-12T12:02:28.886000 | 2019-07-17T02:16:54 | 2019-07-17T02:16:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package diamond.cms.server.mvc.aspect;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Resource;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import diamond.cms.server.model.Comment;
import diamond.cms.server.model.User;
import diamond.cms.server.services.ArticleService;
import diamond.cms.server.services.CommentService;
import diamond.cms.server.services.EmailSendService;
import diamond.cms.server.services.UserService;
import diamond.cms.server.utils.TemplateRenderUtil;
import diamond.cms.server.utils.ValidateUtils;
@Component
@Aspect
public class CommentEmailNoticeAspect{
public static String COMMENT_NOTICE_TEMP = "/email-template/CommentNoticeTemplate.html";
public static String REPLY_NOTICE_TEMP = "/email-template/ReplyCommentNoticeTemplate.html";
@Resource
UserService userService;
@Resource
EmailSendService emailSendService;
@Resource
ArticleService articleService;
@Resource
CommentService commentService;
Logger log = LoggerFactory.getLogger(getClass());
@AfterReturning(returning="comment", pointcut="execution(* diamond.cms.server.mvc.controllers.CommentController.saveComment(..))")
public void after(Comment comment) {
CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
try {
User admin = userService.findAdmin();
if (admin != null) {
String artTitle = articleService.getTitle(comment.getArticleId());
comment.setArticleTitle(artTitle);
try {
String emailContent = TemplateRenderUtil.renderResource(COMMENT_NOTICE_TEMP, comment);
emailSendService.sendEmail(admin.getUsername(), "Blog Comment Notice", emailContent, "comment-notice-" + comment.getId());
} catch (IOException e) {
log.error("template render error, send email after comment faild", e);
}
}
} catch(Exception e) {
log.error("send comment notice email faild", e);
}
}
});
}
@AfterReturning(returning="comment", pointcut="execution(* diamond.cms.server.mvc.controllers.CommentController.replyComment(..))")
public void afterReply(Comment comment) {
CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
try {
Comment byReplyComment = commentService.get(comment.getReplyId());
String toEmail = byReplyComment.getEmail();
if (ValidateUtils.isEmail(toEmail)) {
String articleTitle = articleService.getTitle(comment.getArticleId());
comment.setArticleTitle(articleTitle);
try {
String emailContent = TemplateRenderUtil.renderResource(REPLY_NOTICE_TEMP, comment);
emailSendService.sendEmail(toEmail, "Comment Reply Notice", emailContent, "comment-reply-" + comment.getId());
} catch (IOException e) {
log.error("template render error, send email reply comment faild", e);
}
}
} catch (Exception e) {
log.error("send comment reply email faild", e);
}
}
});
}
}
| UTF-8 | Java | 3,868 | java | CommentEmailNoticeAspect.java | Java | []
| null | []
| package diamond.cms.server.mvc.aspect;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Resource;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import diamond.cms.server.model.Comment;
import diamond.cms.server.model.User;
import diamond.cms.server.services.ArticleService;
import diamond.cms.server.services.CommentService;
import diamond.cms.server.services.EmailSendService;
import diamond.cms.server.services.UserService;
import diamond.cms.server.utils.TemplateRenderUtil;
import diamond.cms.server.utils.ValidateUtils;
@Component
@Aspect
public class CommentEmailNoticeAspect{
public static String COMMENT_NOTICE_TEMP = "/email-template/CommentNoticeTemplate.html";
public static String REPLY_NOTICE_TEMP = "/email-template/ReplyCommentNoticeTemplate.html";
@Resource
UserService userService;
@Resource
EmailSendService emailSendService;
@Resource
ArticleService articleService;
@Resource
CommentService commentService;
Logger log = LoggerFactory.getLogger(getClass());
@AfterReturning(returning="comment", pointcut="execution(* diamond.cms.server.mvc.controllers.CommentController.saveComment(..))")
public void after(Comment comment) {
CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
try {
User admin = userService.findAdmin();
if (admin != null) {
String artTitle = articleService.getTitle(comment.getArticleId());
comment.setArticleTitle(artTitle);
try {
String emailContent = TemplateRenderUtil.renderResource(COMMENT_NOTICE_TEMP, comment);
emailSendService.sendEmail(admin.getUsername(), "Blog Comment Notice", emailContent, "comment-notice-" + comment.getId());
} catch (IOException e) {
log.error("template render error, send email after comment faild", e);
}
}
} catch(Exception e) {
log.error("send comment notice email faild", e);
}
}
});
}
@AfterReturning(returning="comment", pointcut="execution(* diamond.cms.server.mvc.controllers.CommentController.replyComment(..))")
public void afterReply(Comment comment) {
CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
try {
Comment byReplyComment = commentService.get(comment.getReplyId());
String toEmail = byReplyComment.getEmail();
if (ValidateUtils.isEmail(toEmail)) {
String articleTitle = articleService.getTitle(comment.getArticleId());
comment.setArticleTitle(articleTitle);
try {
String emailContent = TemplateRenderUtil.renderResource(REPLY_NOTICE_TEMP, comment);
emailSendService.sendEmail(toEmail, "Comment Reply Notice", emailContent, "comment-reply-" + comment.getId());
} catch (IOException e) {
log.error("template render error, send email reply comment faild", e);
}
}
} catch (Exception e) {
log.error("send comment reply email faild", e);
}
}
});
}
}
| 3,868 | 0.596432 | 0.595915 | 89 | 41.460674 | 34.627735 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.640449 | false | false | 5 |
ddb03e1044ec7b0437f14e37f4545fd7e225efe3 | 23,012,434,804,339 | d7d58df4d95080b80cab4f5668302563cdee05c9 | /privately/app/src/main/java/com/zsoe/businesssharing/bean/SearchBean.java | a28658b3ae2d6fa064ed471c54f0ca2963d9c9b2 | []
| no_license | gaowenjie12/app-and | https://github.com/gaowenjie12/app-and | 6c1a4b92e192c8cf85ce329ef82575428cc5e8b3 | 673b94020adb11100d075e2082fe9f9f30316f61 | refs/heads/master | 2020-06-30T22:31:39.678000 | 2019-12-24T09:44:29 | 2019-12-24T09:44:29 | 200,968,166 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zsoe.businesssharing.bean;
/**
* @author 于长亮 & E-mail: yuchangl3757@qq.com
* @create_time 创建时间:2019-09-23 13:17
* @version:
* @类说明:
*/
public class SearchBean {
private int id;
private String title;
private String thumb;
private int contenttype;
private String contenttypedes;
private String linkurl;
public String getLinkurl() {
return linkurl;
}
public void setLinkurl(String linkurl) {
this.linkurl = linkurl;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
public String getThumb() {
return thumb;
}
public void setContenttype(int contenttype) {
this.contenttype = contenttype;
}
public int getContenttype() {
return contenttype;
}
public void setContenttypedes(String contenttypedes) {
this.contenttypedes = contenttypedes;
}
public String getContenttypedes() {
return contenttypedes;
}
} | UTF-8 | Java | 1,259 | java | SearchBean.java | Java | [
{
"context": "ge com.zsoe.businesssharing.bean;\n\n/**\n * @author 于长亮 & E-mail: yuchangl3757@qq.com\n * @create_time 创",
"end": 58,
"score": 0.9885740280151367,
"start": 55,
"tag": "NAME",
"value": "于长亮"
},
{
"context": "inesssharing.bean;\n\n/**\n * @author 于长亮 & E-mail: yuchangl3757@qq.com\n * @create_time 创建时间:2019-09-23 13:17\n * @version",
"end": 90,
"score": 0.9999290108680725,
"start": 71,
"tag": "EMAIL",
"value": "yuchangl3757@qq.com"
}
]
| null | []
| package com.zsoe.businesssharing.bean;
/**
* @author 于长亮 & E-mail: <EMAIL>
* @create_time 创建时间:2019-09-23 13:17
* @version:
* @类说明:
*/
public class SearchBean {
private int id;
private String title;
private String thumb;
private int contenttype;
private String contenttypedes;
private String linkurl;
public String getLinkurl() {
return linkurl;
}
public void setLinkurl(String linkurl) {
this.linkurl = linkurl;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
public String getThumb() {
return thumb;
}
public void setContenttype(int contenttype) {
this.contenttype = contenttype;
}
public int getContenttype() {
return contenttype;
}
public void setContenttypedes(String contenttypedes) {
this.contenttypedes = contenttypedes;
}
public String getContenttypedes() {
return contenttypedes;
}
} | 1,247 | 0.608731 | 0.595796 | 67 | 17.477612 | 16.178444 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.283582 | false | false | 5 |
6a9d3611b10fd08395313f3c2d2a45fd492f3f8b | 23,012,434,802,207 | fd2b4f1a5524d2a343b53ca23e190fbd3a1bedec | /src/main/java/ac/ca/cput/model/people/PharmacyClerk.java | 0ddd36cce1f2bf82266741c2affa8e3f00d6971f | []
| no_license | MatthewMarkBrown/PharmacyApp | https://github.com/MatthewMarkBrown/PharmacyApp | 16b4313d7018f512f7c1ba1d4cc0fe9cb529ebaa | 19a7f4641a4e8a2ced408729258d1a59c889d23c | refs/heads/master | 2021-07-04T11:57:20.329000 | 2019-10-21T15:11:20 | 2019-10-21T15:11:20 | 180,533,336 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ac.ca.cput.model.people;
import java.util.Objects;
public class PharmacyClerk {
private String clerkId,firstName,lastName;
private PharmacyClerk(){}
private PharmacyClerk(Builder builder) {
this.clerkId = builder.clerkId;
this.firstName = builder.firstName;
this.lastName = builder.lastName;
}
public String getClerkId() {
return clerkId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public static class Builder{
private String clerkId,firstName,lastName;
public Builder clerkId(String clerkId){
this.clerkId = clerkId;
return this;
}
public Builder firstName(String firstName){
this.firstName = firstName;
return this;
}
public Builder lastName(String lastName){
this.lastName = lastName;
return this;
}
public PharmacyClerk.Builder copy(PharmacyClerk pharmacyClerk){
this.clerkId = pharmacyClerk.clerkId;
this.firstName = pharmacyClerk.firstName;
this.lastName = pharmacyClerk.lastName;
return this;
}
public PharmacyClerk build() {
return new PharmacyClerk(this);
}
}
@Override
public String toString() {
return "PharmacyClerk{" +
"clerkId='" + clerkId + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PharmacyClerk that = (PharmacyClerk) o;
return Objects.equals(clerkId, that.clerkId) &&
Objects.equals(firstName, that.firstName) &&
Objects.equals(lastName, that.lastName);
}
@Override
public int hashCode() {
return Objects.hash(clerkId, firstName, lastName);
}
}
| UTF-8 | Java | 2,075 | java | PharmacyClerk.java | Java | [
{
"context": "clerkId + '\\'' +\n \", firstName='\" + firstName + '\\'' +\n \", lastName='\" + lastNam",
"end": 1493,
"score": 0.9110011458396912,
"start": 1484,
"tag": "NAME",
"value": "firstName"
},
{
"context": " hashCode() {\n return Objects.hash(clerkId, firstName, lastName);\n }\n}\n",
"end": 2054,
"score": 0.9989817142486572,
"start": 2045,
"tag": "NAME",
"value": "firstName"
},
{
"context": " {\n return Objects.hash(clerkId, firstName, lastName);\n }\n}\n",
"end": 2064,
"score": 0.99909508228302,
"start": 2056,
"tag": "NAME",
"value": "lastName"
}
]
| null | []
| package ac.ca.cput.model.people;
import java.util.Objects;
public class PharmacyClerk {
private String clerkId,firstName,lastName;
private PharmacyClerk(){}
private PharmacyClerk(Builder builder) {
this.clerkId = builder.clerkId;
this.firstName = builder.firstName;
this.lastName = builder.lastName;
}
public String getClerkId() {
return clerkId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public static class Builder{
private String clerkId,firstName,lastName;
public Builder clerkId(String clerkId){
this.clerkId = clerkId;
return this;
}
public Builder firstName(String firstName){
this.firstName = firstName;
return this;
}
public Builder lastName(String lastName){
this.lastName = lastName;
return this;
}
public PharmacyClerk.Builder copy(PharmacyClerk pharmacyClerk){
this.clerkId = pharmacyClerk.clerkId;
this.firstName = pharmacyClerk.firstName;
this.lastName = pharmacyClerk.lastName;
return this;
}
public PharmacyClerk build() {
return new PharmacyClerk(this);
}
}
@Override
public String toString() {
return "PharmacyClerk{" +
"clerkId='" + clerkId + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PharmacyClerk that = (PharmacyClerk) o;
return Objects.equals(clerkId, that.clerkId) &&
Objects.equals(firstName, that.firstName) &&
Objects.equals(lastName, that.lastName);
}
@Override
public int hashCode() {
return Objects.hash(clerkId, firstName, lastName);
}
}
| 2,075 | 0.582169 | 0.582169 | 82 | 24.304878 | 20.216324 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.487805 | false | false | 5 |
43f3361a70cc830d7049398191a00e02046c7396 | 14,688,788,186,635 | 5449824379ef6828cf3dacafe2ab4ab720f663f5 | /app/src/main/java/byou/yadun/wallet/wallet/LoginActivity.java | 90156a5673e15aed3dbaa9246683482a168253dc | []
| no_license | Xdone111/beyou | https://github.com/Xdone111/beyou | 38735050db0b1daa224cc4064c0858eefc68fb84 | f24acc510070b108f954e4ff1515c4918a322962 | refs/heads/master | 2020-03-17T00:38:40.571000 | 2018-05-12T07:56:17 | 2018-05-12T07:56:17 | 133,125,004 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package byou.yadun.wallet.wallet;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.squareup.okhttp.Request;
import byou.yadun.wallet.MainActivity;
import byou.yadun.wallet.MyApplication;
import byou.yadun.wallet.R;
import byou.yadun.wallet.adapter.MyMainWalletAdapter;
import byou.yadun.wallet.entity.CreateWalletAddressBean;
import byou.yadun.wallet.entity.MyMainWalletBean;
import byou.yadun.wallet.entity.UserResponse;
import byou.yadun.wallet.manager.HttpManager;
import byou.yadun.wallet.utils.JsonUtil;
import byou.yadun.wallet.utils.MyMD5;
import byou.yadun.wallet.utils.NetUtils;
import byou.yadun.wallet.utils.PreferenceUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 登陆页面
*/
public class LoginActivity extends BaseActivity implements View.OnClickListener {
private EditText mEdtUserName;
private EditText mEdtPS;
private Button mBtnLogin;
private Button mBtnSwitch;
private TextView mTxtRegister;
private TextView mTxtForgetPs;
private ImageView mImgShowPS;
private ImageView mImgHidePS;
private Dialog mDialog;
private PreferenceUtil manager;
private List mycointypelist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initView();
initEvent();
}
private void initView() {
manager = new PreferenceUtil();
mEdtUserName = (EditText) findViewById(R.id.edtUserAccount);
mEdtPS = (EditText) findViewById(R.id.edtUserPS);
mBtnLogin = (Button) findViewById(R.id.btnLogin);
mTxtForgetPs = (TextView) findViewById(R.id.txtForgetPs);
mTxtRegister = (TextView) findViewById(R.id.txtRegister);
mImgHidePS = (ImageView) findViewById(R.id.imgHidePs);
mImgShowPS = (ImageView) findViewById(R.id.imgShowPs);
mBtnSwitch = (Button) findViewById(R.id.btnSwitch);
mycointypelist = new ArrayList();
if (manager.getUser("account") != null) {
mEdtUserName.setText(manager.getUser("account"));
}
if (manager.getUser("password") != null) {
mEdtPS.setText(manager.getUser("password"));
}
//登录过
if (PreferenceUtil.getInt("hadlogined", 0) == 1998) {
if (manager.getUser("account") != null && manager.getUser("password") != null) {
login();
return;
}
}
}
private void initEvent() {
mEdtUserName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mEdtPS.setText("");
}
@Override
public void afterTextChanged(Editable s) {
}
});
mBtnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (NetUtils.isNetworkAvailable(LoginActivity.this)) {
login();
} else {
showToast(getResources().getString(R.string.forbidden_net));
}
}
});
mTxtForgetPs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgetPasswordActivity.class));
}
});
mTxtRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
mImgHidePS.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mImgHidePS.setVisibility(View.GONE);
mImgShowPS.setVisibility(View.VISIBLE);
mEdtPS.setTransformationMethod(PasswordTransformationMethod.getInstance());
mEdtPS.setSelection(mEdtPS.length());
}
});
mImgShowPS.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mImgShowPS.setVisibility(View.GONE);
mImgHidePS.setVisibility(View.VISIBLE);
mEdtPS.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
mEdtPS.setSelection(mEdtPS.length());
}
});
mBtnSwitch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayDialog();
}
});
}
@Override
public void onClick(View v) {
mDialog.dismiss();
switch (v.getId()) {
case R.id.select_english:
switchLanguage("en");
break;
case R.id.select_chinese:
switchLanguage("zh");
break;
case R.id.select_thailand:
switchLanguage("th");
break;
}
//更新语言后,destroy当前页面,重新绘制
finish();
Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
startActivity(intent);
}
private void displayDialog() {
if (mDialog == null) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_select_lanuage, null);
TextView english = (TextView) layout.findViewById(R.id.select_english);
TextView chinese = (TextView) layout.findViewById(R.id.select_chinese);
TextView thailand = (TextView) layout.findViewById(R.id.select_thailand);
mDialog = new Dialog(LoginActivity.this, R.style.Custom_Dialog_Theme);
mDialog.setCanceledOnTouchOutside(false);
english.setOnClickListener(LoginActivity.this);
chinese.setOnClickListener(LoginActivity.this);
thailand.setOnClickListener(LoginActivity.this);
mDialog.setContentView(layout);
}
mDialog.show();
}
public void login() {
Map<String, String> parmas = new HashMap<>();
if (mEdtUserName.getText().toString().trim().isEmpty()) {
showToast(getResources().getString(R.string.login_no_username));
return;
}
if (mEdtPS.getText().toString().trim().isEmpty()) {
showToast(getResources().getString(R.string.login_no_password));
return;
}
try {
parmas.put("username", mEdtUserName.getText().toString());
parmas.put("password", MyMD5.bytesToHex(MyApplication.md5.encrypt(mEdtPS.getText().toString())));
Log.d("加密后登录密码", MyMD5.bytesToHex(MyApplication.md5.encrypt(mEdtPS.getText().toString())));
} catch (Exception e) {
e.printStackTrace();
}
HttpManager.postAsync(HttpManager.BASE_URL + "api.php/base/login_post_json.html?", parmas,
new HttpManager.ResultCallback<UserResponse>() {
@Override
public void onBefore(Request request) {
super.onBefore(request);
showLoadingDialog();
}
@Override
public void onError(Request request, Exception e) {
showToast(getResources().getString(R.string.login_net_fail));
// dismissLoadingDialog();
}
@Override
public void onResponse(UserResponse response) {
Log.e("tag", "_+_+" + response.toString());
if (response.getCode() == 1) {
Log.d("登录成功返回json", response.toString());
String userJson = JsonUtil.toJson(response);
manager.saveUser("userJson", userJson);
UserResponse userResponse = (UserResponse) JsonUtil.read2Object(userJson, UserResponse.class);
PreferenceUtil.commitString("token", userResponse.getToken());
Log.d("done============", userResponse.getToken());
PreferenceUtil.commitString("uid", userResponse.getUid());
manager.saveUser("account", mEdtUserName.getText().toString());
manager.saveUser("password", mEdtPS.getText().toString());
//判断是否登录成功注册过
if (PreferenceUtil.getInt("hadlogin", 1) == 12580) {
loginhy();
} else {
getMainWalletData(userResponse.getUid(), userResponse.getToken());
//注册环信id
try {
registhx(mEdtUserName.getText().toString(), MyMD5.bytesToHex(MyApplication.md5.encrypt(mEdtPS.getText().toString())));
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
showToast(response.getMsg());
dismissLoadingDialog();
}
}
@Override
public void onAfter() {
super.onAfter();
// dismissLoadingDialog();
}
});
}
//注册
public void registhx(final String username, final String pwd) {
new Thread(new Runnable() {
public void run() {
try {
// call method in SDK
EMClient.getInstance().createAccount(username, pwd);
loginhy();
} catch (final HyphenateException e) {
runOnUiThread(new Runnable() {
public void run() {
int errorCode = e.getErrorCode();
if (errorCode == EMError.NETWORK_ERROR) {
Toast.makeText(getApplicationContext(), "网络异常", Toast.LENGTH_SHORT).show();
} else if (errorCode == EMError.USER_ALREADY_EXIST) {
loginhy();
// ToastUtil.showToast("用户已存在1");
} else if (errorCode == EMError.USER_AUTHENTICATION_FAILED) {
Toast.makeText(getApplicationContext(), "无权限", Toast.LENGTH_SHORT).show();
} else if (errorCode == EMError.USER_ILLEGAL_ARGUMENT) {
Toast.makeText(getApplicationContext(), "非法id", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), errorCode + "注册失败", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}).start();
}
public void loginhy() {
//登录环信
try {
EMClient.getInstance().login(mEdtUserName.getText().toString(), MyMD5.bytesToHex(MyApplication.md5.encrypt(mEdtPS.getText().toString())), new EMCallBack() {//回调
@Override
public void onSuccess() {
EMClient.getInstance().groupManager().loadAllGroups();
EMClient.getInstance().chatManager().loadAllConversations();
Log.d("登录", "登录聊天服务器成功!");
PreferenceUtil.commitInt("hadlogin", 12580);
PreferenceUtil.commitInt("hadlogined", 1998);
startActivity(new Intent(LoginActivity.this, MainActivity.class));
dismissLoadingDialog();
finish();
}
@Override
public void onProgress(int progress, String status) {
}
@Override
public void onError(int code, String message) {
Log.d("登录", "登录聊天服务器失败!" + message);
dismissLoadingDialog();
// Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
//创建钱包
public void CreateQB(String coin, String uid, String token) {
Map<String, String> parmas = new HashMap<>();
parmas.put("token", token);
parmas.put("uid", uid);
parmas.put("coin", coin);
HttpManager.postAsync(HttpManager.BASE_URL + "api.php/user/usermyzr.html?", parmas, new HttpManager.ResultCallback<CreateWalletAddressBean>() {
@Override
public void onError(Request request, Exception e) {
}
@Override
public void onResponse(final CreateWalletAddressBean response) {
}
});
}
//获取当前用户所以B种,初始化钱包
public void getMainWalletData(final String uid, final String token) {
Map<String, String> parmas1 = new HashMap<>();
parmas1.put("token", token);
parmas1.put("uid", uid);
HttpManager.postAsync(HttpManager.BASE_URL + "api.php/user/myAssets.html?", parmas1, new HttpManager.ResultCallback<MyMainWalletBean>() {
@Override
public void onError(Request request, Exception e) {
Log.d("折合资产", e.toString());
}
@Override
public void onResponse(MyMainWalletBean response) {
int m = response.getData().getCoin().size();
for (int i = 0; i < m; i++) {
CreateQB(response.getData().getCoin().get(i).getName(), uid, token);
}
}
});
}
}
| UTF-8 | Java | 15,117 | java | LoginActivity.java | Java | []
| null | []
| package byou.yadun.wallet.wallet;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.squareup.okhttp.Request;
import byou.yadun.wallet.MainActivity;
import byou.yadun.wallet.MyApplication;
import byou.yadun.wallet.R;
import byou.yadun.wallet.adapter.MyMainWalletAdapter;
import byou.yadun.wallet.entity.CreateWalletAddressBean;
import byou.yadun.wallet.entity.MyMainWalletBean;
import byou.yadun.wallet.entity.UserResponse;
import byou.yadun.wallet.manager.HttpManager;
import byou.yadun.wallet.utils.JsonUtil;
import byou.yadun.wallet.utils.MyMD5;
import byou.yadun.wallet.utils.NetUtils;
import byou.yadun.wallet.utils.PreferenceUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 登陆页面
*/
public class LoginActivity extends BaseActivity implements View.OnClickListener {
private EditText mEdtUserName;
private EditText mEdtPS;
private Button mBtnLogin;
private Button mBtnSwitch;
private TextView mTxtRegister;
private TextView mTxtForgetPs;
private ImageView mImgShowPS;
private ImageView mImgHidePS;
private Dialog mDialog;
private PreferenceUtil manager;
private List mycointypelist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initView();
initEvent();
}
private void initView() {
manager = new PreferenceUtil();
mEdtUserName = (EditText) findViewById(R.id.edtUserAccount);
mEdtPS = (EditText) findViewById(R.id.edtUserPS);
mBtnLogin = (Button) findViewById(R.id.btnLogin);
mTxtForgetPs = (TextView) findViewById(R.id.txtForgetPs);
mTxtRegister = (TextView) findViewById(R.id.txtRegister);
mImgHidePS = (ImageView) findViewById(R.id.imgHidePs);
mImgShowPS = (ImageView) findViewById(R.id.imgShowPs);
mBtnSwitch = (Button) findViewById(R.id.btnSwitch);
mycointypelist = new ArrayList();
if (manager.getUser("account") != null) {
mEdtUserName.setText(manager.getUser("account"));
}
if (manager.getUser("password") != null) {
mEdtPS.setText(manager.getUser("password"));
}
//登录过
if (PreferenceUtil.getInt("hadlogined", 0) == 1998) {
if (manager.getUser("account") != null && manager.getUser("password") != null) {
login();
return;
}
}
}
private void initEvent() {
mEdtUserName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mEdtPS.setText("");
}
@Override
public void afterTextChanged(Editable s) {
}
});
mBtnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (NetUtils.isNetworkAvailable(LoginActivity.this)) {
login();
} else {
showToast(getResources().getString(R.string.forbidden_net));
}
}
});
mTxtForgetPs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgetPasswordActivity.class));
}
});
mTxtRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
mImgHidePS.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mImgHidePS.setVisibility(View.GONE);
mImgShowPS.setVisibility(View.VISIBLE);
mEdtPS.setTransformationMethod(PasswordTransformationMethod.getInstance());
mEdtPS.setSelection(mEdtPS.length());
}
});
mImgShowPS.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mImgShowPS.setVisibility(View.GONE);
mImgHidePS.setVisibility(View.VISIBLE);
mEdtPS.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
mEdtPS.setSelection(mEdtPS.length());
}
});
mBtnSwitch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayDialog();
}
});
}
@Override
public void onClick(View v) {
mDialog.dismiss();
switch (v.getId()) {
case R.id.select_english:
switchLanguage("en");
break;
case R.id.select_chinese:
switchLanguage("zh");
break;
case R.id.select_thailand:
switchLanguage("th");
break;
}
//更新语言后,destroy当前页面,重新绘制
finish();
Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
startActivity(intent);
}
private void displayDialog() {
if (mDialog == null) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_select_lanuage, null);
TextView english = (TextView) layout.findViewById(R.id.select_english);
TextView chinese = (TextView) layout.findViewById(R.id.select_chinese);
TextView thailand = (TextView) layout.findViewById(R.id.select_thailand);
mDialog = new Dialog(LoginActivity.this, R.style.Custom_Dialog_Theme);
mDialog.setCanceledOnTouchOutside(false);
english.setOnClickListener(LoginActivity.this);
chinese.setOnClickListener(LoginActivity.this);
thailand.setOnClickListener(LoginActivity.this);
mDialog.setContentView(layout);
}
mDialog.show();
}
public void login() {
Map<String, String> parmas = new HashMap<>();
if (mEdtUserName.getText().toString().trim().isEmpty()) {
showToast(getResources().getString(R.string.login_no_username));
return;
}
if (mEdtPS.getText().toString().trim().isEmpty()) {
showToast(getResources().getString(R.string.login_no_password));
return;
}
try {
parmas.put("username", mEdtUserName.getText().toString());
parmas.put("password", MyMD5.bytesToHex(MyApplication.md5.encrypt(mEdtPS.getText().toString())));
Log.d("加密后登录密码", MyMD5.bytesToHex(MyApplication.md5.encrypt(mEdtPS.getText().toString())));
} catch (Exception e) {
e.printStackTrace();
}
HttpManager.postAsync(HttpManager.BASE_URL + "api.php/base/login_post_json.html?", parmas,
new HttpManager.ResultCallback<UserResponse>() {
@Override
public void onBefore(Request request) {
super.onBefore(request);
showLoadingDialog();
}
@Override
public void onError(Request request, Exception e) {
showToast(getResources().getString(R.string.login_net_fail));
// dismissLoadingDialog();
}
@Override
public void onResponse(UserResponse response) {
Log.e("tag", "_+_+" + response.toString());
if (response.getCode() == 1) {
Log.d("登录成功返回json", response.toString());
String userJson = JsonUtil.toJson(response);
manager.saveUser("userJson", userJson);
UserResponse userResponse = (UserResponse) JsonUtil.read2Object(userJson, UserResponse.class);
PreferenceUtil.commitString("token", userResponse.getToken());
Log.d("done============", userResponse.getToken());
PreferenceUtil.commitString("uid", userResponse.getUid());
manager.saveUser("account", mEdtUserName.getText().toString());
manager.saveUser("password", mEdtPS.getText().toString());
//判断是否登录成功注册过
if (PreferenceUtil.getInt("hadlogin", 1) == 12580) {
loginhy();
} else {
getMainWalletData(userResponse.getUid(), userResponse.getToken());
//注册环信id
try {
registhx(mEdtUserName.getText().toString(), MyMD5.bytesToHex(MyApplication.md5.encrypt(mEdtPS.getText().toString())));
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
showToast(response.getMsg());
dismissLoadingDialog();
}
}
@Override
public void onAfter() {
super.onAfter();
// dismissLoadingDialog();
}
});
}
//注册
public void registhx(final String username, final String pwd) {
new Thread(new Runnable() {
public void run() {
try {
// call method in SDK
EMClient.getInstance().createAccount(username, pwd);
loginhy();
} catch (final HyphenateException e) {
runOnUiThread(new Runnable() {
public void run() {
int errorCode = e.getErrorCode();
if (errorCode == EMError.NETWORK_ERROR) {
Toast.makeText(getApplicationContext(), "网络异常", Toast.LENGTH_SHORT).show();
} else if (errorCode == EMError.USER_ALREADY_EXIST) {
loginhy();
// ToastUtil.showToast("用户已存在1");
} else if (errorCode == EMError.USER_AUTHENTICATION_FAILED) {
Toast.makeText(getApplicationContext(), "无权限", Toast.LENGTH_SHORT).show();
} else if (errorCode == EMError.USER_ILLEGAL_ARGUMENT) {
Toast.makeText(getApplicationContext(), "非法id", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), errorCode + "注册失败", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}).start();
}
public void loginhy() {
//登录环信
try {
EMClient.getInstance().login(mEdtUserName.getText().toString(), MyMD5.bytesToHex(MyApplication.md5.encrypt(mEdtPS.getText().toString())), new EMCallBack() {//回调
@Override
public void onSuccess() {
EMClient.getInstance().groupManager().loadAllGroups();
EMClient.getInstance().chatManager().loadAllConversations();
Log.d("登录", "登录聊天服务器成功!");
PreferenceUtil.commitInt("hadlogin", 12580);
PreferenceUtil.commitInt("hadlogined", 1998);
startActivity(new Intent(LoginActivity.this, MainActivity.class));
dismissLoadingDialog();
finish();
}
@Override
public void onProgress(int progress, String status) {
}
@Override
public void onError(int code, String message) {
Log.d("登录", "登录聊天服务器失败!" + message);
dismissLoadingDialog();
// Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
//创建钱包
public void CreateQB(String coin, String uid, String token) {
Map<String, String> parmas = new HashMap<>();
parmas.put("token", token);
parmas.put("uid", uid);
parmas.put("coin", coin);
HttpManager.postAsync(HttpManager.BASE_URL + "api.php/user/usermyzr.html?", parmas, new HttpManager.ResultCallback<CreateWalletAddressBean>() {
@Override
public void onError(Request request, Exception e) {
}
@Override
public void onResponse(final CreateWalletAddressBean response) {
}
});
}
//获取当前用户所以B种,初始化钱包
public void getMainWalletData(final String uid, final String token) {
Map<String, String> parmas1 = new HashMap<>();
parmas1.put("token", token);
parmas1.put("uid", uid);
HttpManager.postAsync(HttpManager.BASE_URL + "api.php/user/myAssets.html?", parmas1, new HttpManager.ResultCallback<MyMainWalletBean>() {
@Override
public void onError(Request request, Exception e) {
Log.d("折合资产", e.toString());
}
@Override
public void onResponse(MyMainWalletBean response) {
int m = response.getData().getCoin().size();
for (int i = 0; i < m; i++) {
CreateQB(response.getData().getCoin().get(i).getName(), uid, token);
}
}
});
}
}
| 15,117 | 0.551947 | 0.549459 | 365 | 39.742466 | 29.382307 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684932 | false | false | 5 |
a3c4346663155a7921cec996d7021afd74ee115b | 12,756,052,905,102 | 88ed10e55b9c2d197a2573437d5615e28702c208 | /src/main/java/uk/co/mruoc/ssh/SshMachine.java | 267d3a80e6266d6dba7f0ccfa1fe0ea55204e629 | []
| no_license | michaelruocco/ssh-file-actions | https://github.com/michaelruocco/ssh-file-actions | 0681b80dd20cec4d621f85246869fb831d9909bc | 38210d6835e4b6d43c3c544804a67c55e9f26bea | refs/heads/master | 2016-03-24T23:37:07.610000 | 2015-08-10T22:23:23 | 2015-08-10T22:23:23 | 40,295,901 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.co.mruoc.ssh;
import java.io.File;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import org.apache.log4j.Logger;
public class SshMachine implements Machine {
private static final Logger LOG = Logger.getLogger(SshMachine.class);
private final SshDirectoryMaker directoryMaker = new SshDirectoryMaker();
private final SshConnector sshConnector;
public SshMachine(SshSessionFactory sshSessionFactory) {
this.sshConnector = new SshConnector(sshSessionFactory);
}
@Override
public void copyFileTo(File localFile, String remoteFilePath) {
Session session = getConnectedSession();
ChannelSftp sftpChannel = getConnectedSftpChannel(session);
try {
directoryMaker.makeParentDirectories(sftpChannel, remoteFilePath);
logInfo(createCopyToMessage(remoteFilePath, localFile));
sftpChannel.put(localFile.getAbsolutePath(), remoteFilePath);
} catch (SftpException e) {
throw new MachineException(e);
} finally {
sftpChannel.disconnect();
session.disconnect();
}
}
private String createCopyToMessage(String toPath, File fromFile) {
StringBuilder message = new StringBuilder("trying to copy file to remote machine ");
message.append(toPath);
message.append(" from local machine ");
message.append(fromFile.getAbsolutePath());
return message.toString();
}
@Override
public void copyFileFrom(String remoteFilePath, String localFilePath) {
Session session = getConnectedSession();
ChannelSftp sftpChannel = getConnectedSftpChannel(session);
try {
logInfo(createCopyFromMessage(remoteFilePath, localFilePath));
sftpChannel.get(remoteFilePath, localFilePath);
} catch (SftpException e) {
throw new MachineException(e);
} finally {
sftpChannel.disconnect();
session.disconnect();
}
}
private String createCopyFromMessage(String fromPath, String toPath) {
StringBuilder message = new StringBuilder("trying to get file from remote machine ");
message.append(fromPath);
message.append(" to local machine ");
message.append(toPath);
return message.toString();
}
@Override
public void remove(String remoteFilePath) {
Session session = getConnectedSession();
ChannelSftp sftpChannel = getConnectedSftpChannel(session);
try {
if(fileExists(sftpChannel, remoteFilePath))
sftpChannel.rm(remoteFilePath);
} catch (SftpException e) {
throw new MachineException(e);
} finally {
sftpChannel.disconnect();
session.disconnect();
}
}
@Override
public boolean exists(String filePath) {
Session session = getConnectedSession();
ChannelSftp sftpChannel = getConnectedSftpChannel(session);
try {
return fileExists(sftpChannel, filePath);
} finally {
sftpChannel.disconnect();
session.disconnect();
}
}
@Override
public void runAsynchronousCommand(String command) {
CommandExecutor commandExecutor = new CommandExecutor(sshConnector, command);
Thread thread = new Thread(commandExecutor);
thread.start();
}
@Override
public boolean runSynchronousCommand(String command) {
CommandExecutor commandExecutor = new CommandExecutor(sshConnector, command);
commandExecutor.execute();
return commandExecutor.completed();
}
private Session getConnectedSession() {
return sshConnector.getConnectedSession();
}
private ChannelSftp getConnectedSftpChannel(Session session) {
return sshConnector.getConnectedSftpChannel(session);
}
private boolean fileExists(ChannelSftp sftpChannel, String remoteFilePath) {
try {
return !sftpChannel.ls(remoteFilePath).isEmpty();
} catch (SftpException e) {
logError(e);
return false;
}
}
private void logInfo(String message) {
LOG.info(message);
}
private void logError(Exception e) {
LOG.info(e);
}
}
| UTF-8 | Java | 4,366 | java | SshMachine.java | Java | []
| null | []
| package uk.co.mruoc.ssh;
import java.io.File;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import org.apache.log4j.Logger;
public class SshMachine implements Machine {
private static final Logger LOG = Logger.getLogger(SshMachine.class);
private final SshDirectoryMaker directoryMaker = new SshDirectoryMaker();
private final SshConnector sshConnector;
public SshMachine(SshSessionFactory sshSessionFactory) {
this.sshConnector = new SshConnector(sshSessionFactory);
}
@Override
public void copyFileTo(File localFile, String remoteFilePath) {
Session session = getConnectedSession();
ChannelSftp sftpChannel = getConnectedSftpChannel(session);
try {
directoryMaker.makeParentDirectories(sftpChannel, remoteFilePath);
logInfo(createCopyToMessage(remoteFilePath, localFile));
sftpChannel.put(localFile.getAbsolutePath(), remoteFilePath);
} catch (SftpException e) {
throw new MachineException(e);
} finally {
sftpChannel.disconnect();
session.disconnect();
}
}
private String createCopyToMessage(String toPath, File fromFile) {
StringBuilder message = new StringBuilder("trying to copy file to remote machine ");
message.append(toPath);
message.append(" from local machine ");
message.append(fromFile.getAbsolutePath());
return message.toString();
}
@Override
public void copyFileFrom(String remoteFilePath, String localFilePath) {
Session session = getConnectedSession();
ChannelSftp sftpChannel = getConnectedSftpChannel(session);
try {
logInfo(createCopyFromMessage(remoteFilePath, localFilePath));
sftpChannel.get(remoteFilePath, localFilePath);
} catch (SftpException e) {
throw new MachineException(e);
} finally {
sftpChannel.disconnect();
session.disconnect();
}
}
private String createCopyFromMessage(String fromPath, String toPath) {
StringBuilder message = new StringBuilder("trying to get file from remote machine ");
message.append(fromPath);
message.append(" to local machine ");
message.append(toPath);
return message.toString();
}
@Override
public void remove(String remoteFilePath) {
Session session = getConnectedSession();
ChannelSftp sftpChannel = getConnectedSftpChannel(session);
try {
if(fileExists(sftpChannel, remoteFilePath))
sftpChannel.rm(remoteFilePath);
} catch (SftpException e) {
throw new MachineException(e);
} finally {
sftpChannel.disconnect();
session.disconnect();
}
}
@Override
public boolean exists(String filePath) {
Session session = getConnectedSession();
ChannelSftp sftpChannel = getConnectedSftpChannel(session);
try {
return fileExists(sftpChannel, filePath);
} finally {
sftpChannel.disconnect();
session.disconnect();
}
}
@Override
public void runAsynchronousCommand(String command) {
CommandExecutor commandExecutor = new CommandExecutor(sshConnector, command);
Thread thread = new Thread(commandExecutor);
thread.start();
}
@Override
public boolean runSynchronousCommand(String command) {
CommandExecutor commandExecutor = new CommandExecutor(sshConnector, command);
commandExecutor.execute();
return commandExecutor.completed();
}
private Session getConnectedSession() {
return sshConnector.getConnectedSession();
}
private ChannelSftp getConnectedSftpChannel(Session session) {
return sshConnector.getConnectedSftpChannel(session);
}
private boolean fileExists(ChannelSftp sftpChannel, String remoteFilePath) {
try {
return !sftpChannel.ls(remoteFilePath).isEmpty();
} catch (SftpException e) {
logError(e);
return false;
}
}
private void logInfo(String message) {
LOG.info(message);
}
private void logError(Exception e) {
LOG.info(e);
}
}
| 4,366 | 0.655978 | 0.655749 | 136 | 31.102942 | 25.771416 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536765 | false | false | 5 |
aeefb1c58b7fb3fdc48abd2e8076333884b40652 | 1,760,936,641,991 | 4bc61c5f6fffc7841a00a72f66f7a39c1b43e191 | /src/main/java/ru/iitdgroup/tests/apidriver/Client.java | 6b25a8dc0a124f9f635198c0f69a014c8e09081b | []
| no_license | TIeJlbMeIlleK/sampleWebTest | https://github.com/TIeJlbMeIlleK/sampleWebTest | 94fa035b0b74a588b7b7a9486ba26f561309c0cd | 31f68d3732a171018d5a5d0b748212a483925105 | refs/heads/master | 2023-08-02T14:55:11.791000 | 2021-08-20T05:48:21 | 2021-08-20T05:48:21 | 410,815,635 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.iitdgroup.tests.apidriver;
import ru.iitdgroup.intellinx.dbo.client.ObjectFactory;
import ru.iitdgroup.intellinx.dbo.client.SendClientDataRequestType;
import javax.xml.bind.JAXBException;
import java.io.IOException;
public class Client extends Template<SendClientDataRequestType> {
public Client(String fileName) throws JAXBException, IOException {
super(fileName);
}
@Override
protected Class getObjectFactoryClazz() {
return ObjectFactory.class;
}
}
| UTF-8 | Java | 504 | java | Client.java | Java | []
| null | []
| package ru.iitdgroup.tests.apidriver;
import ru.iitdgroup.intellinx.dbo.client.ObjectFactory;
import ru.iitdgroup.intellinx.dbo.client.SendClientDataRequestType;
import javax.xml.bind.JAXBException;
import java.io.IOException;
public class Client extends Template<SendClientDataRequestType> {
public Client(String fileName) throws JAXBException, IOException {
super(fileName);
}
@Override
protected Class getObjectFactoryClazz() {
return ObjectFactory.class;
}
}
| 504 | 0.767857 | 0.767857 | 19 | 25.526316 | 24.813766 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 5 |
9ef02b612bcdb834634a7cd51908e2d324ff4e2f | 22,926,535,466,455 | 56231681020795939d183df16107b0771163e620 | /miracom-mes-service/src/main/java/kr/co/miracom/mes/a10/resource/simple/flow/model/A10FlowOper.java | 686a9f9ce6140d00bf96896477f12cb59e8a01f3 | []
| no_license | gosangosango/testRepo | https://github.com/gosangosango/testRepo | ed20c2fe1864e9a82d8b1bd36d5782ce41bcf0c8 | ca8767f57b69eab685ee0e765bf7b80524508611 | refs/heads/master | 2020-03-23T09:24:57.644000 | 2018-07-18T22:14:34 | 2018-07-18T22:14:34 | 141,386,250 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*package kr.co.miracom.mes.a10.resource.simple.flow.model;
import java.time.ZonedDateTime;
public class A10FlowOper {
private String id;
private String operCode;
private String operCode;
private String createUserId;
private ZonedDateTime createTime;
private String updateUserId;
private ZonedDateTime updateTime;
}*/
| UTF-8 | Java | 327 | java | A10FlowOper.java | Java | []
| null | []
| /*package kr.co.miracom.mes.a10.resource.simple.flow.model;
import java.time.ZonedDateTime;
public class A10FlowOper {
private String id;
private String operCode;
private String operCode;
private String createUserId;
private ZonedDateTime createTime;
private String updateUserId;
private ZonedDateTime updateTime;
}*/
| 327 | 0.804281 | 0.792049 | 13 | 24.153847 | 15.560533 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.230769 | false | false | 5 |
e712b597c183d46ca382dfc87645179f6a21b91f | 15,298,673,550,516 | f38b4781222ff852563f6ee3b84aba31ef212434 | /manipulate.excel/src/main/java/manipulate/excel/ReadExcelFile.java | eb193623e9789a70f7cf76229cabae7e4edf6cd7 | []
| no_license | KPanDEV/ManipulateExcel | https://github.com/KPanDEV/ManipulateExcel | d02045e714c94021e1815aa1c84ee7c10ac884d6 | 9350bde267a1fc5e2ae24b8c9481b53e373e4814 | refs/heads/master | 2022-07-18T11:58:18.377000 | 2020-03-24T21:10:52 | 2020-03-24T21:10:52 | 249,814,095 | 1 | 0 | null | false | 2021-01-14T20:36:05 | 2020-03-24T20:45:34 | 2020-03-24T21:10:55 | 2021-01-14T20:36:03 | 39 | 1 | 0 | 2 | Java | false | false | package manipulate.excel;
public class ReadExcelFile {
public static void main(String[] args) {
ProcessExcel processExcel = new ProcessExcel();
processExcel.processExcelFile();
}
}
| UTF-8 | Java | 204 | java | ReadExcelFile.java | Java | []
| null | []
| package manipulate.excel;
public class ReadExcelFile {
public static void main(String[] args) {
ProcessExcel processExcel = new ProcessExcel();
processExcel.processExcelFile();
}
}
| 204 | 0.70098 | 0.70098 | 10 | 19.4 | 18.575253 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 5 |
a4b0fa8d8c53fad6c73f3f0289c965436b0a20a4 | 22,196,391,026,472 | a141406a8f6aad91a2a03b6a75018481e6bd9ed2 | /modaclouds-scalingsdatests/src/it/polimi/modaclouds/scalingsdatests/validator/sda/ResultsBuilder.java | d9f6c5803d4d35b43edab62fb2961680e2036bd6 | [
"Apache-2.0"
]
| permissive | deib-polimi/modaclouds-tests | https://github.com/deib-polimi/modaclouds-tests | 12b3448db5ce91b90a731ae7a6a6a529bde25b00 | eb257c84f4aed97803f2616a9c6562bf23d1ffe5 | refs/heads/master | 2016-08-11T12:17:30.631000 | 2016-01-14T02:37:51 | 2016-01-14T02:37:51 | 36,176,484 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.polimi.modaclouds.scalingsdatests.validator.sda;
import it.polimi.modaclouds.scalingsdatests.Test;
import it.polimi.modaclouds.scalingsdatests.validator.util.Datum;
import it.polimi.modaclouds.scalingsdatests.validator.util.FileHelper;
import it.polimi.modaclouds.scalingsdatests.validator.util.GenericChart;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.jfree.data.xy.XYSeriesCollection;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResultsBuilder {
private static final Logger logger = LoggerFactory.getLogger(ResultsBuilder.class);
public static final String RESULT = "results.csv";
public static final String RESULT_REQS = "requests.csv";
public static final String RESULT_WORKLOAD = "workload.csv";
public static final String RESULT_RES_TIMES = "responseTimes.csv";
public static void main(String[] args) {
perform(Paths.get("."), Test.App.MIC, Validator.DEFAULT_WINDOW, 2);
}
private static Map<String, List<Double>> getAsMap(Path f, String[] ss) {
if (f == null || !f.toFile().exists())
throw new RuntimeException("File not found or wrong path ("
+ f == null ? "null" : f.toString() + ")");
if (ss == null || ss.length == 0)
throw new RuntimeException("You should specify at least one column name.");
HashMap<String, List<Double>> res = new HashMap<String, List<Double>>();
HashMap<String, Integer> columnsNeeded = new HashMap<String, Integer>();
try (Scanner sc = new Scanner(f)) {
{
String header = sc.nextLine();
String[] columns = header.split(",");
for (int c = 0; c < columns.length; ++c) {
boolean done = false;
for (int i = 0; i < ss.length && !done; ++i) {
if (columns[c].trim().equalsIgnoreCase(ss[i])) {
done = true;
columnsNeeded.put(ss[i], c);
}
}
}
}
if (columnsNeeded.size() == 0)
throw new RuntimeException("No column matched in the given file!");
for (String key : columnsNeeded.keySet())
res.put(key, new ArrayList<Double>());
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] values = line.split(",");
for (String key : columnsNeeded.keySet())
try {
res.get(key).add(Double.parseDouble(values[columnsNeeded.get(key)]));
} catch (Exception e) { }
}
} catch (Exception e) {
logger.error("Error while dealing with the file.", e);
}
return res;
}
public static final String JMETER_LOG = "test_aggregate.jtl";
private static Map<String, Integer> getRequestsPerPage(Path parent) throws Exception {
HashMap<String, Integer> res = new HashMap<String, Integer>();
boolean goOn = true;
for (int i = 1; goOn; ++i) {
Path jmeterAggregate = Paths.get(parent.getParent().getParent().getParent().toString(), "client" + i, JMETER_LOG);
if (!jmeterAggregate.toFile().exists()) {
goOn = false;
continue;
}
Map<String, Integer> tmp = getRequestsPerPageFromSingleFile(jmeterAggregate);
for (String key : tmp.keySet()) {
Integer val = res.get(key);
if (val == null)
val = 0;
res.put(key, val += tmp.get(key));
}
}
return res;
}
private static Map<String, Integer> getRequestsPerPageFromSingleFile(Path f) throws Exception {
if (f == null || !f.toFile().exists())
throw new RuntimeException("File not found or wrong path ("
+ f == null ? "null" : f.toString() + ")");
HashMap<String, Integer> res = new HashMap<String, Integer>();
Map<String, List<Datum>> data = Datum.getAllData(f, Datum.Type.JMETER_CSV);
for (String resourceId : data.keySet()) {
res.put(resourceId, data.get(resourceId).size());
}
return res;
}
private static Map<String, String> getLatenciesPerPage(Path parent) throws Exception {
LinkedHashMap<String, String> res = new LinkedHashMap<String, String>();
boolean goOn = true;
for (int i = 1; goOn; ++i) {
Path jmeterAggregate = Paths.get(parent.getParent().getParent().getParent().toString(), "client" + i, JMETER_LOG);
if (!jmeterAggregate.toFile().exists()) {
goOn = false;
continue;
}
Map<String, String> tmp = getLatenciesPerPageFromSingleFile(jmeterAggregate);
for (String key : tmp.keySet()) {
String val = tmp.get(key);
res.put(key + "_client" + i, val);
}
}
return res;
}
private static Map<String, String> getLatenciesPerPageFromSingleFile(Path f) throws Exception {
if (f == null || !f.toFile().exists())
throw new RuntimeException("File not found or wrong path ("
+ f == null ? "null" : f.toString() + ")");
HashMap<String, String> res = new HashMap<String, String>();
Map<String, List<Datum>> data = Datum.getAllData(f, Datum.Type.JMETER_CSV);
for (String resourceId : data.keySet()) {
List<Datum> dataRes = data.get(resourceId);
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
double avg = 0.0;
for (Datum d : dataRes) {
if (d.value > max)
max = d.value;
if (d.value < min)
min = d.value;
avg += d.value;
}
avg /= dataRes.size();
double stdDev = 0;
for (Datum d : dataRes)
stdDev += Math.pow(d.value - avg, 2);
stdDev /= dataRes.size();
stdDev = Math.sqrt(stdDev);
res.put(resourceId, String.format("%s,%s,%s,%s", doubleFormatter.format(avg), doubleFormatter.format(stdDev), doubleFormatter.format(min), doubleFormatter.format(max)));
}
return res;
}
public static final String DEMAND_COLUMN_PREFIX = "AvarageEstimatedDemand_";
public static final String CPU_UTIL_COLUMN = "AvarageCPUUtil";
public static final String WORKLOAD_COLUMN = "workload";
private static DecimalFormat doubleFormatter() {
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault());
otherSymbols.setDecimalSeparator('.');
DecimalFormat myFormatter = new DecimalFormat("0.0#########", otherSymbols);
return myFormatter;
}
private static DecimalFormat doubleFormatter = doubleFormatter();
private static List<List<Double>> methodsWorkloads = null;
private static Map<Integer, Integer> methodsWorkloadTot = null;
private static Map<String, List<Double>> demands = null;
private static int maxCommonLength = -1;
private static void init(Path parent, String[] methodsNames) {
if (methodsNames == null || methodsNames.length == 0)
throw new RuntimeException("You should specify at least one method name.");
Path demand = Paths.get(parent.toString(), DemandValidator.RESULT);
if (demand == null || !demand.toFile().exists())
throw new RuntimeException("Demand file not found or wrong path ("
+ demand == null ? "null" : demand.toString() + ")");
ArrayList<Path> methods = new ArrayList<Path>();
for (int i = 1; i <= methodsNames.length; ++i) {
Path method = Paths.get(parent.toString(), "method" + i, WorkloadGapCalculator.RESULT);
if (method == null || !method.toFile().exists())
throw new RuntimeException("Method file not found or wrong path ("
+ method == null ? "null" : method.toString() + ")");
methods.add(method);
}
String[] neededColumnsDemands = new String[methodsNames.length + 1];
for (int i = 0; i < methodsNames.length; ++i)
neededColumnsDemands[i] = DEMAND_COLUMN_PREFIX + methodsNames[i];
neededColumnsDemands[neededColumnsDemands.length - 1] = CPU_UTIL_COLUMN;
maxCommonLength = 0;
logger.info("Reading the demands file...");
demands = getAsMap(demand, neededColumnsDemands);
maxCommonLength = demands.get(CPU_UTIL_COLUMN).size();
logger.info("Reading the workloads for the methods...");
methodsWorkloads = new ArrayList<List<Double>>();
for (Path p : methods) {
List<Double> tmp = getAsMap(p, new String[] { WORKLOAD_COLUMN }).get(WORKLOAD_COLUMN);
if (tmp.size() < maxCommonLength)
maxCommonLength = tmp.size();
methodsWorkloads.add(tmp);
}
methodsWorkloadTot = new HashMap<Integer, Integer>();
for (int i = 0; i < methodsNames.length; ++i) {
double sum = 0;
List<Double> workload = methodsWorkloads.get(i);
for (int j = 0; j < maxCommonLength; ++j)
sum += workload.get(j);
methodsWorkloadTot.put(i, (int)Math.round(sum));
}
}
public static void createDemandAnalysis(Path parent, String[] methodsNames, int cores, int window) {
logger.info("Creating the demand analysis report...");
if (methodsNames == null || methodsNames.length == 0)
throw new RuntimeException("You should specify at least one method name.");
if (methodsWorkloads == null || methodsWorkloadTot == null || demands == null || maxCommonLength == -1)
init(parent, methodsNames);
try (PrintWriter out = new PrintWriter(Paths.get(parent.toString(), RESULT).toFile())) {
for (int i = 0; i < methodsNames.length; ++i)
out.printf("Demand_%1$s,X_%1$s,", methodsNames[i]);
out.println("U_actual,U_measured,U_aoverm");
GenericChart<XYSeriesCollection> graph = GenericChart.createDemandLawGraph();
double sumUaoverm = 0;
for (int i = 0; i < maxCommonLength; ++i) {
double u = 0;
double uMeasured = demands.get(CPU_UTIL_COLUMN).get(i);
StringBuilder sb = new StringBuilder();
for (int j = 0; j < methodsNames.length; ++j) {
double d = demands.get(DEMAND_COLUMN_PREFIX + methodsNames[j]).get(i);
double x = methodsWorkloads.get(j).get(i) / (window * cores);
sb.append(doubleFormatter.format(d) + "," + doubleFormatter.format(x) + ",");
u += d*x;
graph.add(methodsNames[j], x, uMeasured);
}
u /= 1000;
sb.append(doubleFormatter.format(u) + "," + doubleFormatter.format(uMeasured) + "," + doubleFormatter.format(u / uMeasured));
sumUaoverm += u / uMeasured;
out.println(sb.toString());
}
out.printf("%1$s,%1$s,%1$s,%1$s,%2$s", ResponseTimeValidator.EMPTY, doubleFormatter.format(sumUaoverm / maxCommonLength));
graph.updateGraph();
graph.updateImage();
graph.save2png(parent.toString(), "demandLaw.png");
out.flush();
} catch (Exception e) {
logger.error("Error while dealing with the result file.", e);
}
}
public static void createRequestsAnalysis(Path parent, String[] methodsNames, boolean printOnlyTotalRequests) {
logger.info("Creating the requests analysis report...");
if (methodsNames == null || methodsNames.length == 0)
throw new RuntimeException("You should specify at least one method name.");
if (methodsWorkloads == null || methodsWorkloadTot == null || demands == null || maxCommonLength == -1)
init(parent, methodsNames);
try (PrintWriter out = new PrintWriter(Paths.get(parent.toString(), RESULT_REQS).toFile())) {
if (!printOnlyTotalRequests)
for (int i = 0; i < methodsNames.length; ++i)
out.printf("Requests_%s,", methodsNames[i]);
out.print("TotalRequestsConsidered,");
Map<String, Integer> requestsPerPageOnlyOk = getRequestsPerPage(parent);
if (!printOnlyTotalRequests)
for (String key : requestsPerPageOnlyOk.keySet())
out.printf("ActualRequestsOk_%s,", key);
out.println("TotalActualRequestsOk,PercentageOkLost");
int consideredRequests = 0;
// NOTE:
// all the datum must be considered times window, because they're an average computed on that window!
// plus the first 5 data are skipped, and they should be considered too in the count.
// The window is now always 1: the duration of the time window for the sdas and the other are the same!
int window = 1;
for (int j = 0; j < methodsNames.length; ++j) {
List<Double> workload = methodsWorkloads.get(j);
int methodTot = methodsWorkloadTot.get(j) * window;
methodTot += workload.get(0).intValue() * 5 * window;
for (int i = maxCommonLength; i < workload.size(); ++i)
methodTot += workload.get(i).intValue() * window;
if (!printOnlyTotalRequests)
out.print(methodTot + ",");
consideredRequests += methodTot;
}
out.print(consideredRequests + ",");
int actualRequestsOk = 0;
for (String key : requestsPerPageOnlyOk.keySet()) {
int methodTot = requestsPerPageOnlyOk.get(key);
if (!printOnlyTotalRequests)
out.print(methodTot + ",");
actualRequestsOk += methodTot;
}
out.println(actualRequestsOk + "," + doubleFormatter.format((actualRequestsOk - consideredRequests)/(double)actualRequestsOk * 100) + "%");
out.flush();
} catch (Exception e) {
logger.error("Error while dealing with the result file.", e);
}
}
public static void createWorkloadAnalysis(Path parent, String[] methodsNames, int timesteps) {
logger.info("Creating the workload analysis report...");
if (methodsNames == null || methodsNames.length == 0)
throw new RuntimeException("You should specify at least one method name.");
if (timesteps < 1)
throw new RuntimeException("You need at least 1 timestep!");
if (methodsWorkloads == null || methodsWorkloadTot == null || demands == null || maxCommonLength == -1)
init(parent, methodsNames);
try (PrintWriter out = new PrintWriter(Paths.get(parent.toString(), RESULT_WORKLOAD).toFile())) {
out.print("ErrorTimestep1");
for (int i = 2; i <= timesteps; ++i)
out.printf(",ErrorTimestep%d", i);
out.println();
double[] sums = new double[timesteps];
for (int i = 0; i < timesteps; ++i)
sums[i] = 0.0;
for (int i = 1; i <= methodsNames.length; ++i) {
try (Scanner sc = new Scanner(Paths.get(parent.toString(), "method" + i, WorkloadGapCalculator.RESULT))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.contains(WorkloadGapCalculator.EMPTY)) {
String[] splitted = line.split(",");
for (int k = 0, j = 2; k < timesteps; ++k, j+=2)
sums[k] += Double.valueOf(splitted[j].replaceAll("%", ""));
}
}
}
}
out.printf("%s%%", doubleFormatter.format(sums[0] / methodsNames.length));
for (int i = 1; i < timesteps; ++i)
out.printf(",%s%%", doubleFormatter.format(sums[i] / methodsNames.length));
out.println();
} catch (Exception e) {
logger.error("Error while dealing with the result file.", e);
}
}
public static void createResponseTimesAnalysis(Path parent, String appName, String[] methodsNames) {
logger.info("Creating the response times analysis report...");
if (methodsNames == null || methodsNames.length == 0)
throw new RuntimeException("You should specify at least one method name.");
if (methodsWorkloads == null || methodsWorkloadTot == null || demands == null || maxCommonLength == -1)
init(parent, methodsNames);
try (PrintWriter out = new PrintWriter(Paths.get(parent.toString(), RESULT_RES_TIMES).toFile())) {
out.println("Method,AvgResponseTime,StdDevResponseTime,MinResponseTime,MaxResponseTime");
Map<String, String> latenciesPerPage = getLatenciesPerPage(parent);
for (String key : latenciesPerPage.keySet()) {
String res = latenciesPerPage.get(key);
out.printf("%s_JMeter,%s\n", key, res);
}
Map<String, String> glassfishLatenciesPerPage = getLatenciesPerPageFromGlassfish(parent, appName, methodsNames);
for (String key : glassfishLatenciesPerPage.keySet()) {
String res = glassfishLatenciesPerPage.get(key);
out.printf("%s_Glassfish,%s\n", key, res);
}
Map<String, String> dataCollectorRTsPerPage = getResponseTimesPerPageFromDataCollector(parent, methodsNames);
for (String key : dataCollectorRTsPerPage.keySet()) {
String res = dataCollectorRTsPerPage.get(key);
out.printf("%s_DC,%s\n", key, res);
}
out.flush();
} catch (Exception e) {
logger.error("Error while dealing with the result file.", e);
}
}
public static final String TOMCAT_ACCESS_LOG = "localhost_access_log.txt";
private static Map<String, String> getLatenciesPerPageFromGlassfish(Path parent, String appName, String[] methodsNames) throws Exception {
LinkedHashMap<String, String> res = new LinkedHashMap<String, String>();
boolean goOn = true;
for (int i = 1; goOn; ++i) {
Path tomcatLog = Paths.get(parent.getParent().getParent().getParent().toString(), appName + i, "home", "ubuntu", "logs", TOMCAT_ACCESS_LOG);
if (tomcatLog.toFile().exists()) {
logger.info("Generating the fake Glassfish reports...");
FileHelper.createGlassfishReportFromTomcatLog(tomcatLog, Paths.get(parent.getParent().getParent().getParent().toString(), appName + i), methodsNames);
}
for (String method : methodsNames) {
Path jsonFile = Paths.get(parent.getParent().getParent().getParent().toString(), appName + i, method + ".json");
if (!jsonFile.toFile().exists()) {
goOn = false;
continue;
}
res.put(method + "_" + appName + i, parseGlassfishJson(jsonFile));
}
}
return res;
}
private static String parseGlassfishJson(Path jsonFile) throws Exception {
String json = FileUtils.readFileToString(jsonFile.toFile());
JSONObject obj = new JSONObject(json);
JSONObject extraProperties = obj.getJSONObject("extraProperties");
JSONObject entity = extraProperties.getJSONObject("entity");
JSONObject maxtime = entity.getJSONObject("maxtime");
JSONObject processingtime = entity.getJSONObject("processingtime");
return String.format("%d.000,0.000,0.000,%d.000", processingtime.getInt("count"), maxtime.getInt("count"));
}
private static Map<String, String> getResponseTimesPerPageFromDataCollector(Path parent, String[] methodsNames) throws Exception {
LinkedHashMap<String, String> res = new LinkedHashMap<String, String>();
for (int i = 1; i <= methodsNames.length; ++i) {
Path p = Paths.get(parent.toString(), "method" + i, DemandValidator.MONITORED_RESPONSETIME);
Map.Entry<String, String> entry = getResponseTimesPerPageFromSingleFile(p);
res.put(entry.getKey(), entry.getValue());
}
return res;
}
private static Map.Entry<String, String> getResponseTimesPerPageFromSingleFile(Path p) throws Exception {
List<Datum> data = Datum.getAllData(p, true).get(Datum.MIXED);
double avg = 0.0;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (Datum d : data) {
if (d.value > max)
max = d.value;
if (d.value < min)
min = d.value;
avg += d.value;
}
avg /= data.size();
double stdDev = 0;
for (Datum d : data)
stdDev += Math.pow(d.value - avg, 2);
stdDev /= data.size();
stdDev = Math.sqrt(stdDev);
return new AbstractMap.SimpleEntry<String, String>(data.get(0).resourceId, String.format("%s,%s,%s,%s", doubleFormatter.format(avg), doubleFormatter.format(stdDev), doubleFormatter.format(min), doubleFormatter.format(max)));
}
public static final int DEFAULT_TIMESTEPS = 5;
public static void perform(Path parent, Test.App app, int window, int cores) {
perform(parent, app, window, true, cores);
}
public static void perform(Path parent, Test.App app, int window, boolean printOnlyTotalRequests, int cores) {
createDemandAnalysis(parent, app.methods, cores, window);
createRequestsAnalysis(parent, app.methods, printOnlyTotalRequests);
createWorkloadAnalysis(parent, app.methods, DEFAULT_TIMESTEPS);
createResponseTimesAnalysis(parent, app.name, app.methods);
}
}
| UTF-8 | Java | 19,623 | java | ResultsBuilder.java | Java | []
| null | []
| package it.polimi.modaclouds.scalingsdatests.validator.sda;
import it.polimi.modaclouds.scalingsdatests.Test;
import it.polimi.modaclouds.scalingsdatests.validator.util.Datum;
import it.polimi.modaclouds.scalingsdatests.validator.util.FileHelper;
import it.polimi.modaclouds.scalingsdatests.validator.util.GenericChart;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.jfree.data.xy.XYSeriesCollection;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResultsBuilder {
private static final Logger logger = LoggerFactory.getLogger(ResultsBuilder.class);
public static final String RESULT = "results.csv";
public static final String RESULT_REQS = "requests.csv";
public static final String RESULT_WORKLOAD = "workload.csv";
public static final String RESULT_RES_TIMES = "responseTimes.csv";
public static void main(String[] args) {
perform(Paths.get("."), Test.App.MIC, Validator.DEFAULT_WINDOW, 2);
}
private static Map<String, List<Double>> getAsMap(Path f, String[] ss) {
if (f == null || !f.toFile().exists())
throw new RuntimeException("File not found or wrong path ("
+ f == null ? "null" : f.toString() + ")");
if (ss == null || ss.length == 0)
throw new RuntimeException("You should specify at least one column name.");
HashMap<String, List<Double>> res = new HashMap<String, List<Double>>();
HashMap<String, Integer> columnsNeeded = new HashMap<String, Integer>();
try (Scanner sc = new Scanner(f)) {
{
String header = sc.nextLine();
String[] columns = header.split(",");
for (int c = 0; c < columns.length; ++c) {
boolean done = false;
for (int i = 0; i < ss.length && !done; ++i) {
if (columns[c].trim().equalsIgnoreCase(ss[i])) {
done = true;
columnsNeeded.put(ss[i], c);
}
}
}
}
if (columnsNeeded.size() == 0)
throw new RuntimeException("No column matched in the given file!");
for (String key : columnsNeeded.keySet())
res.put(key, new ArrayList<Double>());
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] values = line.split(",");
for (String key : columnsNeeded.keySet())
try {
res.get(key).add(Double.parseDouble(values[columnsNeeded.get(key)]));
} catch (Exception e) { }
}
} catch (Exception e) {
logger.error("Error while dealing with the file.", e);
}
return res;
}
public static final String JMETER_LOG = "test_aggregate.jtl";
private static Map<String, Integer> getRequestsPerPage(Path parent) throws Exception {
HashMap<String, Integer> res = new HashMap<String, Integer>();
boolean goOn = true;
for (int i = 1; goOn; ++i) {
Path jmeterAggregate = Paths.get(parent.getParent().getParent().getParent().toString(), "client" + i, JMETER_LOG);
if (!jmeterAggregate.toFile().exists()) {
goOn = false;
continue;
}
Map<String, Integer> tmp = getRequestsPerPageFromSingleFile(jmeterAggregate);
for (String key : tmp.keySet()) {
Integer val = res.get(key);
if (val == null)
val = 0;
res.put(key, val += tmp.get(key));
}
}
return res;
}
private static Map<String, Integer> getRequestsPerPageFromSingleFile(Path f) throws Exception {
if (f == null || !f.toFile().exists())
throw new RuntimeException("File not found or wrong path ("
+ f == null ? "null" : f.toString() + ")");
HashMap<String, Integer> res = new HashMap<String, Integer>();
Map<String, List<Datum>> data = Datum.getAllData(f, Datum.Type.JMETER_CSV);
for (String resourceId : data.keySet()) {
res.put(resourceId, data.get(resourceId).size());
}
return res;
}
private static Map<String, String> getLatenciesPerPage(Path parent) throws Exception {
LinkedHashMap<String, String> res = new LinkedHashMap<String, String>();
boolean goOn = true;
for (int i = 1; goOn; ++i) {
Path jmeterAggregate = Paths.get(parent.getParent().getParent().getParent().toString(), "client" + i, JMETER_LOG);
if (!jmeterAggregate.toFile().exists()) {
goOn = false;
continue;
}
Map<String, String> tmp = getLatenciesPerPageFromSingleFile(jmeterAggregate);
for (String key : tmp.keySet()) {
String val = tmp.get(key);
res.put(key + "_client" + i, val);
}
}
return res;
}
private static Map<String, String> getLatenciesPerPageFromSingleFile(Path f) throws Exception {
if (f == null || !f.toFile().exists())
throw new RuntimeException("File not found or wrong path ("
+ f == null ? "null" : f.toString() + ")");
HashMap<String, String> res = new HashMap<String, String>();
Map<String, List<Datum>> data = Datum.getAllData(f, Datum.Type.JMETER_CSV);
for (String resourceId : data.keySet()) {
List<Datum> dataRes = data.get(resourceId);
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
double avg = 0.0;
for (Datum d : dataRes) {
if (d.value > max)
max = d.value;
if (d.value < min)
min = d.value;
avg += d.value;
}
avg /= dataRes.size();
double stdDev = 0;
for (Datum d : dataRes)
stdDev += Math.pow(d.value - avg, 2);
stdDev /= dataRes.size();
stdDev = Math.sqrt(stdDev);
res.put(resourceId, String.format("%s,%s,%s,%s", doubleFormatter.format(avg), doubleFormatter.format(stdDev), doubleFormatter.format(min), doubleFormatter.format(max)));
}
return res;
}
public static final String DEMAND_COLUMN_PREFIX = "AvarageEstimatedDemand_";
public static final String CPU_UTIL_COLUMN = "AvarageCPUUtil";
public static final String WORKLOAD_COLUMN = "workload";
private static DecimalFormat doubleFormatter() {
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault());
otherSymbols.setDecimalSeparator('.');
DecimalFormat myFormatter = new DecimalFormat("0.0#########", otherSymbols);
return myFormatter;
}
private static DecimalFormat doubleFormatter = doubleFormatter();
private static List<List<Double>> methodsWorkloads = null;
private static Map<Integer, Integer> methodsWorkloadTot = null;
private static Map<String, List<Double>> demands = null;
private static int maxCommonLength = -1;
private static void init(Path parent, String[] methodsNames) {
if (methodsNames == null || methodsNames.length == 0)
throw new RuntimeException("You should specify at least one method name.");
Path demand = Paths.get(parent.toString(), DemandValidator.RESULT);
if (demand == null || !demand.toFile().exists())
throw new RuntimeException("Demand file not found or wrong path ("
+ demand == null ? "null" : demand.toString() + ")");
ArrayList<Path> methods = new ArrayList<Path>();
for (int i = 1; i <= methodsNames.length; ++i) {
Path method = Paths.get(parent.toString(), "method" + i, WorkloadGapCalculator.RESULT);
if (method == null || !method.toFile().exists())
throw new RuntimeException("Method file not found or wrong path ("
+ method == null ? "null" : method.toString() + ")");
methods.add(method);
}
String[] neededColumnsDemands = new String[methodsNames.length + 1];
for (int i = 0; i < methodsNames.length; ++i)
neededColumnsDemands[i] = DEMAND_COLUMN_PREFIX + methodsNames[i];
neededColumnsDemands[neededColumnsDemands.length - 1] = CPU_UTIL_COLUMN;
maxCommonLength = 0;
logger.info("Reading the demands file...");
demands = getAsMap(demand, neededColumnsDemands);
maxCommonLength = demands.get(CPU_UTIL_COLUMN).size();
logger.info("Reading the workloads for the methods...");
methodsWorkloads = new ArrayList<List<Double>>();
for (Path p : methods) {
List<Double> tmp = getAsMap(p, new String[] { WORKLOAD_COLUMN }).get(WORKLOAD_COLUMN);
if (tmp.size() < maxCommonLength)
maxCommonLength = tmp.size();
methodsWorkloads.add(tmp);
}
methodsWorkloadTot = new HashMap<Integer, Integer>();
for (int i = 0; i < methodsNames.length; ++i) {
double sum = 0;
List<Double> workload = methodsWorkloads.get(i);
for (int j = 0; j < maxCommonLength; ++j)
sum += workload.get(j);
methodsWorkloadTot.put(i, (int)Math.round(sum));
}
}
public static void createDemandAnalysis(Path parent, String[] methodsNames, int cores, int window) {
logger.info("Creating the demand analysis report...");
if (methodsNames == null || methodsNames.length == 0)
throw new RuntimeException("You should specify at least one method name.");
if (methodsWorkloads == null || methodsWorkloadTot == null || demands == null || maxCommonLength == -1)
init(parent, methodsNames);
try (PrintWriter out = new PrintWriter(Paths.get(parent.toString(), RESULT).toFile())) {
for (int i = 0; i < methodsNames.length; ++i)
out.printf("Demand_%1$s,X_%1$s,", methodsNames[i]);
out.println("U_actual,U_measured,U_aoverm");
GenericChart<XYSeriesCollection> graph = GenericChart.createDemandLawGraph();
double sumUaoverm = 0;
for (int i = 0; i < maxCommonLength; ++i) {
double u = 0;
double uMeasured = demands.get(CPU_UTIL_COLUMN).get(i);
StringBuilder sb = new StringBuilder();
for (int j = 0; j < methodsNames.length; ++j) {
double d = demands.get(DEMAND_COLUMN_PREFIX + methodsNames[j]).get(i);
double x = methodsWorkloads.get(j).get(i) / (window * cores);
sb.append(doubleFormatter.format(d) + "," + doubleFormatter.format(x) + ",");
u += d*x;
graph.add(methodsNames[j], x, uMeasured);
}
u /= 1000;
sb.append(doubleFormatter.format(u) + "," + doubleFormatter.format(uMeasured) + "," + doubleFormatter.format(u / uMeasured));
sumUaoverm += u / uMeasured;
out.println(sb.toString());
}
out.printf("%1$s,%1$s,%1$s,%1$s,%2$s", ResponseTimeValidator.EMPTY, doubleFormatter.format(sumUaoverm / maxCommonLength));
graph.updateGraph();
graph.updateImage();
graph.save2png(parent.toString(), "demandLaw.png");
out.flush();
} catch (Exception e) {
logger.error("Error while dealing with the result file.", e);
}
}
public static void createRequestsAnalysis(Path parent, String[] methodsNames, boolean printOnlyTotalRequests) {
logger.info("Creating the requests analysis report...");
if (methodsNames == null || methodsNames.length == 0)
throw new RuntimeException("You should specify at least one method name.");
if (methodsWorkloads == null || methodsWorkloadTot == null || demands == null || maxCommonLength == -1)
init(parent, methodsNames);
try (PrintWriter out = new PrintWriter(Paths.get(parent.toString(), RESULT_REQS).toFile())) {
if (!printOnlyTotalRequests)
for (int i = 0; i < methodsNames.length; ++i)
out.printf("Requests_%s,", methodsNames[i]);
out.print("TotalRequestsConsidered,");
Map<String, Integer> requestsPerPageOnlyOk = getRequestsPerPage(parent);
if (!printOnlyTotalRequests)
for (String key : requestsPerPageOnlyOk.keySet())
out.printf("ActualRequestsOk_%s,", key);
out.println("TotalActualRequestsOk,PercentageOkLost");
int consideredRequests = 0;
// NOTE:
// all the datum must be considered times window, because they're an average computed on that window!
// plus the first 5 data are skipped, and they should be considered too in the count.
// The window is now always 1: the duration of the time window for the sdas and the other are the same!
int window = 1;
for (int j = 0; j < methodsNames.length; ++j) {
List<Double> workload = methodsWorkloads.get(j);
int methodTot = methodsWorkloadTot.get(j) * window;
methodTot += workload.get(0).intValue() * 5 * window;
for (int i = maxCommonLength; i < workload.size(); ++i)
methodTot += workload.get(i).intValue() * window;
if (!printOnlyTotalRequests)
out.print(methodTot + ",");
consideredRequests += methodTot;
}
out.print(consideredRequests + ",");
int actualRequestsOk = 0;
for (String key : requestsPerPageOnlyOk.keySet()) {
int methodTot = requestsPerPageOnlyOk.get(key);
if (!printOnlyTotalRequests)
out.print(methodTot + ",");
actualRequestsOk += methodTot;
}
out.println(actualRequestsOk + "," + doubleFormatter.format((actualRequestsOk - consideredRequests)/(double)actualRequestsOk * 100) + "%");
out.flush();
} catch (Exception e) {
logger.error("Error while dealing with the result file.", e);
}
}
public static void createWorkloadAnalysis(Path parent, String[] methodsNames, int timesteps) {
logger.info("Creating the workload analysis report...");
if (methodsNames == null || methodsNames.length == 0)
throw new RuntimeException("You should specify at least one method name.");
if (timesteps < 1)
throw new RuntimeException("You need at least 1 timestep!");
if (methodsWorkloads == null || methodsWorkloadTot == null || demands == null || maxCommonLength == -1)
init(parent, methodsNames);
try (PrintWriter out = new PrintWriter(Paths.get(parent.toString(), RESULT_WORKLOAD).toFile())) {
out.print("ErrorTimestep1");
for (int i = 2; i <= timesteps; ++i)
out.printf(",ErrorTimestep%d", i);
out.println();
double[] sums = new double[timesteps];
for (int i = 0; i < timesteps; ++i)
sums[i] = 0.0;
for (int i = 1; i <= methodsNames.length; ++i) {
try (Scanner sc = new Scanner(Paths.get(parent.toString(), "method" + i, WorkloadGapCalculator.RESULT))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.contains(WorkloadGapCalculator.EMPTY)) {
String[] splitted = line.split(",");
for (int k = 0, j = 2; k < timesteps; ++k, j+=2)
sums[k] += Double.valueOf(splitted[j].replaceAll("%", ""));
}
}
}
}
out.printf("%s%%", doubleFormatter.format(sums[0] / methodsNames.length));
for (int i = 1; i < timesteps; ++i)
out.printf(",%s%%", doubleFormatter.format(sums[i] / methodsNames.length));
out.println();
} catch (Exception e) {
logger.error("Error while dealing with the result file.", e);
}
}
public static void createResponseTimesAnalysis(Path parent, String appName, String[] methodsNames) {
logger.info("Creating the response times analysis report...");
if (methodsNames == null || methodsNames.length == 0)
throw new RuntimeException("You should specify at least one method name.");
if (methodsWorkloads == null || methodsWorkloadTot == null || demands == null || maxCommonLength == -1)
init(parent, methodsNames);
try (PrintWriter out = new PrintWriter(Paths.get(parent.toString(), RESULT_RES_TIMES).toFile())) {
out.println("Method,AvgResponseTime,StdDevResponseTime,MinResponseTime,MaxResponseTime");
Map<String, String> latenciesPerPage = getLatenciesPerPage(parent);
for (String key : latenciesPerPage.keySet()) {
String res = latenciesPerPage.get(key);
out.printf("%s_JMeter,%s\n", key, res);
}
Map<String, String> glassfishLatenciesPerPage = getLatenciesPerPageFromGlassfish(parent, appName, methodsNames);
for (String key : glassfishLatenciesPerPage.keySet()) {
String res = glassfishLatenciesPerPage.get(key);
out.printf("%s_Glassfish,%s\n", key, res);
}
Map<String, String> dataCollectorRTsPerPage = getResponseTimesPerPageFromDataCollector(parent, methodsNames);
for (String key : dataCollectorRTsPerPage.keySet()) {
String res = dataCollectorRTsPerPage.get(key);
out.printf("%s_DC,%s\n", key, res);
}
out.flush();
} catch (Exception e) {
logger.error("Error while dealing with the result file.", e);
}
}
public static final String TOMCAT_ACCESS_LOG = "localhost_access_log.txt";
private static Map<String, String> getLatenciesPerPageFromGlassfish(Path parent, String appName, String[] methodsNames) throws Exception {
LinkedHashMap<String, String> res = new LinkedHashMap<String, String>();
boolean goOn = true;
for (int i = 1; goOn; ++i) {
Path tomcatLog = Paths.get(parent.getParent().getParent().getParent().toString(), appName + i, "home", "ubuntu", "logs", TOMCAT_ACCESS_LOG);
if (tomcatLog.toFile().exists()) {
logger.info("Generating the fake Glassfish reports...");
FileHelper.createGlassfishReportFromTomcatLog(tomcatLog, Paths.get(parent.getParent().getParent().getParent().toString(), appName + i), methodsNames);
}
for (String method : methodsNames) {
Path jsonFile = Paths.get(parent.getParent().getParent().getParent().toString(), appName + i, method + ".json");
if (!jsonFile.toFile().exists()) {
goOn = false;
continue;
}
res.put(method + "_" + appName + i, parseGlassfishJson(jsonFile));
}
}
return res;
}
private static String parseGlassfishJson(Path jsonFile) throws Exception {
String json = FileUtils.readFileToString(jsonFile.toFile());
JSONObject obj = new JSONObject(json);
JSONObject extraProperties = obj.getJSONObject("extraProperties");
JSONObject entity = extraProperties.getJSONObject("entity");
JSONObject maxtime = entity.getJSONObject("maxtime");
JSONObject processingtime = entity.getJSONObject("processingtime");
return String.format("%d.000,0.000,0.000,%d.000", processingtime.getInt("count"), maxtime.getInt("count"));
}
private static Map<String, String> getResponseTimesPerPageFromDataCollector(Path parent, String[] methodsNames) throws Exception {
LinkedHashMap<String, String> res = new LinkedHashMap<String, String>();
for (int i = 1; i <= methodsNames.length; ++i) {
Path p = Paths.get(parent.toString(), "method" + i, DemandValidator.MONITORED_RESPONSETIME);
Map.Entry<String, String> entry = getResponseTimesPerPageFromSingleFile(p);
res.put(entry.getKey(), entry.getValue());
}
return res;
}
private static Map.Entry<String, String> getResponseTimesPerPageFromSingleFile(Path p) throws Exception {
List<Datum> data = Datum.getAllData(p, true).get(Datum.MIXED);
double avg = 0.0;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (Datum d : data) {
if (d.value > max)
max = d.value;
if (d.value < min)
min = d.value;
avg += d.value;
}
avg /= data.size();
double stdDev = 0;
for (Datum d : data)
stdDev += Math.pow(d.value - avg, 2);
stdDev /= data.size();
stdDev = Math.sqrt(stdDev);
return new AbstractMap.SimpleEntry<String, String>(data.get(0).resourceId, String.format("%s,%s,%s,%s", doubleFormatter.format(avg), doubleFormatter.format(stdDev), doubleFormatter.format(min), doubleFormatter.format(max)));
}
public static final int DEFAULT_TIMESTEPS = 5;
public static void perform(Path parent, Test.App app, int window, int cores) {
perform(parent, app, window, true, cores);
}
public static void perform(Path parent, Test.App app, int window, boolean printOnlyTotalRequests, int cores) {
createDemandAnalysis(parent, app.methods, cores, window);
createRequestsAnalysis(parent, app.methods, printOnlyTotalRequests);
createWorkloadAnalysis(parent, app.methods, DEFAULT_TIMESTEPS);
createResponseTimesAnalysis(parent, app.name, app.methods);
}
}
| 19,623 | 0.675687 | 0.670693 | 550 | 34.678181 | 33.571632 | 226 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.525455 | false | false | 5 |
0392cf87a808dab32f0bbb2691cc67f8bb9948b8 | 7,808,250,577,076 | efdce4ed5061fdd9e3c7fcacccc7b31537723e9a | /Java Files/Outros/JavaBeginnersGuide/src/main/java/JavBegGui_chapter14/MethodRefDemo2.java | f381f3be691abfd879c87bde6decd82caf878671 | []
| no_license | jrzabott/exerciciosUpskill | https://github.com/jrzabott/exerciciosUpskill | 1d48c75f342be6b6c42163a23bf5b58f19694e75 | 70b2ab58e1bed7be20468484bd48ed4f3bdd62de | refs/heads/main | 2023-04-05T18:57:48.219000 | 2021-04-26T08:25:29 | 2021-04-26T08:25:29 | 309,065,593 | 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 JavBegGui_chapter14;
interface IntPredicate2 {
boolean test(int n);
}
class MyIntNum {
private int v;
public MyIntNum(int v) {
this.v = v;
}
int getNum() {
return this.v;
}
boolean isFactor(int n) {
return (v % n) == 0;
}
}
/**
*
* @author user
*/
public class MethodRefDemo2 {
public static void main(String[] args) {
boolean result;
MyIntNum myNum = new MyIntNum(12);
MyIntNum myNum2 = new MyIntNum(16);
//Here, a mthod ref to idFactor on myNum is created.
IntPredicate2 ip = myNum::isFactor;
// Now, it is used to call isFactor() via test()
result = ip.test(3);
if (result) {
System.out.println("3 is a factor of " + myNum.getNum());
}
ip = myNum2::isFactor;
result = ip.test(3);
if (!result) {
System.out.println("3 is not a factor of " + myNum2.getNum());
}
}
}
| UTF-8 | Java | 1,169 | java | MethodRefDemo2.java | Java | [
{
"context": " return (v % n) == 0;\n }\n}\n\n/**\n *\n * @author user\n */\npublic class MethodRefDemo2 {\n\n public sta",
"end": 503,
"score": 0.9992589354515076,
"start": 499,
"tag": "USERNAME",
"value": "user"
}
]
| 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 JavBegGui_chapter14;
interface IntPredicate2 {
boolean test(int n);
}
class MyIntNum {
private int v;
public MyIntNum(int v) {
this.v = v;
}
int getNum() {
return this.v;
}
boolean isFactor(int n) {
return (v % n) == 0;
}
}
/**
*
* @author user
*/
public class MethodRefDemo2 {
public static void main(String[] args) {
boolean result;
MyIntNum myNum = new MyIntNum(12);
MyIntNum myNum2 = new MyIntNum(16);
//Here, a mthod ref to idFactor on myNum is created.
IntPredicate2 ip = myNum::isFactor;
// Now, it is used to call isFactor() via test()
result = ip.test(3);
if (result) {
System.out.println("3 is a factor of " + myNum.getNum());
}
ip = myNum2::isFactor;
result = ip.test(3);
if (!result) {
System.out.println("3 is not a factor of " + myNum2.getNum());
}
}
}
| 1,169 | 0.568862 | 0.55432 | 58 | 19.155172 | 20.980946 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.344828 | false | false | 5 |
0e867ec02f7070fea2dc710a2441a43ec400522c | 3,032,246,948,894 | 83d781a9c2ba33fde6df0c6adc3a434afa1a7f82 | /OrderFulfillment/OrderFulfillment.Jobs/src/main/java/com/servicelive/orderfulfillment/jobs/JobsService.java | 535f6468aa7eac3777778b8295a805edabd30b85 | []
| no_license | ssriha0/sl-b2b-platform | https://github.com/ssriha0/sl-b2b-platform | 71ab8ef1f0ccb0a7ad58b18f28a2bf6d5737fcb6 | 5b4fcafa9edfe4d35c2dcf1659ac30ef58d607a2 | refs/heads/master | 2023-01-06T18:32:24.623000 | 2020-11-05T12:23:26 | 2020-11-05T12:23:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.servicelive.orderfulfillment.jobs;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.servicelive.orderfulfillment.vo.CacheRefreshResponse;
import org.apache.log4j.Logger;
import com.servicelive.orderfulfillment.common.ControllerForRemoteServiceStartupDependentInitializer;
import com.servicelive.orderfulfillment.lookup.QuickLookupCollection;
import com.servicelive.orderfulfillment.orderprep.buyer.OrderBuyerCollection;
@Path("/")
public class JobsService {
private Logger logger = Logger.getLogger(getClass());
private QuickLookupCollection qckLkup;
private ControllerForRemoteServiceStartupDependentInitializer remoteServiceStartupInitializer;
private OrderBuyerCollection orderBuyers;
@GET
@Path("/cache/refresh/{cacheName}")
@Consumes( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public CacheRefreshResponse refreshCache(@PathParam("cacheName") String cacheName) {
/* TO BE IMPLEMENTED */
CacheRefreshResponse response = new CacheRefreshResponse();
response.setMessage("Cache name: " + cacheName);
return response;
}
@GET
@Path("/cache/refreshAll")
@Consumes( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public CacheRefreshResponse refreshAll() {
CacheRefreshResponse response = new CacheRefreshResponse();
try {
orderBuyers.initializeAllOrderBuyers();
qckLkup.initializeLocalNodeLookups();
remoteServiceStartupInitializer.runInitializers();
response.setMessage("All caches refreshed");
} catch (Exception e) {
response.addError(e.getMessage());
logger.error(e);
}
return response;
}
public void setQckLkup(QuickLookupCollection qckLkup) {
this.qckLkup = qckLkup;
}
public void setRemoteServiceStartupInitializer(ControllerForRemoteServiceStartupDependentInitializer remoteServiceStartupInitializer) {
this.remoteServiceStartupInitializer = remoteServiceStartupInitializer;
}
public void setOrderBuyers(OrderBuyerCollection orderBuyers) {
this.orderBuyers = orderBuyers;
}
}
| UTF-8 | Java | 2,397 | java | JobsService.java | Java | []
| null | []
| package com.servicelive.orderfulfillment.jobs;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.servicelive.orderfulfillment.vo.CacheRefreshResponse;
import org.apache.log4j.Logger;
import com.servicelive.orderfulfillment.common.ControllerForRemoteServiceStartupDependentInitializer;
import com.servicelive.orderfulfillment.lookup.QuickLookupCollection;
import com.servicelive.orderfulfillment.orderprep.buyer.OrderBuyerCollection;
@Path("/")
public class JobsService {
private Logger logger = Logger.getLogger(getClass());
private QuickLookupCollection qckLkup;
private ControllerForRemoteServiceStartupDependentInitializer remoteServiceStartupInitializer;
private OrderBuyerCollection orderBuyers;
@GET
@Path("/cache/refresh/{cacheName}")
@Consumes( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public CacheRefreshResponse refreshCache(@PathParam("cacheName") String cacheName) {
/* TO BE IMPLEMENTED */
CacheRefreshResponse response = new CacheRefreshResponse();
response.setMessage("Cache name: " + cacheName);
return response;
}
@GET
@Path("/cache/refreshAll")
@Consumes( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public CacheRefreshResponse refreshAll() {
CacheRefreshResponse response = new CacheRefreshResponse();
try {
orderBuyers.initializeAllOrderBuyers();
qckLkup.initializeLocalNodeLookups();
remoteServiceStartupInitializer.runInitializers();
response.setMessage("All caches refreshed");
} catch (Exception e) {
response.addError(e.getMessage());
logger.error(e);
}
return response;
}
public void setQckLkup(QuickLookupCollection qckLkup) {
this.qckLkup = qckLkup;
}
public void setRemoteServiceStartupInitializer(ControllerForRemoteServiceStartupDependentInitializer remoteServiceStartupInitializer) {
this.remoteServiceStartupInitializer = remoteServiceStartupInitializer;
}
public void setOrderBuyers(OrderBuyerCollection orderBuyers) {
this.orderBuyers = orderBuyers;
}
}
| 2,397 | 0.761786 | 0.761368 | 77 | 29.129869 | 30.251049 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.467533 | false | false | 5 |
21e58514904b46016a94a0c546b73c0375725bfb | 8,057,358,689,914 | 24ecb4f700b8edc68ffcaeae2a38239da58626e5 | /library-cursor/src/main/java/universum/studios/android/database/cursor/CursorUtils.java | 0f3f8d15c9d6b13c151ee6746b00cfdea3de7150 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | universum-studios/android_database | https://github.com/universum-studios/android_database | 669c1e31de0934d5c7086fe5def9f7f933883dc2 | 422890a8fd0212dac58eceda96d0bb4a4eb2270a | refs/heads/master | 2021-01-12T08:56:30.513000 | 2018-12-25T22:19:14 | 2018-12-25T22:19:14 | 76,684,263 | 2 | 0 | Apache-2.0 | false | 2018-11-23T16:46:06 | 2016-12-16T20:42:04 | 2018-11-23T14:23:23 | 2018-11-23T16:46:05 | 158,916 | 2 | 0 | 9 | Java | false | null | /*
* *************************************************************************************************
* Copyright 2017 Universum Studios
* *************************************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License")
* -------------------------------------------------------------------------------------------------
* You may not use this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
* *************************************************************************************************
*/
package universum.studios.android.database.cursor;
import android.database.Cursor;
import androidx.annotation.NonNull;
/**
* Utility class that may be used for safe obtaining of values provided by a specific cursor via
* column names associated with the desired values.
*
* @author Martin Albedinsky
*/
public final class CursorUtils {
/*
* Constants ===================================================================================
*/
/**
* Constant used to determine invalid column index obtained via {@link Cursor#getColumnIndex(String)}.
*/
public static final int INVALID_COLUMN_INDEX = -1;
/*
* Constructors ================================================================================
*/
/**
*/
private CursorUtils() {
// Not allowed to be instantiated publicly.
throw new UnsupportedOperationException();
}
/*
* Methods =====================================================================================
*/
/**
* Delegates to {@link Cursor#getShort(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or {@code 0} if the column index for the specified <var>columnName</var>
* is {@link #INVALID_COLUMN_INDEX}.
*/
@NonNull
public static Short obtainShort(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? 0 : cursor.getShort(index);
}
/**
* Delegates to {@link Cursor#getInt(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or {@code 0} if the column index for the specified <var>columnName</var>
* is {@link #INVALID_COLUMN_INDEX}.
*/
public static int obtainInt(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? 0 : cursor.getInt(index);
}
/**
* Delegates to {@link Cursor#getLong(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or {@code 0} if the column index for the specified <var>columnName</var>
* is {@link #INVALID_COLUMN_INDEX}.
*/
public static long obtainLong(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? 0 : cursor.getLong(index);
}
/**
* Delegates to {@link Cursor#getFloat(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or {@code 0} if the column index for the specified <var>columnName</var>
* is {@link #INVALID_COLUMN_INDEX}.
*/
public static float obtainFloat(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? 0 : cursor.getFloat(index);
}
/**
* Delegates to {@link Cursor#getDouble(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or {@code 0} if the column index for the specified <var>columnName</var>
* is {@link #INVALID_COLUMN_INDEX}.
*/
public static double obtainDouble(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? 0 : cursor.getDouble(index);
}
/**
* Delegates to {@link Cursor#getString(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or an {@code empty string} if the column index for the specified
* <var>columnName</var> is {@link #INVALID_COLUMN_INDEX}.
*/
@NonNull
public static String obtainString(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? "" : cursor.getString(index);
}
/**
* Returns value obtained from {@link #obtainString(Cursor, String)} parsed as <b>boolean</b>.
*
* @return {@code True} if the obtained string has {@code value == 'true'}, {@code false} otherwise.
* @see #obtainIntBoolean(Cursor, String)
*/
public static boolean obtainBoolean(@NonNull final Cursor cursor, @NonNull final String columnName) {
return Boolean.parseBoolean(obtainString(cursor, columnName));
}
/**
* Returns value obtained from {@link #obtainInt(Cursor, String)} resolved as <b>boolean</b>.
*
* @return {@code True} if the obtained integer has {@code value == 1}, {@code false} otherwise.
* @see #obtainBoolean(Cursor, String)
*/
public static boolean obtainIntBoolean(@NonNull final Cursor cursor, @NonNull final String columnName) {
return obtainInt(cursor, columnName) == 1;
}
} | UTF-8 | Java | 7,065 | java | CursorUtils.java | Java | [
{
"context": " associated with the desired values.\n *\n * @author Martin Albedinsky\n */\npublic final class CursorUtils {\n\n\t/*\n\t * Con",
"end": 1357,
"score": 0.9989086389541626,
"start": 1340,
"tag": "NAME",
"value": "Martin Albedinsky"
}
]
| null | []
| /*
* *************************************************************************************************
* Copyright 2017 Universum Studios
* *************************************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License")
* -------------------------------------------------------------------------------------------------
* You may not use this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
* *************************************************************************************************
*/
package universum.studios.android.database.cursor;
import android.database.Cursor;
import androidx.annotation.NonNull;
/**
* Utility class that may be used for safe obtaining of values provided by a specific cursor via
* column names associated with the desired values.
*
* @author <NAME>
*/
public final class CursorUtils {
/*
* Constants ===================================================================================
*/
/**
* Constant used to determine invalid column index obtained via {@link Cursor#getColumnIndex(String)}.
*/
public static final int INVALID_COLUMN_INDEX = -1;
/*
* Constructors ================================================================================
*/
/**
*/
private CursorUtils() {
// Not allowed to be instantiated publicly.
throw new UnsupportedOperationException();
}
/*
* Methods =====================================================================================
*/
/**
* Delegates to {@link Cursor#getShort(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or {@code 0} if the column index for the specified <var>columnName</var>
* is {@link #INVALID_COLUMN_INDEX}.
*/
@NonNull
public static Short obtainShort(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? 0 : cursor.getShort(index);
}
/**
* Delegates to {@link Cursor#getInt(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or {@code 0} if the column index for the specified <var>columnName</var>
* is {@link #INVALID_COLUMN_INDEX}.
*/
public static int obtainInt(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? 0 : cursor.getInt(index);
}
/**
* Delegates to {@link Cursor#getLong(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or {@code 0} if the column index for the specified <var>columnName</var>
* is {@link #INVALID_COLUMN_INDEX}.
*/
public static long obtainLong(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? 0 : cursor.getLong(index);
}
/**
* Delegates to {@link Cursor#getFloat(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or {@code 0} if the column index for the specified <var>columnName</var>
* is {@link #INVALID_COLUMN_INDEX}.
*/
public static float obtainFloat(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? 0 : cursor.getFloat(index);
}
/**
* Delegates to {@link Cursor#getDouble(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or {@code 0} if the column index for the specified <var>columnName</var>
* is {@link #INVALID_COLUMN_INDEX}.
*/
public static double obtainDouble(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? 0 : cursor.getDouble(index);
}
/**
* Delegates to {@link Cursor#getString(int)} with a column index obtained from
* {@link Cursor#getColumnIndex(String)} for the specified <var>columnName</var>.
*
* @param cursor The cursor from which to obtain the desired value.
* @param columnName Name of the column for which to obtain the desired value.
* @return The desired value or an {@code empty string} if the column index for the specified
* <var>columnName</var> is {@link #INVALID_COLUMN_INDEX}.
*/
@NonNull
public static String obtainString(@NonNull final Cursor cursor, @NonNull final String columnName) {
final int index = cursor.getColumnIndex(columnName);
return index == INVALID_COLUMN_INDEX ? "" : cursor.getString(index);
}
/**
* Returns value obtained from {@link #obtainString(Cursor, String)} parsed as <b>boolean</b>.
*
* @return {@code True} if the obtained string has {@code value == 'true'}, {@code false} otherwise.
* @see #obtainIntBoolean(Cursor, String)
*/
public static boolean obtainBoolean(@NonNull final Cursor cursor, @NonNull final String columnName) {
return Boolean.parseBoolean(obtainString(cursor, columnName));
}
/**
* Returns value obtained from {@link #obtainInt(Cursor, String)} resolved as <b>boolean</b>.
*
* @return {@code True} if the obtained integer has {@code value == 1}, {@code false} otherwise.
* @see #obtainBoolean(Cursor, String)
*/
public static boolean obtainIntBoolean(@NonNull final Cursor cursor, @NonNull final String columnName) {
return obtainInt(cursor, columnName) == 1;
}
} | 7,054 | 0.649257 | 0.646285 | 162 | 42.617283 | 39.453228 | 105 | false | false | 0 | 0 | 0 | 0 | 86 | 0.035527 | 1.061728 | false | false | 5 |
2c98b4eecd2eba4645bfcb9403080e70769a58c6 | 15,985,868,323,869 | 1a64fb7388a2f3c489aaf3e55e67ea55beb39075 | /src/main/java/org/javacs/JavacConfig.java | 8490b8e8238efa07e4101cebf3865dcc7cb8c451 | [
"MIT"
]
| permissive | ashfordneil/vscode-javac | https://github.com/ashfordneil/vscode-javac | 42939ab3f2f984f22f14677ba0a3890e3f4ffb61 | 6774f71503710839f1de8a7ee0afdcf23de9817d | refs/heads/master | 2021-09-11T17:48:46.515000 | 2018-04-10T12:02:09 | 2018-04-10T12:02:09 | 107,550,131 | 1 | 0 | null | true | 2017-10-19T13:29:32 | 2017-10-19T13:29:32 | 2017-10-07T00:09:01 | 2017-10-16T19:14:05 | 21,716 | 0 | 0 | 0 | null | null | null | package org.javacs;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Set;
public class JavacConfig {
public final Set<Path> classPath, workspaceClassPath, docPath;
public JavacConfig(Set<Path> classPath, Set<Path> workspaceClassPath, Set<Path> docPath) {
this.classPath = classPath;
this.workspaceClassPath = workspaceClassPath;
this.docPath = docPath;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JavacConfig that = (JavacConfig) o;
return Objects.equals(classPath, that.classPath)
&& Objects.equals(workspaceClassPath, that.workspaceClassPath)
&& Objects.equals(docPath, that.docPath);
}
@Override
public int hashCode() {
return Objects.hash(classPath, workspaceClassPath, docPath);
}
}
| UTF-8 | Java | 935 | java | JavacConfig.java | Java | []
| null | []
| package org.javacs;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Set;
public class JavacConfig {
public final Set<Path> classPath, workspaceClassPath, docPath;
public JavacConfig(Set<Path> classPath, Set<Path> workspaceClassPath, Set<Path> docPath) {
this.classPath = classPath;
this.workspaceClassPath = workspaceClassPath;
this.docPath = docPath;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JavacConfig that = (JavacConfig) o;
return Objects.equals(classPath, that.classPath)
&& Objects.equals(workspaceClassPath, that.workspaceClassPath)
&& Objects.equals(docPath, that.docPath);
}
@Override
public int hashCode() {
return Objects.hash(classPath, workspaceClassPath, docPath);
}
}
| 935 | 0.657754 | 0.657754 | 30 | 30.166666 | 26.267958 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 5 |
dbf1197bd2078d2cbc87abb111d316d7521c1042 | 3,934,190,094,549 | 625b406c53b95ab5c273374384fc5a5d7ab9b164 | /src/clazzcode/classcode0914/runnabletest/PlayAndDownloadRunnableTest.java | 70a61c80afae571c9bb92e3452f77accbc1e5154 | []
| no_license | GLOxxxxi/Itsource | https://github.com/GLOxxxxi/Itsource | ce36391e21214702921ab4432761e93d9e601feb | 0164b82fed6c2f01c3f5d5ee896b5397163623db | refs/heads/master | 2023-08-03T13:16:17.996000 | 2021-09-23T05:11:06 | 2021-09-23T05:11:06 | 409,409,406 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package clazzcode.classcode0914.runnabletest;
/**
* 播放下载多线程测试了 PlayAndDownloadRunnableTest 创建了播放和下载两个线程
*/
public class PlayAndDownloadRunnableTest {
public static void main(String[] args) {
// 创建接口实现类对象
DownloadRunnableImpl downloadRunnable = new DownloadRunnableImpl();
PlayRunnableImpl playRunnable = new PlayRunnableImpl();
// 创建线程对象,将接口实现类传入到线程对象中
Thread downloadThread = new Thread(downloadRunnable);
Thread playThread = new Thread(playRunnable);
// 启动线程
downloadThread.start();
playThread.start();
}
}
| UTF-8 | Java | 705 | java | PlayAndDownloadRunnableTest.java | Java | []
| null | []
| package clazzcode.classcode0914.runnabletest;
/**
* 播放下载多线程测试了 PlayAndDownloadRunnableTest 创建了播放和下载两个线程
*/
public class PlayAndDownloadRunnableTest {
public static void main(String[] args) {
// 创建接口实现类对象
DownloadRunnableImpl downloadRunnable = new DownloadRunnableImpl();
PlayRunnableImpl playRunnable = new PlayRunnableImpl();
// 创建线程对象,将接口实现类传入到线程对象中
Thread downloadThread = new Thread(downloadRunnable);
Thread playThread = new Thread(playRunnable);
// 启动线程
downloadThread.start();
playThread.start();
}
}
| 705 | 0.696459 | 0.689713 | 19 | 30.210526 | 23.849482 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 5 |
afb390a1b62be103faae921d3c100da609d352f2 | 9,715,216,069,226 | 383303413aeb215c40fa5cbd752dd379ae56dd8f | /app/src/main/java/com/lhc/frank/superviewholderdemo/MyBaseAdapter.java | a3dd0c14918a1e280b06fe7918f055b5458ca91a | []
| no_license | hancongAndroid/SuperViewHolder | https://github.com/hancongAndroid/SuperViewHolder | af02e62ed2ffa5a5f308da646a2e9d228cda8ec5 | 71c4d52cffb29619d3a1fbd5b33c9e0813331658 | refs/heads/master | 2018-01-05T06:20:21.495000 | 2016-10-16T15:46:00 | 2016-10-16T15:46:00 | 71,060,132 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lhc.frank.superviewholderdemo;
import android.widget.BaseAdapter;
import java.util.List;
/**
* Project Name: SuperViewHolderDemo
* Package Name: com.lhc.frank.superviewholderdemo
* Created by: Frank 2016/10/16 23:02
* <p>
* Class Desc: TODO
*/
public abstract class MyBaseAdapter<T> extends BaseAdapter {
public static final String TAG = "MyBaseAdapter";
private List<T> data;
public MyBaseAdapter(List<T> data) {
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
| UTF-8 | Java | 762 | java | MyBaseAdapter.java | Java | [
{
"context": ".lhc.frank.superviewholderdemo\n * Created by: Frank 2016/10/16 23:02\n * <p>\n * Class Desc: TODO\n",
"end": 227,
"score": 0.9996657371520996,
"start": 222,
"tag": "NAME",
"value": "Frank"
}
]
| null | []
| package com.lhc.frank.superviewholderdemo;
import android.widget.BaseAdapter;
import java.util.List;
/**
* Project Name: SuperViewHolderDemo
* Package Name: com.lhc.frank.superviewholderdemo
* Created by: Frank 2016/10/16 23:02
* <p>
* Class Desc: TODO
*/
public abstract class MyBaseAdapter<T> extends BaseAdapter {
public static final String TAG = "MyBaseAdapter";
private List<T> data;
public MyBaseAdapter(List<T> data) {
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
| 762 | 0.645669 | 0.629921 | 37 | 19.594595 | 18.263033 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.243243 | false | false | 5 |
535d34418780e12c2c566bed476ff473ec9bd164 | 6,940,667,194,372 | c420b8e8095d35cfe31193ea2d384962ada4a252 | /src/main/java/ru/friends/model/dto/DataChange.java | 69aa4c4ef6f2bd938bb91d6b19f9fe5497d4316c | []
| no_license | Andrey759/vk-deleted-friends | https://github.com/Andrey759/vk-deleted-friends | b5abceb71031e06095d86356216e5f2af7f5f947 | 9969e7e01efbbaa6cc255f9ffff8b3d8735fae56 | refs/heads/master | 2020-05-18T01:16:42.148000 | 2018-02-26T11:40:27 | 2018-02-26T11:40:27 | 24,823,267 | 1 | 1 | null | false | 2017-05-27T18:10:46 | 2014-10-05T18:50:05 | 2017-04-08T11:35:32 | 2017-05-27T12:03:39 | 66 | 1 | 1 | 0 | Java | null | null | package ru.friends.model.dto;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import ru.friends.model.dto.data.AbstractData;
import javax.persistence.*;
import java.time.Instant;
@Entity
@EqualsAndHashCode
@ToString
@Data
public class DataChange {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne
@JoinColumn(name = "data_id")
AbstractData data;
@Column
Instant detectTimeMin;
@Column
Instant detectTimeMax;
@Column
String fieldName;
@Column
String oldValue;
@Column
String newValue;
}
| UTF-8 | Java | 617 | java | DataChange.java | Java | []
| null | []
| package ru.friends.model.dto;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import ru.friends.model.dto.data.AbstractData;
import javax.persistence.*;
import java.time.Instant;
@Entity
@EqualsAndHashCode
@ToString
@Data
public class DataChange {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne
@JoinColumn(name = "data_id")
AbstractData data;
@Column
Instant detectTimeMin;
@Column
Instant detectTimeMax;
@Column
String fieldName;
@Column
String oldValue;
@Column
String newValue;
}
| 617 | 0.708266 | 0.708266 | 40 | 14.425 | 13.408743 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 5 |
c1333ea683bb4c2b923fc4e834b1ba9d63adad02 | 28,003,186,815,919 | 90fad71a4e827ee0c7f4ab7cf3173df54c9927bc | /src/main/java/it/italiancoders/mybudgetrest/dao/movement/impl/MovementDaoCriteriaImpl.java | ad71843ccf5ed2ecd5df4bc0191a9e9008771f72 | []
| no_license | dario-frongillo/my-budget-rest-api | https://github.com/dario-frongillo/my-budget-rest-api | 36559822bff990be3bb037e0c0a66e603141605a | cd270bc450edcb2832e06efa75acf91a80d03ef2 | refs/heads/master | 2021-07-11T02:07:24.698000 | 2019-10-20T07:48:22 | 2019-10-20T07:48:22 | 207,079,496 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.italiancoders.mybudgetrest.dao.movement.impl;
import it.italiancoders.mybudgetrest.dao.movement.MovementDaoCriteria;
import it.italiancoders.mybudgetrest.model.dto.User;
import it.italiancoders.mybudgetrest.model.entity.CategoryEntity;
import it.italiancoders.mybudgetrest.model.entity.MovementEntity;
import it.italiancoders.mybudgetrest.model.entity.UserEntity;
import it.italiancoders.mybudgetrest.model.internal.CategoryEntityExpenseSummary;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Repository
public class MovementDaoCriteriaImpl implements MovementDaoCriteria {
@Autowired
EntityManager em;
@Autowired
private ModelMapper modelMapper;
@Override
public List<CategoryEntityExpenseSummary> calculateCategoryEntityExpenseSummary
(Authentication token, Integer day, Integer month, Integer year, Integer week, CategoryEntity categoryEntity) {
User currentUser = (User) token.getPrincipal();
CriteriaBuilder cb = em.getCriteriaBuilder();
List<Predicate> allPredicates = new ArrayList<>();
UserEntity userEntity = modelMapper.map(currentUser, UserEntity.class);
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<MovementEntity> rootMovement = cq.from(MovementEntity.class);
Join<MovementEntity, CategoryEntity> typeJoin = rootMovement.join("category");
cq.multiselect(typeJoin, cb.sum(rootMovement.get("amount")));
allPredicates.add(cb.equal(rootMovement.get("user"), userEntity));
if (day != null) {
allPredicates.add(cb.equal(rootMovement.get("day"), day));
} else if (week != null) {
allPredicates.add(cb.equal(rootMovement.get("week"), week));
}
if (month != null) {
allPredicates.add(cb.equal(rootMovement.get("month"), month));
}
if (year != null) {
allPredicates.add(cb.equal(rootMovement.get("year"), year));
}
if (categoryEntity != null) {
allPredicates.add(cb.equal(rootMovement.get("category"), categoryEntity));
}
cq.where(allPredicates.toArray(new Predicate[0]));
cq.groupBy(typeJoin);
List<Tuple> tuples = em.createQuery(cq).getResultList();
return tuples.stream().map((v) ->
CategoryEntityExpenseSummary
.newBuilder()
.category((CategoryEntity) v.get(0))
.totalAmount((Double) v.get(1))
.build()
).collect(Collectors.toList());
}
@Override
public Page<MovementEntity> find(Authentication token, Integer day, Integer month, Integer year, Integer week, CategoryEntity categoryEntity, Pageable pageable) {
User currentUser = (User) token.getPrincipal();
UserEntity userEntity = modelMapper.map(currentUser, UserEntity.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MovementEntity> cq = cb.createQuery(MovementEntity.class);
CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
Root<MovementEntity> rootCount = countQuery.from(MovementEntity.class);
Root<MovementEntity> root = cq.from(MovementEntity.class);
countQuery.select(cb.count(rootCount));
List<Predicate> allPredicates = new ArrayList<>();
List<Predicate> countPredicates = new ArrayList<>();
allPredicates.add(cb.equal(root.get("user"), userEntity));
countPredicates.add(cb.equal(rootCount.get("user"), userEntity));
if (day != null) {
allPredicates.add(cb.equal(root.get("day"), day));
countPredicates.add(cb.equal(rootCount.get("day"), day));
} else {
if (week != null) {
allPredicates.add(cb.equal(root.get("week"), week));
countPredicates.add(cb.equal(rootCount.get("week"), week));
}
}
if (month != null) {
allPredicates.add(cb.equal(root.get("month"), month));
countPredicates.add(cb.equal(rootCount.get("month"), month));
}
if (year != null) {
allPredicates.add(cb.equal(root.get("year"), year));
countPredicates.add(cb.equal(rootCount.get("year"), year));
}
if (categoryEntity != null) {
allPredicates.add(cb.equal(root.get("category"), categoryEntity));
countPredicates.add(cb.equal(rootCount.get("category"), categoryEntity));
}
countQuery.where(countPredicates.toArray(new Predicate[0]));
Long count = em.createQuery(countQuery).getSingleResult();
if (count == 0) {
return new PageImpl<>(new ArrayList<>(), pageable, count);
}
cq.where(allPredicates.toArray(new Predicate[0]));
cq.orderBy(em.getCriteriaBuilder().desc(root.get("executedAt")));
TypedQuery<MovementEntity> query = em.createQuery(cq).setFirstResult((int) pageable.getOffset()).setMaxResults(pageable.getPageSize());
List<MovementEntity> retval = query.getResultList();
return new PageImpl<>(retval, pageable, count);
}
}
| UTF-8 | Java | 5,655 | java | MovementDaoCriteriaImpl.java | Java | []
| null | []
| package it.italiancoders.mybudgetrest.dao.movement.impl;
import it.italiancoders.mybudgetrest.dao.movement.MovementDaoCriteria;
import it.italiancoders.mybudgetrest.model.dto.User;
import it.italiancoders.mybudgetrest.model.entity.CategoryEntity;
import it.italiancoders.mybudgetrest.model.entity.MovementEntity;
import it.italiancoders.mybudgetrest.model.entity.UserEntity;
import it.italiancoders.mybudgetrest.model.internal.CategoryEntityExpenseSummary;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Repository
public class MovementDaoCriteriaImpl implements MovementDaoCriteria {
@Autowired
EntityManager em;
@Autowired
private ModelMapper modelMapper;
@Override
public List<CategoryEntityExpenseSummary> calculateCategoryEntityExpenseSummary
(Authentication token, Integer day, Integer month, Integer year, Integer week, CategoryEntity categoryEntity) {
User currentUser = (User) token.getPrincipal();
CriteriaBuilder cb = em.getCriteriaBuilder();
List<Predicate> allPredicates = new ArrayList<>();
UserEntity userEntity = modelMapper.map(currentUser, UserEntity.class);
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<MovementEntity> rootMovement = cq.from(MovementEntity.class);
Join<MovementEntity, CategoryEntity> typeJoin = rootMovement.join("category");
cq.multiselect(typeJoin, cb.sum(rootMovement.get("amount")));
allPredicates.add(cb.equal(rootMovement.get("user"), userEntity));
if (day != null) {
allPredicates.add(cb.equal(rootMovement.get("day"), day));
} else if (week != null) {
allPredicates.add(cb.equal(rootMovement.get("week"), week));
}
if (month != null) {
allPredicates.add(cb.equal(rootMovement.get("month"), month));
}
if (year != null) {
allPredicates.add(cb.equal(rootMovement.get("year"), year));
}
if (categoryEntity != null) {
allPredicates.add(cb.equal(rootMovement.get("category"), categoryEntity));
}
cq.where(allPredicates.toArray(new Predicate[0]));
cq.groupBy(typeJoin);
List<Tuple> tuples = em.createQuery(cq).getResultList();
return tuples.stream().map((v) ->
CategoryEntityExpenseSummary
.newBuilder()
.category((CategoryEntity) v.get(0))
.totalAmount((Double) v.get(1))
.build()
).collect(Collectors.toList());
}
@Override
public Page<MovementEntity> find(Authentication token, Integer day, Integer month, Integer year, Integer week, CategoryEntity categoryEntity, Pageable pageable) {
User currentUser = (User) token.getPrincipal();
UserEntity userEntity = modelMapper.map(currentUser, UserEntity.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MovementEntity> cq = cb.createQuery(MovementEntity.class);
CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
Root<MovementEntity> rootCount = countQuery.from(MovementEntity.class);
Root<MovementEntity> root = cq.from(MovementEntity.class);
countQuery.select(cb.count(rootCount));
List<Predicate> allPredicates = new ArrayList<>();
List<Predicate> countPredicates = new ArrayList<>();
allPredicates.add(cb.equal(root.get("user"), userEntity));
countPredicates.add(cb.equal(rootCount.get("user"), userEntity));
if (day != null) {
allPredicates.add(cb.equal(root.get("day"), day));
countPredicates.add(cb.equal(rootCount.get("day"), day));
} else {
if (week != null) {
allPredicates.add(cb.equal(root.get("week"), week));
countPredicates.add(cb.equal(rootCount.get("week"), week));
}
}
if (month != null) {
allPredicates.add(cb.equal(root.get("month"), month));
countPredicates.add(cb.equal(rootCount.get("month"), month));
}
if (year != null) {
allPredicates.add(cb.equal(root.get("year"), year));
countPredicates.add(cb.equal(rootCount.get("year"), year));
}
if (categoryEntity != null) {
allPredicates.add(cb.equal(root.get("category"), categoryEntity));
countPredicates.add(cb.equal(rootCount.get("category"), categoryEntity));
}
countQuery.where(countPredicates.toArray(new Predicate[0]));
Long count = em.createQuery(countQuery).getSingleResult();
if (count == 0) {
return new PageImpl<>(new ArrayList<>(), pageable, count);
}
cq.where(allPredicates.toArray(new Predicate[0]));
cq.orderBy(em.getCriteriaBuilder().desc(root.get("executedAt")));
TypedQuery<MovementEntity> query = em.createQuery(cq).setFirstResult((int) pageable.getOffset()).setMaxResults(pageable.getPageSize());
List<MovementEntity> retval = query.getResultList();
return new PageImpl<>(retval, pageable, count);
}
}
| 5,655 | 0.673563 | 0.672502 | 132 | 41.840908 | 31.869009 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false | 5 |
bf59472afea4cc51b695e4f2d7d8c5e2744d31f4 | 33,389,075,809,580 | f27a1327cc6e5af701c45ce24fe106742d3be804 | /Java/java-core/src/main/java/com/mercury/java_core/generics/GamingChair.java | fdf34b7fd3e41821daf1010ab05a7215e36d3f19 | []
| no_license | hxz156/Train | https://github.com/hxz156/Train | ac04b0a5d2ba58a385cd0b60f02d1990919bdc99 | e44950c2f0ad14154487be8274dbdeda5a905f94 | refs/heads/master | 2023-02-07T14:15:30.227000 | 2019-12-11T16:38:09 | 2019-12-11T16:38:09 | 227,409,015 | 0 | 0 | null | false | 2023-01-24T00:56:18 | 2019-12-11T16:18:30 | 2019-12-11T16:42:50 | 2023-01-24T00:56:18 | 150,374 | 0 | 0 | 22 | JavaScript | false | false | package com.mercury.java_core.generics;
public class GamingChair extends Chair {
}
| UTF-8 | Java | 91 | java | GamingChair.java | Java | []
| null | []
| package com.mercury.java_core.generics;
public class GamingChair extends Chair {
}
| 91 | 0.736264 | 0.736264 | 5 | 16.200001 | 19.030502 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 5 |
8d868b72977b3b5af60cbe1b0dacaf0b0cb0c8c4 | 32,933,809,275,663 | b6aba21928bbe4b17af7d91299a1ddee9c29fed1 | /src/main/java/com/hz/app/evaluate/controller/EveluateController.java | f5ed30620b251935a4e2d7de84c599aae5108ae8 | []
| no_license | xiangjin0727/shizhuapi | https://github.com/xiangjin0727/shizhuapi | 3de9cbac20d5a0614ae1057ae704fb4986cbce4e | 96a5683135d8d07a0301151a97d84e7cb837c795 | refs/heads/master | 2020-03-28T15:12:36.629000 | 2018-09-13T07:53:27 | 2018-09-13T07:53:27 | 148,567,392 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hz.app.evaluate.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hz.app.evaluate.dao.EveluateDao;
import com.hz.app.servlet.BaseController;
import com.hz.app.user.dao.UserMyInformationDao;
/**
* 投诉建议 S0028
* 投诉建议列表 S0044
* 可维修项目 S0068
*
* @author XJin
*
*/
@Controller
@RequestMapping("evaluate")
public class EveluateController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(EveluateController.class);
@Autowired
UserMyInformationDao userMyInformationDao;
@Autowired
EveluateDao eveluateDao;
/**
* 投诉建议 S0028
* @return
*/
@RequestMapping(value = "doComplaintProposal",produces="text/html;charset=UTF-8")
@ResponseBody
public Map<String, Object> doComplaintProposal(HttpServletRequest request, HttpServletResponse reponse){
Map<String, Object> resultMap = new HashMap<>();
try{
Map<String, Object> parametersMap = getParameters(request);
logger.debug("------投诉建议 S0028 入参:-----{}",parametersMap.toString());
@SuppressWarnings("unchecked")
Map<String, String> data = (Map<String, String>) parametersMap.get("data");
eveluateDao.doComplaintProposal(data);
resultMap.put("result_code", "0000");
resultMap.put("result_message", "投诉建议成功");
Map<String, String> da = new HashMap<>();
da.put("result_code", "0000");
resultMap.put("data", da);
} catch (Exception e) {
logger.error("系统异常:{}",e);
resultMap.put("result_code", "0002");
resultMap.put("result_message", "投诉建议失败");
}
return resultMap;
}
/**
* 投诉建议列表 S0044
* @return
*/
@RequestMapping(value = "doComplaintProposalList",produces="text/html;charset=UTF-8")
@ResponseBody
public Map<String, Object> doComplaintProposalList(HttpServletRequest request, HttpServletResponse reponse){
Map<String, Object> resultMap = new HashMap<>();
try{
Map<String, Object> parametersMap = getParameters(request);
logger.debug("------投诉建议列表 S0044 入参:-----{}",parametersMap.toString());
@SuppressWarnings("unchecked")
Map<String, String> data = (Map<String, String>) parametersMap.get("data");
List<Map<String,String>> mapL=eveluateDao.doComplaintProposalList(data);
resultMap.put("result_code", "0000");
resultMap.put("result_message", "投诉建议列表成功");
resultMap.put("data", mapL);
} catch (Exception e) {
logger.error("系统异常:{}",e);
resultMap.put("result_code", "0002");
resultMap.put("result_message", "投诉建议列表失败");
}
return resultMap;
}
/**
* 可维修项目 S0068
* @return
*/
@RequestMapping(value = "getRepairableProject",produces="text/html;charset=UTF-8")
@ResponseBody
public Map<String, Object> getRepairableProject(HttpServletRequest request, HttpServletResponse reponse){
Map<String, Object> resultMap = new HashMap<>();
try{
Map<String, Object> parametersMap = getParameters(request);
logger.debug("------可维修项目 S0068 入参:-----{}",parametersMap.toString());
@SuppressWarnings("unchecked")
Map<String, String> data = (Map<String, String>) parametersMap.get("data");
List<Map<String,String>> mapL=eveluateDao.getRepairableProject(data);
resultMap.put("result_code", "0000");
resultMap.put("result_message", "可维修项目成功");
resultMap.put("data", mapL);
} catch (Exception e) {
logger.error("系统异常:{}",e);
resultMap.put("result_code", "0002");
resultMap.put("result_message", "可维修项目失败");
}
return resultMap;
}
}
| UTF-8 | Java | 4,050 | java | EveluateController.java | Java | [
{
"context": "028\n * 投诉建议列表 S0044\n * 可维修项目 S0068\n * \n * @author XJin\n *\n */\n@Controller\n@RequestMapping(\"evaluate\")",
"end": 704,
"score": 0.8161343932151794,
"start": 703,
"tag": "NAME",
"value": "X"
},
{
"context": "8\n * 投诉建议列表 S0044\n * 可维修项目 S0068\n * \n * @author XJin\n *\n */\n@Controller\n@RequestMapping(\"evaluate\")\npu",
"end": 707,
"score": 0.6386154890060425,
"start": 704,
"tag": "USERNAME",
"value": "Jin"
}
]
| null | []
| package com.hz.app.evaluate.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hz.app.evaluate.dao.EveluateDao;
import com.hz.app.servlet.BaseController;
import com.hz.app.user.dao.UserMyInformationDao;
/**
* 投诉建议 S0028
* 投诉建议列表 S0044
* 可维修项目 S0068
*
* @author XJin
*
*/
@Controller
@RequestMapping("evaluate")
public class EveluateController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(EveluateController.class);
@Autowired
UserMyInformationDao userMyInformationDao;
@Autowired
EveluateDao eveluateDao;
/**
* 投诉建议 S0028
* @return
*/
@RequestMapping(value = "doComplaintProposal",produces="text/html;charset=UTF-8")
@ResponseBody
public Map<String, Object> doComplaintProposal(HttpServletRequest request, HttpServletResponse reponse){
Map<String, Object> resultMap = new HashMap<>();
try{
Map<String, Object> parametersMap = getParameters(request);
logger.debug("------投诉建议 S0028 入参:-----{}",parametersMap.toString());
@SuppressWarnings("unchecked")
Map<String, String> data = (Map<String, String>) parametersMap.get("data");
eveluateDao.doComplaintProposal(data);
resultMap.put("result_code", "0000");
resultMap.put("result_message", "投诉建议成功");
Map<String, String> da = new HashMap<>();
da.put("result_code", "0000");
resultMap.put("data", da);
} catch (Exception e) {
logger.error("系统异常:{}",e);
resultMap.put("result_code", "0002");
resultMap.put("result_message", "投诉建议失败");
}
return resultMap;
}
/**
* 投诉建议列表 S0044
* @return
*/
@RequestMapping(value = "doComplaintProposalList",produces="text/html;charset=UTF-8")
@ResponseBody
public Map<String, Object> doComplaintProposalList(HttpServletRequest request, HttpServletResponse reponse){
Map<String, Object> resultMap = new HashMap<>();
try{
Map<String, Object> parametersMap = getParameters(request);
logger.debug("------投诉建议列表 S0044 入参:-----{}",parametersMap.toString());
@SuppressWarnings("unchecked")
Map<String, String> data = (Map<String, String>) parametersMap.get("data");
List<Map<String,String>> mapL=eveluateDao.doComplaintProposalList(data);
resultMap.put("result_code", "0000");
resultMap.put("result_message", "投诉建议列表成功");
resultMap.put("data", mapL);
} catch (Exception e) {
logger.error("系统异常:{}",e);
resultMap.put("result_code", "0002");
resultMap.put("result_message", "投诉建议列表失败");
}
return resultMap;
}
/**
* 可维修项目 S0068
* @return
*/
@RequestMapping(value = "getRepairableProject",produces="text/html;charset=UTF-8")
@ResponseBody
public Map<String, Object> getRepairableProject(HttpServletRequest request, HttpServletResponse reponse){
Map<String, Object> resultMap = new HashMap<>();
try{
Map<String, Object> parametersMap = getParameters(request);
logger.debug("------可维修项目 S0068 入参:-----{}",parametersMap.toString());
@SuppressWarnings("unchecked")
Map<String, String> data = (Map<String, String>) parametersMap.get("data");
List<Map<String,String>> mapL=eveluateDao.getRepairableProject(data);
resultMap.put("result_code", "0000");
resultMap.put("result_message", "可维修项目成功");
resultMap.put("data", mapL);
} catch (Exception e) {
logger.error("系统异常:{}",e);
resultMap.put("result_code", "0002");
resultMap.put("result_message", "可维修项目失败");
}
return resultMap;
}
}
| 4,050 | 0.71518 | 0.697183 | 122 | 30.426229 | 27.346867 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.385246 | false | false | 5 |
7e7d8a9d295db519b097ff279efb5bb3c21825e6 | 24,404,004,230,535 | dc5c48ac6ba47ce6ea08761106dc940ba3eb8847 | /ServletDemo1/src/com/clear2pay/cn/listener/ApplicationListener.java | a84ecfe92eedfe19ee52b5e8daf2820488246234 | []
| no_license | zlc409057173/servlet | https://github.com/zlc409057173/servlet | 4e6a3ff225feb8bf3507dfa76c48dc7f4a052476 | cda2da7816e5ee0b874293e5f086de62b17943a6 | refs/heads/master | 2020-04-07T23:16:05.435000 | 2019-03-21T09:09:40 | 2019-03-21T09:09:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.clear2pay.cn.listener;
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class ApplicationListener implements ServletContextListener{
private static Logger log = Logger.getLogger(ApplicationListener.class);
long startServerTime = 0l;
long stopServerTime = 0l;
public void contextDestroyed(ServletContextEvent event) {
stopServerTime = System.currentTimeMillis();
long time = stopServerTime - startServerTime;
// log.info("服务器关闭:"+time);
}
public void contextInitialized(ServletContextEvent event) {
ServletContext application = event.getServletContext();
String log4jLocation = application.getInitParameter("log4j-properties-location");
if (log4jLocation == null) {
System.err.println("*** 没有 log4j-properties-location 初始化的文件, 所以使用 BasicConfigurator初始化");
BasicConfigurator.configure();
} else {
String webAppPath = application.getRealPath("/");
String log4jProp = webAppPath + log4jLocation;
File yoMamaYesThisSaysYoMama = new File(log4jProp);
if (yoMamaYesThisSaysYoMama.exists()) {
System.out.println("使用: " + log4jProp+"初始化日志设置信息");
PropertyConfigurator.configure(log4jProp);
} else {
System.err.println("*** " + log4jProp + " 文件没有找到, 所以使用 BasicConfigurator初始化");
BasicConfigurator.configure();
}
}
startServerTime = System.currentTimeMillis();
log.info("服务器启动:"+startServerTime);
}
}
| UTF-8 | Java | 1,867 | java | ApplicationListener.java | Java | []
| null | []
| package com.clear2pay.cn.listener;
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class ApplicationListener implements ServletContextListener{
private static Logger log = Logger.getLogger(ApplicationListener.class);
long startServerTime = 0l;
long stopServerTime = 0l;
public void contextDestroyed(ServletContextEvent event) {
stopServerTime = System.currentTimeMillis();
long time = stopServerTime - startServerTime;
// log.info("服务器关闭:"+time);
}
public void contextInitialized(ServletContextEvent event) {
ServletContext application = event.getServletContext();
String log4jLocation = application.getInitParameter("log4j-properties-location");
if (log4jLocation == null) {
System.err.println("*** 没有 log4j-properties-location 初始化的文件, 所以使用 BasicConfigurator初始化");
BasicConfigurator.configure();
} else {
String webAppPath = application.getRealPath("/");
String log4jProp = webAppPath + log4jLocation;
File yoMamaYesThisSaysYoMama = new File(log4jProp);
if (yoMamaYesThisSaysYoMama.exists()) {
System.out.println("使用: " + log4jProp+"初始化日志设置信息");
PropertyConfigurator.configure(log4jProp);
} else {
System.err.println("*** " + log4jProp + " 文件没有找到, 所以使用 BasicConfigurator初始化");
BasicConfigurator.configure();
}
}
startServerTime = System.currentTimeMillis();
log.info("服务器启动:"+startServerTime);
}
}
| 1,867 | 0.693704 | 0.684628 | 45 | 38.177776 | 26.7717 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.088889 | false | false | 5 |
1b2d9a3acd7ba2c0b73ccdffeb08653eb76ec7db | 24,404,004,228,644 | a47a6de81222277fd511070bbc69b170cde62b23 | /CS142/testpro2/Solver.java | 6afdee0b5d0ebbeb3a8833f8f829c0964c28a381 | []
| no_license | chaneym/code | https://github.com/chaneym/code | 5240f0be713000e1914505eaf24d8b581d22841b | aaaa05af3f25d7fbf604216dd4b11d84fe6e8605 | refs/heads/master | 2016-03-10T05:08:48.873000 | 2014-04-07T18:19:29 | 2014-04-07T18:19:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class Solver
{
private Random gen;
private Coord[] solution;
private LineSegment[] path;
public void draw_path()
{
int maxx = 10;
int minx = 0;
int maxy = 10;
int miny = 0;
solution = new Coord[8];
gen = new Random();
for (int i = 0; i < solution.length; i++)
{
solution[i] = new Coord(0,0);
solution[i].random(gen, maxx, minx, maxy, miny);
}
solution[0] = new Coord(minx,miny);
solution[7] = new Coord(maxx,maxy);
path = new LineSegment[7];
for (int i = 0; i < path.length; i ++ )
path[i] = new LineSegment(solution[i], solution[i+1]);
}
public boolean grade_path(LineSegment[] problem)
{
int i,j,num;
for (i = 0; i < path.length; i ++ ) // for path blockage
{
for (j = 0; j < problem.length; j++ )
{
if ( path[i].intersect(problem[j] ) )
{
// returns true if lines intersect
return false;
}
}
}
return true;
}
public String toString(int i)
{
return solution[i].toString();
}
}
| UTF-8 | Java | 1,069 | java | Solver.java | Java | []
| null | []
| import java.util.*;
public class Solver
{
private Random gen;
private Coord[] solution;
private LineSegment[] path;
public void draw_path()
{
int maxx = 10;
int minx = 0;
int maxy = 10;
int miny = 0;
solution = new Coord[8];
gen = new Random();
for (int i = 0; i < solution.length; i++)
{
solution[i] = new Coord(0,0);
solution[i].random(gen, maxx, minx, maxy, miny);
}
solution[0] = new Coord(minx,miny);
solution[7] = new Coord(maxx,maxy);
path = new LineSegment[7];
for (int i = 0; i < path.length; i ++ )
path[i] = new LineSegment(solution[i], solution[i+1]);
}
public boolean grade_path(LineSegment[] problem)
{
int i,j,num;
for (i = 0; i < path.length; i ++ ) // for path blockage
{
for (j = 0; j < problem.length; j++ )
{
if ( path[i].intersect(problem[j] ) )
{
// returns true if lines intersect
return false;
}
}
}
return true;
}
public String toString(int i)
{
return solution[i].toString();
}
}
| 1,069 | 0.554724 | 0.538821 | 62 | 16.241936 | 16.444124 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.419355 | false | false | 5 |
4f52ceaa4c34a1f08534165bc9455c30b94d81c3 | 18,597,208,454,225 | fa2c931102925ef102b04d7cac59694cf2f8bf91 | /src/StateComparator.java | 033964355993d108969315fa5a7797b3b36e8c8d | []
| no_license | tholop/rusho | https://github.com/tholop/rusho | 0101baa06499a4b9386ff31dcd258dd17e7a62ca | 7cd61b31575338e6ad73117252cbc59f5b60cb59 | refs/heads/master | 2021-09-07T18:58:24.084000 | 2018-02-27T14:58:07 | 2018-02-27T14:58:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Comparator;
public class StateComparator implements Comparator<State>{
Heuristic h = Heuristic.Null;
public StateComparator(Heuristic h) {
this.h = h;
}
@Override
public int compare(State s0, State s1) {
switch (h) {
case Null:
return s0.statesFromInit-s1.statesFromInit;
case BlockingVehicles:
return (s0.statesFromInit+s0.vehiclesToExit)-(s1.statesFromInit+s1.vehiclesToExit);
case DistanceToExit:
return (s0.statesFromInit+s0.distanceToExit())-(s1.statesFromInit+s1.distanceToExit());
case BlockingVehiclesImproved :
return (s0.statesFromInit+s0.vehiclesToExit+s0.blockedBlockingVehicles())-(s1.statesFromInit+s1.vehiclesToExit+s0.blockedBlockingVehicles());
}
return 0;
}
}
| UTF-8 | Java | 772 | java | StateComparator.java | Java | []
| null | []
| import java.util.Comparator;
public class StateComparator implements Comparator<State>{
Heuristic h = Heuristic.Null;
public StateComparator(Heuristic h) {
this.h = h;
}
@Override
public int compare(State s0, State s1) {
switch (h) {
case Null:
return s0.statesFromInit-s1.statesFromInit;
case BlockingVehicles:
return (s0.statesFromInit+s0.vehiclesToExit)-(s1.statesFromInit+s1.vehiclesToExit);
case DistanceToExit:
return (s0.statesFromInit+s0.distanceToExit())-(s1.statesFromInit+s1.distanceToExit());
case BlockingVehiclesImproved :
return (s0.statesFromInit+s0.vehiclesToExit+s0.blockedBlockingVehicles())-(s1.statesFromInit+s1.vehiclesToExit+s0.blockedBlockingVehicles());
}
return 0;
}
}
| 772 | 0.724093 | 0.699482 | 27 | 26.592592 | 34.019886 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.962963 | false | false | 5 |
60b88f00acd46edfdc63d5b7fb6e7d2c55c09a14 | 29,033,978,964,845 | 3914f5d9864ad49f5d152c7ee3e20a7b617c6435 | /app/src/main/java/com/dace/textreader/util/GlideUtils.java | a4f794e0cd2f0462cabd91df5a70d0a826db5b95 | []
| no_license | PCchenpeng/TextReader | https://github.com/PCchenpeng/TextReader | ad0434eb93030036857fbfbf6919ada61143eb0f | 07fbf9fa828698a1d6785ac0b13e49ba8e00bea3 | refs/heads/master | 2020-04-30T20:27:01.872000 | 2019-05-27T06:50:41 | 2019-05-27T06:50:41 | 177,066,879 | 2 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dace.textreader.util;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.dace.textreader.R;
/**
* =============================================================================
* Copyright (c) 2018 Administrator All rights reserved.
* Packname com.dace.textreader.util
* Created by Administrator.
* Created time 2018/12/18 0018 下午 2:58.
* Version 1.0;
* Describe : Glide图片加载工具类
* History:
* ==============================================================================
*/
public class GlideUtils {
/**
* 加载矩形图片
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
RequestOptions options = new RequestOptions()
.centerCrop()
.transform(new GlideRoundImage(context, 8));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.withCrossFade(1000))
.into(imageView);
}
//加载指定圆角图片
public static void loadImage(Context context, String imageUrl, ImageView imageView,int radius) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(1000)
.setCrossFadeEnabled(true).build();
// DrawableCrossFadeFactory drawableCrossFadeFactory =
// new DrawableCrossFadeFactory.Builder(1000)
// .setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
// .placeholder(R.drawable.image_placeholder_rectangle)
// .error(R.drawable.image_placeholder_rectangle)
.centerCrop()
.transform(new GlideRoundImage(context, radius));
Glide.with(context)
.load(imageUrl)
.apply(options)
// .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.transition(DrawableTransitionOptions.withCrossFade(1000))
.into(imageView);
}
/**
* 加载矩形图片
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadHomeImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
RequestOptions options = new RequestOptions()
.centerCrop();
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.withCrossFade(1000))
.into(imageView);
}
/**
* 加载用户头像
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadHomeUserImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
RequestOptions options = new RequestOptions()
.error(R.drawable.image_student)
.centerCrop()
.transform(new GlideCircleTransform(context));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.withCrossFade(1000))
.into(imageView);
}
/**
* 加载用户头像
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadUserImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(500)
.setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
.error(R.drawable.image_student)
.centerCrop()
.transform(new GlideCircleTransform(context));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.into(imageView);
}
/**
* 加载小图
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadSmallImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(500)
.setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
.error(R.drawable.image_placeholder_rectangle)
.centerCrop()
.transform(new GlideRoundImage(context, 4));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.into(imageView);
}
/**
* 加载方形图片
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadSquareImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(500)
.setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
.error(R.drawable.image_placeholder_square)
.centerCrop()
.transform(new GlideRoundImage(context, 4));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.into(imageView);
}
/**
* 加载矩形图片
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadImageWithNoPlaceholder(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(500)
.setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
.error(R.drawable.image_placeholder_rectangle)
.centerCrop()
.transform(new GlideRoundImage(context, 8));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.into(imageView);
}
/**
* 通过context加载drawable中的图片
*
* @param context 上下文对象
* @param resId 图片ID
* @param imageView 图片容器
*/
public static void loadImageWithNoOptions(Context context, @DrawableRes int resId,
ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
Glide.with(context).asBitmap().load(resId).into(imageView);
}
/**
* 通过context加载drawable中的GIF图片
*
* @param context 上下文对象
* @param resId 图片ID
* @param imageView 图片容器
*/
public static void loadGIFImageWithNoOptions(Context context, @DrawableRes int resId,
ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
Glide.with(context).asGif().load(resId).into(imageView);
}
/**
* 加载矩形图片
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadImageWithNoRadius(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(500)
.setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
.centerCrop();
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.into(imageView);
}
/**
* context是否有效
*
* @param context
* @return
*/
private static boolean isValidContextForGlide(final Context context) {
if (context == null) {
return false;
}
if (context instanceof Activity) {
final Activity activity = (Activity) context;
if (activity.isDestroyed() || activity.isFinishing()) {
return false;
}
}
return true;
}
}
| UTF-8 | Java | 10,137 | java | GlideUtils.java | Java | [
{
"context": " * Packname com.dace.textreader.util\n * Created by Administrator.\n * Created time 2018/12/18 0018 下午 2:58.\n * Vers",
"end": 644,
"score": 0.7102900743484497,
"start": 631,
"tag": "NAME",
"value": "Administrator"
}
]
| null | []
| package com.dace.textreader.util;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.dace.textreader.R;
/**
* =============================================================================
* Copyright (c) 2018 Administrator All rights reserved.
* Packname com.dace.textreader.util
* Created by Administrator.
* Created time 2018/12/18 0018 下午 2:58.
* Version 1.0;
* Describe : Glide图片加载工具类
* History:
* ==============================================================================
*/
public class GlideUtils {
/**
* 加载矩形图片
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
RequestOptions options = new RequestOptions()
.centerCrop()
.transform(new GlideRoundImage(context, 8));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.withCrossFade(1000))
.into(imageView);
}
//加载指定圆角图片
public static void loadImage(Context context, String imageUrl, ImageView imageView,int radius) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(1000)
.setCrossFadeEnabled(true).build();
// DrawableCrossFadeFactory drawableCrossFadeFactory =
// new DrawableCrossFadeFactory.Builder(1000)
// .setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
// .placeholder(R.drawable.image_placeholder_rectangle)
// .error(R.drawable.image_placeholder_rectangle)
.centerCrop()
.transform(new GlideRoundImage(context, radius));
Glide.with(context)
.load(imageUrl)
.apply(options)
// .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.transition(DrawableTransitionOptions.withCrossFade(1000))
.into(imageView);
}
/**
* 加载矩形图片
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadHomeImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
RequestOptions options = new RequestOptions()
.centerCrop();
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.withCrossFade(1000))
.into(imageView);
}
/**
* 加载用户头像
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadHomeUserImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
RequestOptions options = new RequestOptions()
.error(R.drawable.image_student)
.centerCrop()
.transform(new GlideCircleTransform(context));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.withCrossFade(1000))
.into(imageView);
}
/**
* 加载用户头像
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadUserImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(500)
.setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
.error(R.drawable.image_student)
.centerCrop()
.transform(new GlideCircleTransform(context));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.into(imageView);
}
/**
* 加载小图
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadSmallImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(500)
.setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
.error(R.drawable.image_placeholder_rectangle)
.centerCrop()
.transform(new GlideRoundImage(context, 4));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.into(imageView);
}
/**
* 加载方形图片
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadSquareImage(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(500)
.setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
.error(R.drawable.image_placeholder_square)
.centerCrop()
.transform(new GlideRoundImage(context, 4));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.into(imageView);
}
/**
* 加载矩形图片
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadImageWithNoPlaceholder(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(500)
.setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
.error(R.drawable.image_placeholder_rectangle)
.centerCrop()
.transform(new GlideRoundImage(context, 8));
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.into(imageView);
}
/**
* 通过context加载drawable中的图片
*
* @param context 上下文对象
* @param resId 图片ID
* @param imageView 图片容器
*/
public static void loadImageWithNoOptions(Context context, @DrawableRes int resId,
ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
Glide.with(context).asBitmap().load(resId).into(imageView);
}
/**
* 通过context加载drawable中的GIF图片
*
* @param context 上下文对象
* @param resId 图片ID
* @param imageView 图片容器
*/
public static void loadGIFImageWithNoOptions(Context context, @DrawableRes int resId,
ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
Glide.with(context).asGif().load(resId).into(imageView);
}
/**
* 加载矩形图片
*
* @param context 上下文对象
* @param imageUrl 图片链接
* @param imageView 图片容器
*/
public static void loadImageWithNoRadius(Context context, String imageUrl, ImageView imageView) {
if (!isValidContextForGlide(context)){
return;
}
DrawableCrossFadeFactory drawableCrossFadeFactory =
new DrawableCrossFadeFactory.Builder(500)
.setCrossFadeEnabled(true).build();
RequestOptions options = new RequestOptions()
.centerCrop();
Glide.with(context)
.load(imageUrl)
.apply(options)
.transition(DrawableTransitionOptions.with(drawableCrossFadeFactory))
.into(imageView);
}
/**
* context是否有效
*
* @param context
* @return
*/
private static boolean isValidContextForGlide(final Context context) {
if (context == null) {
return false;
}
if (context instanceof Activity) {
final Activity activity = (Activity) context;
if (activity.isDestroyed() || activity.isFinishing()) {
return false;
}
}
return true;
}
}
| 10,137 | 0.574545 | 0.56796 | 305 | 30.865574 | 25.697834 | 106 | false | false | 0 | 0 | 0 | 0 | 79 | 0.016154 | 0.272131 | false | false | 5 |
6e98e794716fc631b9d2d7efdbb7129cbc5dd4e3 | 29,033,978,965,135 | 9a19665bd4dfb042128ca1a093cc70dd51bdb6e5 | /roadapiclient/src/main/java/com/sked/roadapiclient/RoadApiRequest.java | dc6b8cdc445bc3e50f66180eb93f6ba818ccc0e4 | []
| no_license | xibsked/RoadApiClient-Andrid | https://github.com/xibsked/RoadApiClient-Andrid | a6b9fff6f912ff52ca74f6bc85b4566669b3c862 | 56d24d215600dc32e18b631aafb802cff077e660 | refs/heads/master | 2021-01-21T18:10:24.520000 | 2016-09-22T20:27:23 | 2016-09-22T20:27:23 | 68,370,114 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sked.roadapiclient;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
/**
* All Rights Reserved, QuikSeek
* Created by quikseek1 on 17-08-2016.
*/
public class RoadApiRequest extends JsonRequest<ResponseWrapper> {
public RoadApiRequest(int method, String url, String requestBody, Response.Listener<ResponseWrapper> listener, Response.ErrorListener errorListener) {
super(method, url, requestBody, listener, errorListener);
}
@Override
protected Response<ResponseWrapper> parseNetworkResponse(NetworkResponse response) {
ResponseWrapper responseWrapper = new ResponseWrapper();
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
ObjectMapper objectMapper = new ObjectMapper();
if (jsonString.contains("snappedPoints")) {
SnappedPoints snappedPoints = objectMapper.readValue(jsonString, SnappedPoints.class);
responseWrapper.setSnappedPoints(snappedPoints);
} else {
Error error = objectMapper.readValue(jsonString, Error.class);
responseWrapper.setError(error);
}
return Response.success(responseWrapper,
HttpHeaderParser.parseCacheHeaders(response));
} catch (JsonParseException e) {
return Response.error(new ParseError(e));
} catch (JsonMappingException e) {
return Response.error(new ParseError(e));
} catch (IOException e) {
return Response.error(new ParseError(e));
}
}
}
| UTF-8 | Java | 2,013 | java | RoadApiRequest.java | Java | [
{
"context": ".io.IOException;\n\n/**\n * All Rights Reserved, QuikSeek\n * Created by quikseek1 on 17-08-2016.\n */\npublic",
"end": 481,
"score": 0.5985785722732544,
"start": 477,
"tag": "USERNAME",
"value": "Seek"
},
{
"context": "/**\n * All Rights Reserved, QuikSeek\n * Created by quikseek1 on 17-08-2016.\n */\npublic class RoadApiRequest ex",
"end": 505,
"score": 0.9996494650840759,
"start": 496,
"tag": "USERNAME",
"value": "quikseek1"
}
]
| null | []
| package com.sked.roadapiclient;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
/**
* All Rights Reserved, QuikSeek
* Created by quikseek1 on 17-08-2016.
*/
public class RoadApiRequest extends JsonRequest<ResponseWrapper> {
public RoadApiRequest(int method, String url, String requestBody, Response.Listener<ResponseWrapper> listener, Response.ErrorListener errorListener) {
super(method, url, requestBody, listener, errorListener);
}
@Override
protected Response<ResponseWrapper> parseNetworkResponse(NetworkResponse response) {
ResponseWrapper responseWrapper = new ResponseWrapper();
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
ObjectMapper objectMapper = new ObjectMapper();
if (jsonString.contains("snappedPoints")) {
SnappedPoints snappedPoints = objectMapper.readValue(jsonString, SnappedPoints.class);
responseWrapper.setSnappedPoints(snappedPoints);
} else {
Error error = objectMapper.readValue(jsonString, Error.class);
responseWrapper.setError(error);
}
return Response.success(responseWrapper,
HttpHeaderParser.parseCacheHeaders(response));
} catch (JsonParseException e) {
return Response.error(new ParseError(e));
} catch (JsonMappingException e) {
return Response.error(new ParseError(e));
} catch (IOException e) {
return Response.error(new ParseError(e));
}
}
}
| 2,013 | 0.700447 | 0.695976 | 47 | 41.829788 | 31.022516 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.765957 | false | false | 5 |
a794936365a2d5a62074306c59e27b8b28249e6c | 22,651,657,574,601 | e4a48dfea35f83618a2735a36efc52960502063a | /NewSpringTest/src/main/java/com/spring/main/controller/HomeController.java | 1960dbd1199b0287f2af4c3e2ba77e858710f90e | []
| no_license | osideris/SpringTest | https://github.com/osideris/SpringTest | 92c7e7de4c4dfc2cd587f2393d681bd9683bdff3 | 4562e05f1c4184cacc8bc00ee3be0f54fd9d20d9 | refs/heads/master | 2020-04-06T07:56:54.425000 | 2018-11-12T23:18:45 | 2018-11-12T23:18:45 | 157,290,178 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.spring.main.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.spring.main.dao.StudentDAO;
import com.spring.main.model.Student;
@Controller
public class HomeController {
@Autowired
private StudentDAO studentDAO;
@RequestMapping(value="/newStudent", method = RequestMethod.GET)
public ModelAndView newStudent(ModelAndView model) {
Student newStudent = new Student();
model.addObject("student", newStudent);
model.setViewName("StudentForm");
return model;
}
@RequestMapping(value="/saveStudent", method = RequestMethod.POST)
public ModelAndView saveStudent(@ModelAttribute Student student) {
studentDAO.saveOrUpdate(student);
return new ModelAndView("redirect:/");
}
@RequestMapping(value="/deleteStudent", method = RequestMethod.GET)
public ModelAndView deleteStudent(HttpServletRequest request) {
int studentID = Integer.parseInt(request.getParameter("studentID"));
studentDAO.delete(studentID);
return new ModelAndView("redirect:/");
}
@RequestMapping(value="/editStudent", method = RequestMethod.GET)
public ModelAndView editStudent(HttpServletRequest request) {
int studentID = Integer.parseInt(request.getParameter("studentID"));
Student student = studentDAO.get(studentID);
ModelAndView model = new ModelAndView("StudentForm");
model.addObject("student", student);
return model;
}
@RequestMapping(value="/")
public ModelAndView listStudent(ModelAndView model) throws IOException{
List<Student> listStudent = studentDAO.list();
model.addObject("listStudent", listStudent);
model.setViewName("home");
return model;
}
}
| UTF-8 | Java | 2,035 | java | HomeController.java | Java | []
| null | []
| package com.spring.main.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.spring.main.dao.StudentDAO;
import com.spring.main.model.Student;
@Controller
public class HomeController {
@Autowired
private StudentDAO studentDAO;
@RequestMapping(value="/newStudent", method = RequestMethod.GET)
public ModelAndView newStudent(ModelAndView model) {
Student newStudent = new Student();
model.addObject("student", newStudent);
model.setViewName("StudentForm");
return model;
}
@RequestMapping(value="/saveStudent", method = RequestMethod.POST)
public ModelAndView saveStudent(@ModelAttribute Student student) {
studentDAO.saveOrUpdate(student);
return new ModelAndView("redirect:/");
}
@RequestMapping(value="/deleteStudent", method = RequestMethod.GET)
public ModelAndView deleteStudent(HttpServletRequest request) {
int studentID = Integer.parseInt(request.getParameter("studentID"));
studentDAO.delete(studentID);
return new ModelAndView("redirect:/");
}
@RequestMapping(value="/editStudent", method = RequestMethod.GET)
public ModelAndView editStudent(HttpServletRequest request) {
int studentID = Integer.parseInt(request.getParameter("studentID"));
Student student = studentDAO.get(studentID);
ModelAndView model = new ModelAndView("StudentForm");
model.addObject("student", student);
return model;
}
@RequestMapping(value="/")
public ModelAndView listStudent(ModelAndView model) throws IOException{
List<Student> listStudent = studentDAO.list();
model.addObject("listStudent", listStudent);
model.setViewName("home");
return model;
}
}
| 2,035 | 0.784767 | 0.784767 | 63 | 31.301588 | 24.803761 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.619048 | false | false | 5 |
7a518aab15732eb9fbe6f755efe842c6db84c671 | 33,105,607,976,605 | cd19b56a57f1ff58fec6370e1f97458b6dc9008f | /src/com/deguru/dao/orderDao.java | 032af1103c30df73f4c061523d907386c51f9036 | []
| no_license | Sineft/deguru | https://github.com/Sineft/deguru | 67e935f0c13e740689d29d555bd6c010d67dbd18 | 4c7c8ea01364e443f98152b4df91e70253b4da4b | refs/heads/master | 2018-12-08T07:19:46.073000 | 2018-09-11T11:47:34 | 2018-09-11T11:47:34 | 136,173,015 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.deguru.dao;
import java.util.List;
import com.deguru.dto.Address;
import com.deguru.dto.Order;
import com.deguru.dto.OrderItem;
public interface orderDao {
List<Address> selectUserAddress(int id);
int insertOrder(Order order, OrderItem orderitem);
Order selectOrder(String out_trade_no);
List<OrderItem> selectOrderItemList(int id);
}
| UTF-8 | Java | 359 | java | orderDao.java | Java | []
| null | []
| package com.deguru.dao;
import java.util.List;
import com.deguru.dto.Address;
import com.deguru.dto.Order;
import com.deguru.dto.OrderItem;
public interface orderDao {
List<Address> selectUserAddress(int id);
int insertOrder(Order order, OrderItem orderitem);
Order selectOrder(String out_trade_no);
List<OrderItem> selectOrderItemList(int id);
}
| 359 | 0.777159 | 0.777159 | 19 | 17.894737 | 18.171391 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736842 | false | false | 5 |
5151bae07a1ed9daa4ff3ecd16c7c5320120cfa1 | 12,257,836,711,334 | 010b3f1ea13d0f0a2744141f0c3153f706cc9033 | /Back End/Core Java/Core Concept/array/src/com/capg/Array/Sqr.java | 0a5484b924e7a538f50eeb707a4364c69a94ecbe | []
| no_license | AmeyaPatil26/TY_CG_HTD_PuneMumbai_JFS_AmeyaPatil | https://github.com/AmeyaPatil26/TY_CG_HTD_PuneMumbai_JFS_AmeyaPatil | ad056b5c22eab1363a87832418f285df95f1b316 | e371acb6f94ad238f952eaac18135e751a2d5642 | refs/heads/master | 2023-01-10T19:29:25.319000 | 2019-11-14T18:47:24 | 2019-11-14T18:47:24 | 225,846,362 | 0 | 0 | null | false | 2023-01-07T19:01:34 | 2019-12-04T11:02:15 | 2019-12-14T18:49:08 | 2023-01-07T19:01:33 | 90,317 | 0 | 0 | 236 | CSS | false | false | package com.capg.Array;
public interface Sqr {
int square(int i);
}
| UTF-8 | Java | 69 | java | Sqr.java | Java | []
| null | []
| package com.capg.Array;
public interface Sqr {
int square(int i);
}
| 69 | 0.724638 | 0.724638 | 5 | 12.8 | 10.186265 | 23 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 5 |
fc62f67253c51ba27199fde2bbd51eb6e6350c3b | 876,173,394,430 | 8c673fc7fdb9215b6ae99ce4217c12f3c18bc5aa | /app_user/app/src/main/java/com/example/app_user/ServiceThread.java | 9fe6414076f17af090e17318330c4ea99933a62a | []
| no_license | jmingrove21/PyramidTop | https://github.com/jmingrove21/PyramidTop | 4762aed1132e10b6eb3713ac5ad323db979bcd0e | c033a6b96520a98e451a037d063c5ee3a54508c0 | refs/heads/master | 2021-07-16T13:32:53.854000 | 2020-07-04T10:18:48 | 2020-07-04T10:18:48 | 173,879,672 | 3 | 1 | null | false | 2019-06-15T13:41:17 | 2019-03-05T05:25:25 | 2019-06-13T07:03:27 | 2019-06-15T13:41:17 | 82,853 | 2 | 1 | 0 | JavaScript | false | false | package com.example.app_user;
import android.os.Handler;
import android.util.Log;
import com.example.app_user.Item_dir.LoginLogoutInform;
import com.example.app_user.Item_dir.UtilSet;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
public class ServiceThread extends Thread {
Handler handler;
boolean isRun = true;
static int result_output = -1;
static ArrayList<ArrayList<String>> alert_info_al = new ArrayList<>();
public ServiceThread(Handler handler) {
this.handler = handler;
}
public void stopForever() {
synchronized (this) {
this.isRun = false;
}
}
public void run() {
//반복적으로 수행할 작업을 한다.
while (isRun) {
get_user_status_change();
if (result_output == 1 && LoginLogoutInform.getLogin_flag() == 1) {
for (int i = 0; i < alert_info_al.size(); i++) {
handler.sendEmptyMessage(i);//쓰레드에 있는 핸들러에게 메세지를 보냄
try {
Thread.sleep(2000);
} catch (Exception e) {
}
}
} else {
}
try {
Thread.sleep(10000); //10초씩 쉰다.
} catch (Exception e) {
}
}
}
public int get_user_status_change() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
alert_info_al.clear();
JSONObject jsonParam = new JSONObject();
jsonParam.put("user_info", "check_status");
if(UtilSet.my_user!=null)
jsonParam.put("user_serial", UtilSet.my_user.getUser_serial());
HttpURLConnection conn = UtilSet.set_Connect_info(jsonParam);
if (conn.getResponseCode() == 200) {
InputStream response = conn.getInputStream();
String result = UtilSet.convertStreamToString(response);
JSONObject jobj = new JSONObject(result);
Log.d("check_status",jobj.toString());
if(UtilSet.my_user!=null)
UtilSet.my_user.setUser_mileage(Integer.parseInt(jobj.get("mileage").toString()));
if (jobj.get("confirm").toString().equals("1")) {
JSONArray jarray = (JSONArray) jobj.get("data");
Log.d("check_status",jobj.toString());
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobj_store = (JSONObject) jarray.get(i);
JSONArray jobj_store_alert = (JSONArray) jobj_store.get("alarm_check");
for (int j = 0; j < jobj_store_alert.length(); j++) {
ArrayList<String> al_str = new ArrayList<>();
JSONObject jobj_store_detail = (JSONObject) jobj_store_alert.get(j);
String msg=get_alarm_msg(jobj_store_detail.getInt("status"),jobj_store.getString("store_name"));
al_str.add(msg);
al_str.add(jobj_store_detail.getString("time"));
alert_info_al.add(al_str);
}
}
result_output = 1;
} else {
result_output = 0;
}
} else {
Log.d("error", "Connect fail");
result_output = 0;
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
result_output = 0;
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return result_output;
}
public String get_alarm_msg(int status,String store_name){
String result=store_name;
if(status==3){
result+="에서 요청하신 주문이 접수되었습니다.";
}else if(status==4){
result+="에서 요청하신 음식이 완료되었습니다.";
}else if(status==6){
result+="에서 배달 출발하였습니다.";
}else if(status==7){
result+="에서 요청한 음식이 배달완료되었습니다.";
}else if(status==8){
result+="에서 주문이 취소되었습니다.";
}else{
}
return result;
}
}
| UTF-8 | Java | 4,999 | java | ServiceThread.java | Java | []
| null | []
| package com.example.app_user;
import android.os.Handler;
import android.util.Log;
import com.example.app_user.Item_dir.LoginLogoutInform;
import com.example.app_user.Item_dir.UtilSet;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
public class ServiceThread extends Thread {
Handler handler;
boolean isRun = true;
static int result_output = -1;
static ArrayList<ArrayList<String>> alert_info_al = new ArrayList<>();
public ServiceThread(Handler handler) {
this.handler = handler;
}
public void stopForever() {
synchronized (this) {
this.isRun = false;
}
}
public void run() {
//반복적으로 수행할 작업을 한다.
while (isRun) {
get_user_status_change();
if (result_output == 1 && LoginLogoutInform.getLogin_flag() == 1) {
for (int i = 0; i < alert_info_al.size(); i++) {
handler.sendEmptyMessage(i);//쓰레드에 있는 핸들러에게 메세지를 보냄
try {
Thread.sleep(2000);
} catch (Exception e) {
}
}
} else {
}
try {
Thread.sleep(10000); //10초씩 쉰다.
} catch (Exception e) {
}
}
}
public int get_user_status_change() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
alert_info_al.clear();
JSONObject jsonParam = new JSONObject();
jsonParam.put("user_info", "check_status");
if(UtilSet.my_user!=null)
jsonParam.put("user_serial", UtilSet.my_user.getUser_serial());
HttpURLConnection conn = UtilSet.set_Connect_info(jsonParam);
if (conn.getResponseCode() == 200) {
InputStream response = conn.getInputStream();
String result = UtilSet.convertStreamToString(response);
JSONObject jobj = new JSONObject(result);
Log.d("check_status",jobj.toString());
if(UtilSet.my_user!=null)
UtilSet.my_user.setUser_mileage(Integer.parseInt(jobj.get("mileage").toString()));
if (jobj.get("confirm").toString().equals("1")) {
JSONArray jarray = (JSONArray) jobj.get("data");
Log.d("check_status",jobj.toString());
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobj_store = (JSONObject) jarray.get(i);
JSONArray jobj_store_alert = (JSONArray) jobj_store.get("alarm_check");
for (int j = 0; j < jobj_store_alert.length(); j++) {
ArrayList<String> al_str = new ArrayList<>();
JSONObject jobj_store_detail = (JSONObject) jobj_store_alert.get(j);
String msg=get_alarm_msg(jobj_store_detail.getInt("status"),jobj_store.getString("store_name"));
al_str.add(msg);
al_str.add(jobj_store_detail.getString("time"));
alert_info_al.add(al_str);
}
}
result_output = 1;
} else {
result_output = 0;
}
} else {
Log.d("error", "Connect fail");
result_output = 0;
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
result_output = 0;
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return result_output;
}
public String get_alarm_msg(int status,String store_name){
String result=store_name;
if(status==3){
result+="에서 요청하신 주문이 접수되었습니다.";
}else if(status==4){
result+="에서 요청하신 음식이 완료되었습니다.";
}else if(status==6){
result+="에서 배달 출발하였습니다.";
}else if(status==7){
result+="에서 요청한 음식이 배달완료되었습니다.";
}else if(status==8){
result+="에서 주문이 취소되었습니다.";
}else{
}
return result;
}
}
| 4,999 | 0.461667 | 0.4554 | 132 | 35.265152 | 26.93788 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 5 |
00d3920356ba6c110db73b2dec27dfd98af01064 | 2,370,821,999,249 | bdd86e9fbc0ff8288099b80d5043790a11485fc7 | /todolist/src/test/java/com/intuitiv/todolist/dao/impl/UserDaoImpl.java | 6e758284e2ff6094caca0fd08060e4c8f0496ed0 | []
| no_license | fabienCambournac/todolist_grp1 | https://github.com/fabienCambournac/todolist_grp1 | 30fd2cb6572c95d060990cf7ea465619cfb5e07a | 6478683d6dd17a0efc01d188c2ac028b6f1d0b52 | refs/heads/master | 2017-04-27T00:56:33.794000 | 2014-11-12T15:58:33 | 2014-11-12T15:58:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.intuitiv.todolist.dao.impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import com.intuitiv.todolist.dao.UserDao;
import com.intuitiv.todolist.entity.User;
public class UserDaoImpl implements UserDao {
private Session session = new Configuration().configure().buildSessionFactory().openSession();
public User find(int id) {
Query query = session.createQuery("from User u where u.id = :idParam");
query.setParameter("idParam", id);
return (User)query.uniqueResult();
}
@Override
public void save(User user) {
session.save(user);
}
@Override
public List<User> list() {
Query query = session.createQuery("from User");
return query.list();
}
}
| UTF-8 | Java | 793 | java | UserDaoImpl.java | Java | []
| null | []
| package com.intuitiv.todolist.dao.impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import com.intuitiv.todolist.dao.UserDao;
import com.intuitiv.todolist.entity.User;
public class UserDaoImpl implements UserDao {
private Session session = new Configuration().configure().buildSessionFactory().openSession();
public User find(int id) {
Query query = session.createQuery("from User u where u.id = :idParam");
query.setParameter("idParam", id);
return (User)query.uniqueResult();
}
@Override
public void save(User user) {
session.save(user);
}
@Override
public List<User> list() {
Query query = session.createQuery("from User");
return query.list();
}
}
| 793 | 0.711223 | 0.711223 | 33 | 22.030304 | 22.903599 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.121212 | false | false | 5 |
136cee49b1d0325e6c0b9a5fb28efff63285175b | 2,336,462,275,969 | 351cf10d7fb474a112f033626b94dfb84297dd41 | /src/ninoo_jobs/jobs_helpclasses/sectionControllers/JobsQuest.java | 954b7b854ec20fefd4026eab699eb6c6f841b876 | []
| no_license | NinoCookie/FruchtJobs | https://github.com/NinoCookie/FruchtJobs | 6d151e91cd6ab8ad1ec99e415f9a1667e36b8cf8 | 410cd7f46f3194df05fbc07bda8fc8301ff6e3a6 | refs/heads/master | 2020-04-27T22:32:27.491000 | 2019-03-27T20:33:34 | 2019-03-27T20:33:34 | 174,740,699 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ninoo_jobs.jobs_helpclasses.sectionControllers;
import ninoo_jobs.jobs_helpclasses.helpfulObjects.JobsRItem;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class JobsQuest {
public String questname;
public String jobname;
public List<String> materialList;
public String type;
public List<String> beforeQuests;
public List<ItemStack> f_materialList;
public String guiicon;
public JobsQuest(ConfigurationSection section) {
this.questname = section.getString("questname");
this.jobname = section.getString("jobname");
this.materialList = section.getStringList("materiallist");
this.type = section.getString("type");
this.beforeQuests = section.getStringList("beforequests");
constructMaterialList(materialList);
this.guiicon=section.getString("guiicon");
}
private void constructMaterialList(List<String> materialList){
f_materialList=new ArrayList<>();
try {
for (String s : materialList) {
String[] str = s.split(":");
JobsRItem item = new JobsRItem("", str[0], null, "", null, Integer.parseInt(str[1]));
f_materialList.add(item.contruct());
}
}catch (Exception e){
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,429 | java | JobsQuest.java | Java | []
| null | []
| package ninoo_jobs.jobs_helpclasses.sectionControllers;
import ninoo_jobs.jobs_helpclasses.helpfulObjects.JobsRItem;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class JobsQuest {
public String questname;
public String jobname;
public List<String> materialList;
public String type;
public List<String> beforeQuests;
public List<ItemStack> f_materialList;
public String guiicon;
public JobsQuest(ConfigurationSection section) {
this.questname = section.getString("questname");
this.jobname = section.getString("jobname");
this.materialList = section.getStringList("materiallist");
this.type = section.getString("type");
this.beforeQuests = section.getStringList("beforequests");
constructMaterialList(materialList);
this.guiicon=section.getString("guiicon");
}
private void constructMaterialList(List<String> materialList){
f_materialList=new ArrayList<>();
try {
for (String s : materialList) {
String[] str = s.split(":");
JobsRItem item = new JobsRItem("", str[0], null, "", null, Integer.parseInt(str[1]));
f_materialList.add(item.contruct());
}
}catch (Exception e){
e.printStackTrace();
}
}
}
| 1,429 | 0.662001 | 0.660602 | 42 | 33 | 23.479475 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 5 |
720002b49fb5bd875478b32e1f48864872ab5ce2 | 26,173,530,756,019 | 3477e979815f243fdbe7b6748238dc33415d2b85 | /20210428_집/src/package1/Ex06.java | 510bf441d67953f8894ee1e485f71ea336c5c9b7 | []
| no_license | youngminSong-git/Youngmin_world | https://github.com/youngminSong-git/Youngmin_world | 43439ee60b238f35b3ca7b2a9c209e6f5dec522d | ff85d9489af98bff228cfe0fb72410ca3dc2b13a | refs/heads/main | 2023-06-28T01:35:00.005000 | 2021-07-28T08:01:21 | 2021-07-28T08:01:21 | 362,669,603 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package package1;
import java.util.Scanner;
public class Ex06 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("나눗셈 프로그램 실행");
while(true) {
System.out.println("프로그램을 종료하려면 exit를 입력하세요.");
System.out.println("분자를 입력해요. ");
String data1 = sc.nextLine();
System.out.println("분모를 입력하세요. ");
String data2 = sc.nextLine();
System.out.println("idx 번호를 입력하세요. ");
String data3 = sc.nextLine();
int idx = Integer.parseInt(data3); //parsing, num 배열에서 사용해야 하는데, idx가 정수여야만 사용이가능하기때문에 변수에 파싱해서 받아온다.
if(data1.equals("exit") || data2.contentEquals("exit") || data3.contentEquals("exit")) {
System.out.println("프로그램이 종료되었습니다.");
break;
}
int num[] = new int[2];
try {
num[0] = Integer.parseInt(data1);
num[idx] = Integer.parseInt(data2);
System.out.println(num[0] / num[idx]);
} catch(ArithmeticException e) {
System.out.println("분모는 0이면 안됩니다.");
} catch(NumberFormatException e) {
System.out.println("숫자만 입력하세요");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("idx는 1이상이면 안됩니다.");
} finally {
System.out.println("다시시작");
}
}
}
}
| UHC | Java | 1,511 | java | Ex06.java | Java | []
| null | []
| package package1;
import java.util.Scanner;
public class Ex06 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("나눗셈 프로그램 실행");
while(true) {
System.out.println("프로그램을 종료하려면 exit를 입력하세요.");
System.out.println("분자를 입력해요. ");
String data1 = sc.nextLine();
System.out.println("분모를 입력하세요. ");
String data2 = sc.nextLine();
System.out.println("idx 번호를 입력하세요. ");
String data3 = sc.nextLine();
int idx = Integer.parseInt(data3); //parsing, num 배열에서 사용해야 하는데, idx가 정수여야만 사용이가능하기때문에 변수에 파싱해서 받아온다.
if(data1.equals("exit") || data2.contentEquals("exit") || data3.contentEquals("exit")) {
System.out.println("프로그램이 종료되었습니다.");
break;
}
int num[] = new int[2];
try {
num[0] = Integer.parseInt(data1);
num[idx] = Integer.parseInt(data2);
System.out.println(num[0] / num[idx]);
} catch(ArithmeticException e) {
System.out.println("분모는 0이면 안됩니다.");
} catch(NumberFormatException e) {
System.out.println("숫자만 입력하세요");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("idx는 1이상이면 안됩니다.");
} finally {
System.out.println("다시시작");
}
}
}
}
| 1,511 | 0.615139 | 0.601594 | 44 | 26.522728 | 22.553461 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.295455 | false | false | 5 |
0a6af72656e926b9ee9174f0db619aad99b9d45f | 23,467,701,357,238 | 1eefce8a923ff58d991dc1af23b8c1254bc3428d | /DCJVisualizer_final_current/src/ca/corefacility/gview/map/gui/editor/node/BackboneSlotNode.java | b972c68782ca383ae7478c19b9f228625c3f641f | []
| no_license | sruthi10/DCJVis | https://github.com/sruthi10/DCJVis | 1f3293783fc9611600ec3ccba3e7f3f0bd32bce2 | 117a5327508938ac959c3ac6afeb2c21e4deaaaf | refs/heads/master | 2022-01-18T14:44:53.176000 | 2019-05-11T05:47:33 | 2019-05-11T05:47:33 | 148,814,730 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ca.corefacility.gview.map.gui.editor.node;
import java.awt.Paint;
import ca.corefacility.gview.map.gui.editor.panel.BackbonePanel;
/**
* The node used to represent the backbone as it sits in GView's collection of slots.
*
* This should be as minimal as possible, as it is only for representation on the tree
* and not for manipulation of the backbone itself.
*
* @author Eric Marinier
*
*/
public class BackboneSlotNode extends StyleEditorNode implements Slotable
{
private static final long serialVersionUID = 1L;
private static final String BACKBONE = "Backbone Slot";
private final BackbonePanel backbonePanel;
/**
*
* @param backbonePanel The associate backbone slot panel.
*/
public BackboneSlotNode(BackbonePanel backbonePanel)
{
super(backbonePanel, BACKBONE);
if(backbonePanel == null)
{
throw new IllegalArgumentException("BackboneSlotPanel is null.");
}
else
{
this.backbonePanel = backbonePanel;
}
}
@Override
/**
* @return The BackbonePanel.
*/
public BackbonePanel getPanel()
{
if(this.backbonePanel == null)
throw new NullPointerException("BackbonePanel is null.");
return this.backbonePanel;
}
@Override
public void updateName()
{
super.rename(BACKBONE);
}
@Override
public int getSlotNumber()
{
return Slotable.BACKBONE_SLOT_NUMBER;
}
public Paint getNodeColor()
{
return this.backbonePanel.getBackboneStyleController().getColor();
}
}
| UTF-8 | Java | 1,457 | java | BackboneSlotNode.java | Java | [
{
"context": "anipulation of the backbone itself.\n * \n * @author Eric Marinier\n *\n */\npublic class BackboneSlotNode extends Styl",
"end": 403,
"score": 0.9997743964195251,
"start": 390,
"tag": "NAME",
"value": "Eric Marinier"
}
]
| null | []
| package ca.corefacility.gview.map.gui.editor.node;
import java.awt.Paint;
import ca.corefacility.gview.map.gui.editor.panel.BackbonePanel;
/**
* The node used to represent the backbone as it sits in GView's collection of slots.
*
* This should be as minimal as possible, as it is only for representation on the tree
* and not for manipulation of the backbone itself.
*
* @author <NAME>
*
*/
public class BackboneSlotNode extends StyleEditorNode implements Slotable
{
private static final long serialVersionUID = 1L;
private static final String BACKBONE = "Backbone Slot";
private final BackbonePanel backbonePanel;
/**
*
* @param backbonePanel The associate backbone slot panel.
*/
public BackboneSlotNode(BackbonePanel backbonePanel)
{
super(backbonePanel, BACKBONE);
if(backbonePanel == null)
{
throw new IllegalArgumentException("BackboneSlotPanel is null.");
}
else
{
this.backbonePanel = backbonePanel;
}
}
@Override
/**
* @return The BackbonePanel.
*/
public BackbonePanel getPanel()
{
if(this.backbonePanel == null)
throw new NullPointerException("BackbonePanel is null.");
return this.backbonePanel;
}
@Override
public void updateName()
{
super.rename(BACKBONE);
}
@Override
public int getSlotNumber()
{
return Slotable.BACKBONE_SLOT_NUMBER;
}
public Paint getNodeColor()
{
return this.backbonePanel.getBackboneStyleController().getColor();
}
}
| 1,450 | 0.729581 | 0.728895 | 69 | 20.115942 | 24.315878 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.231884 | false | false | 5 |
f4b445e1caf757c5b9acc1a78d29fbd418719ffb | 23,149,873,750,067 | a215f39d5dab5b983d0169754fbd5e01faea7e11 | /collaboration/src/main/java/com/niit/collaboration/service/FriendListService.java | 5b4410a119d8b71b83b135b141f8cc5bd30f3e8a | []
| no_license | NiruRai/Collaboration-Project | https://github.com/NiruRai/Collaboration-Project | a859f1b4a368e239687a845a4c2c82f163dfe9b3 | 8ad256f57b5c2cb19e4b6bea4e918c67e9a1423a | refs/heads/master | 2020-04-12T01:23:20.971000 | 2016-09-27T07:33:11 | 2016-09-27T07:33:11 | 65,290,170 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.niit.collaboration.service;
import com.niit.collaboration.model.FriendList;
import com.niit.collaboration.model.Users;
public interface FriendListService {
public FriendList getFriendByFromId(int id);
public void saveOrUpdate(FriendList friendList);
public void delete(int id);
public void addFriendList(FriendList friendList,Users userFrom,Users userTo);
}
| UTF-8 | Java | 384 | java | FriendListService.java | Java | []
| null | []
| package com.niit.collaboration.service;
import com.niit.collaboration.model.FriendList;
import com.niit.collaboration.model.Users;
public interface FriendListService {
public FriendList getFriendByFromId(int id);
public void saveOrUpdate(FriendList friendList);
public void delete(int id);
public void addFriendList(FriendList friendList,Users userFrom,Users userTo);
}
| 384 | 0.809896 | 0.809896 | 16 | 23 | 24.413111 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 5 |
a3052daaa19771cd59067b5275fe3d476f8f1e12 | 30,837,865,245,510 | 1a20d481381a4704ef0970a36cb2e66f37a94d12 | /src/main/java/com/computeralchemist/desktop/gui/alerts/PostedComponentAlert.java | 9edd28389ee960a9e009f525cc8b9a4a9cd76b70 | []
| no_license | meksula/computer-alchemist-UI | https://github.com/meksula/computer-alchemist-UI | 1ca3c93487b7da7dfe527df2e10e375ee915eb66 | debf19e275425a2c4a7a1258b93cc719a139bf79 | refs/heads/master | 2020-03-13T02:40:29.499000 | 2018-06-09T18:20:12 | 2018-06-09T18:20:12 | 130,929,205 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.computeralchemist.desktop.gui.alerts;
import javafx.scene.control.Alert;
/**
* @Author
* Karol Meksuła
* 22-05-2018
* */
public class PostedComponentAlert {
public void popupAlert(String httpStatus) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("POST process");
alert.setHeaderText(null);
if (httpStatus.equals("201"))
alert.setContentText("Component correctly posted and saved in database.");
else alert.setContentText("Unfortunatelly something went wrong and component hasn'n been posted.");
alert.showAndWait();
}
}
| UTF-8 | Java | 636 | java | PostedComponentAlert.java | Java | [
{
"context": "ort javafx.scene.control.Alert;\n\n/**\n * @Author\n * Karol Meksuła\n * 22-05-2018\n * */\n\npublic class PostedComponent",
"end": 118,
"score": 0.9998529553413391,
"start": 105,
"tag": "NAME",
"value": "Karol Meksuła"
}
]
| null | []
| package com.computeralchemist.desktop.gui.alerts;
import javafx.scene.control.Alert;
/**
* @Author
* <NAME>
* 22-05-2018
* */
public class PostedComponentAlert {
public void popupAlert(String httpStatus) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("POST process");
alert.setHeaderText(null);
if (httpStatus.equals("201"))
alert.setContentText("Component correctly posted and saved in database.");
else alert.setContentText("Unfortunatelly something went wrong and component hasn'n been posted.");
alert.showAndWait();
}
}
| 628 | 0.683465 | 0.666142 | 25 | 24.4 | 28.346428 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false | 5 |
c7c093abbfb42898c6353a75e56194db49bd9d3b | 5,961,414,671,706 | 2e1c5b7b5e6dd23619b303647bef5462034e0b79 | /Weather_save/app/src/main/java/com/example/wuken/weather_save/MainActivity.java | 5826c8e1a655265e13f53450a489806ca5bbe82e | []
| no_license | lllidontknowl/Weather_save | https://github.com/lllidontknowl/Weather_save | 98ec132300c00ff06f3bae70da86cdb65e6486fa | b273c5cabf43046bcb7a201fc3b8b003d82095af | refs/heads/master | 2020-09-06T12:42:00.599000 | 2018-05-02T01:43:16 | 2018-05-02T01:43:16 | 94,419,290 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.wuken.weather_save;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.view.View;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import static com.example.wuken.weather_save.DbConstants.TABLE_NAME;
import static android.provider.BaseColumns._ID;
import static com.example.wuken.weather_save.DbConstants.WEATHER;
import static com.example.wuken.weather_save.DbConstants.TEMP;
import static com.example.wuken.weather_save.DbConstants.DATE;
import static com.example.wuken.weather_save.R.drawable.clear;
import static com.example.wuken.weather_save.R.drawable.clearnight;
import static com.example.wuken.weather_save.R.drawable.cloudy;
import static com.example.wuken.weather_save.R.drawable.fog;
import static com.example.wuken.weather_save.R.drawable.freezing;
import static com.example.wuken.weather_save.R.drawable.freezingrain;
import static com.example.wuken.weather_save.R.drawable.freezingsnow;
import static com.example.wuken.weather_save.R.drawable.frost;
import static com.example.wuken.weather_save.R.drawable.hot01;
import static com.example.wuken.weather_save.R.drawable.mostlysunny;
import static com.example.wuken.weather_save.R.drawable.partlycloudy;
import static com.example.wuken.weather_save.R.drawable.partlycloundynight;
import static com.example.wuken.weather_save.R.drawable.rain01;
import static com.example.wuken.weather_save.R.drawable.rain02;
import static com.example.wuken.weather_save.R.drawable.sleet;
import static com.example.wuken.weather_save.R.drawable.snow;
import static com.example.wuken.weather_save.R.drawable.snow01;
import static com.example.wuken.weather_save.R.drawable.thunder;
import static com.example.wuken.weather_save.R.drawable.thunderstorms01;
import static com.example.wuken.weather_save.R.drawable.thunderstorms02;
import static com.example.wuken.weather_save.R.drawable.unknown;
import static com.example.wuken.weather_save.R.drawable.windy;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity implements ATresult<String[]>{
String mWeather = "weather"; //不要改成null
String mTemp = "fat";
String mDate = "boy";
Button btn_viewdb;
Button btn_save;
TextView txt_weatherview;
TextView txt_temp;
TextView txt_time;
ImageView imageview;
private DBHelper dbhelper = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_viewdb = (Button) findViewById(R.id.btn_viewdb);
btn_save = (Button) findViewById(R.id.btn_save);
txt_weatherview = (TextView) findViewById(R.id.txt_weatherview);
txt_temp=(TextView)findViewById(R.id.temp_text);
txt_time=(TextView)findViewById(R.id.time_text);
imageview=(ImageView)findViewById(R.id.imageView);
theReceiver myAyncTask = new theReceiver();
myAyncTask.weather_result=this;
myAyncTask.execute();
dbhelper = new DBHelper(this);
btn_viewdb.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, activity_viewdb.class);
startActivity(intent);
MainActivity.this.finish();
}
});
btn_save.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
dataUpdate(mWeather,mTemp,mDate);
}
});
}
@Override
public void taskFinish(String[] result) {
mWeather=result[0];
mTemp=result[1];
mDate=result[2];
Main_Set(mWeather,mTemp,mDate);
//dataUpdate(mWeather,mTemp,mDate);
// Log.v("weather之內容",mWeather);
// Log.v("temp之內容",mTemp);
// Log.v("date之內容",mDate);
}
public void dataUpdate(String weather,String temp,String Date){
SQLiteDatabase db = dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(WEATHER,weather);
values.put(TEMP,temp);
values.put(DATE,Date);
db.insert(TABLE_NAME, null, values);
}
protected void Main_Set(String weather,String temp,String time){
txt_weatherview.setText(weather);
txt_temp.setText(temp);
txt_time.setText(time);
/*介面更新請使用這
temp是溫度
Date是偵測日期
如果weather無吻合,幫我注意一下大小寫
天氣列表https://developer.yahoo.com/weather/documentation.html*/
switch (weather){
case "Tornado":
imageview.setImageResource(windy);
break;
case "Rain":
imageview.setImageResource(rain02);
break;
case "Tropical Storm":
imageview.setImageResource(windy);
break;
case "Hurricane":
imageview.setImageResource(windy);
break;
case "Severe Thunderstorms":
imageview.setImageResource(thunderstorms02);
break;
case "Thunderstorms":
imageview.setImageResource(thunderstorms01);
break;
case "Mixed Rain And Snow":
imageview.setImageResource(snow);
break;
case "Mixed Rain And Sleet":
imageview.setImageResource(sleet);
break;
case "Mixed Snow And Sleet":
imageview.setImageResource(snow01);
break;
case "Freezing Drizzle":
imageview.setImageResource(freezingsnow);
break;
case "Drizzle":
imageview.setImageResource(snow01);
break;
case "Freezing Rain":
imageview.setImageResource(freezingrain);
break;
case "Showers":
imageview.setImageResource(rain01);
break;
case "Snow Flurries":
imageview.setImageResource(snow01);
break;
case "Light Snow Showers":
imageview.setImageResource(snow01);
break;
case "Blowing Snow":
imageview.setImageResource(snow01);
break;
case "Snow":
imageview.setImageResource(snow01);
break;
case "Hail":
imageview.setImageResource(frost);
break;
case "Sleet":
imageview.setImageResource(sleet);
break;
case "Dust":
imageview.setImageResource(unknown);
break;
case "Foggy":
imageview.setImageResource(unknown);
break;
case "Haze":
imageview.setImageResource(fog);
break;
case "Smoky":
imageview.setImageResource(fog);
break;
case "Blustery":
imageview.setImageResource(windy);
break;
case "Windy":
imageview.setImageResource(windy);
break;
case "Cold":
imageview.setImageResource(freezing);
break;
case "Cloudy":
imageview.setImageResource(cloudy);
break;
case "Mostly Cloudy (night)":
imageview.setImageResource(partlycloundynight);
break;
case "Mostly Cloudy (day)":
imageview.setImageResource(partlycloudy);
break;
case "Partly cloudy (night)":
imageview.setImageResource(partlycloundynight);
break;
case "Partly cloudy (day)":
imageview.setImageResource(partlycloudy);
break;
case "Clear (night)":
imageview.setImageResource(clearnight);
break;
case "Sunny":
imageview.setImageResource(clear);
break;
case "Fair (night)":
imageview.setImageResource(partlycloundynight);
break;
case "Fair (day)":
imageview.setImageResource(mostlysunny);
break;
case "Mixed rain and hail":
imageview.setImageResource(rain02);
break;
case "Hot":
imageview.setImageResource(hot01);
break;
case "Isolated thunderstorms":
imageview.setImageResource(thunder);
break;
case "Scattered thunderstorms":
imageview.setImageResource(thunder);
break;
case "Scattered showers":
imageview.setImageResource(snow);
break;
case "Heavy snow":
imageview.setImageResource(snow);
break;
case "Scattered snow showers":
imageview.setImageResource(snow);
break;
case "Partly cloudy":
imageview.setImageResource(partlycloudy);
break;
case "Thundershowers":
break;
case "Snow showers":
break;
case "Isolated thundershowers":
break;
case "Not available":
break;
default:
Log.v("天氣怪怪的","It's a bug!");
}
}
}
| UTF-8 | Java | 10,367 | java | MainActivity.java | Java | []
| null | []
| package com.example.wuken.weather_save;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.view.View;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import static com.example.wuken.weather_save.DbConstants.TABLE_NAME;
import static android.provider.BaseColumns._ID;
import static com.example.wuken.weather_save.DbConstants.WEATHER;
import static com.example.wuken.weather_save.DbConstants.TEMP;
import static com.example.wuken.weather_save.DbConstants.DATE;
import static com.example.wuken.weather_save.R.drawable.clear;
import static com.example.wuken.weather_save.R.drawable.clearnight;
import static com.example.wuken.weather_save.R.drawable.cloudy;
import static com.example.wuken.weather_save.R.drawable.fog;
import static com.example.wuken.weather_save.R.drawable.freezing;
import static com.example.wuken.weather_save.R.drawable.freezingrain;
import static com.example.wuken.weather_save.R.drawable.freezingsnow;
import static com.example.wuken.weather_save.R.drawable.frost;
import static com.example.wuken.weather_save.R.drawable.hot01;
import static com.example.wuken.weather_save.R.drawable.mostlysunny;
import static com.example.wuken.weather_save.R.drawable.partlycloudy;
import static com.example.wuken.weather_save.R.drawable.partlycloundynight;
import static com.example.wuken.weather_save.R.drawable.rain01;
import static com.example.wuken.weather_save.R.drawable.rain02;
import static com.example.wuken.weather_save.R.drawable.sleet;
import static com.example.wuken.weather_save.R.drawable.snow;
import static com.example.wuken.weather_save.R.drawable.snow01;
import static com.example.wuken.weather_save.R.drawable.thunder;
import static com.example.wuken.weather_save.R.drawable.thunderstorms01;
import static com.example.wuken.weather_save.R.drawable.thunderstorms02;
import static com.example.wuken.weather_save.R.drawable.unknown;
import static com.example.wuken.weather_save.R.drawable.windy;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity implements ATresult<String[]>{
String mWeather = "weather"; //不要改成null
String mTemp = "fat";
String mDate = "boy";
Button btn_viewdb;
Button btn_save;
TextView txt_weatherview;
TextView txt_temp;
TextView txt_time;
ImageView imageview;
private DBHelper dbhelper = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_viewdb = (Button) findViewById(R.id.btn_viewdb);
btn_save = (Button) findViewById(R.id.btn_save);
txt_weatherview = (TextView) findViewById(R.id.txt_weatherview);
txt_temp=(TextView)findViewById(R.id.temp_text);
txt_time=(TextView)findViewById(R.id.time_text);
imageview=(ImageView)findViewById(R.id.imageView);
theReceiver myAyncTask = new theReceiver();
myAyncTask.weather_result=this;
myAyncTask.execute();
dbhelper = new DBHelper(this);
btn_viewdb.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, activity_viewdb.class);
startActivity(intent);
MainActivity.this.finish();
}
});
btn_save.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
dataUpdate(mWeather,mTemp,mDate);
}
});
}
@Override
public void taskFinish(String[] result) {
mWeather=result[0];
mTemp=result[1];
mDate=result[2];
Main_Set(mWeather,mTemp,mDate);
//dataUpdate(mWeather,mTemp,mDate);
// Log.v("weather之內容",mWeather);
// Log.v("temp之內容",mTemp);
// Log.v("date之內容",mDate);
}
public void dataUpdate(String weather,String temp,String Date){
SQLiteDatabase db = dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(WEATHER,weather);
values.put(TEMP,temp);
values.put(DATE,Date);
db.insert(TABLE_NAME, null, values);
}
protected void Main_Set(String weather,String temp,String time){
txt_weatherview.setText(weather);
txt_temp.setText(temp);
txt_time.setText(time);
/*介面更新請使用這
temp是溫度
Date是偵測日期
如果weather無吻合,幫我注意一下大小寫
天氣列表https://developer.yahoo.com/weather/documentation.html*/
switch (weather){
case "Tornado":
imageview.setImageResource(windy);
break;
case "Rain":
imageview.setImageResource(rain02);
break;
case "Tropical Storm":
imageview.setImageResource(windy);
break;
case "Hurricane":
imageview.setImageResource(windy);
break;
case "Severe Thunderstorms":
imageview.setImageResource(thunderstorms02);
break;
case "Thunderstorms":
imageview.setImageResource(thunderstorms01);
break;
case "Mixed Rain And Snow":
imageview.setImageResource(snow);
break;
case "Mixed Rain And Sleet":
imageview.setImageResource(sleet);
break;
case "Mixed Snow And Sleet":
imageview.setImageResource(snow01);
break;
case "Freezing Drizzle":
imageview.setImageResource(freezingsnow);
break;
case "Drizzle":
imageview.setImageResource(snow01);
break;
case "Freezing Rain":
imageview.setImageResource(freezingrain);
break;
case "Showers":
imageview.setImageResource(rain01);
break;
case "Snow Flurries":
imageview.setImageResource(snow01);
break;
case "Light Snow Showers":
imageview.setImageResource(snow01);
break;
case "Blowing Snow":
imageview.setImageResource(snow01);
break;
case "Snow":
imageview.setImageResource(snow01);
break;
case "Hail":
imageview.setImageResource(frost);
break;
case "Sleet":
imageview.setImageResource(sleet);
break;
case "Dust":
imageview.setImageResource(unknown);
break;
case "Foggy":
imageview.setImageResource(unknown);
break;
case "Haze":
imageview.setImageResource(fog);
break;
case "Smoky":
imageview.setImageResource(fog);
break;
case "Blustery":
imageview.setImageResource(windy);
break;
case "Windy":
imageview.setImageResource(windy);
break;
case "Cold":
imageview.setImageResource(freezing);
break;
case "Cloudy":
imageview.setImageResource(cloudy);
break;
case "Mostly Cloudy (night)":
imageview.setImageResource(partlycloundynight);
break;
case "Mostly Cloudy (day)":
imageview.setImageResource(partlycloudy);
break;
case "Partly cloudy (night)":
imageview.setImageResource(partlycloundynight);
break;
case "Partly cloudy (day)":
imageview.setImageResource(partlycloudy);
break;
case "Clear (night)":
imageview.setImageResource(clearnight);
break;
case "Sunny":
imageview.setImageResource(clear);
break;
case "Fair (night)":
imageview.setImageResource(partlycloundynight);
break;
case "Fair (day)":
imageview.setImageResource(mostlysunny);
break;
case "Mixed rain and hail":
imageview.setImageResource(rain02);
break;
case "Hot":
imageview.setImageResource(hot01);
break;
case "Isolated thunderstorms":
imageview.setImageResource(thunder);
break;
case "Scattered thunderstorms":
imageview.setImageResource(thunder);
break;
case "Scattered showers":
imageview.setImageResource(snow);
break;
case "Heavy snow":
imageview.setImageResource(snow);
break;
case "Scattered snow showers":
imageview.setImageResource(snow);
break;
case "Partly cloudy":
imageview.setImageResource(partlycloudy);
break;
case "Thundershowers":
break;
case "Snow showers":
break;
case "Isolated thundershowers":
break;
case "Not available":
break;
default:
Log.v("天氣怪怪的","It's a bug!");
}
}
}
| 10,367 | 0.596725 | 0.592827 | 287 | 34.74913 | 19.390175 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.721254 | false | false | 5 |
1db5abaf8066aee3bacaa9cb53509b1614196c85 | 5,970,004,580,403 | 16dd3abe38c9ad6445991c33b23fc353a361b08f | /src/main/java/reflection/inClass/proxy/Main.java | 7e2bcb905f6a3defe626e1ffad55189439dbd76b | []
| no_license | Lolret/InnopolisTests2018 | https://github.com/Lolret/InnopolisTests2018 | 71532a341a8f7dcc37e5d7d8d3895b1e4470b6c1 | 14f5281d3a4920db50c2dfa22a730b3a1bdbc1d0 | refs/heads/master | 2020-03-28T12:37:39.092000 | 2018-09-30T07:21:17 | 2018-09-30T07:21:18 | 148,317,026 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package reflection.inClass.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
Trainer trainer = new JavaTrainer();
InvocationHandler center = new TrainingCenter(trainer);
Trainer stc = (Trainer) Proxy.newProxyInstance(TrainingCenter.class.getClassLoader(),
new Class[]{Trainer.class}, center);
System.out.println("Without proxy:");
trainer.sleep();
trainer.eat();
trainer.teach();
System.out.println("With proxy:");
stc.sleep();
stc.eat();
stc.teach();
}
} | UTF-8 | Java | 669 | java | Main.java | Java | []
| null | []
| package reflection.inClass.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
Trainer trainer = new JavaTrainer();
InvocationHandler center = new TrainingCenter(trainer);
Trainer stc = (Trainer) Proxy.newProxyInstance(TrainingCenter.class.getClassLoader(),
new Class[]{Trainer.class}, center);
System.out.println("Without proxy:");
trainer.sleep();
trainer.eat();
trainer.teach();
System.out.println("With proxy:");
stc.sleep();
stc.eat();
stc.teach();
}
} | 669 | 0.626308 | 0.626308 | 27 | 23.814816 | 23.346087 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false | 5 |
dc29fb0b822ee3d2ede4b68e0e63adf9c57e6a06 | 17,042,430,296,199 | 350fb8f8cba86f8099f288c4d4f4fb04136af4cb | /src/School.java | 3638ed88d1c9e8a73a6475df7c3465d9c588281a | []
| no_license | Saumya1988/School_System | https://github.com/Saumya1988/School_System | 26efcfe0274cb14bfd7afa7bf9ca03699f0891b5 | 25030ea8eb964b6f0259ea4d4dfdf2a3df4d7b71 | refs/heads/master | 2020-05-15T22:47:58.268000 | 2019-04-21T16:45:01 | 2019-04-21T16:45:01 | 182,536,461 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
public class School
{
String school_name;
String school_branch;
Standard[] arr=new Standard[10];
}
| UTF-8 | Java | 137 | java | School.java | Java | []
| null | []
| import java.util.ArrayList;
public class School
{
String school_name;
String school_branch;
Standard[] arr=new Standard[10];
}
| 137 | 0.715328 | 0.70073 | 8 | 15.125 | 11.86842 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 5 |
9dd11d3389d13e9ed4481db290a7bcd51a36b562 | 26,920,855,075,769 | aa5a255389230e836157b4e8477ace06dd50bef5 | /test1/opengl3dtexture2/MainGLRenderer.java | fb5b2db4ba6e10d959b50953fe36e22257770c70 | []
| no_license | homg93/homg93git | https://github.com/homg93/homg93git | aa43b3207a8f573cea045141afde255481de4d5d | f8b3a88ee766df1769f288cddfeec6118af732c0 | refs/heads/master | 2021-05-14T06:32:18.860000 | 2018-01-09T12:11:28 | 2018-01-09T12:11:28 | 116,242,765 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.ac.hallym.opengl3dtexture;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;
import android.view.MotionEvent;
import java.io.BufferedInputStream;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class MainGLRenderer implements GLSurfaceView.Renderer {
private Context myContext;
//private MySquare mySquare;
private TexCube myCube;
private MyTrackBall myTrackBall;
private float[] mtxProj = new float[16];
private float[] mtxView = new float[16];
long lastTime;
float rotAngle;
public MainGLRenderer(Context context){
myContext = context; //bitmap을 사용하기 위해서
}
@Override
public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
myCube = new TexCube(this, loadBitmap("bobargb8888.png")); //texture이미지를 전달
myTrackBall = new MyTrackBall();
lastTime = System.currentTimeMillis();
rotAngle = 0.0f;
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
}
@Override
public void onSurfaceChanged(GL10 gl10, int i, int i1) {
//(0,0) 은 윈쪽 하단
GLES20.glViewport(0, 0, i, i1);//GLES20.glViewport(xPosition,yPosition,w,h);
myTrackBall.resize(i,i1);
Matrix.setIdentityM(mtxProj,0);//항등행렬로 셋팅
Matrix.perspectiveM(mtxProj, 0, 90.0f, i/(float)i1, 0.001f, 1000.0f);
Matrix.setIdentityM(mtxView,0);
Matrix.setLookAtM(mtxView,0, 1.0f,1.0f,1.0f,0.0f,0.0f,0.0f,0.0f,1.0f,0.0f);
//카메라 위치 목표지점 업벡터
}
@Override
public void onDrawFrame(GL10 gl10) {
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
//배경색 설정. 현재 색은 cyan
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
//GLES20.GL_DEPTH_BUFFER_BIT); 버퍼를 지울때 깊이버퍼도 같이 지워라
//배경색 버퍼 지우기(컬러버퍼 = 프레임버퍼)
long currentTime = System.currentTimeMillis();
if(currentTime < lastTime)
return;
long elapsedTime = currentTime - lastTime;
lastTime = currentTime;
rotAngle += elapsedTime*0.1f;
if(rotAngle > 36000.0f)
rotAngle = 36000.0f;
float[] mtxModel = new float[16];
Matrix.setIdentityM(mtxModel,0);
//Matrix.setRotateM(mtxModel,0,rotAngle,0.0f,1.0f,0.0f);
//float[] mtxTrans = new float[16];
//Matrix.setIdentityM(mtxTrans,0);
//Matrix.translateM(mtxTrans, 0, 0.0f, -0.5f, 0.0f);
Matrix.multiplyMM(mtxModel,0,myTrackBall.roataionMatrix,0,mtxModel,0);
// mySquare.draw();
myCube.draw(mtxProj, mtxView,mtxModel);
//삼각형 그리기
}
public static int loadShader(int type, String shaderCode) {//2.0서부터 꼭써야함 gpu 에서 실행
int shader = GLES20.glCreateShader(type);//shader생성!! (type2개 vertexShader Fragment Shader
//쉐이더 생성(type : vertexshader, fragmentshader)
GLES20.glShaderSource(shader, shaderCode); //Shader 소수코드지정 Text Type
//쉐이더 소스코드 지정(텍스트 타입) -> 그래서 MyTriangle에서 string형식으로 선언 오류메세지 보는법이 있지만 자세하게 안나옴
GLES20.glCompileShader(shader);//소스코드 컴파일
//쉐이더 소스코드 컴파일
int compiled[] = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if(compiled[0] <= 0){
Log.e("MainGLRenderer", GLES20.glGetShaderInfoLog(shader));
return 0;
}
return shader;
}
public void onPause() {
}
public void onResume() {
}
public boolean onTouchEvent(MotionEvent event){
final int action = event.getActionMasked();
final int x = (int)event.getX();
final int y = (int)event.getY();
switch(action){
case MotionEvent.ACTION_DOWN:
myTrackBall.start(x,y);
break;
case MotionEvent.ACTION_MOVE:
myTrackBall.end(x,y);
break;
}
return true;
}
public Bitmap loadBitmap(String filename){
Bitmap bitmap = null;
try{
AssetManager manager = myContext.getAssets();
BufferedInputStream inputStream = new BufferedInputStream(manager.open(filename));
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (Exception ex){
Log.e("MainGLRenderer", "Error in loading a bitmap:" + ex.toString());
}
return bitmap;
}
} | UTF-8 | Java | 4,919 | java | MainGLRenderer.java | Java | []
| null | []
| package kr.ac.hallym.opengl3dtexture;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;
import android.view.MotionEvent;
import java.io.BufferedInputStream;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class MainGLRenderer implements GLSurfaceView.Renderer {
private Context myContext;
//private MySquare mySquare;
private TexCube myCube;
private MyTrackBall myTrackBall;
private float[] mtxProj = new float[16];
private float[] mtxView = new float[16];
long lastTime;
float rotAngle;
public MainGLRenderer(Context context){
myContext = context; //bitmap을 사용하기 위해서
}
@Override
public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
myCube = new TexCube(this, loadBitmap("bobargb8888.png")); //texture이미지를 전달
myTrackBall = new MyTrackBall();
lastTime = System.currentTimeMillis();
rotAngle = 0.0f;
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
}
@Override
public void onSurfaceChanged(GL10 gl10, int i, int i1) {
//(0,0) 은 윈쪽 하단
GLES20.glViewport(0, 0, i, i1);//GLES20.glViewport(xPosition,yPosition,w,h);
myTrackBall.resize(i,i1);
Matrix.setIdentityM(mtxProj,0);//항등행렬로 셋팅
Matrix.perspectiveM(mtxProj, 0, 90.0f, i/(float)i1, 0.001f, 1000.0f);
Matrix.setIdentityM(mtxView,0);
Matrix.setLookAtM(mtxView,0, 1.0f,1.0f,1.0f,0.0f,0.0f,0.0f,0.0f,1.0f,0.0f);
//카메라 위치 목표지점 업벡터
}
@Override
public void onDrawFrame(GL10 gl10) {
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
//배경색 설정. 현재 색은 cyan
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
//GLES20.GL_DEPTH_BUFFER_BIT); 버퍼를 지울때 깊이버퍼도 같이 지워라
//배경색 버퍼 지우기(컬러버퍼 = 프레임버퍼)
long currentTime = System.currentTimeMillis();
if(currentTime < lastTime)
return;
long elapsedTime = currentTime - lastTime;
lastTime = currentTime;
rotAngle += elapsedTime*0.1f;
if(rotAngle > 36000.0f)
rotAngle = 36000.0f;
float[] mtxModel = new float[16];
Matrix.setIdentityM(mtxModel,0);
//Matrix.setRotateM(mtxModel,0,rotAngle,0.0f,1.0f,0.0f);
//float[] mtxTrans = new float[16];
//Matrix.setIdentityM(mtxTrans,0);
//Matrix.translateM(mtxTrans, 0, 0.0f, -0.5f, 0.0f);
Matrix.multiplyMM(mtxModel,0,myTrackBall.roataionMatrix,0,mtxModel,0);
// mySquare.draw();
myCube.draw(mtxProj, mtxView,mtxModel);
//삼각형 그리기
}
public static int loadShader(int type, String shaderCode) {//2.0서부터 꼭써야함 gpu 에서 실행
int shader = GLES20.glCreateShader(type);//shader생성!! (type2개 vertexShader Fragment Shader
//쉐이더 생성(type : vertexshader, fragmentshader)
GLES20.glShaderSource(shader, shaderCode); //Shader 소수코드지정 Text Type
//쉐이더 소스코드 지정(텍스트 타입) -> 그래서 MyTriangle에서 string형식으로 선언 오류메세지 보는법이 있지만 자세하게 안나옴
GLES20.glCompileShader(shader);//소스코드 컴파일
//쉐이더 소스코드 컴파일
int compiled[] = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if(compiled[0] <= 0){
Log.e("MainGLRenderer", GLES20.glGetShaderInfoLog(shader));
return 0;
}
return shader;
}
public void onPause() {
}
public void onResume() {
}
public boolean onTouchEvent(MotionEvent event){
final int action = event.getActionMasked();
final int x = (int)event.getX();
final int y = (int)event.getY();
switch(action){
case MotionEvent.ACTION_DOWN:
myTrackBall.start(x,y);
break;
case MotionEvent.ACTION_MOVE:
myTrackBall.end(x,y);
break;
}
return true;
}
public Bitmap loadBitmap(String filename){
Bitmap bitmap = null;
try{
AssetManager manager = myContext.getAssets();
BufferedInputStream inputStream = new BufferedInputStream(manager.open(filename));
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (Exception ex){
Log.e("MainGLRenderer", "Error in loading a bitmap:" + ex.toString());
}
return bitmap;
}
} | 4,919 | 0.634535 | 0.601312 | 139 | 31.920864 | 24.954943 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.971223 | false | false | 5 |
f196b3e83c3223813435b17af3fc1cd7fce7b2d9 | 19,799,799,295,468 | fc9f059bea72dabdbd1b7e77d87db4fad403fbb6 | /Programacio1- UB/Laboratori/Llistab/GomezFarrusVictor-B/EncriptarRotN.java | 0441e6ef9db28a0ffd4ddc74c3daceea25e1fef4 | []
| no_license | fitigf15/JAVA-VICTOR | https://github.com/fitigf15/JAVA-VICTOR | cc6f787fd04295b30718ee5a589509957af188e0 | 5d5dcecfdce29f2b1a93c0aa48427465a4b150e0 | refs/heads/master | 2016-09-06T19:42:34.490000 | 2015-04-15T19:25:54 | 2015-04-15T19:25:54 | 24,456,705 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Autor: Victor Gomez Farrus
* Grup de practiques: B
*
*
* EncriptarRotN,java
* Aquest programa reemplaça la lletra per la lletra que esta n posicions mes endavant a l'alfabet. n valdra 1 ≤ n ≤ 9. Llegira paraula a paraula una frase acabada amb "fi"
* i imprimira el resultat codificat desplaçant la paraula n caracters.
*/
import java.util.Scanner;
public class EncriptarRotN{
public static void main(String[]args){
String paraula = ""; //Tindra el valor de cada paraula que escanegem fins que la paraula acabi en "fi"
String frase = ""; //Sera un string amb totes els paraules que hagim escanejat fins tenir una paraula que acabi en "fi"
String frasecodif=""; //Sera la frase codificada
//boolean acaba=false; //Ens indicara quan acabar d'escanejar paraules
int n,lenfrase=0,codif,noucodif=0; // n es la codificacio
// lenfrase es el nombre de caracters de la frase acabada en fi
// codif es el valor de cada caracter ascii de la frase
// noucodif es codif afegint n, que ens donara el nou valor del caracter ascii
// i es la posicio de cada caracter a la frase
char noucaracter; //noucaracter es el caracter ascii corresponent a la nova codificacio noucodif
Scanner sc = new Scanner(System.in);
System.out.println("Escriviu una frase que vulgueu codificar que acabi amb la paraula fi. Si no escriviu fi al final, el programa no acabara mai i llavors haureu de picar ctrl+c per cancelar l'ordre.");
//Escanejarem la primera paraula
paraula=sc.next();
//Si la paraula acaba en "fi" el programa no te cap sentit perque no es codifica res
if (paraula.equals("fi")) {
System.out.println("No heu escrit res mes que fi...");
}else{
//El print de sota es per comprovar si la paraula acaba o no en "fi"
//System.out.println(paraula+" = "+acaba);
while(!paraula.equals("fi")){
//El print de sota es per comprovar si la paraula acaba o no en "fi"
//System.out.println(paraula+" = "+acaba);
frase = frase + paraula+ " ";
paraula=sc.next();
}
//El print de sota es per comprovar que la frase acaba en fi
//System.out.println(frase);
lenfrase=frase.length();
System.out.println("Escriviu un n amb el que volgueu codificar la frase. n ha de valdre entre 1 i 9, ambdos inclosos.");
n = sc.nextInt();
if ((n<=9)&&(n>=1)){ //posem entre 1 i 9, pero podria ser qualsevol nombre positiu
for(int i=0; i<frase.length();i++){
codif = (int)frase.charAt(i);
if (((65<=codif)&&(codif<=90)) || ((97<=codif)&&(codif<=122))){
if (((codif<=90)&&(codif>=90-n+1))||((codif<=122)&&(codif>=122-n+1))){
noucodif = codif-26+ n;
}else{
noucodif = codif + n;
}
}else if((codif==32)||(codif==10)||(codif==33)||(codif==39)||(codif==44)||(codif==45||(codif==46)||(codif==63))){
noucodif = codif;
}
noucaracter = (char)noucodif;
//Els prints de sota son per veure pas a pas la codificacio de caracters
//System.out.print(frase.charAt(i)+"=");
//System.out.print(codif+"=");
//System.out.print(noucodif+"=");
//System.out.print(noucaracter);
frasecodif = frasecodif + noucaracter;
//System.out.println();
}
System.out.println("La frase codificada amb n="+n+" es: "+frasecodif); // imprimim la nova frase codificada
/* Aixo podria servir per encriptar amb n negativa
}else if (n<0){
for(int i=0; i<frase.length();i++){
codif = (int)frase.charAt(i);
if (((65<=codif)&&(codif<=90)) || ((97<=codif)&&(codif<=122))){
if (((codif>=65)&&(codif<=65-n-1))||((codif>=97)&&(codif<=97-n-1))){
noucodif = codif+26+n;
}else{
noucodif = codif+n;
}
}else if((codif==32)||(codif==10)||(codif==33)||(codif==39)||(codif==44)||(codif==45||(codif==46)||(codif==63))){
noucodif = codif;
}
noucaracter = (char)noucodif;
//Els prints de sota son per veure pas a pas la codificacio
//System.out.print(frase.charAt(i)+"=");
//System.out.print(codif+"=");
//System.out.print(noucodif+"=");
//System.out.print(noucaracter);
frasecodif = frasecodif + noucaracter;
//System.out.println();
}
System.out.println("La frase codificada amb n="+n+" es: "+frasecodif);
*/
}else{
System.out.println("No has posat una n d'acord amb el que s'ha demanat.");
}
}
}
}
| UTF-8 | Java | 4,741 | java | EncriptarRotN.java | Java | [
{
"context": "/*\n*\tAutor: Victor Gomez Farrus\n*\tGrup de practiques: B\n*\t\n*\n*\t\t\t\t\tEncriptarRotN,",
"end": 31,
"score": 0.9998726844787598,
"start": 12,
"tag": "NAME",
"value": "Victor Gomez Farrus"
}
]
| null | []
| /*
* Autor: <NAME>
* Grup de practiques: B
*
*
* EncriptarRotN,java
* Aquest programa reemplaça la lletra per la lletra que esta n posicions mes endavant a l'alfabet. n valdra 1 ≤ n ≤ 9. Llegira paraula a paraula una frase acabada amb "fi"
* i imprimira el resultat codificat desplaçant la paraula n caracters.
*/
import java.util.Scanner;
public class EncriptarRotN{
public static void main(String[]args){
String paraula = ""; //Tindra el valor de cada paraula que escanegem fins que la paraula acabi en "fi"
String frase = ""; //Sera un string amb totes els paraules que hagim escanejat fins tenir una paraula que acabi en "fi"
String frasecodif=""; //Sera la frase codificada
//boolean acaba=false; //Ens indicara quan acabar d'escanejar paraules
int n,lenfrase=0,codif,noucodif=0; // n es la codificacio
// lenfrase es el nombre de caracters de la frase acabada en fi
// codif es el valor de cada caracter ascii de la frase
// noucodif es codif afegint n, que ens donara el nou valor del caracter ascii
// i es la posicio de cada caracter a la frase
char noucaracter; //noucaracter es el caracter ascii corresponent a la nova codificacio noucodif
Scanner sc = new Scanner(System.in);
System.out.println("Escriviu una frase que vulgueu codificar que acabi amb la paraula fi. Si no escriviu fi al final, el programa no acabara mai i llavors haureu de picar ctrl+c per cancelar l'ordre.");
//Escanejarem la primera paraula
paraula=sc.next();
//Si la paraula acaba en "fi" el programa no te cap sentit perque no es codifica res
if (paraula.equals("fi")) {
System.out.println("No heu escrit res mes que fi...");
}else{
//El print de sota es per comprovar si la paraula acaba o no en "fi"
//System.out.println(paraula+" = "+acaba);
while(!paraula.equals("fi")){
//El print de sota es per comprovar si la paraula acaba o no en "fi"
//System.out.println(paraula+" = "+acaba);
frase = frase + paraula+ " ";
paraula=sc.next();
}
//El print de sota es per comprovar que la frase acaba en fi
//System.out.println(frase);
lenfrase=frase.length();
System.out.println("Escriviu un n amb el que volgueu codificar la frase. n ha de valdre entre 1 i 9, ambdos inclosos.");
n = sc.nextInt();
if ((n<=9)&&(n>=1)){ //posem entre 1 i 9, pero podria ser qualsevol nombre positiu
for(int i=0; i<frase.length();i++){
codif = (int)frase.charAt(i);
if (((65<=codif)&&(codif<=90)) || ((97<=codif)&&(codif<=122))){
if (((codif<=90)&&(codif>=90-n+1))||((codif<=122)&&(codif>=122-n+1))){
noucodif = codif-26+ n;
}else{
noucodif = codif + n;
}
}else if((codif==32)||(codif==10)||(codif==33)||(codif==39)||(codif==44)||(codif==45||(codif==46)||(codif==63))){
noucodif = codif;
}
noucaracter = (char)noucodif;
//Els prints de sota son per veure pas a pas la codificacio de caracters
//System.out.print(frase.charAt(i)+"=");
//System.out.print(codif+"=");
//System.out.print(noucodif+"=");
//System.out.print(noucaracter);
frasecodif = frasecodif + noucaracter;
//System.out.println();
}
System.out.println("La frase codificada amb n="+n+" es: "+frasecodif); // imprimim la nova frase codificada
/* Aixo podria servir per encriptar amb n negativa
}else if (n<0){
for(int i=0; i<frase.length();i++){
codif = (int)frase.charAt(i);
if (((65<=codif)&&(codif<=90)) || ((97<=codif)&&(codif<=122))){
if (((codif>=65)&&(codif<=65-n-1))||((codif>=97)&&(codif<=97-n-1))){
noucodif = codif+26+n;
}else{
noucodif = codif+n;
}
}else if((codif==32)||(codif==10)||(codif==33)||(codif==39)||(codif==44)||(codif==45||(codif==46)||(codif==63))){
noucodif = codif;
}
noucaracter = (char)noucodif;
//Els prints de sota son per veure pas a pas la codificacio
//System.out.print(frase.charAt(i)+"=");
//System.out.print(codif+"=");
//System.out.print(noucodif+"=");
//System.out.print(noucaracter);
frasecodif = frasecodif + noucaracter;
//System.out.println();
}
System.out.println("La frase codificada amb n="+n+" es: "+frasecodif);
*/
}else{
System.out.println("No has posat una n d'acord amb el que s'ha demanat.");
}
}
}
}
| 4,728 | 0.586906 | 0.56811 | 103 | 44.941746 | 38.221333 | 204 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.990291 | false | false | 5 |
d289008304af6950251c149fb767cc3df60b3b98 | 19,799,799,294,889 | 17bbcbd480e012937c3580e2da1be68339024b93 | /SimpleInterestCalculatorRunner.java | 226e3a2f55d6f712447dc34f52942f7fbdc623e7 | []
| no_license | NidhiBans/Coderecipe | https://github.com/NidhiBans/Coderecipe | 81d73ce25757cccbfca232d818025cb94cd58d61 | 0566f3f12c7321b5c5b7f3e7feef65e6f669fa01 | refs/heads/master | 2020-03-18T16:20:32.740000 | 2018-06-17T18:25:03 | 2018-06-17T18:25:03 | 134,960,464 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.primitive;
import java.math.BigDecimal;
public class SimpleInterestCalculatorRunner {
public static void main(String[] args) {
SimpleInterestCalculator calculator = new SimpleInterestCalculator("4500.00", "70.0");
BigDecimal totalsum = calculator.calculatevalue(5);
System.out.println(totalsum);
}
}
| UTF-8 | Java | 341 | java | SimpleInterestCalculatorRunner.java | Java | []
| null | []
| package com.primitive;
import java.math.BigDecimal;
public class SimpleInterestCalculatorRunner {
public static void main(String[] args) {
SimpleInterestCalculator calculator = new SimpleInterestCalculator("4500.00", "70.0");
BigDecimal totalsum = calculator.calculatevalue(5);
System.out.println(totalsum);
}
}
| 341 | 0.73607 | 0.706745 | 15 | 20.733334 | 25.877832 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.933333 | false | false | 5 |
906afa1fb678c7e7a7916c9a3f99a7595eff800d | 16,234,976,443,125 | dca047b27d9ad630fa943871933e86a426c349fb | /credit/creditNetty/src/quartz/QuartzTaskManager.java | db33cb52c3e534c802bcb1ae885fb283b6320fe8 | []
| no_license | 13361997280/mstrunk_new | https://github.com/13361997280/mstrunk_new | 0c6934fdee41ba387428a73794065e61719a3749 | 67519a705fcbfbc93fd0aa3f1f0c8fafa754825f | refs/heads/master | 2021-04-29T21:12:19.741000 | 2018-02-15T10:23:18 | 2018-02-15T10:23:18 | 121,611,157 | 1 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package quartz;
import com.qbao.search.conf.Config;
import com.qbao.search.logging.ESLogger;
import com.qbao.search.logging.Loggers;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import java.util.Calendar;
/**
* can run timer task reduce to minut/per reduce to hour/per reduce to day/per
* ruduce to month/per ruduce to year/per if loss some log period , can init
* special customized task to add in logs;
* **/
public class QuartzTaskManager {
private static final ESLogger logger = Loggers.getLogger(QuartzTaskManager.class);
// 通过schedulerFactory获取一个调度器
SchedulerFactory schedulerfactory = new StdSchedulerFactory();
public static long adjustDate = Config.get().getInt("log.task.hbase.reduce.adjustDate", 60 * 60 * 2 * 1000);
private static QuartzTaskManager quartzTaskManager;
public static final QuartzTaskManager getInstance() {
if (quartzTaskManager == null) {
synchronized (QuartzTaskManager.class) {
if (quartzTaskManager == null) {
quartzTaskManager = new QuartzTaskManager();
}
}
}
return quartzTaskManager;
}
public QuartzTaskManager() {
//initTask("RecommendDicTask", "0 1 4 * * ? ", RecommendAllDicTask.class);
//initTask("UbtTask", "0 40 2 * * ? ", UbtTask.class);
//initTask("PropertySolrStaticTask", "0 30 6 * * ? ", PropertySolrStaticTask.class);
// initTask("RecommendDicTask", "0 1 4 * * ? ", RecommendDicTask.class);
// initTask("RecommendPinYin2dyCnDic_subTask", "0 3 4 * * ? ",
// RecommendPinYin2dyCnDic_subTask.class);
// HbaseTask("920601", HbaseLogReducer.DATE_LEVEL_HOUR,
// "swd_has_return_group_search", "search_logs_analysis",
// "30 01 * * * ? ", adjustDate);
// Hive task
// HiveTask("topkeywordsearchnumber", "0 25 10 * * ? ",
// TopKeywordSearchNumberService.class);
// EngineDaily
// EngineDailyTask("920601", "0 23 8 * * ? ",
// com.ctrip.search.lexis.engine.daily.report.EngineDailyTask.class);
// engineDaily Email
// EngineDailyTask("engineDailyMail", "0 5 8 * * ? ",
// com.ctrip.search.lexis.engine.daily.report.EngineDailyMailTask.class);
// EngineDailyTask("engineDailyMail", "30 01 13 * * ? ",
// com.ctrip.search.lexis.engine.daily.report.EngineDailyMailTask.class);
}
// 复杂调度
// 格式: [秒] [分] [小时] [日] [月] [周] [年]
// mmContrigger.setCronExpression("30 * * * * ? ");//每分钟 30秒启动
// 每分钟, 0-5秒,10-15秒启动
// mmContrigger.setCronExpression("0-5,10-15 * * * * ? ");
// mmContrigger.setCronExpression("0 30 * * * ? ");//每小时30分启动
// mmContrigger.setCronExpression("0 0 10 * * ? ");//每天10点启动
// mmContrigger.setCronExpression("0 0 0 15 * ? ");//每月启动
// mmContrigger.setCronExpression("0 0 0 1 6 ? * ");//每年启动
public void initTask(String taskName, String TimerRegex, Class clz) {
try {
Scheduler hhSchedul = schedulerfactory.getScheduler();
JobDetail hhcondJob = new JobDetail("name." + taskName, "group." + taskName, clz);
CronTrigger hhContrigger = new CronTrigger("name." + taskName, "group." + taskName);
hhContrigger.setCronExpression(TimerRegex);// 定时规则
hhSchedul.scheduleJob(hhcondJob, hhContrigger);
hhSchedul.start();
logger.info("+++++quartz." + taskName + " 任务启动 " + Calendar.getInstance().getTime() + "__" + taskName);
} catch (Exception e) {
}
}
public void EngineDailyTask(String appId, String TimerRegex, Class clz) {
try {
Scheduler hhSchedul = schedulerfactory.getScheduler();
JobDetail hhcondJob = new JobDetail("job.EngineDaily" + appId, "job.EngineDaily" + appId, clz);
// 传参
hhcondJob.getJobDataMap().put("appId", appId);
CronTrigger hhContrigger = new CronTrigger("trigger.EngineDaily" + appId, "trigger.EngineDaily" + appId);
hhContrigger.setCronExpression(TimerRegex);// 定时规则
hhSchedul.scheduleJob(hhcondJob, hhContrigger);
hhSchedul.start();
logger.info("quartz.EngineDaily 任务启动 " + Calendar.getInstance().getTime() + "__" + appId);
} catch (Exception e) {
}
}
public static void main(String[] args) throws Exception {
}
}
| UTF-8 | Java | 4,226 | java | QuartzTaskManager.java | Java | []
| null | []
| package quartz;
import com.qbao.search.conf.Config;
import com.qbao.search.logging.ESLogger;
import com.qbao.search.logging.Loggers;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import java.util.Calendar;
/**
* can run timer task reduce to minut/per reduce to hour/per reduce to day/per
* ruduce to month/per ruduce to year/per if loss some log period , can init
* special customized task to add in logs;
* **/
public class QuartzTaskManager {
private static final ESLogger logger = Loggers.getLogger(QuartzTaskManager.class);
// 通过schedulerFactory获取一个调度器
SchedulerFactory schedulerfactory = new StdSchedulerFactory();
public static long adjustDate = Config.get().getInt("log.task.hbase.reduce.adjustDate", 60 * 60 * 2 * 1000);
private static QuartzTaskManager quartzTaskManager;
public static final QuartzTaskManager getInstance() {
if (quartzTaskManager == null) {
synchronized (QuartzTaskManager.class) {
if (quartzTaskManager == null) {
quartzTaskManager = new QuartzTaskManager();
}
}
}
return quartzTaskManager;
}
public QuartzTaskManager() {
//initTask("RecommendDicTask", "0 1 4 * * ? ", RecommendAllDicTask.class);
//initTask("UbtTask", "0 40 2 * * ? ", UbtTask.class);
//initTask("PropertySolrStaticTask", "0 30 6 * * ? ", PropertySolrStaticTask.class);
// initTask("RecommendDicTask", "0 1 4 * * ? ", RecommendDicTask.class);
// initTask("RecommendPinYin2dyCnDic_subTask", "0 3 4 * * ? ",
// RecommendPinYin2dyCnDic_subTask.class);
// HbaseTask("920601", HbaseLogReducer.DATE_LEVEL_HOUR,
// "swd_has_return_group_search", "search_logs_analysis",
// "30 01 * * * ? ", adjustDate);
// Hive task
// HiveTask("topkeywordsearchnumber", "0 25 10 * * ? ",
// TopKeywordSearchNumberService.class);
// EngineDaily
// EngineDailyTask("920601", "0 23 8 * * ? ",
// com.ctrip.search.lexis.engine.daily.report.EngineDailyTask.class);
// engineDaily Email
// EngineDailyTask("engineDailyMail", "0 5 8 * * ? ",
// com.ctrip.search.lexis.engine.daily.report.EngineDailyMailTask.class);
// EngineDailyTask("engineDailyMail", "30 01 13 * * ? ",
// com.ctrip.search.lexis.engine.daily.report.EngineDailyMailTask.class);
}
// 复杂调度
// 格式: [秒] [分] [小时] [日] [月] [周] [年]
// mmContrigger.setCronExpression("30 * * * * ? ");//每分钟 30秒启动
// 每分钟, 0-5秒,10-15秒启动
// mmContrigger.setCronExpression("0-5,10-15 * * * * ? ");
// mmContrigger.setCronExpression("0 30 * * * ? ");//每小时30分启动
// mmContrigger.setCronExpression("0 0 10 * * ? ");//每天10点启动
// mmContrigger.setCronExpression("0 0 0 15 * ? ");//每月启动
// mmContrigger.setCronExpression("0 0 0 1 6 ? * ");//每年启动
public void initTask(String taskName, String TimerRegex, Class clz) {
try {
Scheduler hhSchedul = schedulerfactory.getScheduler();
JobDetail hhcondJob = new JobDetail("name." + taskName, "group." + taskName, clz);
CronTrigger hhContrigger = new CronTrigger("name." + taskName, "group." + taskName);
hhContrigger.setCronExpression(TimerRegex);// 定时规则
hhSchedul.scheduleJob(hhcondJob, hhContrigger);
hhSchedul.start();
logger.info("+++++quartz." + taskName + " 任务启动 " + Calendar.getInstance().getTime() + "__" + taskName);
} catch (Exception e) {
}
}
public void EngineDailyTask(String appId, String TimerRegex, Class clz) {
try {
Scheduler hhSchedul = schedulerfactory.getScheduler();
JobDetail hhcondJob = new JobDetail("job.EngineDaily" + appId, "job.EngineDaily" + appId, clz);
// 传参
hhcondJob.getJobDataMap().put("appId", appId);
CronTrigger hhContrigger = new CronTrigger("trigger.EngineDaily" + appId, "trigger.EngineDaily" + appId);
hhContrigger.setCronExpression(TimerRegex);// 定时规则
hhSchedul.scheduleJob(hhcondJob, hhContrigger);
hhSchedul.start();
logger.info("quartz.EngineDaily 任务启动 " + Calendar.getInstance().getTime() + "__" + appId);
} catch (Exception e) {
}
}
public static void main(String[] args) throws Exception {
}
}
| 4,226 | 0.698627 | 0.67435 | 111 | 35.738739 | 30.49168 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.135135 | false | false | 5 |
e3120a18b17b25dcda354f8aa1aa06ccc50181cb | 17,892,833,759,247 | b2077049ef06f0e095a46c5f9013b6c4e6e08dcd | /core/src/main/java/chaos/core/model/ExceptionModel_.java | 54e46f7019b1d58f9c60849b226a8cef71bb0f4b | []
| no_license | wsad137/chaos | https://github.com/wsad137/chaos | ba8d156406a3d6d88dc2012bcaf387ef333c8cb1 | 956b02ad8424aa93b523e89cc4ff3b036a330e65 | refs/heads/master | 2018-11-11T11:40:54.500000 | 2018-08-28T12:43:32 | 2018-08-28T12:43:32 | 114,718,273 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chaos.core.model;
import chaos.api.annoatation.ApiField;
import java.io.Serializable;
public class ExceptionModel_ implements Serializable {
@ApiField("ip///")
private String ip;
/**
* 用户id
*/
@ApiField("userId/用户id//")
private Long userId;
/**
* 异常标题
*/
@ApiField("title/异常标题//")
private String title;
/**
* 设备信息
*/
@ApiField("device/设备信息//")
private String device;
/**
* 创建时间
*/
@ApiField("cDate/创建时间//")
private Long cDate;
/**
* 异常内容
*/
@ApiField("context/异常内容//")
private String context;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table exceptions_
*
* @mbg.generated
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public String getIp() {
return ip;
}
/**
*
*/
public void setIp(String ip) {
this.ip = ip == null ? null : ip.trim();
}
/**
* 用户id
*/
public Long getUserId() {
return userId;
}
/**
* 用户id
*/
public void setUserId(Long userId) {
this.userId = userId;
}
/**
* 异常标题
*/
public String getTitle() {
return title;
}
/**
* 异常标题
*/
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
/**
* 设备信息
*/
public String getDevice() {
return device;
}
/**
* 设备信息
*/
public void setDevice(String device) {
this.device = device == null ? null : device.trim();
}
/**
* 创建时间
*/
public Long getcDate() {
return cDate;
}
/**
* 创建时间
*/
public void setcDate(Long cDate) {
this.cDate = cDate;
}
/**
* 异常内容
*/
public String getContext() {
return context;
}
/**
* 异常内容
*/
public void setContext(String context) {
this.context = context == null ? null : context.trim();
}
} | UTF-8 | Java | 2,251 | java | ExceptionModel_.java | Java | []
| null | []
| package chaos.core.model;
import chaos.api.annoatation.ApiField;
import java.io.Serializable;
public class ExceptionModel_ implements Serializable {
@ApiField("ip///")
private String ip;
/**
* 用户id
*/
@ApiField("userId/用户id//")
private Long userId;
/**
* 异常标题
*/
@ApiField("title/异常标题//")
private String title;
/**
* 设备信息
*/
@ApiField("device/设备信息//")
private String device;
/**
* 创建时间
*/
@ApiField("cDate/创建时间//")
private Long cDate;
/**
* 异常内容
*/
@ApiField("context/异常内容//")
private String context;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table exceptions_
*
* @mbg.generated
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public String getIp() {
return ip;
}
/**
*
*/
public void setIp(String ip) {
this.ip = ip == null ? null : ip.trim();
}
/**
* 用户id
*/
public Long getUserId() {
return userId;
}
/**
* 用户id
*/
public void setUserId(Long userId) {
this.userId = userId;
}
/**
* 异常标题
*/
public String getTitle() {
return title;
}
/**
* 异常标题
*/
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
/**
* 设备信息
*/
public String getDevice() {
return device;
}
/**
* 设备信息
*/
public void setDevice(String device) {
this.device = device == null ? null : device.trim();
}
/**
* 创建时间
*/
public Long getcDate() {
return cDate;
}
/**
* 创建时间
*/
public void setcDate(Long cDate) {
this.cDate = cDate;
}
/**
* 异常内容
*/
public String getContext() {
return context;
}
/**
* 异常内容
*/
public void setContext(String context) {
this.context = context == null ? null : context.trim();
}
} | 2,251 | 0.492644 | 0.492169 | 132 | 14.969697 | 15.276711 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 5 |
f887dd3aff88cb628299cf757f6395ae203678a1 | 32,057,635,963,033 | 0b817ccc5ee6e59ed6531256bb51ddc9b1be7ec9 | /Vina- Java/SPRING/book-management/src/main/java/com/hung/dto/RoleDTO.java | 2d35e549e984d3dc487afc69137707bf74bb03c7 | []
| no_license | hungqtc/Vina_spring | https://github.com/hungqtc/Vina_spring | 06fee4401e5adf1675d99d64c4295740a8d441c9 | fe4e2fdf9097515d4944fefee10a4607ebae8830 | refs/heads/master | 2023-02-01T00:22:02.595000 | 2020-12-20T10:30:00 | 2020-12-20T10:30:00 | 323,043,205 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hung.dto;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper=false)
public class RoleDTO extends BaseDTO{
private String name;
List<String> users = new ArrayList<String>();
}
| UTF-8 | Java | 387 | java | RoleDTO.java | Java | []
| null | []
| package com.hung.dto;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper=false)
public class RoleDTO extends BaseDTO{
private String name;
List<String> users = new ArrayList<String>();
}
| 387 | 0.81137 | 0.81137 | 19 | 19.368422 | 14.302045 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 5 |
bf788c2d178a7728c3fb8d3e4912ba78c7a60ca2 | 20,435,454,402,439 | efa111e72e82f3bf1f03ae853ca13f16bac370bd | /yifu_system/src/main/java/com/jwk/common/constant/FileUtil.java | 3c6573a77514c3e74c12e94431c484b60952cd18 | []
| no_license | shiyijun0/microonfig | https://github.com/shiyijun0/microonfig | 5fe2a38bee69a19e2489476006c58a3b1967a622 | 83b80ac70bbe8c2b993143d800a7d1991c6bc786 | refs/heads/master | 2020-03-26T20:51:27.096000 | 2018-08-20T02:07:29 | 2018-08-20T02:09:39 | 145,350,290 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jwk.common.constant;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import com.jwk.common.utils.ServletUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.jwk.common.utils.MessageUtils;
import com.jwk.common.utils.StringUtils;
public class FileUtil {
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
//单文件上传
public static String fileInput(MultipartFile file){
String path= ServletUtils.getHttpServletRequest().getSession().getServletContext().getRealPath("");
String type="upload";
if(file.getContentType().contains("image")){
type+="/image";
}
if(file.getContentType().contains("video")){
type+="/video";
}
File f=new File(path+type);
if(!f.exists()){
f.mkdirs();
}
System.out.println(path+type);
String fileName=file.getOriginalFilename();
String firstname= UUID.randomUUID().toString().replace("-","");
String lastname=fileName.substring(fileName.lastIndexOf("."));
fileName=firstname+lastname;
File target=new File(path+type,fileName);
try {
file.transferTo(target);
} catch (IOException e) {
e.printStackTrace();
}
return "/"+type+"/"+fileName;
}
//文件上传的工具类
public static List<String> uploadAttachment(HttpServletRequest request, String type) throws IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> files = multipartRequest.getFiles(type);
System.out.println("数据长度========>>>>>>>>>>" + files.size());
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1;
// String realPath = MessageUtils.message("file.upload.path", null);
// System.err.println("realpath=====>>>>>" + realPath);
String savePath = request.getSession().getServletContext().getRealPath("/") + "p_image\\" + type + "\\" + year+ "\\" + month + "\\";
// String savePath = "government"+ File.separator + "image"+ File.separator + year+ File.separator + month + File.separator;
System.out.println("保存路径=====>" + savePath);
List<String> fileNames = new ArrayList<String>();
for (MultipartFile multipartFile : files) {
System.out.println("------" + multipartFile.getOriginalFilename());
String fileName = multipartFile.getOriginalFilename();
System.out.println("文件绝对路径名字=====>" + savePath);
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
String custName = "" + System.currentTimeMillis() + "." + prefix;
System.out.println("**custName******"+custName);
if (StringUtils.isNotNull(fileName)) {
File targetFile = new File(savePath, custName);
// fileName = year+"-"+month+"-"+fileName;
if (!targetFile.exists()) {
targetFile.mkdirs();
System.out.println("********"+"保存文件");
multipartFile.transferTo(targetFile);
}
try {
} catch (Exception e) {
e.printStackTrace();
}
fileNames.add(savePath + custName);
}
}
return fileNames;
}
public static String getRequestPayload(HttpServletRequest req) {
StringBuilder sb = new StringBuilder(); String res=null;
try(BufferedReader reader = req.getReader();) {
char[]buff = new char[1024];
int len=0;;
while((len = reader.read(buff)) != -1) {
// String res = new String(buff, 0, len,"UTF-8");
sb.append(buff,0, len);
}
}catch (IOException e) {
e.printStackTrace();
}
try {
res = new String(sb.toString().getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
public static String getRequestPayloadJsonObject(HttpServletRequest request ){
InputStream inputStream=null;
String res=null;
try {
inputStream = request.getInputStream();
byte[] buff = new byte[1024];
int len = -1;
while (-1 != (len = inputStream.read(buff))) {
// 将字节数组转换为字符串,并且设置为“UTF-8”格式编码(不然会出现乱码)
res = new String(buff, 0, len,"UTF-8");
System.out.println("**res***"+res);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
public static Map<String, String> requestUtil(String request)
{
Map<String, String> map = new HashMap<String, String>();
map=strRequest(map, request);
return map;
}
public static Map<String, String> strRequest(Map<String, String> map, String s)
{
int length = s.length();
int index1 = s.indexOf("=");
String parm1 = s.substring(0, index1);
int index2 = s.indexOf("&");
if (index2 == -1)
{
String parm2 = s.substring(index1 + 1);
map.put(parm1, parm2);
// return null;
return map;
}
String parm2 = s.substring(index1 + 1, index2);
map.put(parm1, parm2);
return strRequest(map, s.substring(index2 + 1));
}
} | UTF-8 | Java | 5,895 | java | FileUtil.java | Java | []
| null | []
| package com.jwk.common.constant;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import com.jwk.common.utils.ServletUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.jwk.common.utils.MessageUtils;
import com.jwk.common.utils.StringUtils;
public class FileUtil {
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
//单文件上传
public static String fileInput(MultipartFile file){
String path= ServletUtils.getHttpServletRequest().getSession().getServletContext().getRealPath("");
String type="upload";
if(file.getContentType().contains("image")){
type+="/image";
}
if(file.getContentType().contains("video")){
type+="/video";
}
File f=new File(path+type);
if(!f.exists()){
f.mkdirs();
}
System.out.println(path+type);
String fileName=file.getOriginalFilename();
String firstname= UUID.randomUUID().toString().replace("-","");
String lastname=fileName.substring(fileName.lastIndexOf("."));
fileName=firstname+lastname;
File target=new File(path+type,fileName);
try {
file.transferTo(target);
} catch (IOException e) {
e.printStackTrace();
}
return "/"+type+"/"+fileName;
}
//文件上传的工具类
public static List<String> uploadAttachment(HttpServletRequest request, String type) throws IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> files = multipartRequest.getFiles(type);
System.out.println("数据长度========>>>>>>>>>>" + files.size());
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1;
// String realPath = MessageUtils.message("file.upload.path", null);
// System.err.println("realpath=====>>>>>" + realPath);
String savePath = request.getSession().getServletContext().getRealPath("/") + "p_image\\" + type + "\\" + year+ "\\" + month + "\\";
// String savePath = "government"+ File.separator + "image"+ File.separator + year+ File.separator + month + File.separator;
System.out.println("保存路径=====>" + savePath);
List<String> fileNames = new ArrayList<String>();
for (MultipartFile multipartFile : files) {
System.out.println("------" + multipartFile.getOriginalFilename());
String fileName = multipartFile.getOriginalFilename();
System.out.println("文件绝对路径名字=====>" + savePath);
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
String custName = "" + System.currentTimeMillis() + "." + prefix;
System.out.println("**custName******"+custName);
if (StringUtils.isNotNull(fileName)) {
File targetFile = new File(savePath, custName);
// fileName = year+"-"+month+"-"+fileName;
if (!targetFile.exists()) {
targetFile.mkdirs();
System.out.println("********"+"保存文件");
multipartFile.transferTo(targetFile);
}
try {
} catch (Exception e) {
e.printStackTrace();
}
fileNames.add(savePath + custName);
}
}
return fileNames;
}
public static String getRequestPayload(HttpServletRequest req) {
StringBuilder sb = new StringBuilder(); String res=null;
try(BufferedReader reader = req.getReader();) {
char[]buff = new char[1024];
int len=0;;
while((len = reader.read(buff)) != -1) {
// String res = new String(buff, 0, len,"UTF-8");
sb.append(buff,0, len);
}
}catch (IOException e) {
e.printStackTrace();
}
try {
res = new String(sb.toString().getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
public static String getRequestPayloadJsonObject(HttpServletRequest request ){
InputStream inputStream=null;
String res=null;
try {
inputStream = request.getInputStream();
byte[] buff = new byte[1024];
int len = -1;
while (-1 != (len = inputStream.read(buff))) {
// 将字节数组转换为字符串,并且设置为“UTF-8”格式编码(不然会出现乱码)
res = new String(buff, 0, len,"UTF-8");
System.out.println("**res***"+res);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
public static Map<String, String> requestUtil(String request)
{
Map<String, String> map = new HashMap<String, String>();
map=strRequest(map, request);
return map;
}
public static Map<String, String> strRequest(Map<String, String> map, String s)
{
int length = s.length();
int index1 = s.indexOf("=");
String parm1 = s.substring(0, index1);
int index2 = s.indexOf("&");
if (index2 == -1)
{
String parm2 = s.substring(index1 + 1);
map.put(parm1, parm2);
// return null;
return map;
}
String parm2 = s.substring(index1 + 1, index2);
map.put(parm1, parm2);
return strRequest(map, s.substring(index2 + 1));
}
} | 5,895 | 0.631396 | 0.624284 | 174 | 32.137932 | 25.898197 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.764368 | false | false | 5 |
0e9c0a27eeb62fe7797cf72e39bd27ed05a08795 | 7,662,221,693,067 | dd55a3e5740526902a7780a54a61bba2944e1410 | /branches/qrcom/util/ejb/connection/AccessDriver.java | 1a01e03bb692f4845a8095f5d3dd4b4980e928d6 | []
| no_license | STLHWLIAU/ROUTINE | https://github.com/STLHWLIAU/ROUTINE | 5fdc3268ab2619e22698054ef1ab49172a37a2f8 | 08a4ce142aab9bbc57bbe97b02d0a18dc6512158 | refs/heads/master | 2018-01-14T23:16:26.392000 | 2016-09-23T09:55:59 | 2016-09-23T09:55:59 | 69,008,491 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package qrcom.util.ejb.connection;
import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import java.lang.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
/*
* V001 18/08/2005 Sin Yee
* - create this file to read Data from condb.ini
* V002 04/01/2011 Keng Wai [Log Ref: SSB001414]
* - added AccessDriver(..), getHRDriver(),
*
*
* */
public class AccessDriver {
String sServerIP="";
String sUsername="";
String sPassword="";
String sBase_URL="";
public AccessDriver(){
getDriver();
}
private void getDriver(){
try
{
String findPath = new File("").getCanonicalPath();
System.out.println("PATH 1 : "+findPath);
iniFile inif= new iniFile(findPath +"/condb.ini");
boolean binif = inif.loadIni();
if (binif==true)
{
Object obj;
String sServer = "";
obj = inif.HashData.get("SERVER");
sServer = (String)obj;
if(sServer==null){
sServer = "";
}
this.setServerIP(sServer);
String sUserName = "";
obj = inif.HashData.get("USERNAME");
sUserName = (String)obj;
if(sUserName==null){
sUserName = "";
}
this.setUsername(sUserName);
String sPassword = "";
obj = inif.HashData.get("PASSWORD");
sPassword = (String)obj;
if(sPassword==null){
sPassword = "";
}
this.setPassword(sPassword);
String sBase_Url = "";
obj = inif.HashData.get("BASE_URL");
sBase_Url = (String)obj;
if(sBase_Url==null){
sBase_Url = "";
}
this.setBase_URL(sBase_Url);
}
} catch(Exception e) {
e.printStackTrace();
System.out.println("Unable to read property file");
return;
}
}
// V002
public AccessDriver(String strHR){
getHRDriver();
}
private void getHRDriver() {
try
{
String findPath = new File("").getCanonicalPath();
//System.out.println("PATH 1 : "+findPath);
iniFile inif= new iniFile(findPath +"/conHRdb.ini");
boolean binif = inif.loadIni();
if (binif==true)
{
Object obj;
String sServer = "";
obj = inif.HashData.get("SERVER");
sServer = (String)obj;
if(sServer==null){
sServer = "";
}
this.setServerIP(sServer);
String sUserName = "";
obj = inif.HashData.get("USERNAME");
sUserName = (String)obj;
if(sUserName==null){
sUserName = "";
}
this.setUsername(sUserName);
String sPassword = "";
obj = inif.HashData.get("PASSWORD");
sPassword = (String)obj;
if(sPassword==null){
sPassword = "";
}
this.setPassword(sPassword);
String sBase_Url = "";
obj = inif.HashData.get("BASE_URL");
sBase_Url = (String)obj;
if(sBase_Url==null){
sBase_Url = "";
}
this.setBase_URL(sBase_Url);
}
} catch(Exception e) {
e.printStackTrace();
System.out.println("Unable to read property file");
return;
}
}
// end V002
public void setServerIP(String ip) {
sServerIP = ip;
}
public String isServerIP() {
return sServerIP;
}
public void setUsername(String username) {
sUsername = username;
}
public String isUsername() {
return sUsername;
}
public void setPassword(String password) {
sPassword = password;
}
public String isPassword() {
return sPassword;
}
public void setBase_URL(String base_url) {
sBase_URL = base_url;
}
public String isBase_URL() {
return sBase_URL;
}
} | UTF-8 | Java | 5,595 | java | AccessDriver.java | Java | [
{
"context": "\r\r\nimport java.net.*;\r\r\n\r\r\n/*\r\r\n * V001 18/08/2005 Sin Yee\r\r\n * - create this file to read Data from co",
"end": 247,
"score": 0.9996492862701416,
"start": 240,
"tag": "NAME",
"value": "Sin Yee"
},
{
"context": "e to read Data from condb.ini\r\r\n * V002 04/01/2011 Keng Wai [Log Ref: SSB001414]\r\r\n * - added AccessDriv",
"end": 334,
"score": 0.9998384714126587,
"start": 326,
"tag": "NAME",
"value": "Keng Wai"
},
{
"context": "d setUsername(String username) {\r\r\n sUsername = username;\r\r\n }\r\r\n\r\r\n public String isUsername() {\r\r\n ",
"end": 5218,
"score": 0.9885818362236023,
"start": 5210,
"tag": "USERNAME",
"value": "username"
},
{
"context": "}\r\r\n\r\r\n public String isUsername() {\r\r\n return sUsername;\r\r\n }\r\r\n public void setPassword(String passwor",
"end": 5284,
"score": 0.6193934679031372,
"start": 5275,
"tag": "USERNAME",
"value": "sUsername"
},
{
"context": "d setPassword(String password) {\r\r\n sPassword = password;\r\r\n }\r\r\n\r\r\n public String isPassword() {\r\r\n ",
"end": 5365,
"score": 0.9658255577087402,
"start": 5357,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package qrcom.util.ejb.connection;
import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import java.lang.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
/*
* V001 18/08/2005 <NAME>
* - create this file to read Data from condb.ini
* V002 04/01/2011 <NAME> [Log Ref: SSB001414]
* - added AccessDriver(..), getHRDriver(),
*
*
* */
public class AccessDriver {
String sServerIP="";
String sUsername="";
String sPassword="";
String sBase_URL="";
public AccessDriver(){
getDriver();
}
private void getDriver(){
try
{
String findPath = new File("").getCanonicalPath();
System.out.println("PATH 1 : "+findPath);
iniFile inif= new iniFile(findPath +"/condb.ini");
boolean binif = inif.loadIni();
if (binif==true)
{
Object obj;
String sServer = "";
obj = inif.HashData.get("SERVER");
sServer = (String)obj;
if(sServer==null){
sServer = "";
}
this.setServerIP(sServer);
String sUserName = "";
obj = inif.HashData.get("USERNAME");
sUserName = (String)obj;
if(sUserName==null){
sUserName = "";
}
this.setUsername(sUserName);
String sPassword = "";
obj = inif.HashData.get("PASSWORD");
sPassword = (String)obj;
if(sPassword==null){
sPassword = "";
}
this.setPassword(sPassword);
String sBase_Url = "";
obj = inif.HashData.get("BASE_URL");
sBase_Url = (String)obj;
if(sBase_Url==null){
sBase_Url = "";
}
this.setBase_URL(sBase_Url);
}
} catch(Exception e) {
e.printStackTrace();
System.out.println("Unable to read property file");
return;
}
}
// V002
public AccessDriver(String strHR){
getHRDriver();
}
private void getHRDriver() {
try
{
String findPath = new File("").getCanonicalPath();
//System.out.println("PATH 1 : "+findPath);
iniFile inif= new iniFile(findPath +"/conHRdb.ini");
boolean binif = inif.loadIni();
if (binif==true)
{
Object obj;
String sServer = "";
obj = inif.HashData.get("SERVER");
sServer = (String)obj;
if(sServer==null){
sServer = "";
}
this.setServerIP(sServer);
String sUserName = "";
obj = inif.HashData.get("USERNAME");
sUserName = (String)obj;
if(sUserName==null){
sUserName = "";
}
this.setUsername(sUserName);
String sPassword = "";
obj = inif.HashData.get("PASSWORD");
sPassword = (String)obj;
if(sPassword==null){
sPassword = "";
}
this.setPassword(sPassword);
String sBase_Url = "";
obj = inif.HashData.get("BASE_URL");
sBase_Url = (String)obj;
if(sBase_Url==null){
sBase_Url = "";
}
this.setBase_URL(sBase_Url);
}
} catch(Exception e) {
e.printStackTrace();
System.out.println("Unable to read property file");
return;
}
}
// end V002
public void setServerIP(String ip) {
sServerIP = ip;
}
public String isServerIP() {
return sServerIP;
}
public void setUsername(String username) {
sUsername = username;
}
public String isUsername() {
return sUsername;
}
public void setPassword(String password) {
sPassword = <PASSWORD>;
}
public String isPassword() {
return sPassword;
}
public void setBase_URL(String base_url) {
sBase_URL = base_url;
}
public String isBase_URL() {
return sBase_URL;
}
} | 5,594 | 0.369258 | 0.362824 | 343 | 14.816326 | 21.319958 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.236152 | false | false | 5 |
4967c0f2f59ff974f193fb897593ffe01f2fd35d | 33,595,234,256,627 | 0c8aa7355abbfe24a9f94ae21eaae3de1b3448d0 | /src/main/java/magician/core/properties/SearchGetter.java | f8e943510d84622edfe2d0984407d9e5a9f0e815 | []
| no_license | yaviworks/magician | https://github.com/yaviworks/magician | da4a18b2307a79dbaaf698f8b14ddee6956bd98b | f51e37b6ffd6c5199e3891132bfa0f5d3ef726ae | refs/heads/master | 2018-11-02T06:33:38.310000 | 2018-09-30T14:47:56 | 2018-09-30T14:47:56 | 144,318,762 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package magician.core.properties;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import magician.api.core.CustomStringProperty;
import magician.api.core.PropertyGetter;
import magician.api.core.StringProperty;
import magician.api.core.Version;
//TODO move to magician.core.properties.getters
public final class SearchGetter implements PropertyGetter {
private String _searchString;
private PropertyGetter _searchProperty;
private Pattern _searchPattern;
public SearchGetter(final PropertyGetter property, final String searchString) {
setSearchProperty(property);
setSearchString(searchString);
}
@Override
public String getPropertyName() {
return "Search " + getSearchPropertyName() + " for: '" + getSearchString() + "'";
}
@Override
public StringProperty getProperty(final Version version) {
final String value = _searchProperty.getProperty(version).getStringValue();
final Matcher matcher = _searchPattern.matcher(value);
// TODO add help/reminder for patterns
// for pattern syntax see:
// http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
if (matcher.find()) {
if (matcher.groupCount() > 0) {
final StringBuilder buf = new StringBuilder();
for (int i = 0; i < matcher.groupCount(); i++) {
if (i > 0) {
buf.append(' ');
}
buf.append(matcher.group(i + 1));
}
return new CustomStringProperty(buf.toString());
}
return new CustomStringProperty(getSearchString());
}
return new CustomStringProperty("<no match>");
}
@Override
public Set<StringProperty> getProperties(final Version version) {
final HashSet<StringProperty> properties = new HashSet<>();
try {
for (final StringProperty p : _searchProperty.getProperties(version)) {
final Matcher matcher = _searchPattern.matcher(p.getStringValue());
// TODO add help/reminder for patterns
// for pattern syntax see:
// http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
while (matcher.find()) {
if (matcher.groupCount() > 0) {
final StringBuilder buf = new StringBuilder();
for (int i = 0; i < matcher.groupCount(); i++) {
if (i > 0) {
buf.append(' ');
}
buf.append(matcher.group(i + 1));
}
properties.add(new CustomStringProperty(buf.toString()));
} else {
properties.add(new CustomStringProperty(getSearchString()));
}
}
}
} catch (final RuntimeException e) {
System.err.println("error getting properties for version: " + version);
e.printStackTrace();
}
if (properties.size() == 0) {
properties.add(new CustomStringProperty(""));
}
return properties;
}
public String getSearchString() {
return _searchString;
}
public String getSearchPropertyName() {
return _searchProperty.getPropertyName();
}
private void setSearchString(final String searchString) {
_searchString = searchString;
_searchPattern = Pattern.compile(_searchString, Pattern.CASE_INSENSITIVE);
}
private void setSearchProperty(final PropertyGetter searchProperty) {
_searchProperty = searchProperty;
}
@Override
public void setUp() {
_searchProperty.setUp();
}
@Override
public void tearDown() {
_searchProperty.tearDown();
}
}
| UTF-8 | Java | 4,125 | java | SearchGetter.java | Java | []
| null | []
| package magician.core.properties;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import magician.api.core.CustomStringProperty;
import magician.api.core.PropertyGetter;
import magician.api.core.StringProperty;
import magician.api.core.Version;
//TODO move to magician.core.properties.getters
public final class SearchGetter implements PropertyGetter {
private String _searchString;
private PropertyGetter _searchProperty;
private Pattern _searchPattern;
public SearchGetter(final PropertyGetter property, final String searchString) {
setSearchProperty(property);
setSearchString(searchString);
}
@Override
public String getPropertyName() {
return "Search " + getSearchPropertyName() + " for: '" + getSearchString() + "'";
}
@Override
public StringProperty getProperty(final Version version) {
final String value = _searchProperty.getProperty(version).getStringValue();
final Matcher matcher = _searchPattern.matcher(value);
// TODO add help/reminder for patterns
// for pattern syntax see:
// http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
if (matcher.find()) {
if (matcher.groupCount() > 0) {
final StringBuilder buf = new StringBuilder();
for (int i = 0; i < matcher.groupCount(); i++) {
if (i > 0) {
buf.append(' ');
}
buf.append(matcher.group(i + 1));
}
return new CustomStringProperty(buf.toString());
}
return new CustomStringProperty(getSearchString());
}
return new CustomStringProperty("<no match>");
}
@Override
public Set<StringProperty> getProperties(final Version version) {
final HashSet<StringProperty> properties = new HashSet<>();
try {
for (final StringProperty p : _searchProperty.getProperties(version)) {
final Matcher matcher = _searchPattern.matcher(p.getStringValue());
// TODO add help/reminder for patterns
// for pattern syntax see:
// http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
while (matcher.find()) {
if (matcher.groupCount() > 0) {
final StringBuilder buf = new StringBuilder();
for (int i = 0; i < matcher.groupCount(); i++) {
if (i > 0) {
buf.append(' ');
}
buf.append(matcher.group(i + 1));
}
properties.add(new CustomStringProperty(buf.toString()));
} else {
properties.add(new CustomStringProperty(getSearchString()));
}
}
}
} catch (final RuntimeException e) {
System.err.println("error getting properties for version: " + version);
e.printStackTrace();
}
if (properties.size() == 0) {
properties.add(new CustomStringProperty(""));
}
return properties;
}
public String getSearchString() {
return _searchString;
}
public String getSearchPropertyName() {
return _searchProperty.getPropertyName();
}
private void setSearchString(final String searchString) {
_searchString = searchString;
_searchPattern = Pattern.compile(_searchString, Pattern.CASE_INSENSITIVE);
}
private void setSearchProperty(final PropertyGetter searchProperty) {
_searchProperty = searchProperty;
}
@Override
public void setUp() {
_searchProperty.setUp();
}
@Override
public void tearDown() {
_searchProperty.tearDown();
}
}
| 4,125 | 0.561212 | 0.557091 | 116 | 33.560345 | 26.291237 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405172 | false | false | 5 |
47ea3f56c421bb5dfa9ccd1d27da424861d50d0f | 26,998,164,480,259 | 1179fb110ded33268567c0157c81600f64e4b15a | /13/ElasticsearchProductSearch/src/main/java/com/example/demo/repository/ProductRepository.java | 25e525b38be7a322ecf9103395ed399c26c314e4 | [
"Apache-2.0"
]
| permissive | Rockhorse/Spring-Boot-Book | https://github.com/Rockhorse/Spring-Boot-Book | c4a0f75e23048d568b6541b7a4ef500e63aaa190 | 30c790501e8ebb7acf3a1620df392fdaac7903f8 | refs/heads/master | 2022-03-30T20:32:14.263000 | 2020-01-13T05:21:37 | 2020-01-13T05:21:37 | 269,574,100 | 0 | 2 | Apache-2.0 | true | 2020-06-05T08:31:59 | 2020-06-05T08:31:58 | 2020-01-17T07:16:47 | 2020-01-17T07:15:12 | 322 | 0 | 0 | 0 | null | false | false | package com.example.demo.repository;
import com.example.demo.entity.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
import java.util.List;
/**
Elasticsearch案例
*/
@Component
public interface ProductRepository extends ElasticsearchRepository<Product,Long> {
Product findById(long id);
Product findByName(String name);
List<Product> findByPriceBetween(double price1, double price2);
} | UTF-8 | Java | 495 | java | ProductRepository.java | Java | []
| null | []
| package com.example.demo.repository;
import com.example.demo.entity.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
import java.util.List;
/**
Elasticsearch案例
*/
@Component
public interface ProductRepository extends ElasticsearchRepository<Product,Long> {
Product findById(long id);
Product findByName(String name);
List<Product> findByPriceBetween(double price1, double price2);
} | 495 | 0.808554 | 0.804481 | 18 | 26.333334 | 27.353651 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 5 |
28943bb6f36511196fbb2509c6dddfccb6315ba0 | 5,162,550,699,729 | eae25e981aa8a3c0029249b6ce980fed0333b212 | /lab2/src/test/java/System/TestWithoutAll.java | dffc7763b006e3a0a51f4a71b1bf86f766c5d248 | []
| no_license | nestdimmy/testpo | https://github.com/nestdimmy/testpo | d292717b5c74dce4a6c422c25b574d5276fd8479 | 00949febafb9826b64ec0c68930520c0dc9a13c1 | refs/heads/master | 2021-01-22T08:33:56.125000 | 2017-05-27T21:28:52 | 2017-05-27T21:28:52 | 92,623,755 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package System;
import Function.FirstStatement;
import Function.Main;
import Function.SecondStatement;
import Logarifm.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import static Function.MathUtil.d;
import static Function.MathUtil.delta;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Created by di452 on 22.05.2017.
*/
@RunWith(Parameterized.class)
public class TestWithoutAll {
private double input;
private double expected;
private FirstStatement firstStatement;
private SecondStatement secondStatement;
private Main main;
public TestWithoutAll(double input, double expected) {
this.input = input;
this.expected = expected;
}
@Parameterized.Parameters
public static Collection<Object[]> input_data() {
return Arrays.asList(new Object[][]{
{0,Double.NaN},
{-3*Math.PI/4, -1.89},
{-7*Math.PI/4, 5.88},
{-4*Math.PI/3, -0.13},
{-Math.PI/5, 0.50997}
});
}
@Before
public void initTest () {
firstStatement = mock(FirstStatement.class);
secondStatement = new SecondStatement(new Ln(),new Log2(), new Log3(), new Log5(), new Log10());
main = new Main(firstStatement, secondStatement);
when(firstStatement.calculate(0.0 - d)).thenReturn(0.98);
when(firstStatement.calculate(0.0)).thenReturn(Double.NaN);
when(firstStatement.calculate(-3*Math.PI/4)).thenReturn(-1.89011);
when(firstStatement.calculate(-7*Math.PI/4)).thenReturn(5.88829);
when(firstStatement.calculate(-4*Math.PI/3)).thenReturn(-0.12772);
when(firstStatement.calculate(-Math.PI/5)).thenReturn(0.50997);
}
@Test
public void test () throws Exception {
double result = main.calculate(input);
if (Double.isNaN(expected) || Double.isInfinite(expected)) {
Assert.assertTrue(Double.isInfinite(result) || Double.isNaN(result));
} else {
Assert.assertEquals(expected, result, delta);
}
}
}
| UTF-8 | Java | 2,263 | java | TestWithoutAll.java | Java | [
{
"context": "tatic org.mockito.Mockito.when;\n\n/**\n * Created by di452 on 22.05.2017.\n */\n@RunWith(Parameterized.class)\n",
"end": 503,
"score": 0.9995861649513245,
"start": 498,
"tag": "USERNAME",
"value": "di452"
}
]
| null | []
| package System;
import Function.FirstStatement;
import Function.Main;
import Function.SecondStatement;
import Logarifm.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import static Function.MathUtil.d;
import static Function.MathUtil.delta;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Created by di452 on 22.05.2017.
*/
@RunWith(Parameterized.class)
public class TestWithoutAll {
private double input;
private double expected;
private FirstStatement firstStatement;
private SecondStatement secondStatement;
private Main main;
public TestWithoutAll(double input, double expected) {
this.input = input;
this.expected = expected;
}
@Parameterized.Parameters
public static Collection<Object[]> input_data() {
return Arrays.asList(new Object[][]{
{0,Double.NaN},
{-3*Math.PI/4, -1.89},
{-7*Math.PI/4, 5.88},
{-4*Math.PI/3, -0.13},
{-Math.PI/5, 0.50997}
});
}
@Before
public void initTest () {
firstStatement = mock(FirstStatement.class);
secondStatement = new SecondStatement(new Ln(),new Log2(), new Log3(), new Log5(), new Log10());
main = new Main(firstStatement, secondStatement);
when(firstStatement.calculate(0.0 - d)).thenReturn(0.98);
when(firstStatement.calculate(0.0)).thenReturn(Double.NaN);
when(firstStatement.calculate(-3*Math.PI/4)).thenReturn(-1.89011);
when(firstStatement.calculate(-7*Math.PI/4)).thenReturn(5.88829);
when(firstStatement.calculate(-4*Math.PI/3)).thenReturn(-0.12772);
when(firstStatement.calculate(-Math.PI/5)).thenReturn(0.50997);
}
@Test
public void test () throws Exception {
double result = main.calculate(input);
if (Double.isNaN(expected) || Double.isInfinite(expected)) {
Assert.assertTrue(Double.isInfinite(result) || Double.isNaN(result));
} else {
Assert.assertEquals(expected, result, delta);
}
}
}
| 2,263 | 0.654441 | 0.620415 | 80 | 27.2875 | 24.303392 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7125 | false | false | 5 |
031d133235fc5bb1b3d8b75694a39b3866cc2e04 | 20,633,022,904,306 | 314769267781a2648027d74001b789e81ffda843 | /modules/java/server/service-websockets/src/main/java/org/geogig/server/websockets/WebSocketsPushEventsService.java | 7e933f530ee907167088d1203ba46b23767395d5 | []
| no_license | ngageoint/geogig-web | https://github.com/ngageoint/geogig-web | 46299479666a73f5de321d03bb6a794ffb1b55d5 | c8d07fd37013474460073acd899b1f83245c0d3c | refs/heads/master | 2022-10-22T09:05:56.718000 | 2019-06-19T16:42:18 | 2019-06-19T16:42:18 | 192,582,240 | 3 | 2 | null | false | 2022-10-04T23:53:01 | 2019-06-18T17:10:08 | 2022-05-27T07:51:17 | 2022-10-04T23:52:59 | 482 | 1 | 2 | 3 | Java | false | false | package org.geogig.server.websockets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import org.geogig.server.model.RepoInfo;
import org.geogig.server.model.User;
import org.geogig.server.service.repositories.RepositoryManagementService;
import org.geogig.server.service.user.UserService;
import org.geogig.web.model.ForkEvent;
import org.geogig.web.model.PullRequestInfo;
import org.geogig.web.model.RepositoryInfo;
import org.geogig.web.model.ServerEvent;
import org.geogig.web.model.ServerEvent.EventTypeEnum;
import org.geogig.web.model.TransactionInfo;
import org.geogig.web.model.UserConnectionEvent;
import org.geogig.web.model.events.EventTopics;
import org.geogig.web.model.events.EventTopics.Topic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import lombok.NonNull;
public @Service class WebSocketsPushEventsService extends AbstractPushEventService {
private @Autowired RepositoryManagementService repos;
private @Autowired UserService users;
private ConcurrentMap<String, UserConnectionEvent> sessions = new ConcurrentHashMap<>();
final @VisibleForTesting void reset() {
sessions.clear();
}
public List<UserConnectionEvent> getSessions() {
List<UserConnectionEvent> list = new ArrayList<>(sessions.values());
return list;
}
public Set<String> getLoggedInAdmins() {
return sessions.values().stream().filter(e -> e.getSubject().isSiteAdmin())
.map(e -> e.getSubject().getIdentity()).collect(Collectors.toSet());
}
protected void sendToAdminsAnd(@NonNull Topic topic, @NonNull ServerEvent event,
Set<String> users) {
Set<String> to = getLoggedInAdmins();
to.addAll(users);
super.sendToUsers(topic, event, to);
}
protected void sendToAdminsAnd(@NonNull Topic topic, @NonNull ServerEvent event,
String... users) {
Set<String> to = getLoggedInAdmins();
if (users != null && users.length > 0) {
to.addAll(Sets.newHashSet(users).stream().filter(s -> !Strings.isNullOrEmpty(s))
.collect(Collectors.toList()));
}
super.sendToUsers(topic, event, to);
}
public @EventListener void pushUserConnectionEvent(
@NonNull org.geogig.web.model.UserConnectionEvent event) {
String sessionId = event.getSessionId();
Preconditions.checkNotNull(sessionId);
if (event.isConnected()) {
sessions.put(sessionId, event);
send(EventTopics.USER_CONNECTED, event);
} else {
sessions.remove(sessionId);
send(EventTopics.USER_DISCONNECTED, event);
}
}
public @EventListener void pushStoreEvent(org.geogig.web.model.StoreEvent event) {
super.sendToUsers(EventTopics.STORE_EVENTS, event, getLoggedInAdmins());
}
public @EventListener void pushUserEvent(org.geogig.web.model.UserEvent event) {
EventTypeEnum eventType = event.getEventType();
String caller = event.getCaller() == null ? null : event.getCaller().getIdentity();
String self = eventType == EventTypeEnum.MODIFIED ? event.getSubject().getIdentity() : null;
sendToAdminsAnd(EventTopics.USER_EVENTS, event, caller, self);
}
public @EventListener void pushTransactionEvent(org.geogig.web.model.TransactionEvent event) {
TransactionInfo txInfo = event.getSubject();
String caller = event.getCaller() == null ? null : event.getCaller().getIdentity();
String createdBy = txInfo.getCreatedBy().getIdentity();
String repoOwner = txInfo.getRepository().getOwner().getIdentity();
if (caller != null) {
super.sendToUser(caller, EventTopics.TRANSACTION_EVENTS, event);
}
if (createdBy != null && !createdBy.equals(caller)) {
super.sendToUser(createdBy, EventTopics.TRANSACTION_EVENTS, event);
}
if (repoOwner != null && !(repoOwner.equals(createdBy) || repoOwner.equals(caller))) {
super.sendToUser(repoOwner, EventTopics.TRANSACTION_EVENTS, event);
}
}
/**
* Depending on the event type, notifies the following users:
* <ul>
* <li>CREATED: admins, owner, caller, and forked from owner if it's a {@link ForkEvent}
* <li>UPDATED: admins, owner, caller, and forks owners
* <li>DELETED: admins, owner, caller, and forks owners
* </ul>
*/
public @EventListener void pushRepositoryEvent(org.geogig.web.model.RepositoryEvent event) {
RepositoryInfo repositoryInfo = event.getSubject();
final String caller = event.getCaller() == null ? null : event.getCaller().getIdentity();
final String owner = repositoryInfo.getOwner().getIdentity();
Set<String> notify = Sets.newHashSet(caller, owner);
if (event instanceof ForkEvent) {
RepositoryInfo forkedFrom = repositoryInfo.getForkedFrom();
String parentOwner = forkedFrom.getOwner().getIdentity();
notify.add(parentOwner);
}
if (event.getEventType() != EventTypeEnum.ADDED) {
Set<RepoInfo> forks = repos.getForksOf(repositoryInfo.getId(), false);
for (RepoInfo f : forks) {
UUID ownerId = f.getOwnerId();
Optional<User> forkOwner = users.get(ownerId);
if (forkOwner.isPresent()) {
notify.add(forkOwner.get().getIdentity());
}
}
}
sendToAdminsAnd(EventTopics.REPO_EVENTS, event, notify);
}
public @EventListener void pushPullRequestEvent(org.geogig.web.model.PullRequestEvent event) {
PullRequestInfo pr = event.getSubject();
String owner = pr.getTargetRepo().getOwner().getIdentity();
String issuer = pr.getSourceRepo().getOwner().getIdentity();
sendToAdminsAnd(EventTopics.PR_EVENTS, event, owner, issuer);
}
}
| UTF-8 | Java | 6,417 | java | WebSocketsPushEventsService.java | Java | []
| null | []
| package org.geogig.server.websockets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import org.geogig.server.model.RepoInfo;
import org.geogig.server.model.User;
import org.geogig.server.service.repositories.RepositoryManagementService;
import org.geogig.server.service.user.UserService;
import org.geogig.web.model.ForkEvent;
import org.geogig.web.model.PullRequestInfo;
import org.geogig.web.model.RepositoryInfo;
import org.geogig.web.model.ServerEvent;
import org.geogig.web.model.ServerEvent.EventTypeEnum;
import org.geogig.web.model.TransactionInfo;
import org.geogig.web.model.UserConnectionEvent;
import org.geogig.web.model.events.EventTopics;
import org.geogig.web.model.events.EventTopics.Topic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import lombok.NonNull;
public @Service class WebSocketsPushEventsService extends AbstractPushEventService {
private @Autowired RepositoryManagementService repos;
private @Autowired UserService users;
private ConcurrentMap<String, UserConnectionEvent> sessions = new ConcurrentHashMap<>();
final @VisibleForTesting void reset() {
sessions.clear();
}
public List<UserConnectionEvent> getSessions() {
List<UserConnectionEvent> list = new ArrayList<>(sessions.values());
return list;
}
public Set<String> getLoggedInAdmins() {
return sessions.values().stream().filter(e -> e.getSubject().isSiteAdmin())
.map(e -> e.getSubject().getIdentity()).collect(Collectors.toSet());
}
protected void sendToAdminsAnd(@NonNull Topic topic, @NonNull ServerEvent event,
Set<String> users) {
Set<String> to = getLoggedInAdmins();
to.addAll(users);
super.sendToUsers(topic, event, to);
}
protected void sendToAdminsAnd(@NonNull Topic topic, @NonNull ServerEvent event,
String... users) {
Set<String> to = getLoggedInAdmins();
if (users != null && users.length > 0) {
to.addAll(Sets.newHashSet(users).stream().filter(s -> !Strings.isNullOrEmpty(s))
.collect(Collectors.toList()));
}
super.sendToUsers(topic, event, to);
}
public @EventListener void pushUserConnectionEvent(
@NonNull org.geogig.web.model.UserConnectionEvent event) {
String sessionId = event.getSessionId();
Preconditions.checkNotNull(sessionId);
if (event.isConnected()) {
sessions.put(sessionId, event);
send(EventTopics.USER_CONNECTED, event);
} else {
sessions.remove(sessionId);
send(EventTopics.USER_DISCONNECTED, event);
}
}
public @EventListener void pushStoreEvent(org.geogig.web.model.StoreEvent event) {
super.sendToUsers(EventTopics.STORE_EVENTS, event, getLoggedInAdmins());
}
public @EventListener void pushUserEvent(org.geogig.web.model.UserEvent event) {
EventTypeEnum eventType = event.getEventType();
String caller = event.getCaller() == null ? null : event.getCaller().getIdentity();
String self = eventType == EventTypeEnum.MODIFIED ? event.getSubject().getIdentity() : null;
sendToAdminsAnd(EventTopics.USER_EVENTS, event, caller, self);
}
public @EventListener void pushTransactionEvent(org.geogig.web.model.TransactionEvent event) {
TransactionInfo txInfo = event.getSubject();
String caller = event.getCaller() == null ? null : event.getCaller().getIdentity();
String createdBy = txInfo.getCreatedBy().getIdentity();
String repoOwner = txInfo.getRepository().getOwner().getIdentity();
if (caller != null) {
super.sendToUser(caller, EventTopics.TRANSACTION_EVENTS, event);
}
if (createdBy != null && !createdBy.equals(caller)) {
super.sendToUser(createdBy, EventTopics.TRANSACTION_EVENTS, event);
}
if (repoOwner != null && !(repoOwner.equals(createdBy) || repoOwner.equals(caller))) {
super.sendToUser(repoOwner, EventTopics.TRANSACTION_EVENTS, event);
}
}
/**
* Depending on the event type, notifies the following users:
* <ul>
* <li>CREATED: admins, owner, caller, and forked from owner if it's a {@link ForkEvent}
* <li>UPDATED: admins, owner, caller, and forks owners
* <li>DELETED: admins, owner, caller, and forks owners
* </ul>
*/
public @EventListener void pushRepositoryEvent(org.geogig.web.model.RepositoryEvent event) {
RepositoryInfo repositoryInfo = event.getSubject();
final String caller = event.getCaller() == null ? null : event.getCaller().getIdentity();
final String owner = repositoryInfo.getOwner().getIdentity();
Set<String> notify = Sets.newHashSet(caller, owner);
if (event instanceof ForkEvent) {
RepositoryInfo forkedFrom = repositoryInfo.getForkedFrom();
String parentOwner = forkedFrom.getOwner().getIdentity();
notify.add(parentOwner);
}
if (event.getEventType() != EventTypeEnum.ADDED) {
Set<RepoInfo> forks = repos.getForksOf(repositoryInfo.getId(), false);
for (RepoInfo f : forks) {
UUID ownerId = f.getOwnerId();
Optional<User> forkOwner = users.get(ownerId);
if (forkOwner.isPresent()) {
notify.add(forkOwner.get().getIdentity());
}
}
}
sendToAdminsAnd(EventTopics.REPO_EVENTS, event, notify);
}
public @EventListener void pushPullRequestEvent(org.geogig.web.model.PullRequestEvent event) {
PullRequestInfo pr = event.getSubject();
String owner = pr.getTargetRepo().getOwner().getIdentity();
String issuer = pr.getSourceRepo().getOwner().getIdentity();
sendToAdminsAnd(EventTopics.PR_EVENTS, event, owner, issuer);
}
}
| 6,417 | 0.682562 | 0.682406 | 157 | 39.872612 | 30.072042 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.757962 | false | false | 5 |
29be442be359a69370d7e08590da37598e2dc30c | 8,169,027,802,767 | d04a3f2c650aa6b71be4999f49dabeeac471b5f5 | /app/src/main/java/com/treycc/cocaread/function/rxutils/CommenConsumer.java | 27a0994923ce5bb5ffabbf5e11d91fc775c2d6ca | []
| no_license | treycc/CocaRead | https://github.com/treycc/CocaRead | 74c2c677962d76af08063eb1d393b39fce8ed9e7 | 944899398e3bd05610e56aed4c7eb8b118b40114 | refs/heads/master | 2020-04-02T02:49:30.324000 | 2018-11-10T12:09:14 | 2018-11-10T12:09:14 | 153,930,127 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.treycc.cocaread.function.rxutils;
import com.treycc.commensdk.utils.ToastUtils;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
/**
* Created by treycc on 2017/4/9.
*/
public class CommenConsumer implements Consumer<Throwable> {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
throwable.printStackTrace();
ToastUtils.debugShow(throwable.toString());
doAfterThrowable();
}
public void doAfterThrowable() {
}
}
| UTF-8 | Java | 536 | java | CommenConsumer.java | Java | [
{
"context": "o.reactivex.functions.Consumer;\n\n/**\n * Created by treycc on 2017/4/9.\n */\n\npublic class CommenConsumer imp",
"end": 200,
"score": 0.9996263384819031,
"start": 194,
"tag": "USERNAME",
"value": "treycc"
}
]
| null | []
| package com.treycc.cocaread.function.rxutils;
import com.treycc.commensdk.utils.ToastUtils;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
/**
* Created by treycc on 2017/4/9.
*/
public class CommenConsumer implements Consumer<Throwable> {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
throwable.printStackTrace();
ToastUtils.debugShow(throwable.toString());
doAfterThrowable();
}
public void doAfterThrowable() {
}
}
| 536 | 0.723881 | 0.712687 | 23 | 22.304348 | 22.475948 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false | 5 |
970bf6cbd3c99b7677b16a29d67fcece92b1f52c | 15,307,263,446,691 | 4360f67db067ceff6035a3b300976ec78bb23391 | /wemirr-platform-framework/websocket-framework-starter/src/main/java/com/wemirr/framework/websocket/WebSocketConnectEvent.java | 70ad2d6a3838d12705c0a3a6f34d9ae59178d2b4 | [
"Apache-2.0"
]
| permissive | yang755994/wemirr-platform | https://github.com/yang755994/wemirr-platform | b4b815d8949f9df364b04dfe1008eabea6076196 | a43e27e250525fb5e27d8005bbd4df43165fde25 | refs/heads/master | 2023-07-17T14:46:22.656000 | 2021-07-14T05:31:05 | 2021-07-14T05:31:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wemirr.framework.websocket;
import org.springframework.context.ApplicationEvent;
/**
* @author Levin
*/
public class WebSocketConnectEvent extends ApplicationEvent {
public WebSocketConnectEvent(WebSocket webSocket) {
super(webSocket);
}
}
| UTF-8 | Java | 272 | java | WebSocketConnectEvent.java | Java | [
{
"context": "ramework.context.ApplicationEvent;\n\n/**\n * @author Levin\n */\npublic class WebSocketConnectEvent extends Ap",
"end": 115,
"score": 0.999701738357544,
"start": 110,
"tag": "NAME",
"value": "Levin"
}
]
| null | []
| package com.wemirr.framework.websocket;
import org.springframework.context.ApplicationEvent;
/**
* @author Levin
*/
public class WebSocketConnectEvent extends ApplicationEvent {
public WebSocketConnectEvent(WebSocket webSocket) {
super(webSocket);
}
}
| 272 | 0.757353 | 0.757353 | 12 | 21.666666 | 22.844887 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.