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
2883df9e39750085a473c1334a5d6e126542bb01
30,451,318,176,561
1cb57d5871ad63acedc1d0ff654244d032d7bdce
/src/main/java/com/sudoplay/axion/registry/AxionTagRegistrationException.java
770a7061385e3c81031e1f0945ae0ee6e3aa7fa2
[ "Apache-2.0" ]
permissive
SudoPlayGames/Axion
https://github.com/SudoPlayGames/Axion
4e891d208ddfcf5c96fda6e38fe1bb4240bb56f6
298fe4b2753e0ee03457c083eaeb6804fc7950a9
refs/heads/master
2021-01-21T14:04:36.398000
2017-08-14T19:37:48
2017-08-14T19:37:48
20,071,176
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sudoplay.axion.registry; public class AxionTagRegistrationException extends RuntimeException { private static final long serialVersionUID = 6575639902716176697L; public AxionTagRegistrationException() { super(); } public AxionTagRegistrationException(String message) { super(message); } public AxionTagRegistrationException(Throwable cause) { super(cause); } public AxionTagRegistrationException(String message, Throwable cause) { super(message, cause); } }
UTF-8
Java
511
java
AxionTagRegistrationException.java
Java
[]
null
[]
package com.sudoplay.axion.registry; public class AxionTagRegistrationException extends RuntimeException { private static final long serialVersionUID = 6575639902716176697L; public AxionTagRegistrationException() { super(); } public AxionTagRegistrationException(String message) { super(message); } public AxionTagRegistrationException(Throwable cause) { super(cause); } public AxionTagRegistrationException(String message, Throwable cause) { super(message, cause); } }
511
0.763209
0.726027
23
21.217392
25.801847
73
false
false
0
0
0
0
0
0
0.347826
false
false
10
650688813a38ade5656d6a289c3c6e91a063aefd
35,261,681,506,094
2beb2ec5be374d0bd748ad8ca599abef6017ea38
/simple-helloworld/src/main/java/demo/SimpleHelloworldApp.java
0b76418ef0351ee599e44d5f8722c4127a302896
[]
no_license
pgovindraj/spring-boot2-training
https://github.com/pgovindraj/spring-boot2-training
c9d9895aa81a1cf83ae0bbc758d8d92b1805d92f
78c84c23a0e10e108d6d0225273b9c4364afc717
refs/heads/master
2020-07-19T15:51:24.614000
2018-10-02T06:41:10
2018-10-02T06:41:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.time.Instant; @SpringBootApplication public class SimpleHelloworldApp { public static void main(String[] args) { SpringApplication.run(SimpleHelloworldApp.class, args); } } @RestController class GreetingController { @GetMapping("/") String greet(@RequestParam(defaultValue = "World") String name) { return String.format("Hello %s @ %s", name, Instant.now()); } }
UTF-8
Java
733
java
SimpleHelloworldApp.java
Java
[]
null
[]
package demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.time.Instant; @SpringBootApplication public class SimpleHelloworldApp { public static void main(String[] args) { SpringApplication.run(SimpleHelloworldApp.class, args); } } @RestController class GreetingController { @GetMapping("/") String greet(@RequestParam(defaultValue = "World") String name) { return String.format("Hello %s @ %s", name, Instant.now()); } }
733
0.768076
0.768076
26
27.23077
26.013765
69
false
false
0
0
0
0
0
0
0.461538
false
false
10
bb6e0f2928391449edc07ae451efb950461ab28c
21,431,886,838,870
57e12a6698400ced0ec72072c437519657beb32c
/src/com/mentor/action/GatepassToDistrict_FL2_FL2B_oldStockAction.java
91d4ff2e539810b48ace5abfea52f960c3bd6ca8
[]
no_license
prasoon-web/BWFL
https://github.com/prasoon-web/BWFL
f9dba29894ae94b3275547c3f91535716c1b9d1c
fe016dfccdda8c446603a62aeba30372cd3dd577
refs/heads/master
2023-01-25T01:05:20.447000
2020-11-19T13:54:12
2020-11-19T13:54:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mentor.action; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.faces.application.FacesMessage; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.event.ValueChangeEvent; import javax.servlet.ServletContext; import org.richfaces.component.UIDataTable; import org.richfaces.event.UploadEvent; import org.richfaces.model.UploadItem; import com.mentor.datatable.GatepassToDistrict_FL2_FL2B_oldStockDT; import com.mentor.impl.GatepassToDistrict_FL2_FL2B_oldStockImpl; import com.mentor.utility.Validate; public class GatepassToDistrict_FL2_FL2B_oldStockAction { GatepassToDistrict_FL2_FL2B_oldStockImpl impl = new GatepassToDistrict_FL2_FL2B_oldStockImpl(); private boolean disable_flag; public boolean isDisable_flag() { return disable_flag; } public void setDisable_flag(boolean disable_flag) { this.disable_flag = disable_flag; } private String draftpdfname; private String DraftPdfname; public String getDraftpdfname() { return draftpdfname; } public void setDraftpdfname(String draftpdfname) { this.draftpdfname = draftpdfname; } private String fl2_fl2bName; private String fl2_fl2bAdrs; private String hidden; private int fl2_fl2bId; public Date dt_date = new Date(); public Date validtilldt_date; public String vch_to; private int districtLic; public String vch_to_lic_no; private String licenseeName; private String licenseeAdrs; private int licenseeId; private String vehicleDrvrName; private String vehicleAgencyNmAdrs; private int district1; private int district2; private int district3; private String routeDtl; private String vehicleNo; private double grossWeight = 0; private double tierWeight = 0; private double netWeight = 0; private ArrayList districtList = new ArrayList(); private ArrayList displaylist = new ArrayList(); private String officrEmail; public String vch_from; private String fl2LicenseType; private ArrayList licNmbrList = new ArrayList(); private String brc_to_lic; private boolean drpdwnFlg; private boolean drpdwnFlg1; private ArrayList brclicNmbrList = new ArrayList(); public Date table_dt = new Date(); private String challan_no; private Date challan_dt; private String challan_amt; public String vch_to_lic_noNew; public String getVch_to_lic_noNew() { return vch_to_lic_noNew; } public void setVch_to_lic_noNew(String vch_to_lic_noNew) { this.vch_to_lic_noNew = vch_to_lic_noNew; } public String getChallan_no() { return challan_no; } public void setChallan_no(String challan_no) { this.challan_no = challan_no; } public Date getChallan_dt() { return challan_dt; } public void setChallan_dt(Date challan_dt) { this.challan_dt = challan_dt; } public String getChallan_amt() { return challan_amt; } public void setChallan_amt(String challan_amt) { this.challan_amt = challan_amt; } public Date getTable_dt() { return table_dt; } public void setTable_dt(Date table_dt) { this.table_dt = table_dt; } public String getFl2_fl2bName() { return fl2_fl2bName; } public void setFl2_fl2bName(String fl2_fl2bName) { this.fl2_fl2bName = fl2_fl2bName; } public String getFl2_fl2bAdrs() { return fl2_fl2bAdrs; } public void setFl2_fl2bAdrs(String fl2_fl2bAdrs) { this.fl2_fl2bAdrs = fl2_fl2bAdrs; } public String getHidden() { try { impl.getDetails(this); if (this.fl2LicenseType.equalsIgnoreCase("CL2")) { this.brcFlag = false; this.rtFlag = true; } else { this.brcFlag = true; this.rtFlag = false; } // impl.getEmailDetails(this); if (this.brc_to_lic != null) { // impl.getlicenseeDetail(this, this.brc_to_lic); } if (this.vch_to_lic_no != null) { // impl.getretailLicenseeDetail(this, this.vch_to_lic_no); } } catch (Exception e) { e.printStackTrace(); } return hidden; } public void setHidden(String hidden) { this.hidden = hidden; } public int getFl2_fl2bId() { return fl2_fl2bId; } public void setFl2_fl2bId(int fl2_fl2bId) { this.fl2_fl2bId = fl2_fl2bId; } public Date getDt_date() { return dt_date; } public void setDt_date(Date dt_date) { this.dt_date = dt_date; } public Date getValidtilldt_date() { return validtilldt_date; } public void setValidtilldt_date(Date validtilldt_date) { this.validtilldt_date = validtilldt_date; } public String getVch_to() { return vch_to; } public void setVch_to(String vch_to) { this.vch_to = vch_to; } public int getDistrictLic() { return districtLic; } public void setDistrictLic(int districtLic) { this.districtLic = districtLic; } public String getVch_to_lic_no() { return vch_to_lic_no; } public void setVch_to_lic_no(String vch_to_lic_no) { this.vch_to_lic_no = vch_to_lic_no; } public String getLicenseeName() { return licenseeName; } public void setLicenseeName(String licenseeName) { this.licenseeName = licenseeName; } public String getLicenseeAdrs() { return licenseeAdrs; } public void setLicenseeAdrs(String licenseeAdrs) { this.licenseeAdrs = licenseeAdrs; } public int getLicenseeId() { return licenseeId; } public void setLicenseeId(int licenseeId) { this.licenseeId = licenseeId; } public String getVehicleDrvrName() { return vehicleDrvrName; } public void setVehicleDrvrName(String vehicleDrvrName) { this.vehicleDrvrName = vehicleDrvrName; } public String getVehicleAgencyNmAdrs() { return vehicleAgencyNmAdrs; } public void setVehicleAgencyNmAdrs(String vehicleAgencyNmAdrs) { this.vehicleAgencyNmAdrs = vehicleAgencyNmAdrs; } public int getDistrict1() { return district1; } public void setDistrict1(int district1) { this.district1 = district1; } public int getDistrict2() { return district2; } public void setDistrict2(int district2) { this.district2 = district2; } public int getDistrict3() { return district3; } public void setDistrict3(int district3) { this.district3 = district3; } public String getRouteDtl() { return routeDtl; } public void setRouteDtl(String routeDtl) { this.routeDtl = routeDtl; } public String getVehicleNo() { return vehicleNo; } public void setVehicleNo(String vehicleNo) { this.vehicleNo = vehicleNo; } public double getGrossWeight() { return grossWeight; } public void setGrossWeight(double grossWeight) { this.grossWeight = grossWeight; } public double getTierWeight() { return tierWeight; } public void setTierWeight(double tierWeight) { this.tierWeight = tierWeight; } public double getNetWeight() { if (this.grossWeight > 0.0 && this.tierWeight > 0.0) { this.netWeight = this.grossWeight - this.tierWeight; } else { this.netWeight = 0.0; } return netWeight; } public void setNetWeight(double netWeight) { this.netWeight = netWeight; } public ArrayList getDistrictList() { /* * try { this.districtList = impl.getDistrictList(this); } catch * (Exception e) { e.printStackTrace(); } */ return districtList; } public void setDistrictList(ArrayList districtList) { this.districtList = districtList; } public ArrayList getDisplaylist() { if (addrowflg) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = new GatepassToDistrict_FL2_FL2B_oldStockDT(); dt.setSrNo(this.displaylist.size() + 1); this.displaylist.add(dt); addrowflg = false; } return displaylist; } public void setDisplaylist(ArrayList displaylist) { this.displaylist = displaylist; } public String getOfficrEmail() { return officrEmail; } public void setOfficrEmail(String officrEmail) { this.officrEmail = officrEmail; } public String getVch_from() { return vch_from; } public void setVch_from(String vch_from) { this.vch_from = vch_from; } public String getFl2LicenseType() { return fl2LicenseType; } public void setFl2LicenseType(String fl2LicenseType) { this.fl2LicenseType = fl2LicenseType; } public ArrayList getLicNmbrList() { return licNmbrList; } public void setLicNmbrList(ArrayList licNmbrList) { this.licNmbrList = licNmbrList; } public String getBrc_to_lic() { return brc_to_lic; } public void setBrc_to_lic(String brc_to_lic) { this.brc_to_lic = brc_to_lic; } public boolean isDrpdwnFlg() { return drpdwnFlg; } public void setDrpdwnFlg(boolean drpdwnFlg) { this.drpdwnFlg = drpdwnFlg; } public boolean isDrpdwnFlg1() { return drpdwnFlg1; } public void setDrpdwnFlg1(boolean drpdwnFlg1) { this.drpdwnFlg1 = drpdwnFlg1; } public ArrayList getBrclicNmbrList() { return brclicNmbrList; } public void setBrclicNmbrList(ArrayList brclicNmbrList) { this.brclicNmbrList = brclicNmbrList; } public String listMethod(ValueChangeEvent vce) { //this.displaylist = impl.displaylistImpl(this); impl.getDistrictList(this); this.disable_flag = false; this.flagshop = false; this.brc_to_lic = null; this.brclicNmbrList.clear(); this.vch_to_lic_no = null; this.licNmbrList.clear(); this.licenseeName = null; this.licenseeAdrs = null; this.licenseeId = 0; this.licenseeName = null; this.licenseeAdrs = null; this.licenseeId = 0; this.printDraft = true; this.printFlag = false; return ""; } public String listMethod1(ValueChangeEvent vce) { Date ev = (Date) vce.getNewValue(); this.table2List = impl.getTable2List1(this, ev); return ""; } public String drpdownMethod(ValueChangeEvent vce) { String val = (String) vce.getNewValue(); impl.getlicenseeDetail(this, val); return ""; } public String retaildrpMethod(ValueChangeEvent vce) { String val = (String) vce.getNewValue(); impl.getretailLicenseeDetail(this, val); return ""; } public double db_total_value = 0; public double sum = 0; public boolean flag = true; public double db_total_add_value = 0; public double sum_add = 0; public boolean addflag = true; public double getDb_total_value() { double duty = 0.0; try { for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.getDisplaylist().get(i); duty += dt.getCalculated_duty(); db_total_value = duty; } } catch (Exception e) { e.printStackTrace(); } return db_total_value; } public void setDb_total_value(double db_total_value) { this.db_total_value = db_total_value; } public double getSum() { return sum; } public void setSum(double sum) { this.sum = sum; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public double getDb_total_add_value() { double addduty = 0.0; try { for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.getDisplaylist().get(i); addduty += dt.getCalculated_add_duty(); } db_total_add_value = addduty; } catch (Exception e) { e.printStackTrace(); } return db_total_add_value; } public void setDb_total_add_value(double db_total_add_value) { this.db_total_add_value = db_total_add_value; } public double getSum_add() { return sum_add; } public void setSum_add(double sum_add) { this.sum_add = sum_add; } public boolean isAddflag() { return addflag; } public void setAddflag(boolean addflag) { this.addflag = addflag; } public void calculateTotalDuty(ActionEvent ae) { if (isFlag()) { this.setSum(0); for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.displaylist.get(i); this.setSum(this.getSum() + dt.getCalculated_duty()); } } this.flag = false; } public void calculateTotalAddDuty(ActionEvent ae) { if (isAddflag()) { this.setSum_add(0); for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.displaylist.get(i); this.setSum_add(this.getSum_add() + dt.getCalculated_add_duty()); } } this.addflag = false; } private boolean validateInput1; public boolean isValidateInput1() { validateInput1 = true; if (!(Validate.validateDate("validtill", this.getValidtilldt_date()))) validateInput1 = false; else if (!(Validate.validateStrReq("radioto", this.getVch_to()))) validateInput1 = false; else if (!(Validate.validateStrReq("gatepass", this.getGatepassNmbr()))) validateInput1 = false; // /////////////////////////////////// else if (this.vch_to.equalsIgnoreCase("BRC")) { if (!(Validate.validateStrReq("licenseno", this.getVch_to_lic_no()))) validateInput1 = false; else if (!(Validate.validateStrReq("licenseenm", this.getLicenseeName()))) validateInput1 = false; else if (!(Validate.validateStrReq("lic enseeaddress", this.getLicenseeAdrs()))) validateInput1 = false; else if (!(Validate.validateStrReq("routedtl", this.getRouteDtl()))) validateInput1 = false; else if (!(Validate.validateStrReq("vehiclenmbr", this.getVehicleNo()))) validateInput1 = false; else if (!(Validate.validateStrReq("vehicledriver", this.getVehicleDrvrName()))) validateInput1 = false; else if (!(Validate.validateStrReq("agencyNameAddress", this.getVehicleAgencyNmAdrs()))) validateInput1 = false; /*else if (!(Validate.validateDouble("duty", this.getDutyEnterd()))) validateInput1 = false; else if (!(Validate.validateDouble("addDuty",this.getAddDutyEnterd()))) validateInput1 = false;*/ } else if (this.vch_to.equalsIgnoreCase("RT")) { if (!(Validate.validateStrReq("shopno", this.getShopno()))) validateInput1 = false; else if (!(Validate.validateStrReq("shopname", this.getShopName()))) validateInput1 = false; else if (!(Validate.validateStrReq("licenseenm", this.getLicenseeName()))) validateInput1 = false; else if (!(Validate.validateStrReq("licenseeaddress", this.getLicenseeAdrs()))) validateInput1 = false; else if (!(Validate.validateStrReq("routedtl", this.getRouteDtl()))) validateInput1 = false; else if (!(Validate.validateStrReq("vehiclenmbr", this.getVehicleNo()))) validateInput1 = false; else if (!(Validate.validateStrReq("vehicledriver", this.getVehicleDrvrName()))) validateInput1 = false; else if (!(Validate.validateStrReq("agencyNameAddress", this.getVehicleAgencyNmAdrs()))) validateInput1 = false; /*else if (!(Validate.validateDouble("duty", this.getDutyEnterd()))) validateInput1 = false; else if (!(Validate.validateDouble("addDuty",this.getAddDutyEnterd()))) validateInput1 = false;*/ } for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) displaylist.get(i); if (dt.getDispatchbox() > 0 && dt.getDispatchbottls() > 0) { if (dt.getBatchNo() == null || dt.getBatchNo().equals("")) { validateInput1 = false; FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Enter Batch No At Line No !!! "+ (i + 1),"Enter Batch No At Line No !!! "+ (i + 1))); break; } } } int sumBottles = 0; int sumBoxes = 0; for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) displaylist.get(i); sumBottles += dt.getDispatchbottls(); sumBoxes += dt.getDispatchbox(); /*if (dt.getDispatchbottls() > 0) { if ((dt.getDispatchbottls()) > dt.getInt_bottle_avaliable()) { FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Dispatch Bottles Should Not Be More Than Available Bottles at Line "+ (i + 1) + " !!! ", "Dispatch Bottles Should Not Be More Than Available Bottles at Line "+ (i + 1) + " !!!")); validateInput1 = false; } }*/ } if (sumBoxes == 0) { FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Dispatch Boxes Should Be Greater Than Zero !!! ","Dispatch Boxes Should Be Greater Than Zero !!!")); validateInput1 = false; } else if (sumBottles == 0) { FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Dispatch Bottles Should Be Greater Than Zero !!! ","Dispatch Bottles Should Be Greater Than Zero !!!")); validateInput1 = false; } return validateInput1; } public void setValidateInput1(boolean validateInput1) { this.validateInput1 = validateInput1; } public boolean eco_flag; public void saveMethod() { try { if (isValidateInput1()) { if (this.dt_date.after(this.validtilldt_date)) { FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Valid Till Date !!","Invalid Valid Till Date !!")); } else { impl.saveMethodImpl(this); //this.displaylist = impl.displaylistImpl(this); } } } catch (Exception e) { e.printStackTrace(); } } public boolean check_economy(int id) { if (impl.check_economy(id)) return true; return false; } public void clearAll() { this.disable_flag = false; this.flagshop = false; this.shopno = ""; this.shopName = ""; this.fl2_fl2bName = null; this.fl2_fl2bAdrs = null; this.validtilldt_date = null; this.vch_to = ""; this.vch_to_lic_no = ""; this.displaylist.clear(); this.routeDtl = null; this.vehicleNo = null; this.vehicleDrvrName = null; this.vehicleAgencyNmAdrs = null; this.district1 = 0; this.district2 = 0; this.district3 = 0; this.districtLic = 0; this.tierWeight = 0.0; this.netWeight = 0.0; this.grossWeight = 0.0; this.licenseeName = null; this.licenseeAdrs = null; this.licenseeId = 0; this.brc_to_lic = null; this.licNmbrList.clear(); this.brclicNmbrList.clear(); // this.table2List.clear(); dt_date = new Date(); table_dt = new Date(); this.gatepassNmbr = null; this.listFlagForPrint = true; this.addrowflg = true; this.dutyEnterd = 0.0; this.addDutyEnterd = 0.0; } private ArrayList table2List = new ArrayList(); private Date printDate; private String printGatePassNo; private String pdfname; private String pdfDraft; private boolean listFlagForPrint = true; private String scanGatePassNo; private String shopid; private String shoptype; public String getShopid() { return shopid; } public void setShopid(String shopid) { this.shopid = shopid; } public String getShoptype() { return shoptype; } public void setShoptype(String shoptype) { this.shoptype = shoptype; } public String getScanGatePassNo() { return scanGatePassNo; } public void setScanGatePassNo(String scanGatePassNo) { this.scanGatePassNo = scanGatePassNo; } public ArrayList getTable2List() { if (this.listFlagForPrint == true) { this.table2List = impl.getTable2List(this); this.listFlagForPrint = false; } return table2List; } public void setTable2List(ArrayList table2List) { this.table2List = table2List; } public Date getPrintDate() { return printDate; } public void setPrintDate(Date printDate) { this.printDate = printDate; } public String getPrintGatePassNo() { return printGatePassNo; } public void setPrintGatePassNo(String printGatePassNo) { this.printGatePassNo = printGatePassNo; } public String getPdfname() { return pdfname; } public void setPdfname(String pdfname) { this.pdfname = pdfname; } public boolean isListFlagForPrint() { return listFlagForPrint; } public void setListFlagForPrint(boolean listFlagForPrint) { this.listFlagForPrint = listFlagForPrint; } private String pdfname_CaseCode; public String getPdfname_CaseCode() { return pdfname_CaseCode; } public void setPdfname_CaseCode(String pdfname_CaseCode) { this.pdfname_CaseCode = pdfname_CaseCode; } private String vchToPrint; public String getVchToPrint() { return vchToPrint; } public void setVchToPrint(String vchToPrint) { this.vchToPrint = vchToPrint; } public void printReport(ActionEvent e) { UIDataTable uiTable = (UIDataTable) e.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setPrintDate(dt.getCurrentDate()); this.setPrintGatePassNo(dt.getGatepassNo()); this.printFlag = true; this.setVchToPrint(dt.getVchTO()); if (impl.printReport(this, dt) == true) { dt.setPrintFlag(true); } else { dt.setPrintFlag(false); } this.viewReportFlag = true; } public void printDraftReport(ActionEvent e) { UIDataTable uiTable = (UIDataTable) e.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setPrintDate(dt.getCurrentDate()); this.setPrintGatePassNo(dt.getGatepassNo()); // System.out.println("-------- action gate pass ----"+this.getPrintGatePassNo()); if (impl.printDraftReport(this, dt) == true) { dt.setPrintDraftFlagDt(true); } else { dt.setPrintDraftFlagDt(false); } this.printDraftFlag = true; this.scanUploadFlag = true; } private boolean printFlag; private boolean printDraftFlag; private boolean scanUploadFlag; private boolean uploaderFlag; private boolean submitFlag; private boolean cancelFlag; private boolean finalsubmit; private boolean tableFlag; private boolean deleteFlag; private boolean kidnlyUploadFlag; private boolean gatePassFlag; private boolean viewDraftFlag; private boolean viewReportFlag; private int excelCases; private int recieveCases; private boolean printDraft; public boolean isDeleteFlag() { return deleteFlag; } public void setDeleteFlag(boolean deleteFlag) { this.deleteFlag = deleteFlag; } public int getRecieveCases() { return recieveCases; } public void setRecieveCases(int recieveCases) { this.recieveCases = recieveCases; } public boolean isViewDraftFlag() { return viewDraftFlag; } public void setViewDraftFlag(boolean viewDraftFlag) { this.viewDraftFlag = viewDraftFlag; } public boolean isViewReportFlag() { return viewReportFlag; } public void setViewReportFlag(boolean viewReportFlag) { this.viewReportFlag = viewReportFlag; } public boolean isKidnlyUploadFlag() { return kidnlyUploadFlag; } public void setKidnlyUploadFlag(boolean kidnlyUploadFlag) { this.kidnlyUploadFlag = kidnlyUploadFlag; } public boolean isGatePassFlag() { return gatePassFlag; } public void setGatePassFlag(boolean gatePassFlag) { this.gatePassFlag = gatePassFlag; } // ------------------ excel scan and upload ---------------------------- public void scanAndUpload(ActionEvent ae) { UIDataTable uiTable = (UIDataTable) ae.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setScanGatePassNo(dt.getGatepassNo()); this.setShopid(dt.getLicenseNo()); this.setShoptype(dt.getVchTO()); this.submitFlag = true; this.cancelFlag = true; this.uploaderFlag = true; this.tableFlag = true; this.finalsubmit = true; this.kidnlyUploadFlag = true; this.gatePassFlag = true; this.scanUploadFlag = true; // this.getVal = impl.getExcelData(this); // this.scanUploadFlag=true; // this.printDraft=true; } // ------------------- excel submit------------------ public String importExcel() { impl.saveExcelData(this); this.tableFlag = true; this.submitFlag = false; this.cancelFlag = true; this.gatePassFlag = false; this.kidnlyUploadFlag = false; this.scanUploadFlag = true; this.finalsubmit = true; this.uploaderFlag = false; return ""; } // -------------------final submit------------------ public void finalSubmitcl2(ActionEvent ae) { UIDataTable uiTable = (UIDataTable) ae.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setScanGatePassNo(dt.getGatepassNo()); listFlagForPrint = true; } public void finalSubmit() { // impl.recieveCases(this); if (impl.excelCases(this) == impl.recieveCases(this)) { if (impl.updateFL3(this) == true) { this.printFlag = true; this.scanUploadFlag = false; this.submitFlag = false; this.cancelFlag = false; this.finalsubmit = true; this.uploaderFlag = false; this.finalsubmit = false; this.deleteFlag = false; this.tableFlag = false; this.kidnlyUploadFlag = false; this.gatePassFlag = false; this.printFlag = true; listFlagForPrint = true; FacesContext.getCurrentInstance().addMessage( null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Data Save Successfully", "Data Save Successfully")); } else { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("Error Occured while saving !!! ", "Error Occured while saving !!!")); } } else { FacesContext .getCurrentInstance() .addMessage( null, new FacesMessage( "No.of casecodes uploaded by you is not equal to number of cases mentioned in gatepass.", "No.of casecodes uploaded by you is not equal to number of cases mentioned in gatepass.")); } } private String excelFilename; private String excelFilepath; public String getExcelFilename() { return excelFilename; } public void setExcelFilename(String excelFilename) { this.excelFilename = excelFilename; } public String getExcelFilepath() { return excelFilepath; } public void setExcelFilepath(String excelFilepath) { this.excelFilepath = excelFilepath; } // --------------------------------------------delete excel data------------------ public void delete() { impl.deleteData(this); this.tableFlag = false; this.finalsubmit = false; this.cancelFlag = false; this.gatePassFlag = false; this.kidnlyUploadFlag = false; this.uploaderFlag = false; this.submitFlag = false; this.scanUploadFlag = false; listFlagForPrint = true; this.getVal.clear(); } public void uploadExcel(UploadEvent event) { try { int size = 0; int counter = 0; UploadItem item = event.getUploadItem(); String FullfileName = item.getFileName(); String path = item.getFile().getPath(); String fileName = FullfileName.substring(FullfileName .lastIndexOf("\\") + 1); ExternalContext con = FacesContext.getCurrentInstance() .getExternalContext(); ServletContext sCon = (ServletContext) con.getContext(); size = item.getFileSize(); this.excelFilename = FullfileName; this.excelFilepath = path; } catch (Exception ee) { } finally { } } private boolean valFlag; public ArrayList getVal = new ArrayList(); public ArrayList tempList = new ArrayList(); public ArrayList getTempList() { return tempList; } public void setTempList(ArrayList tempList) { this.tempList = tempList; } public ArrayList getGetVal() { return getVal; } public void setGetVal(ArrayList getVal) { this.getVal = getVal; } public boolean isPrintFlag() { return printFlag; } public void setPrintFlag(boolean printFlag) { this.printFlag = printFlag; } public boolean isScanUploadFlag() { return scanUploadFlag; } public void setScanUploadFlag(boolean scanUploadFlag) { this.scanUploadFlag = scanUploadFlag; } public boolean isUploaderFlag() { return uploaderFlag; } public void setUploaderFlag(boolean uploaderFlag) { this.uploaderFlag = uploaderFlag; } public boolean isSubmitFlag() { return submitFlag; } public void setSubmitFlag(boolean submitFlag) { this.submitFlag = submitFlag; } public boolean isCancelFlag() { return cancelFlag; } public void setCancelFlag(boolean cancelFlag) { this.cancelFlag = cancelFlag; } public boolean isFinalsubmit() { return finalsubmit; } public void setFinalsubmit(boolean finalsubmit) { this.finalsubmit = finalsubmit; } public boolean isTableFlag() { return tableFlag; } public void setTableFlag(boolean tableFlag) { this.tableFlag = tableFlag; } public boolean isPrintDraftFlag() { return printDraftFlag; } public void setPrintDraftFlag(boolean printDraftFlag) { this.printDraftFlag = printDraftFlag; } public String getPdfDraft() { return pdfDraft; } public void setPdfDraft(String pdfDraft) { this.pdfDraft = pdfDraft; } public int getExcelCases() { return excelCases; } public void setExcelCases(int excelCases) { this.excelCases = excelCases; } public boolean isValFlag() { return valFlag; } public void setValFlag(boolean valFlag) { this.valFlag = valFlag; } public boolean isPrintDraft() { return printDraft; } public void setPrintDraft(boolean printDraft) { this.printDraft = printDraft; } private String vch_TO_Print = null; public String getVch_TO_Print() { return vch_TO_Print; } public void setVch_TO_Print(String vch_TO_Print) { this.vch_TO_Print = vch_TO_Print; } public void printDraft(ActionEvent e) { this.vch_TO_Print = null; UIDataTable uiTable = (UIDataTable) e.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setPrintDate(dt.getDt_date()); this.setPrintGatePassNo(dt.getGatepassNo()); this.setVch_TO_Print(dt.getVchTO()); if (impl.printDraftReport(this, dt) == true) { dt.setDraftprintFlag(true); } else { dt.setDraftprintFlag(false); } } public String getDraftPdfname() { return DraftPdfname; } public void setDraftPdfname(String draftPdfname) { DraftPdfname = draftPdfname; } // ----------------------------code for cancel // gatepass---------------------- public void cancelGatepass(ActionEvent e) { UIDataTable uiTable = (UIDataTable) e.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setPrintDate(dt.getDt_date()); this.setPrintGatePassNo(dt.getGatepassNo()); impl.cancelGatepassImpl(this); } // ==========================code for csv=================================== private String csvFilename; private String csvFilepath; private String exclcsv = "C"; public String getCsvFilename() { return csvFilename; } public void setCsvFilename(String csvFilename) { this.csvFilename = csvFilename; } public String getCsvFilepath() { return csvFilepath; } public void setCsvFilepath(String csvFilepath) { this.csvFilepath = csvFilepath; } public String getExclcsv() { return exclcsv; } public void setExclcsv(String exclcsv) { this.exclcsv = exclcsv; } public void uploadCsv(UploadEvent event) { try { int size = 0; int counter = 0; UploadItem item = event.getUploadItem(); String FullfileName = item.getFileName(); String path = item.getFile().getPath(); String fileName = FullfileName.substring(FullfileName .lastIndexOf("\\") + 1); ExternalContext con = FacesContext.getCurrentInstance() .getExternalContext(); ServletContext sCon = (ServletContext) con.getContext(); size = item.getFileSize(); this.setCsvFilename(FullfileName); this.setCsvFilepath(path); } catch (Exception ee) { ee.printStackTrace(); System.out.println("exception in upload@"); } finally { } } ArrayList sourceList = new ArrayList<String>(); public ArrayList getSourceList() { return sourceList; } public void setSourceList(ArrayList sourceList) { this.sourceList = sourceList; } public String csvSubmit() throws IOException { /* * if(this.fl2LicenseType.equalsIgnoreCase("FL2")){ * impl.saveCSVfl(this); }else{ */ tempList.clear(); ArrayList matchdata = new ArrayList<>(); impl.saveCSV(this); if (this.getFl2LicenseType().equalsIgnoreCase("CL2")) { this.getVal = impl.getExcelData(this.getScanGatePassNo() .toUpperCase().trim()); } else if (this.getFl2LicenseType().equalsIgnoreCase("FL2")) { this.getVal = impl.getExcelDatafl2(this.getScanGatePassNo() .toUpperCase().trim()); } else if (this.getFl2LicenseType().equalsIgnoreCase("FL2B")) { this.getVal = impl.getExcelDatafl2b(this.getScanGatePassNo() .toUpperCase().trim()); } for (int ik = 0; ik < getVal.size(); ik++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this .getGetVal().get(ik); String casecode = dt.getCasecode().trim(); Date date = dt.getCasecodedt(); SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd"); String datt = sdf.format(date); for (int p = 0; p < this.tempList.size(); p++) { String s = (String) this.tempList.get(p); String dat = s.substring(16, 22).trim(); String caseno = s.substring(26, s.length()).trim(); if (datt.equals(dat) && caseno.equals(casecode)) { this.tempList.remove(this.tempList.get(p)); } } sourceList = tempList; } // } this.scanUploadFlag = true; // this.getVal = impl.getExcelData(this); return ""; } public String shopno; private boolean flagshop; private boolean flaglicense; public String shopName; public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public boolean isFlagshop() { return flagshop; } public void setFlagshop(boolean flagshop) { this.flagshop = flagshop; } public boolean isFlaglicense() { return flaglicense; } public void setFlaglicense(boolean flaglicense) { this.flaglicense = flaglicense; } public String getShopno() { return shopno; } public void setShopno(String shopno) { this.shopno = shopno; } public void fetch() { if (this.shopno.length() > 0 && this.shopno != null && this.shopno != "") { if (this.shopno.charAt(0) == ' ' || this.shopno.charAt(this.shopno.length() - 1) == ' ') { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("enter shop id without spaces", "enter shop id without spaces")); } else { impl.getShopDetails(this); this.setShopnoNew(this.shopno); } } else { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("enter valid shop id ", "enter valid shop id ")); } } private String vch_licence_no; public String getVch_licence_no() { return vch_licence_no; } public void setVch_licence_no(String vch_licence_no) { this.vch_licence_no = vch_licence_no; } public boolean rtFlag; public boolean brcFlag; public String shopnoNew; public boolean isRtFlag() { return rtFlag; } public void setRtFlag(boolean rtFlag) { this.rtFlag = rtFlag; } public boolean isBrcFlag() { return brcFlag; } public void setBrcFlag(boolean brcFlag) { this.brcFlag = brcFlag; } public String getShopnoNew() { return shopnoNew; } public void setShopnoNew(String shopnoNew) { this.shopnoNew = shopnoNew; } public void fetch1() { if (this.vch_to_lic_no.length() > 0 && this.vch_to_lic_no != null && this.vch_to_lic_no != "") { if (this.vch_to_lic_no.charAt(0) == ' ' || this.vch_to_lic_no .charAt(this.vch_to_lic_no.length() - 1) == ' ') { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("enter HBR ID without spaces", "enter HBR ID without spaces")); } else { impl.checklic(this); this.setVch_to_lic_noNew(this.vch_to_lic_no); } } else { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("enter valid HBR ID ", "enter valid HBR ID ")); } } private String gatepassNmbr; private double dutyEnterd; private double addDutyEnterd; public String getGatepassNmbr() { return gatepassNmbr; } public void setGatepassNmbr(String gatepassNmbr) { this.gatepassNmbr = gatepassNmbr; } public double getDutyEnterd() { return dutyEnterd; } public void setDutyEnterd(double dutyEnterd) { this.dutyEnterd = dutyEnterd; } public double getAddDutyEnterd() { return addDutyEnterd; } public void setAddDutyEnterd(double addDutyEnterd) { this.addDutyEnterd = addDutyEnterd; } private boolean addrowflg = true; public boolean isAddrowflg() { return addrowflg; } public void setAddrowflg(boolean addrowflg) { this.addrowflg = addrowflg; } public String addRowMethodPackaging() { GatepassToDistrict_FL2_FL2B_oldStockDT dt = new GatepassToDistrict_FL2_FL2B_oldStockDT(); dt.setSrNo(this.displaylist.size() + 1); this.displaylist.add(dt); return ""; } public void deleteRowMethodPackaging(ActionEvent e) { UIDataTable uiTable = (UIDataTable) e.getComponent().getParent().getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.displaylist.get(uiTable.getRowIndex()); this.displaylist.remove(dt); } public void brandListener(ValueChangeEvent e) { String val = (String) e.getNewValue(); UIDataTable uiTable = (UIDataTable) e.getComponent().getParent().getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.displaylist.get(uiTable.getRowIndex()); //System.out.println("val========="+val); if(val.equalsIgnoreCase("O")){ dt.setBrandFlg(true); dt.setBrandValue("O"); }else{ dt.setBrandFlg(false); dt.setBrandValue("N"); } } }
UTF-8
Java
37,926
java
GatepassToDistrict_FL2_FL2B_oldStockAction.java
Java
[]
null
[]
package com.mentor.action; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.faces.application.FacesMessage; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.event.ValueChangeEvent; import javax.servlet.ServletContext; import org.richfaces.component.UIDataTable; import org.richfaces.event.UploadEvent; import org.richfaces.model.UploadItem; import com.mentor.datatable.GatepassToDistrict_FL2_FL2B_oldStockDT; import com.mentor.impl.GatepassToDistrict_FL2_FL2B_oldStockImpl; import com.mentor.utility.Validate; public class GatepassToDistrict_FL2_FL2B_oldStockAction { GatepassToDistrict_FL2_FL2B_oldStockImpl impl = new GatepassToDistrict_FL2_FL2B_oldStockImpl(); private boolean disable_flag; public boolean isDisable_flag() { return disable_flag; } public void setDisable_flag(boolean disable_flag) { this.disable_flag = disable_flag; } private String draftpdfname; private String DraftPdfname; public String getDraftpdfname() { return draftpdfname; } public void setDraftpdfname(String draftpdfname) { this.draftpdfname = draftpdfname; } private String fl2_fl2bName; private String fl2_fl2bAdrs; private String hidden; private int fl2_fl2bId; public Date dt_date = new Date(); public Date validtilldt_date; public String vch_to; private int districtLic; public String vch_to_lic_no; private String licenseeName; private String licenseeAdrs; private int licenseeId; private String vehicleDrvrName; private String vehicleAgencyNmAdrs; private int district1; private int district2; private int district3; private String routeDtl; private String vehicleNo; private double grossWeight = 0; private double tierWeight = 0; private double netWeight = 0; private ArrayList districtList = new ArrayList(); private ArrayList displaylist = new ArrayList(); private String officrEmail; public String vch_from; private String fl2LicenseType; private ArrayList licNmbrList = new ArrayList(); private String brc_to_lic; private boolean drpdwnFlg; private boolean drpdwnFlg1; private ArrayList brclicNmbrList = new ArrayList(); public Date table_dt = new Date(); private String challan_no; private Date challan_dt; private String challan_amt; public String vch_to_lic_noNew; public String getVch_to_lic_noNew() { return vch_to_lic_noNew; } public void setVch_to_lic_noNew(String vch_to_lic_noNew) { this.vch_to_lic_noNew = vch_to_lic_noNew; } public String getChallan_no() { return challan_no; } public void setChallan_no(String challan_no) { this.challan_no = challan_no; } public Date getChallan_dt() { return challan_dt; } public void setChallan_dt(Date challan_dt) { this.challan_dt = challan_dt; } public String getChallan_amt() { return challan_amt; } public void setChallan_amt(String challan_amt) { this.challan_amt = challan_amt; } public Date getTable_dt() { return table_dt; } public void setTable_dt(Date table_dt) { this.table_dt = table_dt; } public String getFl2_fl2bName() { return fl2_fl2bName; } public void setFl2_fl2bName(String fl2_fl2bName) { this.fl2_fl2bName = fl2_fl2bName; } public String getFl2_fl2bAdrs() { return fl2_fl2bAdrs; } public void setFl2_fl2bAdrs(String fl2_fl2bAdrs) { this.fl2_fl2bAdrs = fl2_fl2bAdrs; } public String getHidden() { try { impl.getDetails(this); if (this.fl2LicenseType.equalsIgnoreCase("CL2")) { this.brcFlag = false; this.rtFlag = true; } else { this.brcFlag = true; this.rtFlag = false; } // impl.getEmailDetails(this); if (this.brc_to_lic != null) { // impl.getlicenseeDetail(this, this.brc_to_lic); } if (this.vch_to_lic_no != null) { // impl.getretailLicenseeDetail(this, this.vch_to_lic_no); } } catch (Exception e) { e.printStackTrace(); } return hidden; } public void setHidden(String hidden) { this.hidden = hidden; } public int getFl2_fl2bId() { return fl2_fl2bId; } public void setFl2_fl2bId(int fl2_fl2bId) { this.fl2_fl2bId = fl2_fl2bId; } public Date getDt_date() { return dt_date; } public void setDt_date(Date dt_date) { this.dt_date = dt_date; } public Date getValidtilldt_date() { return validtilldt_date; } public void setValidtilldt_date(Date validtilldt_date) { this.validtilldt_date = validtilldt_date; } public String getVch_to() { return vch_to; } public void setVch_to(String vch_to) { this.vch_to = vch_to; } public int getDistrictLic() { return districtLic; } public void setDistrictLic(int districtLic) { this.districtLic = districtLic; } public String getVch_to_lic_no() { return vch_to_lic_no; } public void setVch_to_lic_no(String vch_to_lic_no) { this.vch_to_lic_no = vch_to_lic_no; } public String getLicenseeName() { return licenseeName; } public void setLicenseeName(String licenseeName) { this.licenseeName = licenseeName; } public String getLicenseeAdrs() { return licenseeAdrs; } public void setLicenseeAdrs(String licenseeAdrs) { this.licenseeAdrs = licenseeAdrs; } public int getLicenseeId() { return licenseeId; } public void setLicenseeId(int licenseeId) { this.licenseeId = licenseeId; } public String getVehicleDrvrName() { return vehicleDrvrName; } public void setVehicleDrvrName(String vehicleDrvrName) { this.vehicleDrvrName = vehicleDrvrName; } public String getVehicleAgencyNmAdrs() { return vehicleAgencyNmAdrs; } public void setVehicleAgencyNmAdrs(String vehicleAgencyNmAdrs) { this.vehicleAgencyNmAdrs = vehicleAgencyNmAdrs; } public int getDistrict1() { return district1; } public void setDistrict1(int district1) { this.district1 = district1; } public int getDistrict2() { return district2; } public void setDistrict2(int district2) { this.district2 = district2; } public int getDistrict3() { return district3; } public void setDistrict3(int district3) { this.district3 = district3; } public String getRouteDtl() { return routeDtl; } public void setRouteDtl(String routeDtl) { this.routeDtl = routeDtl; } public String getVehicleNo() { return vehicleNo; } public void setVehicleNo(String vehicleNo) { this.vehicleNo = vehicleNo; } public double getGrossWeight() { return grossWeight; } public void setGrossWeight(double grossWeight) { this.grossWeight = grossWeight; } public double getTierWeight() { return tierWeight; } public void setTierWeight(double tierWeight) { this.tierWeight = tierWeight; } public double getNetWeight() { if (this.grossWeight > 0.0 && this.tierWeight > 0.0) { this.netWeight = this.grossWeight - this.tierWeight; } else { this.netWeight = 0.0; } return netWeight; } public void setNetWeight(double netWeight) { this.netWeight = netWeight; } public ArrayList getDistrictList() { /* * try { this.districtList = impl.getDistrictList(this); } catch * (Exception e) { e.printStackTrace(); } */ return districtList; } public void setDistrictList(ArrayList districtList) { this.districtList = districtList; } public ArrayList getDisplaylist() { if (addrowflg) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = new GatepassToDistrict_FL2_FL2B_oldStockDT(); dt.setSrNo(this.displaylist.size() + 1); this.displaylist.add(dt); addrowflg = false; } return displaylist; } public void setDisplaylist(ArrayList displaylist) { this.displaylist = displaylist; } public String getOfficrEmail() { return officrEmail; } public void setOfficrEmail(String officrEmail) { this.officrEmail = officrEmail; } public String getVch_from() { return vch_from; } public void setVch_from(String vch_from) { this.vch_from = vch_from; } public String getFl2LicenseType() { return fl2LicenseType; } public void setFl2LicenseType(String fl2LicenseType) { this.fl2LicenseType = fl2LicenseType; } public ArrayList getLicNmbrList() { return licNmbrList; } public void setLicNmbrList(ArrayList licNmbrList) { this.licNmbrList = licNmbrList; } public String getBrc_to_lic() { return brc_to_lic; } public void setBrc_to_lic(String brc_to_lic) { this.brc_to_lic = brc_to_lic; } public boolean isDrpdwnFlg() { return drpdwnFlg; } public void setDrpdwnFlg(boolean drpdwnFlg) { this.drpdwnFlg = drpdwnFlg; } public boolean isDrpdwnFlg1() { return drpdwnFlg1; } public void setDrpdwnFlg1(boolean drpdwnFlg1) { this.drpdwnFlg1 = drpdwnFlg1; } public ArrayList getBrclicNmbrList() { return brclicNmbrList; } public void setBrclicNmbrList(ArrayList brclicNmbrList) { this.brclicNmbrList = brclicNmbrList; } public String listMethod(ValueChangeEvent vce) { //this.displaylist = impl.displaylistImpl(this); impl.getDistrictList(this); this.disable_flag = false; this.flagshop = false; this.brc_to_lic = null; this.brclicNmbrList.clear(); this.vch_to_lic_no = null; this.licNmbrList.clear(); this.licenseeName = null; this.licenseeAdrs = null; this.licenseeId = 0; this.licenseeName = null; this.licenseeAdrs = null; this.licenseeId = 0; this.printDraft = true; this.printFlag = false; return ""; } public String listMethod1(ValueChangeEvent vce) { Date ev = (Date) vce.getNewValue(); this.table2List = impl.getTable2List1(this, ev); return ""; } public String drpdownMethod(ValueChangeEvent vce) { String val = (String) vce.getNewValue(); impl.getlicenseeDetail(this, val); return ""; } public String retaildrpMethod(ValueChangeEvent vce) { String val = (String) vce.getNewValue(); impl.getretailLicenseeDetail(this, val); return ""; } public double db_total_value = 0; public double sum = 0; public boolean flag = true; public double db_total_add_value = 0; public double sum_add = 0; public boolean addflag = true; public double getDb_total_value() { double duty = 0.0; try { for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.getDisplaylist().get(i); duty += dt.getCalculated_duty(); db_total_value = duty; } } catch (Exception e) { e.printStackTrace(); } return db_total_value; } public void setDb_total_value(double db_total_value) { this.db_total_value = db_total_value; } public double getSum() { return sum; } public void setSum(double sum) { this.sum = sum; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public double getDb_total_add_value() { double addduty = 0.0; try { for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.getDisplaylist().get(i); addduty += dt.getCalculated_add_duty(); } db_total_add_value = addduty; } catch (Exception e) { e.printStackTrace(); } return db_total_add_value; } public void setDb_total_add_value(double db_total_add_value) { this.db_total_add_value = db_total_add_value; } public double getSum_add() { return sum_add; } public void setSum_add(double sum_add) { this.sum_add = sum_add; } public boolean isAddflag() { return addflag; } public void setAddflag(boolean addflag) { this.addflag = addflag; } public void calculateTotalDuty(ActionEvent ae) { if (isFlag()) { this.setSum(0); for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.displaylist.get(i); this.setSum(this.getSum() + dt.getCalculated_duty()); } } this.flag = false; } public void calculateTotalAddDuty(ActionEvent ae) { if (isAddflag()) { this.setSum_add(0); for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.displaylist.get(i); this.setSum_add(this.getSum_add() + dt.getCalculated_add_duty()); } } this.addflag = false; } private boolean validateInput1; public boolean isValidateInput1() { validateInput1 = true; if (!(Validate.validateDate("validtill", this.getValidtilldt_date()))) validateInput1 = false; else if (!(Validate.validateStrReq("radioto", this.getVch_to()))) validateInput1 = false; else if (!(Validate.validateStrReq("gatepass", this.getGatepassNmbr()))) validateInput1 = false; // /////////////////////////////////// else if (this.vch_to.equalsIgnoreCase("BRC")) { if (!(Validate.validateStrReq("licenseno", this.getVch_to_lic_no()))) validateInput1 = false; else if (!(Validate.validateStrReq("licenseenm", this.getLicenseeName()))) validateInput1 = false; else if (!(Validate.validateStrReq("lic enseeaddress", this.getLicenseeAdrs()))) validateInput1 = false; else if (!(Validate.validateStrReq("routedtl", this.getRouteDtl()))) validateInput1 = false; else if (!(Validate.validateStrReq("vehiclenmbr", this.getVehicleNo()))) validateInput1 = false; else if (!(Validate.validateStrReq("vehicledriver", this.getVehicleDrvrName()))) validateInput1 = false; else if (!(Validate.validateStrReq("agencyNameAddress", this.getVehicleAgencyNmAdrs()))) validateInput1 = false; /*else if (!(Validate.validateDouble("duty", this.getDutyEnterd()))) validateInput1 = false; else if (!(Validate.validateDouble("addDuty",this.getAddDutyEnterd()))) validateInput1 = false;*/ } else if (this.vch_to.equalsIgnoreCase("RT")) { if (!(Validate.validateStrReq("shopno", this.getShopno()))) validateInput1 = false; else if (!(Validate.validateStrReq("shopname", this.getShopName()))) validateInput1 = false; else if (!(Validate.validateStrReq("licenseenm", this.getLicenseeName()))) validateInput1 = false; else if (!(Validate.validateStrReq("licenseeaddress", this.getLicenseeAdrs()))) validateInput1 = false; else if (!(Validate.validateStrReq("routedtl", this.getRouteDtl()))) validateInput1 = false; else if (!(Validate.validateStrReq("vehiclenmbr", this.getVehicleNo()))) validateInput1 = false; else if (!(Validate.validateStrReq("vehicledriver", this.getVehicleDrvrName()))) validateInput1 = false; else if (!(Validate.validateStrReq("agencyNameAddress", this.getVehicleAgencyNmAdrs()))) validateInput1 = false; /*else if (!(Validate.validateDouble("duty", this.getDutyEnterd()))) validateInput1 = false; else if (!(Validate.validateDouble("addDuty",this.getAddDutyEnterd()))) validateInput1 = false;*/ } for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) displaylist.get(i); if (dt.getDispatchbox() > 0 && dt.getDispatchbottls() > 0) { if (dt.getBatchNo() == null || dt.getBatchNo().equals("")) { validateInput1 = false; FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Enter Batch No At Line No !!! "+ (i + 1),"Enter Batch No At Line No !!! "+ (i + 1))); break; } } } int sumBottles = 0; int sumBoxes = 0; for (int i = 0; i < this.displaylist.size(); i++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) displaylist.get(i); sumBottles += dt.getDispatchbottls(); sumBoxes += dt.getDispatchbox(); /*if (dt.getDispatchbottls() > 0) { if ((dt.getDispatchbottls()) > dt.getInt_bottle_avaliable()) { FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Dispatch Bottles Should Not Be More Than Available Bottles at Line "+ (i + 1) + " !!! ", "Dispatch Bottles Should Not Be More Than Available Bottles at Line "+ (i + 1) + " !!!")); validateInput1 = false; } }*/ } if (sumBoxes == 0) { FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Dispatch Boxes Should Be Greater Than Zero !!! ","Dispatch Boxes Should Be Greater Than Zero !!!")); validateInput1 = false; } else if (sumBottles == 0) { FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Dispatch Bottles Should Be Greater Than Zero !!! ","Dispatch Bottles Should Be Greater Than Zero !!!")); validateInput1 = false; } return validateInput1; } public void setValidateInput1(boolean validateInput1) { this.validateInput1 = validateInput1; } public boolean eco_flag; public void saveMethod() { try { if (isValidateInput1()) { if (this.dt_date.after(this.validtilldt_date)) { FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Valid Till Date !!","Invalid Valid Till Date !!")); } else { impl.saveMethodImpl(this); //this.displaylist = impl.displaylistImpl(this); } } } catch (Exception e) { e.printStackTrace(); } } public boolean check_economy(int id) { if (impl.check_economy(id)) return true; return false; } public void clearAll() { this.disable_flag = false; this.flagshop = false; this.shopno = ""; this.shopName = ""; this.fl2_fl2bName = null; this.fl2_fl2bAdrs = null; this.validtilldt_date = null; this.vch_to = ""; this.vch_to_lic_no = ""; this.displaylist.clear(); this.routeDtl = null; this.vehicleNo = null; this.vehicleDrvrName = null; this.vehicleAgencyNmAdrs = null; this.district1 = 0; this.district2 = 0; this.district3 = 0; this.districtLic = 0; this.tierWeight = 0.0; this.netWeight = 0.0; this.grossWeight = 0.0; this.licenseeName = null; this.licenseeAdrs = null; this.licenseeId = 0; this.brc_to_lic = null; this.licNmbrList.clear(); this.brclicNmbrList.clear(); // this.table2List.clear(); dt_date = new Date(); table_dt = new Date(); this.gatepassNmbr = null; this.listFlagForPrint = true; this.addrowflg = true; this.dutyEnterd = 0.0; this.addDutyEnterd = 0.0; } private ArrayList table2List = new ArrayList(); private Date printDate; private String printGatePassNo; private String pdfname; private String pdfDraft; private boolean listFlagForPrint = true; private String scanGatePassNo; private String shopid; private String shoptype; public String getShopid() { return shopid; } public void setShopid(String shopid) { this.shopid = shopid; } public String getShoptype() { return shoptype; } public void setShoptype(String shoptype) { this.shoptype = shoptype; } public String getScanGatePassNo() { return scanGatePassNo; } public void setScanGatePassNo(String scanGatePassNo) { this.scanGatePassNo = scanGatePassNo; } public ArrayList getTable2List() { if (this.listFlagForPrint == true) { this.table2List = impl.getTable2List(this); this.listFlagForPrint = false; } return table2List; } public void setTable2List(ArrayList table2List) { this.table2List = table2List; } public Date getPrintDate() { return printDate; } public void setPrintDate(Date printDate) { this.printDate = printDate; } public String getPrintGatePassNo() { return printGatePassNo; } public void setPrintGatePassNo(String printGatePassNo) { this.printGatePassNo = printGatePassNo; } public String getPdfname() { return pdfname; } public void setPdfname(String pdfname) { this.pdfname = pdfname; } public boolean isListFlagForPrint() { return listFlagForPrint; } public void setListFlagForPrint(boolean listFlagForPrint) { this.listFlagForPrint = listFlagForPrint; } private String pdfname_CaseCode; public String getPdfname_CaseCode() { return pdfname_CaseCode; } public void setPdfname_CaseCode(String pdfname_CaseCode) { this.pdfname_CaseCode = pdfname_CaseCode; } private String vchToPrint; public String getVchToPrint() { return vchToPrint; } public void setVchToPrint(String vchToPrint) { this.vchToPrint = vchToPrint; } public void printReport(ActionEvent e) { UIDataTable uiTable = (UIDataTable) e.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setPrintDate(dt.getCurrentDate()); this.setPrintGatePassNo(dt.getGatepassNo()); this.printFlag = true; this.setVchToPrint(dt.getVchTO()); if (impl.printReport(this, dt) == true) { dt.setPrintFlag(true); } else { dt.setPrintFlag(false); } this.viewReportFlag = true; } public void printDraftReport(ActionEvent e) { UIDataTable uiTable = (UIDataTable) e.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setPrintDate(dt.getCurrentDate()); this.setPrintGatePassNo(dt.getGatepassNo()); // System.out.println("-------- action gate pass ----"+this.getPrintGatePassNo()); if (impl.printDraftReport(this, dt) == true) { dt.setPrintDraftFlagDt(true); } else { dt.setPrintDraftFlagDt(false); } this.printDraftFlag = true; this.scanUploadFlag = true; } private boolean printFlag; private boolean printDraftFlag; private boolean scanUploadFlag; private boolean uploaderFlag; private boolean submitFlag; private boolean cancelFlag; private boolean finalsubmit; private boolean tableFlag; private boolean deleteFlag; private boolean kidnlyUploadFlag; private boolean gatePassFlag; private boolean viewDraftFlag; private boolean viewReportFlag; private int excelCases; private int recieveCases; private boolean printDraft; public boolean isDeleteFlag() { return deleteFlag; } public void setDeleteFlag(boolean deleteFlag) { this.deleteFlag = deleteFlag; } public int getRecieveCases() { return recieveCases; } public void setRecieveCases(int recieveCases) { this.recieveCases = recieveCases; } public boolean isViewDraftFlag() { return viewDraftFlag; } public void setViewDraftFlag(boolean viewDraftFlag) { this.viewDraftFlag = viewDraftFlag; } public boolean isViewReportFlag() { return viewReportFlag; } public void setViewReportFlag(boolean viewReportFlag) { this.viewReportFlag = viewReportFlag; } public boolean isKidnlyUploadFlag() { return kidnlyUploadFlag; } public void setKidnlyUploadFlag(boolean kidnlyUploadFlag) { this.kidnlyUploadFlag = kidnlyUploadFlag; } public boolean isGatePassFlag() { return gatePassFlag; } public void setGatePassFlag(boolean gatePassFlag) { this.gatePassFlag = gatePassFlag; } // ------------------ excel scan and upload ---------------------------- public void scanAndUpload(ActionEvent ae) { UIDataTable uiTable = (UIDataTable) ae.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setScanGatePassNo(dt.getGatepassNo()); this.setShopid(dt.getLicenseNo()); this.setShoptype(dt.getVchTO()); this.submitFlag = true; this.cancelFlag = true; this.uploaderFlag = true; this.tableFlag = true; this.finalsubmit = true; this.kidnlyUploadFlag = true; this.gatePassFlag = true; this.scanUploadFlag = true; // this.getVal = impl.getExcelData(this); // this.scanUploadFlag=true; // this.printDraft=true; } // ------------------- excel submit------------------ public String importExcel() { impl.saveExcelData(this); this.tableFlag = true; this.submitFlag = false; this.cancelFlag = true; this.gatePassFlag = false; this.kidnlyUploadFlag = false; this.scanUploadFlag = true; this.finalsubmit = true; this.uploaderFlag = false; return ""; } // -------------------final submit------------------ public void finalSubmitcl2(ActionEvent ae) { UIDataTable uiTable = (UIDataTable) ae.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setScanGatePassNo(dt.getGatepassNo()); listFlagForPrint = true; } public void finalSubmit() { // impl.recieveCases(this); if (impl.excelCases(this) == impl.recieveCases(this)) { if (impl.updateFL3(this) == true) { this.printFlag = true; this.scanUploadFlag = false; this.submitFlag = false; this.cancelFlag = false; this.finalsubmit = true; this.uploaderFlag = false; this.finalsubmit = false; this.deleteFlag = false; this.tableFlag = false; this.kidnlyUploadFlag = false; this.gatePassFlag = false; this.printFlag = true; listFlagForPrint = true; FacesContext.getCurrentInstance().addMessage( null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Data Save Successfully", "Data Save Successfully")); } else { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("Error Occured while saving !!! ", "Error Occured while saving !!!")); } } else { FacesContext .getCurrentInstance() .addMessage( null, new FacesMessage( "No.of casecodes uploaded by you is not equal to number of cases mentioned in gatepass.", "No.of casecodes uploaded by you is not equal to number of cases mentioned in gatepass.")); } } private String excelFilename; private String excelFilepath; public String getExcelFilename() { return excelFilename; } public void setExcelFilename(String excelFilename) { this.excelFilename = excelFilename; } public String getExcelFilepath() { return excelFilepath; } public void setExcelFilepath(String excelFilepath) { this.excelFilepath = excelFilepath; } // --------------------------------------------delete excel data------------------ public void delete() { impl.deleteData(this); this.tableFlag = false; this.finalsubmit = false; this.cancelFlag = false; this.gatePassFlag = false; this.kidnlyUploadFlag = false; this.uploaderFlag = false; this.submitFlag = false; this.scanUploadFlag = false; listFlagForPrint = true; this.getVal.clear(); } public void uploadExcel(UploadEvent event) { try { int size = 0; int counter = 0; UploadItem item = event.getUploadItem(); String FullfileName = item.getFileName(); String path = item.getFile().getPath(); String fileName = FullfileName.substring(FullfileName .lastIndexOf("\\") + 1); ExternalContext con = FacesContext.getCurrentInstance() .getExternalContext(); ServletContext sCon = (ServletContext) con.getContext(); size = item.getFileSize(); this.excelFilename = FullfileName; this.excelFilepath = path; } catch (Exception ee) { } finally { } } private boolean valFlag; public ArrayList getVal = new ArrayList(); public ArrayList tempList = new ArrayList(); public ArrayList getTempList() { return tempList; } public void setTempList(ArrayList tempList) { this.tempList = tempList; } public ArrayList getGetVal() { return getVal; } public void setGetVal(ArrayList getVal) { this.getVal = getVal; } public boolean isPrintFlag() { return printFlag; } public void setPrintFlag(boolean printFlag) { this.printFlag = printFlag; } public boolean isScanUploadFlag() { return scanUploadFlag; } public void setScanUploadFlag(boolean scanUploadFlag) { this.scanUploadFlag = scanUploadFlag; } public boolean isUploaderFlag() { return uploaderFlag; } public void setUploaderFlag(boolean uploaderFlag) { this.uploaderFlag = uploaderFlag; } public boolean isSubmitFlag() { return submitFlag; } public void setSubmitFlag(boolean submitFlag) { this.submitFlag = submitFlag; } public boolean isCancelFlag() { return cancelFlag; } public void setCancelFlag(boolean cancelFlag) { this.cancelFlag = cancelFlag; } public boolean isFinalsubmit() { return finalsubmit; } public void setFinalsubmit(boolean finalsubmit) { this.finalsubmit = finalsubmit; } public boolean isTableFlag() { return tableFlag; } public void setTableFlag(boolean tableFlag) { this.tableFlag = tableFlag; } public boolean isPrintDraftFlag() { return printDraftFlag; } public void setPrintDraftFlag(boolean printDraftFlag) { this.printDraftFlag = printDraftFlag; } public String getPdfDraft() { return pdfDraft; } public void setPdfDraft(String pdfDraft) { this.pdfDraft = pdfDraft; } public int getExcelCases() { return excelCases; } public void setExcelCases(int excelCases) { this.excelCases = excelCases; } public boolean isValFlag() { return valFlag; } public void setValFlag(boolean valFlag) { this.valFlag = valFlag; } public boolean isPrintDraft() { return printDraft; } public void setPrintDraft(boolean printDraft) { this.printDraft = printDraft; } private String vch_TO_Print = null; public String getVch_TO_Print() { return vch_TO_Print; } public void setVch_TO_Print(String vch_TO_Print) { this.vch_TO_Print = vch_TO_Print; } public void printDraft(ActionEvent e) { this.vch_TO_Print = null; UIDataTable uiTable = (UIDataTable) e.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setPrintDate(dt.getDt_date()); this.setPrintGatePassNo(dt.getGatepassNo()); this.setVch_TO_Print(dt.getVchTO()); if (impl.printDraftReport(this, dt) == true) { dt.setDraftprintFlag(true); } else { dt.setDraftprintFlag(false); } } public String getDraftPdfname() { return DraftPdfname; } public void setDraftPdfname(String draftPdfname) { DraftPdfname = draftPdfname; } // ----------------------------code for cancel // gatepass---------------------- public void cancelGatepass(ActionEvent e) { UIDataTable uiTable = (UIDataTable) e.getComponent().getParent() .getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.table2List .get(uiTable.getRowIndex()); this.setPrintDate(dt.getDt_date()); this.setPrintGatePassNo(dt.getGatepassNo()); impl.cancelGatepassImpl(this); } // ==========================code for csv=================================== private String csvFilename; private String csvFilepath; private String exclcsv = "C"; public String getCsvFilename() { return csvFilename; } public void setCsvFilename(String csvFilename) { this.csvFilename = csvFilename; } public String getCsvFilepath() { return csvFilepath; } public void setCsvFilepath(String csvFilepath) { this.csvFilepath = csvFilepath; } public String getExclcsv() { return exclcsv; } public void setExclcsv(String exclcsv) { this.exclcsv = exclcsv; } public void uploadCsv(UploadEvent event) { try { int size = 0; int counter = 0; UploadItem item = event.getUploadItem(); String FullfileName = item.getFileName(); String path = item.getFile().getPath(); String fileName = FullfileName.substring(FullfileName .lastIndexOf("\\") + 1); ExternalContext con = FacesContext.getCurrentInstance() .getExternalContext(); ServletContext sCon = (ServletContext) con.getContext(); size = item.getFileSize(); this.setCsvFilename(FullfileName); this.setCsvFilepath(path); } catch (Exception ee) { ee.printStackTrace(); System.out.println("exception in upload@"); } finally { } } ArrayList sourceList = new ArrayList<String>(); public ArrayList getSourceList() { return sourceList; } public void setSourceList(ArrayList sourceList) { this.sourceList = sourceList; } public String csvSubmit() throws IOException { /* * if(this.fl2LicenseType.equalsIgnoreCase("FL2")){ * impl.saveCSVfl(this); }else{ */ tempList.clear(); ArrayList matchdata = new ArrayList<>(); impl.saveCSV(this); if (this.getFl2LicenseType().equalsIgnoreCase("CL2")) { this.getVal = impl.getExcelData(this.getScanGatePassNo() .toUpperCase().trim()); } else if (this.getFl2LicenseType().equalsIgnoreCase("FL2")) { this.getVal = impl.getExcelDatafl2(this.getScanGatePassNo() .toUpperCase().trim()); } else if (this.getFl2LicenseType().equalsIgnoreCase("FL2B")) { this.getVal = impl.getExcelDatafl2b(this.getScanGatePassNo() .toUpperCase().trim()); } for (int ik = 0; ik < getVal.size(); ik++) { GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this .getGetVal().get(ik); String casecode = dt.getCasecode().trim(); Date date = dt.getCasecodedt(); SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd"); String datt = sdf.format(date); for (int p = 0; p < this.tempList.size(); p++) { String s = (String) this.tempList.get(p); String dat = s.substring(16, 22).trim(); String caseno = s.substring(26, s.length()).trim(); if (datt.equals(dat) && caseno.equals(casecode)) { this.tempList.remove(this.tempList.get(p)); } } sourceList = tempList; } // } this.scanUploadFlag = true; // this.getVal = impl.getExcelData(this); return ""; } public String shopno; private boolean flagshop; private boolean flaglicense; public String shopName; public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public boolean isFlagshop() { return flagshop; } public void setFlagshop(boolean flagshop) { this.flagshop = flagshop; } public boolean isFlaglicense() { return flaglicense; } public void setFlaglicense(boolean flaglicense) { this.flaglicense = flaglicense; } public String getShopno() { return shopno; } public void setShopno(String shopno) { this.shopno = shopno; } public void fetch() { if (this.shopno.length() > 0 && this.shopno != null && this.shopno != "") { if (this.shopno.charAt(0) == ' ' || this.shopno.charAt(this.shopno.length() - 1) == ' ') { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("enter shop id without spaces", "enter shop id without spaces")); } else { impl.getShopDetails(this); this.setShopnoNew(this.shopno); } } else { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("enter valid shop id ", "enter valid shop id ")); } } private String vch_licence_no; public String getVch_licence_no() { return vch_licence_no; } public void setVch_licence_no(String vch_licence_no) { this.vch_licence_no = vch_licence_no; } public boolean rtFlag; public boolean brcFlag; public String shopnoNew; public boolean isRtFlag() { return rtFlag; } public void setRtFlag(boolean rtFlag) { this.rtFlag = rtFlag; } public boolean isBrcFlag() { return brcFlag; } public void setBrcFlag(boolean brcFlag) { this.brcFlag = brcFlag; } public String getShopnoNew() { return shopnoNew; } public void setShopnoNew(String shopnoNew) { this.shopnoNew = shopnoNew; } public void fetch1() { if (this.vch_to_lic_no.length() > 0 && this.vch_to_lic_no != null && this.vch_to_lic_no != "") { if (this.vch_to_lic_no.charAt(0) == ' ' || this.vch_to_lic_no .charAt(this.vch_to_lic_no.length() - 1) == ' ') { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("enter HBR ID without spaces", "enter HBR ID without spaces")); } else { impl.checklic(this); this.setVch_to_lic_noNew(this.vch_to_lic_no); } } else { FacesContext.getCurrentInstance().addMessage( null, new FacesMessage("enter valid HBR ID ", "enter valid HBR ID ")); } } private String gatepassNmbr; private double dutyEnterd; private double addDutyEnterd; public String getGatepassNmbr() { return gatepassNmbr; } public void setGatepassNmbr(String gatepassNmbr) { this.gatepassNmbr = gatepassNmbr; } public double getDutyEnterd() { return dutyEnterd; } public void setDutyEnterd(double dutyEnterd) { this.dutyEnterd = dutyEnterd; } public double getAddDutyEnterd() { return addDutyEnterd; } public void setAddDutyEnterd(double addDutyEnterd) { this.addDutyEnterd = addDutyEnterd; } private boolean addrowflg = true; public boolean isAddrowflg() { return addrowflg; } public void setAddrowflg(boolean addrowflg) { this.addrowflg = addrowflg; } public String addRowMethodPackaging() { GatepassToDistrict_FL2_FL2B_oldStockDT dt = new GatepassToDistrict_FL2_FL2B_oldStockDT(); dt.setSrNo(this.displaylist.size() + 1); this.displaylist.add(dt); return ""; } public void deleteRowMethodPackaging(ActionEvent e) { UIDataTable uiTable = (UIDataTable) e.getComponent().getParent().getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.displaylist.get(uiTable.getRowIndex()); this.displaylist.remove(dt); } public void brandListener(ValueChangeEvent e) { String val = (String) e.getNewValue(); UIDataTable uiTable = (UIDataTable) e.getComponent().getParent().getParent(); GatepassToDistrict_FL2_FL2B_oldStockDT dt = (GatepassToDistrict_FL2_FL2B_oldStockDT) this.displaylist.get(uiTable.getRowIndex()); //System.out.println("val========="+val); if(val.equalsIgnoreCase("O")){ dt.setBrandFlg(true); dt.setBrandValue("O"); }else{ dt.setBrandFlg(false); dt.setBrandValue("N"); } } }
37,926
0.699098
0.691004
1,648
22.01335
22.056494
131
false
false
0
0
0
0
0
0
1.946602
false
false
10
f440ea2095dd7513724d330817735b000f5cf0d1
34,136,400,087,927
3036373431fdf5e70e57ac88f75e2e8a98bfe08c
/adit-war/src/main/java/ee/adit/ws/endpoint/document/DeleteDocumentsEndpoint.java
cf879bebca38e241a6955ae899711ef21fe029f6
[]
no_license
cckmit/ADIT
https://github.com/cckmit/ADIT
ca34cacc1e17657fcc61dbdba312016223aa8bbe
e91819ec46140d4e3802af11d5571bd4bd56c3fa
refs/heads/master
2023-06-30T02:09:58.604000
2021-05-06T13:52:19
2021-05-06T13:52:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ee.adit.ws.endpoint.document; import java.util.Calendar; import java.util.List; import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import ee.adit.dao.pojo.AditUser; import ee.adit.exception.AditCodedException; import ee.adit.exception.AditInternalException; import ee.adit.pojo.ArrayOfDocumentActionStatus; import ee.adit.pojo.ArrayOfDocumentId; import ee.adit.pojo.ArrayOfMessage; import ee.adit.pojo.DeleteDocumentRequest; import ee.adit.pojo.DeleteDocumentResponse; import ee.adit.pojo.DeleteDocumentsRequest; import ee.adit.pojo.DeleteDocumentsResponse; import ee.adit.pojo.DocumentActionStatus; import ee.adit.pojo.Message; import ee.adit.pojo.Success; import ee.adit.service.DocumentService; import ee.adit.service.LogService; import ee.adit.service.MessageService; import ee.adit.service.UserService; import ee.adit.util.Util; import ee.adit.util.xroad.CustomXRoadHeader; import ee.adit.ws.endpoint.AbstractAditBaseEndpoint; import ee.webmedia.xtee.annotation.XTeeService; import org.springframework.ws.soap.saaj.SaajSoapMessage; /** * Implementation of "deleteDocument" web method (web service request). Contains * request input validation, request-specific workflow and response composition. * * @author Marko Kurm, Microlink Eesti AS, marko.kurm@microlink.ee * @author Jaak Lember, Interinx, jaak@interinx.com */ @XTeeService(name = "deleteDocuments", version = "v1") @Component public class DeleteDocumentsEndpoint extends AbstractAditBaseEndpoint { private static Logger logger = LogManager.getLogger(DeleteDocumentsEndpoint.class); private UserService userService; private DocumentService documentService; @Override protected Object invokeInternal(Object requestObject, int version, SaajSoapMessage requestMessage, SaajSoapMessage responseMessage, CustomXRoadHeader xRoadHeader) throws Exception { logger.debug("deleteDocuments invoked. Version: " + version); if (version == 1) { return v1(requestObject, requestMessage, responseMessage, xRoadHeader); } else { throw new AditInternalException("This method does not support version specified: " + version); } } /** * Executes "V1" version of "deleteDocuments" request. * * @param requestObject * Request body object * @return Response body object */ protected Object v1(Object requestObject, SaajSoapMessage requestMessage, SaajSoapMessage responseMessage, CustomXRoadHeader xRoadHeader) { DeleteDocumentsResponse response = new DeleteDocumentsResponse(); ArrayOfMessage messages = new ArrayOfMessage(); ArrayOfDocumentActionStatus documentStatuses = new ArrayOfDocumentActionStatus(); Calendar requestDate = Calendar.getInstance(); String additionalInformationForLog = null; //Long documentId = null; ArrayOfDocumentId documents = null; boolean success = true; try { logger.debug("deleteDocument.v1 invoked."); DeleteDocumentsRequest request = (DeleteDocumentsRequest) requestObject; if (request != null) { documents = request.getDocuments(); } String applicationName = xRoadHeader.getInfosysteem(this.getConfiguration().getXteeProducerName()); // Log request Util.printHeader(xRoadHeader, this.getConfiguration()); printRequest(request); // Check header for required fields checkHeader(xRoadHeader); // Check request body checkRequest(request); // Kontrollime, kas päringu käivitanud infosüsteem on ADITis // registreeritud this.getUserService().checkApplicationRegistered(applicationName); // Kontrollime, kas päringu käivitanud infosüsteem tohib // andmeid muuta (või üldse näha) this.getUserService().checkApplicationWritePrivilege(applicationName); // Kontrollime, kas päringus märgitud isik on teenuse kasutaja AditUser user = Util.getAditUserFromXroadHeader(xRoadHeader, this.getUserService()); AditUser xroadRequestUser = Util.getXroadUserFromXroadHeader(user, xRoadHeader, this.getUserService()); // Kontrollime, et kasutajakonto ligipääs poleks peatatud (kasutaja // lahkunud) if ((user.getActive() == null) || !user.getActive()) { AditCodedException aditCodedException = new AditCodedException("user.inactive"); aditCodedException.setParameters(new Object[] {user.getUserCode()}); throw aditCodedException; } // Check whether or not the application has rights to // modify current user's data. int applicationAccessLevelForUser = userService.getAccessLevelForUser(applicationName, user); if (applicationAccessLevelForUser != 2) { AditCodedException aditCodedException = new AditCodedException( "application.insufficientPrivileges.forUser.write"); aditCodedException.setParameters(new Object[] {applicationName, user.getUserCode() }); throw aditCodedException; } for (Long documentId: request.getDocuments().getDocumentId()){ DocumentActionStatus documentStatus = new DocumentActionStatus(); documentStatus.setSuccess(true); documentStatus.setDocumentId(documentId); try { this.getDocumentService().deleteDocument(documentId, user.getUserCode(), applicationName); // If deletion was successful then add history event this.getDocumentService().addHistoryEvent(applicationName, documentId, user.getUserCode(), DocumentService.HISTORY_TYPE_DELETE, xroadRequestUser.getUserCode(), xroadRequestUser.getFullName(), DocumentService.DOCUMENT_HISTORY_DESCRIPTION_DELETE, user.getFullName(), requestDate.getTime()); } catch (Exception e) { logger.error("Exception while deleting document: ", e); documentStatus.setSuccess(false); String errorMessage = null; List<Message> errorMessages = this.getMessageService().getMessages("service.error", new Object[] {}); ArrayOfMessage documentMessages = new ArrayOfMessage(); documentMessages.setMessage(errorMessages); if (e instanceof AditCodedException) { logger.debug("Adding exception messages to response object."); documentMessages.setMessage(this.getMessageService().getMessages((AditCodedException) e)); errorMessage = this.getMessageService().getMessage(e.getMessage(), ((AditCodedException) e).getParameters(), Locale.ENGLISH); errorMessage = "ERROR: " + errorMessage; } else { documentMessages.setMessage(this.getMessageService().getMessages(MessageService.GENERIC_ERROR_CODE, new Object[]{})); errorMessage = "ERROR: " + e.getMessage(); } documentStatus.setMessages(documentMessages); success = false; additionalInformationForLog = errorMessage; super.logError(documentId, requestDate.getTime(), LogService.ERROR_LOG_LEVEL_ERROR, errorMessage, xRoadHeader); logger.debug("Adding exception messages to response object."); /*############## logger.error("Exception: ", e); String errorMessage = null; response.setSuccess(new Success(false)); ArrayOfMessage arrayOfMessage = new ArrayOfMessage(); if (e instanceof AditCodedException) { logger.debug("Adding exception messages to response object."); arrayOfMessage.setMessage(this.getMessageService().getMessages((AditCodedException) e)); errorMessage = this.getMessageService().getMessage(e.getMessage(), ((AditCodedException) e).getParameters(), Locale.ENGLISH); errorMessage = "ERROR: " + errorMessage; } else { arrayOfMessage.setMessage(this.getMessageService().getMessages(MessageService.GENERIC_ERROR_CODE, new Object[]{})); errorMessage = "ERROR: " + e.getMessage(); } additionalInformationForLog = errorMessage; super.logError(documentId, requestDate.getTime(), LogService.ERROR_LOG_LEVEL_ERROR, errorMessage); logger.debug("Adding exception messages to response object."); response.setMessages(arrayOfMessage); */ } documentStatuses.addDocument(documentStatus); } // Set response messages response.setSuccess(new Success(success)); response.setDocuments(documentStatuses); if (success) { messages.setMessage(this.getMessageService().getMessages("request.deleteDocuments.success", new Object[] {})); response.setMessages(messages); String additionalMessage = this.getMessageService().getMessage("request.deleteDocuments.success", new Object[] {}, Locale.ENGLISH); additionalInformationForLog = LogService.REQUEST_LOG_SUCCESS + ": " + additionalMessage; } else { messages.setMessage(this.getMessageService().getMessages("request.deleteDocuments.fail", new Object[] {})); response.setMessages(messages); String additionalMessage = this.getMessageService().getMessage("request.deleteDocuments.fail", new Object[] {}, Locale.ENGLISH); additionalInformationForLog = LogService.REQUEST_LOG_SUCCESS + ": " + additionalMessage; } response.setMessages(messages); } catch (Exception e) { logger.error("Exception: ", e); String errorMessage = null; response.setSuccess(new Success(false)); ArrayOfMessage arrayOfMessage = new ArrayOfMessage(); if (e instanceof AditCodedException) { logger.debug("Adding exception messages to response object."); arrayOfMessage.setMessage(this.getMessageService().getMessages((AditCodedException) e)); errorMessage = this.getMessageService().getMessage(e.getMessage(), ((AditCodedException) e).getParameters(), Locale.ENGLISH); errorMessage = "ERROR: " + errorMessage; } else { arrayOfMessage.setMessage(this.getMessageService().getMessages(MessageService.GENERIC_ERROR_CODE, new Object[]{})); errorMessage = "ERROR: " + e.getMessage(); } additionalInformationForLog = errorMessage; super.logError(null, requestDate.getTime(), LogService.ERROR_LOG_LEVEL_ERROR, errorMessage, xRoadHeader); logger.debug("Adding exception messages to response object."); response.setMessages(arrayOfMessage); } super.logCurrentRequest(null, requestDate.getTime(), additionalInformationForLog, xRoadHeader); return response; } @Override protected Object getResultForGenericException(Exception ex, SaajSoapMessage requestMessage, SaajSoapMessage responseMessage, CustomXRoadHeader xRoadHeader) { super.logError(null, Calendar.getInstance().getTime(), LogService.ERROR_LOG_LEVEL_FATAL, "ERROR: " + ex.getMessage(), xRoadHeader); DeleteDocumentResponse response = new DeleteDocumentResponse(); response.setSuccess(new Success(false)); ArrayOfMessage arrayOfMessage = new ArrayOfMessage(); arrayOfMessage.getMessage().add(new Message("en", ex.getMessage())); response.setMessages(arrayOfMessage); return response; } /** * Validates request body and makes sure that all required fields exist and * are not empty. <br> * <br> * Throws {@link AditCodedException} if any errors in request data are * found. * * @param request * Request body as {@link DeleteDocumentsRequest} object. * @throws AditCodedException * Exception describing error found in request body. */ private void checkRequest(DeleteDocumentsRequest request) throws AditCodedException { if (request !=null) { if ((request.getDocuments() == null) || (request.getDocuments().getDocumentId() == null) || request.getDocuments().getDocumentId().isEmpty()){ throw new AditCodedException("request.deleteDocuments.documents.notSpecified"); } else if (request != null && request.getDocuments().getDocumentId().isEmpty()) { for (Long documentId: request.getDocuments().getDocumentId()) { if (documentId <= 0) { throw new AditCodedException("request.body.undefined.documentId"); } } } } else { throw new AditCodedException("request.body.empty"); } } /** * Writes request parameters to application DEBUG log. * * @param request * Request body as {@link DeleteDocumentRequest} object. */ private void printRequest(DeleteDocumentsRequest request) { logger.debug("-------- DeleteDocumentRequest -------"); logger.debug("Documents: " + String.valueOf(request.getDocuments().toString())); logger.debug("--------------------------------------"); } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public DocumentService getDocumentService() { return documentService; } public void setDocumentService(DocumentService documentService) { this.documentService = documentService; } }
UTF-8
Java
15,221
java
DeleteDocumentsEndpoint.java
Java
[ { "context": "workflow and response composition.\r\n *\r\n * @author Marko Kurm, Microlink Eesti AS, marko.kurm@microlink.ee\r\n * ", "end": 1382, "score": 0.9998924732208252, "start": 1372, "tag": "NAME", "value": "Marko Kurm" }, { "context": "n.\r\n *\r\n * @author Marko Kurm, Microlink Eesti AS, marko.kurm@microlink.ee\r\n * @author Jaak Lember, Interinx, jaak@interinx.", "end": 1427, "score": 0.9999129772186279, "start": 1404, "tag": "EMAIL", "value": "marko.kurm@microlink.ee" }, { "context": "link Eesti AS, marko.kurm@microlink.ee\r\n * @author Jaak Lember, Interinx, jaak@interinx.com\r\n */\r\n@XTeeService(n", "end": 1451, "score": 0.9998925924301147, "start": 1440, "tag": "NAME", "value": "Jaak Lember" }, { "context": "rm@microlink.ee\r\n * @author Jaak Lember, Interinx, jaak@interinx.com\r\n */\r\n@XTeeService(name = \"deleteDocuments\", vers", "end": 1480, "score": 0.9999295473098755, "start": 1463, "tag": "EMAIL", "value": "jaak@interinx.com" } ]
null
[]
package ee.adit.ws.endpoint.document; import java.util.Calendar; import java.util.List; import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import ee.adit.dao.pojo.AditUser; import ee.adit.exception.AditCodedException; import ee.adit.exception.AditInternalException; import ee.adit.pojo.ArrayOfDocumentActionStatus; import ee.adit.pojo.ArrayOfDocumentId; import ee.adit.pojo.ArrayOfMessage; import ee.adit.pojo.DeleteDocumentRequest; import ee.adit.pojo.DeleteDocumentResponse; import ee.adit.pojo.DeleteDocumentsRequest; import ee.adit.pojo.DeleteDocumentsResponse; import ee.adit.pojo.DocumentActionStatus; import ee.adit.pojo.Message; import ee.adit.pojo.Success; import ee.adit.service.DocumentService; import ee.adit.service.LogService; import ee.adit.service.MessageService; import ee.adit.service.UserService; import ee.adit.util.Util; import ee.adit.util.xroad.CustomXRoadHeader; import ee.adit.ws.endpoint.AbstractAditBaseEndpoint; import ee.webmedia.xtee.annotation.XTeeService; import org.springframework.ws.soap.saaj.SaajSoapMessage; /** * Implementation of "deleteDocument" web method (web service request). Contains * request input validation, request-specific workflow and response composition. * * @author <NAME>, Microlink Eesti AS, <EMAIL> * @author <NAME>, Interinx, <EMAIL> */ @XTeeService(name = "deleteDocuments", version = "v1") @Component public class DeleteDocumentsEndpoint extends AbstractAditBaseEndpoint { private static Logger logger = LogManager.getLogger(DeleteDocumentsEndpoint.class); private UserService userService; private DocumentService documentService; @Override protected Object invokeInternal(Object requestObject, int version, SaajSoapMessage requestMessage, SaajSoapMessage responseMessage, CustomXRoadHeader xRoadHeader) throws Exception { logger.debug("deleteDocuments invoked. Version: " + version); if (version == 1) { return v1(requestObject, requestMessage, responseMessage, xRoadHeader); } else { throw new AditInternalException("This method does not support version specified: " + version); } } /** * Executes "V1" version of "deleteDocuments" request. * * @param requestObject * Request body object * @return Response body object */ protected Object v1(Object requestObject, SaajSoapMessage requestMessage, SaajSoapMessage responseMessage, CustomXRoadHeader xRoadHeader) { DeleteDocumentsResponse response = new DeleteDocumentsResponse(); ArrayOfMessage messages = new ArrayOfMessage(); ArrayOfDocumentActionStatus documentStatuses = new ArrayOfDocumentActionStatus(); Calendar requestDate = Calendar.getInstance(); String additionalInformationForLog = null; //Long documentId = null; ArrayOfDocumentId documents = null; boolean success = true; try { logger.debug("deleteDocument.v1 invoked."); DeleteDocumentsRequest request = (DeleteDocumentsRequest) requestObject; if (request != null) { documents = request.getDocuments(); } String applicationName = xRoadHeader.getInfosysteem(this.getConfiguration().getXteeProducerName()); // Log request Util.printHeader(xRoadHeader, this.getConfiguration()); printRequest(request); // Check header for required fields checkHeader(xRoadHeader); // Check request body checkRequest(request); // Kontrollime, kas päringu käivitanud infosüsteem on ADITis // registreeritud this.getUserService().checkApplicationRegistered(applicationName); // Kontrollime, kas päringu käivitanud infosüsteem tohib // andmeid muuta (või üldse näha) this.getUserService().checkApplicationWritePrivilege(applicationName); // Kontrollime, kas päringus märgitud isik on teenuse kasutaja AditUser user = Util.getAditUserFromXroadHeader(xRoadHeader, this.getUserService()); AditUser xroadRequestUser = Util.getXroadUserFromXroadHeader(user, xRoadHeader, this.getUserService()); // Kontrollime, et kasutajakonto ligipääs poleks peatatud (kasutaja // lahkunud) if ((user.getActive() == null) || !user.getActive()) { AditCodedException aditCodedException = new AditCodedException("user.inactive"); aditCodedException.setParameters(new Object[] {user.getUserCode()}); throw aditCodedException; } // Check whether or not the application has rights to // modify current user's data. int applicationAccessLevelForUser = userService.getAccessLevelForUser(applicationName, user); if (applicationAccessLevelForUser != 2) { AditCodedException aditCodedException = new AditCodedException( "application.insufficientPrivileges.forUser.write"); aditCodedException.setParameters(new Object[] {applicationName, user.getUserCode() }); throw aditCodedException; } for (Long documentId: request.getDocuments().getDocumentId()){ DocumentActionStatus documentStatus = new DocumentActionStatus(); documentStatus.setSuccess(true); documentStatus.setDocumentId(documentId); try { this.getDocumentService().deleteDocument(documentId, user.getUserCode(), applicationName); // If deletion was successful then add history event this.getDocumentService().addHistoryEvent(applicationName, documentId, user.getUserCode(), DocumentService.HISTORY_TYPE_DELETE, xroadRequestUser.getUserCode(), xroadRequestUser.getFullName(), DocumentService.DOCUMENT_HISTORY_DESCRIPTION_DELETE, user.getFullName(), requestDate.getTime()); } catch (Exception e) { logger.error("Exception while deleting document: ", e); documentStatus.setSuccess(false); String errorMessage = null; List<Message> errorMessages = this.getMessageService().getMessages("service.error", new Object[] {}); ArrayOfMessage documentMessages = new ArrayOfMessage(); documentMessages.setMessage(errorMessages); if (e instanceof AditCodedException) { logger.debug("Adding exception messages to response object."); documentMessages.setMessage(this.getMessageService().getMessages((AditCodedException) e)); errorMessage = this.getMessageService().getMessage(e.getMessage(), ((AditCodedException) e).getParameters(), Locale.ENGLISH); errorMessage = "ERROR: " + errorMessage; } else { documentMessages.setMessage(this.getMessageService().getMessages(MessageService.GENERIC_ERROR_CODE, new Object[]{})); errorMessage = "ERROR: " + e.getMessage(); } documentStatus.setMessages(documentMessages); success = false; additionalInformationForLog = errorMessage; super.logError(documentId, requestDate.getTime(), LogService.ERROR_LOG_LEVEL_ERROR, errorMessage, xRoadHeader); logger.debug("Adding exception messages to response object."); /*############## logger.error("Exception: ", e); String errorMessage = null; response.setSuccess(new Success(false)); ArrayOfMessage arrayOfMessage = new ArrayOfMessage(); if (e instanceof AditCodedException) { logger.debug("Adding exception messages to response object."); arrayOfMessage.setMessage(this.getMessageService().getMessages((AditCodedException) e)); errorMessage = this.getMessageService().getMessage(e.getMessage(), ((AditCodedException) e).getParameters(), Locale.ENGLISH); errorMessage = "ERROR: " + errorMessage; } else { arrayOfMessage.setMessage(this.getMessageService().getMessages(MessageService.GENERIC_ERROR_CODE, new Object[]{})); errorMessage = "ERROR: " + e.getMessage(); } additionalInformationForLog = errorMessage; super.logError(documentId, requestDate.getTime(), LogService.ERROR_LOG_LEVEL_ERROR, errorMessage); logger.debug("Adding exception messages to response object."); response.setMessages(arrayOfMessage); */ } documentStatuses.addDocument(documentStatus); } // Set response messages response.setSuccess(new Success(success)); response.setDocuments(documentStatuses); if (success) { messages.setMessage(this.getMessageService().getMessages("request.deleteDocuments.success", new Object[] {})); response.setMessages(messages); String additionalMessage = this.getMessageService().getMessage("request.deleteDocuments.success", new Object[] {}, Locale.ENGLISH); additionalInformationForLog = LogService.REQUEST_LOG_SUCCESS + ": " + additionalMessage; } else { messages.setMessage(this.getMessageService().getMessages("request.deleteDocuments.fail", new Object[] {})); response.setMessages(messages); String additionalMessage = this.getMessageService().getMessage("request.deleteDocuments.fail", new Object[] {}, Locale.ENGLISH); additionalInformationForLog = LogService.REQUEST_LOG_SUCCESS + ": " + additionalMessage; } response.setMessages(messages); } catch (Exception e) { logger.error("Exception: ", e); String errorMessage = null; response.setSuccess(new Success(false)); ArrayOfMessage arrayOfMessage = new ArrayOfMessage(); if (e instanceof AditCodedException) { logger.debug("Adding exception messages to response object."); arrayOfMessage.setMessage(this.getMessageService().getMessages((AditCodedException) e)); errorMessage = this.getMessageService().getMessage(e.getMessage(), ((AditCodedException) e).getParameters(), Locale.ENGLISH); errorMessage = "ERROR: " + errorMessage; } else { arrayOfMessage.setMessage(this.getMessageService().getMessages(MessageService.GENERIC_ERROR_CODE, new Object[]{})); errorMessage = "ERROR: " + e.getMessage(); } additionalInformationForLog = errorMessage; super.logError(null, requestDate.getTime(), LogService.ERROR_LOG_LEVEL_ERROR, errorMessage, xRoadHeader); logger.debug("Adding exception messages to response object."); response.setMessages(arrayOfMessage); } super.logCurrentRequest(null, requestDate.getTime(), additionalInformationForLog, xRoadHeader); return response; } @Override protected Object getResultForGenericException(Exception ex, SaajSoapMessage requestMessage, SaajSoapMessage responseMessage, CustomXRoadHeader xRoadHeader) { super.logError(null, Calendar.getInstance().getTime(), LogService.ERROR_LOG_LEVEL_FATAL, "ERROR: " + ex.getMessage(), xRoadHeader); DeleteDocumentResponse response = new DeleteDocumentResponse(); response.setSuccess(new Success(false)); ArrayOfMessage arrayOfMessage = new ArrayOfMessage(); arrayOfMessage.getMessage().add(new Message("en", ex.getMessage())); response.setMessages(arrayOfMessage); return response; } /** * Validates request body and makes sure that all required fields exist and * are not empty. <br> * <br> * Throws {@link AditCodedException} if any errors in request data are * found. * * @param request * Request body as {@link DeleteDocumentsRequest} object. * @throws AditCodedException * Exception describing error found in request body. */ private void checkRequest(DeleteDocumentsRequest request) throws AditCodedException { if (request !=null) { if ((request.getDocuments() == null) || (request.getDocuments().getDocumentId() == null) || request.getDocuments().getDocumentId().isEmpty()){ throw new AditCodedException("request.deleteDocuments.documents.notSpecified"); } else if (request != null && request.getDocuments().getDocumentId().isEmpty()) { for (Long documentId: request.getDocuments().getDocumentId()) { if (documentId <= 0) { throw new AditCodedException("request.body.undefined.documentId"); } } } } else { throw new AditCodedException("request.body.empty"); } } /** * Writes request parameters to application DEBUG log. * * @param request * Request body as {@link DeleteDocumentRequest} object. */ private void printRequest(DeleteDocumentsRequest request) { logger.debug("-------- DeleteDocumentRequest -------"); logger.debug("Documents: " + String.valueOf(request.getDocuments().toString())); logger.debug("--------------------------------------"); } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public DocumentService getDocumentService() { return documentService; } public void setDocumentService(DocumentService documentService) { this.documentService = documentService; } }
15,186
0.614479
0.613822
324
44.938271
35.882042
185
false
false
0
0
0
0
0
0
0.802469
false
false
10
fac62d5dab7321d527270a1082d87b758e91a1fa
34,136,400,088,040
fa31a0fc93f6cb86291889d635d6eec54a66af73
/src/ksomemo/b1/ch10/Main.java
aac1a227f50f0b07c4ad4995262d6fb7e8e2533c
[]
no_license
ksomemo/java-study
https://github.com/ksomemo/java-study
8e5313cffe1479543ef51e4b02adf168670c5dda
a2f4343c1f3e0379f0915ae81f9df70f073f0fff
refs/heads/master
2021-01-01T05:35:36.088000
2014-08-31T13:39:00
2014-08-31T13:39:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ksomemo.b1.ch10; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; class Main { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.print(">input:"); System.out.println("input is " + br.readLine()); System.out.println(Integer.parseInt("100")); System.out.println(Double.parseDouble("100.0")); try { Integer.parseInt("a"); } catch (NumberFormatException e) { System.err.println(e.getMessage()); System.err.println(e); // e.getStackTrace() } Scanner sc = new Scanner(System.in); sc.useDelimiter(","); while (sc.hasNext()) { String s = sc.next(); System.out.println("s:" + s); if (s.equals("end")) break; } } }
UTF-8
Java
998
java
Main.java
Java
[]
null
[]
package ksomemo.b1.ch10; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; class Main { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.print(">input:"); System.out.println("input is " + br.readLine()); System.out.println(Integer.parseInt("100")); System.out.println(Double.parseDouble("100.0")); try { Integer.parseInt("a"); } catch (NumberFormatException e) { System.err.println(e.getMessage()); System.err.println(e); // e.getStackTrace() } Scanner sc = new Scanner(System.in); sc.useDelimiter(","); while (sc.hasNext()) { String s = sc.next(); System.out.println("s:" + s); if (s.equals("end")) break; } } }
998
0.59018
0.58016
35
27.514286
20.908468
65
false
false
0
0
0
0
0
0
0.571429
false
false
10
2ff1da956e999b18ca35a633a34a0f34ba2d639a
27,315,992,060,572
ebaa0055554710c2ab78ec712462e702fcfb997a
/Esercizi/Metodi/Esercizio-16/MagicBallTest.java
521e4972a782b9894c879d147e93b37194d83793
[]
no_license
leonardo-rinaldi/Java-projects
https://github.com/leonardo-rinaldi/Java-projects
4f4c1fcd472921004691f83608250743f56c1797
17c0c5cc487fca390c6d39af428d069aa4f6891a
refs/heads/master
2021-04-23T22:40:52.396000
2020-11-25T17:19:02
2020-11-25T17:19:02
250,022,841
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package metodi; import java.util.Scanner; /* * Test del metodo pallaMagica. */ public class MagicBallTest { public static void main(String[] args) { String domanda, risposta; Scanner tastiera = new Scanner(System.in); do { System.out.println("Fai una domanda alla palla magica e riceverai una risposta"); domanda = tastiera.nextLine(); System.out.println(MagicBall.pallaMagica()); System.out.println(); System.out.println("Vuoi fare un'altra domanda alla palla magica?"); System.out.println("Rispondi si oppure no"); risposta = tastiera.nextLine(); } while(risposta.equalsIgnoreCase("si")); } }
UTF-8
Java
653
java
MagicBallTest.java
Java
[]
null
[]
package metodi; import java.util.Scanner; /* * Test del metodo pallaMagica. */ public class MagicBallTest { public static void main(String[] args) { String domanda, risposta; Scanner tastiera = new Scanner(System.in); do { System.out.println("Fai una domanda alla palla magica e riceverai una risposta"); domanda = tastiera.nextLine(); System.out.println(MagicBall.pallaMagica()); System.out.println(); System.out.println("Vuoi fare un'altra domanda alla palla magica?"); System.out.println("Rispondi si oppure no"); risposta = tastiera.nextLine(); } while(risposta.equalsIgnoreCase("si")); } }
653
0.689127
0.689127
31
20.064516
22.528742
84
false
false
0
0
0
0
0
0
1.870968
false
false
10
7d377061e3c89160f5ddc95dd5332fb5a9165537
9,904,194,609,585
7e6dc87f6ec220070ddd7bd632f50e2120769d7c
/src/com/fighting/principle/liskov/demo1/B.java
c1e6cb8cd574d8f9c8daba0f69980be4423ea4e9
[]
no_license
helloworld404/designPattern
https://github.com/helloworld404/designPattern
5ed95d5be72378363551977ab61c10bd88e6ac90
a3cada00edcea3ea6577bf46ae7e1c1a0e7a1baf
refs/heads/master
2022-09-21T21:15:33.373000
2020-06-06T17:06:50
2020-06-06T17:06:50
258,835,381
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fighting.principle.liskov.demo1; public class B extends A { //这里,重写了 A 类的方法, 可能是无意识 public int func1(int a, int b) { return a + b; } public int func2(int a, int b) { return func1(a, b) + 9; } }
UTF-8
Java
277
java
B.java
Java
[]
null
[]
package com.fighting.principle.liskov.demo1; public class B extends A { //这里,重写了 A 类的方法, 可能是无意识 public int func1(int a, int b) { return a + b; } public int func2(int a, int b) { return func1(a, b) + 9; } }
277
0.571429
0.55102
12
19.333334
15.547419
44
false
false
0
0
0
0
0
0
0.583333
false
false
10
bb0a8a72037bd23460abcf4e9c09147d4ca4153f
9,904,194,610,701
17d0c775c7198a7f58be398754b6ffb41c593110
/archive/blazegraph/src/main/java/gov/pnnl/goss/cim2glm/components/DistXfmrCodeOCTest.java
74ec5f983c775ba6b34c92a503eee50a72860558
[]
no_license
GRIDAPPSD/Powergrid-Models
https://github.com/GRIDAPPSD/Powergrid-Models
1802d6795840d71eabcbd678b6afdcb96ff0e0cb
2ec0ba442b4ef30206c71eab205758e18a77a564
refs/heads/develop
2023-06-08T01:07:22.730000
2023-06-06T18:03:40
2023-06-06T18:03:40
74,505,030
27
29
null
false
2023-06-06T18:03:42
2016-11-22T19:13:52
2023-03-12T15:27:51
2023-06-06T18:03:40
443,374
26
23
5
Java
false
false
package gov.pnnl.goss.cim2glm.components; // ---------------------------------------------------------- // Copyright (c) 2017, Battelle Memorial Institute // All rights reserved. // ---------------------------------------------------------- import org.apache.jena.query.*; public class DistXfmrCodeOCTest extends DistComponent { public static final String szQUERY = "SELECT DISTINCT ?pname ?tname ?nll ?iexc WHERE {"+ " ?fdr c:IdentifiedObject.mRID ?fdrid."+ " ?xft c:TransformerTank.PowerTransformer ?eq."+ " ?eq c:Equipment.EquipmentContainer ?fdr."+ " ?asset c:Asset.PowerSystemResources ?xft."+ " ?asset c:Asset.AssetInfo ?t."+ " ?p r:type c:PowerTransformerInfo."+ " ?p c:IdentifiedObject.name ?pname."+ " ?t c:TransformerTankInfo.PowerTransformerInfo ?p."+ " ?t c:IdentifiedObject.name ?tname."+ " ?e c:TransformerEndInfo.TransformerTankInfo ?t."+ " ?nlt c:NoLoadTest.EnergisedEnd ?e."+ " ?nlt c:NoLoadTest.loss ?nll."+ " ?nlt c:NoLoadTest.excitingCurrent ?iexc."+ "} ORDER BY ?pname ?tname"; public String pname; public String tname; public double nll; public double iexc; public String GetJSONEntry () { StringBuilder buf = new StringBuilder (); buf.append ("{\"name\":\"" + pname +"\""); buf.append ("}"); return buf.toString(); } public DistXfmrCodeOCTest (ResultSet results) { if (results.hasNext()) { QuerySolution soln = results.next(); pname = SafeName (soln.get("?pname").toString()); tname = SafeName (soln.get("?tname").toString()); nll = Double.parseDouble (soln.get("?nll").toString()); iexc = Double.parseDouble (soln.get("?iexc").toString()); } } public String DisplayString() { StringBuilder buf = new StringBuilder (""); buf.append (pname + ":" + tname + " NLL=" + df4.format(nll) + " iexc=" + df4.format(iexc)); return buf.toString(); } public String GetKey() { return tname; } }
UTF-8
Java
1,894
java
DistXfmrCodeOCTest.java
Java
[]
null
[]
package gov.pnnl.goss.cim2glm.components; // ---------------------------------------------------------- // Copyright (c) 2017, Battelle Memorial Institute // All rights reserved. // ---------------------------------------------------------- import org.apache.jena.query.*; public class DistXfmrCodeOCTest extends DistComponent { public static final String szQUERY = "SELECT DISTINCT ?pname ?tname ?nll ?iexc WHERE {"+ " ?fdr c:IdentifiedObject.mRID ?fdrid."+ " ?xft c:TransformerTank.PowerTransformer ?eq."+ " ?eq c:Equipment.EquipmentContainer ?fdr."+ " ?asset c:Asset.PowerSystemResources ?xft."+ " ?asset c:Asset.AssetInfo ?t."+ " ?p r:type c:PowerTransformerInfo."+ " ?p c:IdentifiedObject.name ?pname."+ " ?t c:TransformerTankInfo.PowerTransformerInfo ?p."+ " ?t c:IdentifiedObject.name ?tname."+ " ?e c:TransformerEndInfo.TransformerTankInfo ?t."+ " ?nlt c:NoLoadTest.EnergisedEnd ?e."+ " ?nlt c:NoLoadTest.loss ?nll."+ " ?nlt c:NoLoadTest.excitingCurrent ?iexc."+ "} ORDER BY ?pname ?tname"; public String pname; public String tname; public double nll; public double iexc; public String GetJSONEntry () { StringBuilder buf = new StringBuilder (); buf.append ("{\"name\":\"" + pname +"\""); buf.append ("}"); return buf.toString(); } public DistXfmrCodeOCTest (ResultSet results) { if (results.hasNext()) { QuerySolution soln = results.next(); pname = SafeName (soln.get("?pname").toString()); tname = SafeName (soln.get("?tname").toString()); nll = Double.parseDouble (soln.get("?nll").toString()); iexc = Double.parseDouble (soln.get("?iexc").toString()); } } public String DisplayString() { StringBuilder buf = new StringBuilder (""); buf.append (pname + ":" + tname + " NLL=" + df4.format(nll) + " iexc=" + df4.format(iexc)); return buf.toString(); } public String GetKey() { return tname; } }
1,894
0.629356
0.62566
59
31.084745
21.321817
93
false
false
0
0
0
0
0
0
1.779661
false
false
10
aa8ab24eff80535115a1228fdc015a0ae38339b0
18,803,366,877,765
1082ea69cc6a5ddc23250aa0089eda73f6ead878
/app/src/main/java/lzuer/net/playground/util/time/TimeUtil.java
84b09782061b9a567bd6ebfb8f2227fd4308c181
[]
no_license
lichunqiang/playground
https://github.com/lichunqiang/playground
657d84c143443aaae411daab9d5a5c7d9a61817e
9f736246cd94d3ef6e88b5f19a95333005c955a3
refs/heads/master
2016-09-13T08:26:56.277000
2016-05-24T06:09:19
2016-05-24T06:09:19
58,509,886
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lzuer.net.playground.util.time; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Created by chunqiang on 2016/5/19. */ public class TimeUtil { public static final long DAY = 86400; /** * convert to 2016-05-12 * @param time long 毫秒,如果是秒需要转成毫秒 * @return String */ public static String Long2Date(long time) { Date currentTime = new Date(time); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA); return formatter.format(currentTime); } /** * * @param time long * @return String */ public static String Long2DateTime(long time) { Date currentTime = new Date(time); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA); return formatter.format(currentTime); } /** * * @param time long * @return String */ public static String Long2Time(long time) { Date currentTime = new Date(time); SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", Locale.CHINA); return formatter.format(currentTime); } /** * String(yyyy-MM-dd HH:mm:ss)转10位时间戳 * @param time int * @return Integer */ public static Integer String2Timestamp(String time) { int times = 0; try { times = (int) (Timestamp.valueOf(time).getTime() / 1000); } catch (Exception e) { e.printStackTrace(); } return times; } public static String getRelativeTime(long startTime) { long currentTimeWithSecond = System.currentTimeMillis() / 1000; long timeDiff = currentTimeWithSecond - startTime / 1000; //相差毫秒数 if (timeDiff == 0) { return "刚刚"; } String time; if (timeDiff > 30* DAY) { //一个月以上 time = Long2Date(startTime); } else if (timeDiff > DAY) { //1天以上 time = Long2DateTime(startTime); } else if (timeDiff > 3600) { //1小时上 time = timeDiff / 3600 + "小时前"; } else if (timeDiff > 60) { time = timeDiff / 60 + "分钟前"; } else { time = timeDiff + "秒前"; } return time; } }
UTF-8
Java
2,392
java
TimeUtil.java
Java
[ { "context": ".Date;\nimport java.util.Locale;\n\n/**\n * Created by chunqiang on 2016/5/19.\n */\npublic class TimeUtil {\n pub", "end": 179, "score": 0.9996707439422607, "start": 170, "tag": "USERNAME", "value": "chunqiang" } ]
null
[]
package lzuer.net.playground.util.time; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Created by chunqiang on 2016/5/19. */ public class TimeUtil { public static final long DAY = 86400; /** * convert to 2016-05-12 * @param time long 毫秒,如果是秒需要转成毫秒 * @return String */ public static String Long2Date(long time) { Date currentTime = new Date(time); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA); return formatter.format(currentTime); } /** * * @param time long * @return String */ public static String Long2DateTime(long time) { Date currentTime = new Date(time); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA); return formatter.format(currentTime); } /** * * @param time long * @return String */ public static String Long2Time(long time) { Date currentTime = new Date(time); SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", Locale.CHINA); return formatter.format(currentTime); } /** * String(yyyy-MM-dd HH:mm:ss)转10位时间戳 * @param time int * @return Integer */ public static Integer String2Timestamp(String time) { int times = 0; try { times = (int) (Timestamp.valueOf(time).getTime() / 1000); } catch (Exception e) { e.printStackTrace(); } return times; } public static String getRelativeTime(long startTime) { long currentTimeWithSecond = System.currentTimeMillis() / 1000; long timeDiff = currentTimeWithSecond - startTime / 1000; //相差毫秒数 if (timeDiff == 0) { return "刚刚"; } String time; if (timeDiff > 30* DAY) { //一个月以上 time = Long2Date(startTime); } else if (timeDiff > DAY) { //1天以上 time = Long2DateTime(startTime); } else if (timeDiff > 3600) { //1小时上 time = timeDiff / 3600 + "小时前"; } else if (timeDiff > 60) { time = timeDiff / 60 + "分钟前"; } else { time = timeDiff + "秒前"; } return time; } }
2,392
0.578559
0.553385
86
25.790697
22.059706
92
false
false
0
0
0
0
0
0
0.372093
false
false
10
0b4c868b3fbc8ad9c99b3d4a6054bb32a755b884
6,287,832,153,649
6f12e700e0a7347ff66172a46119317ec8a5db17
/web/src/main/java/com/epam/esm/web/config/WebConfig.java
00440b0cf07568eedd096aa58576ef568800dee3
[]
no_license
Okami-Kato/Gift-Certificates-System
https://github.com/Okami-Kato/Gift-Certificates-System
9f8a2f8ddee946a38ac4bf87518141ad29e45416
51997bef97e37441f58960ba940b054c6636b449
refs/heads/master
2023-07-15T15:03:11.814000
2021-09-05T17:46:56
2021-09-05T17:46:56
398,289,252
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.epam.esm.web.config; import com.epam.esm.service.config.ServiceConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import javax.annotation.PostConstruct; @Configuration @EnableWebMvc @ComponentScan("com.epam.esm.web") @Import({ServiceConfig.class}) public class WebConfig { @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } @PostConstruct public void setUp() { objectMapper().registerModule(new JavaTimeModule()); } }
UTF-8
Java
864
java
WebConfig.java
Java
[]
null
[]
package com.epam.esm.web.config; import com.epam.esm.service.config.ServiceConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import javax.annotation.PostConstruct; @Configuration @EnableWebMvc @ComponentScan("com.epam.esm.web") @Import({ServiceConfig.class}) public class WebConfig { @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } @PostConstruct public void setUp() { objectMapper().registerModule(new JavaTimeModule()); } }
864
0.790509
0.787037
28
29.857143
22.403307
70
false
false
0
0
0
0
0
0
0.428571
false
false
12
f6e02ee254f63568b3701eff7a6cd8e0821ad6cc
14,809,047,288,726
909965d28fa983e8956ca90cc51ba00b9691175e
/src/main/java/com/crm/cust/service/IUmsAdminService.java
3d01f8ebd9e49815748023111daaf0e26290fe24
[]
no_license
wobuzhidaoqishenmemmingzi/CRM
https://github.com/wobuzhidaoqishenmemmingzi/CRM
b675bdc8762ae2acdfe46c6d5743d232476e1d3b
4e6f04bd837085760f10e476b7c90996da716f8d
refs/heads/master
2022-12-17T21:28:06.523000
2020-09-14T14:33:18
2020-09-14T14:33:18
295,138,245
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.crm.cust.service; import com.crm.cust.entity.UmsAdmin; import com.baomidou.mybatisplus.extension.service.IService; import org.springframework.security.core.userdetails.UserDetails; import java.util.List; /** * <p> * 后台用户表 服务类 * </p> * * @author lvhd * @since 2020-09-10 */ public interface IUmsAdminService extends IService<UmsAdmin> { /** * 获取用户信息 */ UmsAdmin loadUserByUsername(String username); /** * 根据用户名获取所有用户 * @param userName * @return */ List<UmsAdmin> getUmsAdminByUserName(String userName); /** * 根据用户名模糊查询用户信息分页 * @param userName * @param pageSize * @param pageNum * @return */ List<UmsAdmin> getListLikeUserNamePage(String userName, Integer pageSize, Integer pageNum); }
UTF-8
Java
873
java
IUmsAdminService.java
Java
[ { "context": "st;\n\n/**\n * <p>\n * 后台用户表 服务类\n * </p>\n *\n * @author lvhd\n * @since 2020-09-10\n */\npublic interface IUmsAdm", "end": 269, "score": 0.9996593594551086, "start": 265, "tag": "USERNAME", "value": "lvhd" } ]
null
[]
package com.crm.cust.service; import com.crm.cust.entity.UmsAdmin; import com.baomidou.mybatisplus.extension.service.IService; import org.springframework.security.core.userdetails.UserDetails; import java.util.List; /** * <p> * 后台用户表 服务类 * </p> * * @author lvhd * @since 2020-09-10 */ public interface IUmsAdminService extends IService<UmsAdmin> { /** * 获取用户信息 */ UmsAdmin loadUserByUsername(String username); /** * 根据用户名获取所有用户 * @param userName * @return */ List<UmsAdmin> getUmsAdminByUserName(String userName); /** * 根据用户名模糊查询用户信息分页 * @param userName * @param pageSize * @param pageNum * @return */ List<UmsAdmin> getListLikeUserNamePage(String userName, Integer pageSize, Integer pageNum); }
873
0.667087
0.656999
39
19.333334
21.965397
95
false
false
0
0
0
0
0
0
0.25641
false
false
12
a0a9061def57b192ae53f9f00c91a998c733805b
14,809,047,287,135
0131a166e0c3c68e71ec94ef488f468699f9480b
/src/main/java/com/rdas/perftest/model/Address.java
fea1fcab46d52d81c6b88290c73d9303b9e21078
[]
no_license
ranadas/gatling-performance-testing
https://github.com/ranadas/gatling-performance-testing
bb73e7b3624d9c2932f92b4022ccd606484789be
688acff9423c657885aead4821fd5b126e61828b
refs/heads/master
2020-03-23T18:27:13.396000
2018-07-23T05:33:26
2018-07-23T05:33:26
141,909,604
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rdas.perftest.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable @NoArgsConstructor @AllArgsConstructor @Getter @Setter public class Address { private String country; private String city; @Column(name = "postal_code") private String postalCode; private String street; @Column(name = "house_no") private int houseNo; @Column(name = "flat_no") private int flatNo; }
UTF-8
Java
565
java
Address.java
Java
[]
null
[]
package com.rdas.perftest.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable @NoArgsConstructor @AllArgsConstructor @Getter @Setter public class Address { private String country; private String city; @Column(name = "postal_code") private String postalCode; private String street; @Column(name = "house_no") private int houseNo; @Column(name = "flat_no") private int flatNo; }
565
0.746903
0.746903
27
19.925926
11.900594
36
false
false
0
0
0
0
0
0
0.481481
false
false
12
3e514dd7183dd533119dbdc9915174320cc65b81
24,988,119,773,759
8ea96821e33804438afd066dd0e4780f16e40253
/login2/app/src/main/java/com/hypermart/login/SignIn.java
65389e67d29aa5f09673c413480cfe2c3ba09286
[]
no_license
vimanga/Madnew
https://github.com/vimanga/Madnew
51883b9b688643ff7ed6adaff05e263270b61b88
e3b95f3e72589b495515e4dd04603eae7773b306
refs/heads/master
2020-03-26T00:07:08.952000
2018-08-10T16:04:18
2018-08-10T16:04:18
144,307,051
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hypermart.login; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class SignIn extends AppCompatActivity { Button b; TextView txtView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); txtView = this.findViewById(R.id.signuptxt); txtView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(SignIn.this, "Loading Sign Up Page", Toast.LENGTH_SHORT).show(); SignIn.this.startActivity(new Intent(SignIn.this, SignUp.class)); } }); b = findViewById(R.id.signin); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(SignIn.this, "Loading Main Page", Toast.LENGTH_SHORT).show(); SignIn.this.startActivity(new Intent(SignIn.this, Main.class)); } }); } }
UTF-8
Java
1,279
java
SignIn.java
Java
[]
null
[]
package com.hypermart.login; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class SignIn extends AppCompatActivity { Button b; TextView txtView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); txtView = this.findViewById(R.id.signuptxt); txtView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(SignIn.this, "Loading Sign Up Page", Toast.LENGTH_SHORT).show(); SignIn.this.startActivity(new Intent(SignIn.this, SignUp.class)); } }); b = findViewById(R.id.signin); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(SignIn.this, "Loading Main Page", Toast.LENGTH_SHORT).show(); SignIn.this.startActivity(new Intent(SignIn.this, Main.class)); } }); } }
1,279
0.645035
0.644253
45
27.444445
26.363743
95
false
false
0
0
0
0
0
0
0.577778
false
false
12
e020babc4ec099cde0ae4343b0916556ced3d249
27,839,978,026,382
31a68a694120e47505a7b628a6b9f232618378e2
/peony-tancms/src/main/java/com/peony/peonyfront/warningkeyws/dao/WarningkeywsMapper.java
cea29f41ec936ceb8b66af2801f2a6f5f35e7222
[]
no_license
ganzhiping/peony-newTancms
https://github.com/ganzhiping/peony-newTancms
1b02ad1f137c882147c756230e0cb28cbb7823ab
cf2eb49ea5728e9338138ada2c29f6853b95cffd
refs/heads/master
2021-01-16T21:29:55.002000
2018-03-23T02:15:10
2018-03-23T02:15:10
100,232,075
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.peony.peonyfront.warningkeyws.dao; import java.util.List; import com.peony.peonyfront.warningkeyws.model.Warningkeyws; public interface WarningkeywsMapper { int deleteByPrimaryKey(Integer warningkeywsId); int insert(Warningkeyws record); int insertSelective(Warningkeyws record); Warningkeyws selectByPrimaryKey(Integer warningkeywsId); int updateByPrimaryKeySelective(Warningkeyws record); int updateByPrimaryKey(Warningkeyws record); List<Warningkeyws> selectByPage(Warningkeyws warningkeyws); }
UTF-8
Java
546
java
WarningkeywsMapper.java
Java
[]
null
[]
package com.peony.peonyfront.warningkeyws.dao; import java.util.List; import com.peony.peonyfront.warningkeyws.model.Warningkeyws; public interface WarningkeywsMapper { int deleteByPrimaryKey(Integer warningkeywsId); int insert(Warningkeyws record); int insertSelective(Warningkeyws record); Warningkeyws selectByPrimaryKey(Integer warningkeywsId); int updateByPrimaryKeySelective(Warningkeyws record); int updateByPrimaryKey(Warningkeyws record); List<Warningkeyws> selectByPage(Warningkeyws warningkeyws); }
546
0.804029
0.804029
21
25.047619
25.297235
63
false
false
0
0
0
0
0
0
0.47619
false
false
12
e83a49af499474a6f4d333f893f697dd934d85fa
16,638,703,361,126
30db3bfc31a6c10cfa70eaaa025c3935324f7fc4
/item/src/main/java/org/exnihilo/Item/util/cytoscapeDTO/edges.java
7d806a06d6d9d2fdd025950a7dd81dc5ade50345
[]
no_license
marcola1910/item
https://github.com/marcola1910/item
5364269e060ed56a96400555b5a6d5ec18e9ae27
17e5e69337ac845a375b5a882cc77297a9374dcb
refs/heads/master
2020-05-22T00:04:15.317000
2017-01-18T15:34:06
2017-01-18T15:34:06
62,510,598
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.exnihilo.Item.util.cytoscapeDTO; import java.util.ArrayList; import java.util.Collection; public class edges { private Collection<datanode> data = new ArrayList<datanode>(); public edges() { // TODO Auto-generated constructor stub } @SuppressWarnings("rawtypes") public Collection getData() { return data; } @SuppressWarnings("unchecked") public void setData(@SuppressWarnings("rawtypes") Collection data) { this.data = data; } }
UTF-8
Java
466
java
edges.java
Java
[]
null
[]
package org.exnihilo.Item.util.cytoscapeDTO; import java.util.ArrayList; import java.util.Collection; public class edges { private Collection<datanode> data = new ArrayList<datanode>(); public edges() { // TODO Auto-generated constructor stub } @SuppressWarnings("rawtypes") public Collection getData() { return data; } @SuppressWarnings("unchecked") public void setData(@SuppressWarnings("rawtypes") Collection data) { this.data = data; } }
466
0.733906
0.733906
24
18.416666
20.277073
69
false
false
0
0
0
0
0
0
0.916667
false
false
12
d454f949631b3c57118e4921c9c81834a8d7e5e0
14,800,457,339,437
b90ed9bd2f3dce91604156e19cf08b6649370b49
/app/src/main/java/com/martin/fruit/readdb/FruitActivity.java
0e5817a5a7c9a8c1e7fc4a3f7fe5bc99b3026569
[ "Apache-2.0" ]
permissive
MartinXu1909/Fruit
https://github.com/MartinXu1909/Fruit
9797e5ec3668ffc517c8a3303a57b7f587400280
c731b53f9ccf0934aaf4259fa820e6ed4b219664
refs/heads/master
2021-01-20T05:26:10.896000
2017-05-05T15:28:44
2017-05-05T15:28:44
89,781,579
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.martin.fruit.readdb; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.webkit.WebView; import com.martin.fruit.R; /** * Created by Martin on 2017/4/29 0029. */ public class FruitActivity extends AppCompatActivity { public static final String FRUIT_INTRODUCE = "fruit_introduce"; public static final String FRUIT_IMAGE_ID = "fruit_image_id"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fruit); Intent intent = getIntent(); String intraduce = intent.getStringExtra(FRUIT_INTRODUCE); // String imageString = intent.getStringExtra(FRUIT_IMAGE_ID); // ImageView fruitImage = (ImageView) findViewById(R.id.image); // Bitmap image = MyBaseAdapter.getImageFromAssetsFile(this, imageString); // fruitImage.setImageBitmap(image); WebView webView = (WebView) findViewById(R.id.web); webView.loadDataWithBaseURL(null, intraduce, "text/html", "utf-8", null); } }
UTF-8
Java
1,172
java
FruitActivity.java
Java
[ { "context": "\r\nimport com.martin.fruit.R;\r\n\r\n/**\r\n * Created by Martin on 2017/4/29 0029.\r\n */\r\n\r\npublic class FruitActi", "end": 234, "score": 0.6491421461105347, "start": 228, "tag": "NAME", "value": "Martin" } ]
null
[]
package com.martin.fruit.readdb; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.webkit.WebView; import com.martin.fruit.R; /** * Created by Martin on 2017/4/29 0029. */ public class FruitActivity extends AppCompatActivity { public static final String FRUIT_INTRODUCE = "fruit_introduce"; public static final String FRUIT_IMAGE_ID = "fruit_image_id"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fruit); Intent intent = getIntent(); String intraduce = intent.getStringExtra(FRUIT_INTRODUCE); // String imageString = intent.getStringExtra(FRUIT_IMAGE_ID); // ImageView fruitImage = (ImageView) findViewById(R.id.image); // Bitmap image = MyBaseAdapter.getImageFromAssetsFile(this, imageString); // fruitImage.setImageBitmap(image); WebView webView = (WebView) findViewById(R.id.web); webView.loadDataWithBaseURL(null, intraduce, "text/html", "utf-8", null); } }
1,172
0.687713
0.676621
32
34.625
26.149509
81
false
false
0
0
0
0
0
0
0.71875
false
false
12
6452580db57fffa51cfaf40312b4d36b081db8a7
6,820,408,095,718
e9d555f5046cc4f985c64cf34b4c2f962d6ce39c
/src/main/java/com/rest/shoppinglist/services/impl/ShoppingListServiceImpl.java
6c4e17b9a0958a6420497a5ab075d22ec6649bd4
[]
no_license
faahta/shopping-list
https://github.com/faahta/shopping-list
b163632502628e82d34f801dd2c4d34b1d9f660c
165bd28c74e9ef0320deb923a107bdb05425aea1
refs/heads/master
2023-01-23T16:21:35.813000
2020-12-06T04:52:26
2020-12-06T04:52:26
318,952,929
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rest.shoppinglist.services.impl; import com.rest.shoppinglist.dao.ShoppingListDao; import com.rest.shoppinglist.models.Item; import com.rest.shoppinglist.models.ShoppingList; import com.rest.shoppinglist.services.ShoppingListService; import org.springframework.stereotype.Service; import java.util.List; /** * Created by Fassil on 05/12/20. */ @Service public class ShoppingListServiceImpl implements ShoppingListService { final ShoppingListDao shoppingListDao; public ShoppingListServiceImpl(ShoppingListDao shoppingListDao) { this.shoppingListDao = shoppingListDao; } @Override public List<ShoppingList> getShoppingList(Integer userId) { return this.shoppingListDao.getShoppingList(userId); } @Override public void createList(ShoppingList shoppingList) { this.shoppingListDao.createShoppingList(shoppingList); } @Override public void addItemToList(Integer listId, Item item) { this.shoppingListDao.addItemToList(listId, item); } @Override public void removeItem(Integer listId, Integer itemId) { this.shoppingListDao.removeItem(listId, itemId); } @Override public void deleteList(Integer listId) { this.shoppingListDao.deleteShoppingList(listId); } }
UTF-8
Java
1,297
java
ShoppingListServiceImpl.java
Java
[ { "context": "ervice;\n\nimport java.util.List;\n\n/**\n * Created by Fassil on 05/12/20.\n */\n@Service\npublic class ShoppingLi", "end": 343, "score": 0.9969382286071777, "start": 337, "tag": "NAME", "value": "Fassil" } ]
null
[]
package com.rest.shoppinglist.services.impl; import com.rest.shoppinglist.dao.ShoppingListDao; import com.rest.shoppinglist.models.Item; import com.rest.shoppinglist.models.ShoppingList; import com.rest.shoppinglist.services.ShoppingListService; import org.springframework.stereotype.Service; import java.util.List; /** * Created by Fassil on 05/12/20. */ @Service public class ShoppingListServiceImpl implements ShoppingListService { final ShoppingListDao shoppingListDao; public ShoppingListServiceImpl(ShoppingListDao shoppingListDao) { this.shoppingListDao = shoppingListDao; } @Override public List<ShoppingList> getShoppingList(Integer userId) { return this.shoppingListDao.getShoppingList(userId); } @Override public void createList(ShoppingList shoppingList) { this.shoppingListDao.createShoppingList(shoppingList); } @Override public void addItemToList(Integer listId, Item item) { this.shoppingListDao.addItemToList(listId, item); } @Override public void removeItem(Integer listId, Integer itemId) { this.shoppingListDao.removeItem(listId, itemId); } @Override public void deleteList(Integer listId) { this.shoppingListDao.deleteShoppingList(listId); } }
1,297
0.747109
0.742483
47
26.595745
25.120695
69
false
false
0
0
0
0
0
0
0.382979
false
false
12
24b2122be8d8a8220b3ab753057a9189019bfb57
9,234,179,715,813
08311a6b313b0a59a5c534174c61bc3b089fcb37
/financials/egf-budget/src/main/java/org/egov/egf/budget/domain/service/BudgetReAppropriationService.java
d7456674fbd96a341d2d74b3c5bb68510bb663d3
[]
no_license
soumyaghosh13/egov-services
https://github.com/soumyaghosh13/egov-services
2bd61403d33343b0546850f8a7ffcdb04a6a6c2c
6fb737aaf876b26d758acc590895a8635e6e61e1
refs/heads/master
2021-01-19T14:49:44.055000
2017-08-21T07:45:14
2017-08-21T07:45:14
100,927,188
0
0
null
true
2017-08-21T07:51:08
2017-08-21T07:51:08
2017-07-12T06:05:46
2017-08-21T07:45:21
106,152
0
0
0
null
null
null
/* * eGov suite of products aim to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) <2015> eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org. */ package org.egov.egf.budget.domain.service; import java.util.List; import org.egov.common.contract.request.RequestInfo; import org.egov.common.domain.exception.CustomBindException; import org.egov.common.domain.exception.InvalidDataException; import org.egov.common.domain.model.Pagination; import org.egov.egf.budget.domain.model.BudgetDetail; import org.egov.egf.budget.domain.model.BudgetReAppropriation; import org.egov.egf.budget.domain.model.BudgetReAppropriationSearch; import org.egov.egf.budget.domain.repository.BudgetDetailRepository; import org.egov.egf.budget.domain.repository.BudgetReAppropriationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.validation.SmartValidator; @Service @Transactional(readOnly = true) public class BudgetReAppropriationService { public static final String ACTION_CREATE = "create"; public static final String ACTION_UPDATE = "update"; public static final String ACTION_DELETE = "delete"; public static final String ACTION_VIEW = "view"; public static final String ACTION_EDIT = "edit"; public static final String ACTION_SEARCH = "search"; private final BudgetReAppropriationRepository budgetReAppropriationRepository; private final SmartValidator validator; private final BudgetDetailRepository budgetDetailRepository; @Autowired public BudgetReAppropriationService(final BudgetReAppropriationRepository budgetReAppropriationRepository, final SmartValidator validator, final BudgetDetailRepository budgetDetailRepository) { this.budgetReAppropriationRepository = budgetReAppropriationRepository; this.validator = validator; this.budgetDetailRepository = budgetDetailRepository; } @Transactional public List<BudgetReAppropriation> create(List<BudgetReAppropriation> budgetReAppropriations, final BindingResult errors, final RequestInfo requestInfo) { try { budgetReAppropriations = fetchRelated(budgetReAppropriations); validate(budgetReAppropriations, ACTION_CREATE, errors); if (errors.hasErrors()) throw new CustomBindException(errors); } catch (final CustomBindException e) { throw new CustomBindException(errors); } return budgetReAppropriationRepository.save(budgetReAppropriations, requestInfo); } @Transactional public List<BudgetReAppropriation> update(List<BudgetReAppropriation> budgetReAppropriations, final BindingResult errors, final RequestInfo requestInfo) { try { budgetReAppropriations = fetchRelated(budgetReAppropriations); validate(budgetReAppropriations, ACTION_UPDATE, errors); if (errors.hasErrors()) throw new CustomBindException(errors); } catch (final CustomBindException e) { throw new CustomBindException(errors); } return budgetReAppropriationRepository.update(budgetReAppropriations, requestInfo); } @Transactional public List<BudgetReAppropriation> delete(List<BudgetReAppropriation> budgetReAppropriations, final BindingResult errors, final RequestInfo requestInfo) { try { validate(budgetReAppropriations, ACTION_DELETE, errors); if (errors.hasErrors()) throw new CustomBindException(errors); } catch (final CustomBindException e) { throw new CustomBindException(errors); } return budgetReAppropriationRepository.delete(budgetReAppropriations, requestInfo); } private BindingResult validate(final List<BudgetReAppropriation> budgetreappropriations, final String method, final BindingResult errors) { try { switch (method) { case ACTION_VIEW: // validator.validate(budgetReAppropriationContractRequest.getBudgetReAppropriation(), // errors); break; case ACTION_CREATE: Assert.notNull(budgetreappropriations, "BudgetReAppropriations to create must not be null"); for (final BudgetReAppropriation budgetReAppropriation : budgetreappropriations) validator.validate(budgetReAppropriation, errors); break; case ACTION_UPDATE: Assert.notNull(budgetreappropriations, "BudgetReAppropriations to update must not be null"); for (final BudgetReAppropriation budgetReAppropriation : budgetreappropriations){ Assert.notNull(budgetReAppropriation.getId(), "BudgetReAppropriation ID to update must not be null"); validator.validate(budgetReAppropriation, errors); } break; case ACTION_DELETE: Assert.notNull(budgetreappropriations, "BudgetReAppropriations to delete must not be null"); for (final BudgetReAppropriation budgetReAppropriation : budgetreappropriations){ Assert.notNull(budgetReAppropriation.getId(), "BudgetReAppropriation ID to delete must not be null"); } break; default: } } catch (final IllegalArgumentException e) { errors.addError(new ObjectError("Missing data", e.getMessage())); } return errors; } public List<BudgetReAppropriation> fetchRelated(final List<BudgetReAppropriation> budgetreappropriations) { if (budgetreappropriations != null) for (final BudgetReAppropriation budgetReAppropriation : budgetreappropriations) // fetch related items if (budgetReAppropriation.getBudgetDetail() != null && budgetReAppropriation.getBudgetDetail().getId() != null && budgetReAppropriation.getBudgetDetail().getTenantId() != null) { final BudgetDetail budgetDetail = budgetDetailRepository .findById(budgetReAppropriation.getBudgetDetail()); if (budgetDetail == null) throw new InvalidDataException("budgetDetail", "budgetDetail.invalid", " Invalid budgetDetail"); budgetReAppropriation.setBudgetDetail(budgetDetail); } return budgetreappropriations; } public Pagination<BudgetReAppropriation> search(final BudgetReAppropriationSearch budgetReAppropriationSearch) { return budgetReAppropriationRepository.search(budgetReAppropriationSearch); } @Transactional public BudgetReAppropriation save(final BudgetReAppropriation budgetReAppropriation) { return budgetReAppropriationRepository.save(budgetReAppropriation); } @Transactional public BudgetReAppropriation update(final BudgetReAppropriation budgetReAppropriation) { return budgetReAppropriationRepository.update(budgetReAppropriation); } @Transactional public BudgetReAppropriation delete(final BudgetReAppropriation budgetReAppropriation) { return budgetReAppropriationRepository.delete(budgetReAppropriation); } }
UTF-8
Java
9,488
java
BudgetReAppropriationService.java
Java
[ { "context": " queries, you can reach eGovernments Foundation at contact@egovernments.org.\n */\npackage org.egov.egf.budget.domain.service;\n", "end": 1973, "score": 0.9998741149902344, "start": 1949, "tag": "EMAIL", "value": "contact@egovernments.org" } ]
null
[]
/* * eGov suite of products aim to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) <2015> eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at <EMAIL>. */ package org.egov.egf.budget.domain.service; import java.util.List; import org.egov.common.contract.request.RequestInfo; import org.egov.common.domain.exception.CustomBindException; import org.egov.common.domain.exception.InvalidDataException; import org.egov.common.domain.model.Pagination; import org.egov.egf.budget.domain.model.BudgetDetail; import org.egov.egf.budget.domain.model.BudgetReAppropriation; import org.egov.egf.budget.domain.model.BudgetReAppropriationSearch; import org.egov.egf.budget.domain.repository.BudgetDetailRepository; import org.egov.egf.budget.domain.repository.BudgetReAppropriationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.validation.SmartValidator; @Service @Transactional(readOnly = true) public class BudgetReAppropriationService { public static final String ACTION_CREATE = "create"; public static final String ACTION_UPDATE = "update"; public static final String ACTION_DELETE = "delete"; public static final String ACTION_VIEW = "view"; public static final String ACTION_EDIT = "edit"; public static final String ACTION_SEARCH = "search"; private final BudgetReAppropriationRepository budgetReAppropriationRepository; private final SmartValidator validator; private final BudgetDetailRepository budgetDetailRepository; @Autowired public BudgetReAppropriationService(final BudgetReAppropriationRepository budgetReAppropriationRepository, final SmartValidator validator, final BudgetDetailRepository budgetDetailRepository) { this.budgetReAppropriationRepository = budgetReAppropriationRepository; this.validator = validator; this.budgetDetailRepository = budgetDetailRepository; } @Transactional public List<BudgetReAppropriation> create(List<BudgetReAppropriation> budgetReAppropriations, final BindingResult errors, final RequestInfo requestInfo) { try { budgetReAppropriations = fetchRelated(budgetReAppropriations); validate(budgetReAppropriations, ACTION_CREATE, errors); if (errors.hasErrors()) throw new CustomBindException(errors); } catch (final CustomBindException e) { throw new CustomBindException(errors); } return budgetReAppropriationRepository.save(budgetReAppropriations, requestInfo); } @Transactional public List<BudgetReAppropriation> update(List<BudgetReAppropriation> budgetReAppropriations, final BindingResult errors, final RequestInfo requestInfo) { try { budgetReAppropriations = fetchRelated(budgetReAppropriations); validate(budgetReAppropriations, ACTION_UPDATE, errors); if (errors.hasErrors()) throw new CustomBindException(errors); } catch (final CustomBindException e) { throw new CustomBindException(errors); } return budgetReAppropriationRepository.update(budgetReAppropriations, requestInfo); } @Transactional public List<BudgetReAppropriation> delete(List<BudgetReAppropriation> budgetReAppropriations, final BindingResult errors, final RequestInfo requestInfo) { try { validate(budgetReAppropriations, ACTION_DELETE, errors); if (errors.hasErrors()) throw new CustomBindException(errors); } catch (final CustomBindException e) { throw new CustomBindException(errors); } return budgetReAppropriationRepository.delete(budgetReAppropriations, requestInfo); } private BindingResult validate(final List<BudgetReAppropriation> budgetreappropriations, final String method, final BindingResult errors) { try { switch (method) { case ACTION_VIEW: // validator.validate(budgetReAppropriationContractRequest.getBudgetReAppropriation(), // errors); break; case ACTION_CREATE: Assert.notNull(budgetreappropriations, "BudgetReAppropriations to create must not be null"); for (final BudgetReAppropriation budgetReAppropriation : budgetreappropriations) validator.validate(budgetReAppropriation, errors); break; case ACTION_UPDATE: Assert.notNull(budgetreappropriations, "BudgetReAppropriations to update must not be null"); for (final BudgetReAppropriation budgetReAppropriation : budgetreappropriations){ Assert.notNull(budgetReAppropriation.getId(), "BudgetReAppropriation ID to update must not be null"); validator.validate(budgetReAppropriation, errors); } break; case ACTION_DELETE: Assert.notNull(budgetreappropriations, "BudgetReAppropriations to delete must not be null"); for (final BudgetReAppropriation budgetReAppropriation : budgetreappropriations){ Assert.notNull(budgetReAppropriation.getId(), "BudgetReAppropriation ID to delete must not be null"); } break; default: } } catch (final IllegalArgumentException e) { errors.addError(new ObjectError("Missing data", e.getMessage())); } return errors; } public List<BudgetReAppropriation> fetchRelated(final List<BudgetReAppropriation> budgetreappropriations) { if (budgetreappropriations != null) for (final BudgetReAppropriation budgetReAppropriation : budgetreappropriations) // fetch related items if (budgetReAppropriation.getBudgetDetail() != null && budgetReAppropriation.getBudgetDetail().getId() != null && budgetReAppropriation.getBudgetDetail().getTenantId() != null) { final BudgetDetail budgetDetail = budgetDetailRepository .findById(budgetReAppropriation.getBudgetDetail()); if (budgetDetail == null) throw new InvalidDataException("budgetDetail", "budgetDetail.invalid", " Invalid budgetDetail"); budgetReAppropriation.setBudgetDetail(budgetDetail); } return budgetreappropriations; } public Pagination<BudgetReAppropriation> search(final BudgetReAppropriationSearch budgetReAppropriationSearch) { return budgetReAppropriationRepository.search(budgetReAppropriationSearch); } @Transactional public BudgetReAppropriation save(final BudgetReAppropriation budgetReAppropriation) { return budgetReAppropriationRepository.save(budgetReAppropriation); } @Transactional public BudgetReAppropriation update(final BudgetReAppropriation budgetReAppropriation) { return budgetReAppropriationRepository.update(budgetReAppropriation); } @Transactional public BudgetReAppropriation delete(final BudgetReAppropriation budgetReAppropriation) { return budgetReAppropriationRepository.delete(budgetReAppropriation); } }
9,471
0.698567
0.697723
225
41.168888
36.44939
125
false
false
0
0
0
0
0
0
0.48
false
false
12
280994f5202aa70c3d55866a0291e9a8d2ba6f36
9,766,755,634,328
e59b5c079172754c3efa3991065c5b256ddbc1b3
/src/fr/staci/ecats/core/common/utils/FTPUtils.java
1d777c5ad56a7991938d361965ce41f4f9938023
[]
no_license
Itelis/webcom3
https://github.com/Itelis/webcom3
b6b1ec26be0419fc94ab9ed52cb8e1a9fde377ac
4a6bc4281640a77a6ff4e11f65a441f58565cf57
refs/heads/master
2015-09-25T18:10:59.953000
2015-08-18T10:11:32
2015-08-18T10:11:32
40,962,666
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.staci.ecats.core.common.utils; import java.io.IOException; import java.io.InputStream; import org.apache.commons.net.ftp.FTPClient; import org.apache.log4j.Logger; import fr.staci.ecats.core.common.services.WebGlobalConfig; @Deprecated public class FTPUtils { private static final Logger LOG = Logger.getLogger(FTPUtils.class); private static final int nbServer = Integer.parseInt(WebGlobalConfig.getConfigInstance().getString("upload.files.ftp.nbserver")); private static final String url = "upload.files.ftp.url"; private static final String login = "upload.files.ftp.login"; private static final String mdp = "upload.files.ftp.mdp"; /** * retourne succes du transfert * @param in * @param path * @return * @throws IOException */ public static boolean uploadFile(InputStream in, String path, String fileName) throws IOException{ boolean result = false; //envoi sur tous les serveurs définis for (int i = 1; i <= nbServer; i++) { String urlI = WebGlobalConfig.getConfigInstance().getString(url+i); String loginI = WebGlobalConfig.getConfigInstance().getString(login+i); String mdpI = WebGlobalConfig.getConfigInstance().getString(mdp+i); FTPClient client = new FTPClient(); try { client.connect(urlI); client.login(loginI, mdpI); //transfer de fichier binaire, par defaut ascii //si non setté les fichiers sont corrompus client.setFileType(FTPClient.BINARY_FILE_TYPE); //creer les fichiers intermediaire si besoin ftpCreateDirectoryTree(client, path); //se place dans le dossier client.changeWorkingDirectory(path); //upload le fichier result = client.storeFile(fileName, in); client.logout(); } catch (IOException e) { throw new IOException("Erreur sur le serveur FTP.", e); } finally { try { client.disconnect(); } catch (IOException e) { throw new IOException("Impossible de fermer la connexion sur le serveur FTP.", e); } } } return result; } /** * utility to create an arbitrary directory hierarchy on the remote ftp server * @param client * @param dirTree the directory tree only delimited with / chars. No file name! * @throws Exception */ private static void ftpCreateDirectoryTree( FTPClient client, String dirTree ) throws IOException { boolean dirExists = true; //tokenize the string and attempt to change into each directory level. If you cannot, then start creating. String[] directories = dirTree.split("/"); for (String dir : directories ) { if (!dir.isEmpty() ) { if (dirExists) { dirExists = client.changeWorkingDirectory(dir); } if (!dirExists) { if (!client.makeDirectory(dir)) { throw new IOException("Unable to create remote directory '" + dir + "'. error='" + client.getReplyString()+"'"); } if (!client.changeWorkingDirectory(dir)) { throw new IOException("Unable to change into newly created remote directory '" + dir + "'. error='" + client.getReplyString()+"'"); } } } } } }
ISO-8859-1
Java
3,287
java
FTPUtils.java
Java
[]
null
[]
package fr.staci.ecats.core.common.utils; import java.io.IOException; import java.io.InputStream; import org.apache.commons.net.ftp.FTPClient; import org.apache.log4j.Logger; import fr.staci.ecats.core.common.services.WebGlobalConfig; @Deprecated public class FTPUtils { private static final Logger LOG = Logger.getLogger(FTPUtils.class); private static final int nbServer = Integer.parseInt(WebGlobalConfig.getConfigInstance().getString("upload.files.ftp.nbserver")); private static final String url = "upload.files.ftp.url"; private static final String login = "upload.files.ftp.login"; private static final String mdp = "upload.files.ftp.mdp"; /** * retourne succes du transfert * @param in * @param path * @return * @throws IOException */ public static boolean uploadFile(InputStream in, String path, String fileName) throws IOException{ boolean result = false; //envoi sur tous les serveurs définis for (int i = 1; i <= nbServer; i++) { String urlI = WebGlobalConfig.getConfigInstance().getString(url+i); String loginI = WebGlobalConfig.getConfigInstance().getString(login+i); String mdpI = WebGlobalConfig.getConfigInstance().getString(mdp+i); FTPClient client = new FTPClient(); try { client.connect(urlI); client.login(loginI, mdpI); //transfer de fichier binaire, par defaut ascii //si non setté les fichiers sont corrompus client.setFileType(FTPClient.BINARY_FILE_TYPE); //creer les fichiers intermediaire si besoin ftpCreateDirectoryTree(client, path); //se place dans le dossier client.changeWorkingDirectory(path); //upload le fichier result = client.storeFile(fileName, in); client.logout(); } catch (IOException e) { throw new IOException("Erreur sur le serveur FTP.", e); } finally { try { client.disconnect(); } catch (IOException e) { throw new IOException("Impossible de fermer la connexion sur le serveur FTP.", e); } } } return result; } /** * utility to create an arbitrary directory hierarchy on the remote ftp server * @param client * @param dirTree the directory tree only delimited with / chars. No file name! * @throws Exception */ private static void ftpCreateDirectoryTree( FTPClient client, String dirTree ) throws IOException { boolean dirExists = true; //tokenize the string and attempt to change into each directory level. If you cannot, then start creating. String[] directories = dirTree.split("/"); for (String dir : directories ) { if (!dir.isEmpty() ) { if (dirExists) { dirExists = client.changeWorkingDirectory(dir); } if (!dirExists) { if (!client.makeDirectory(dir)) { throw new IOException("Unable to create remote directory '" + dir + "'. error='" + client.getReplyString()+"'"); } if (!client.changeWorkingDirectory(dir)) { throw new IOException("Unable to change into newly created remote directory '" + dir + "'. error='" + client.getReplyString()+"'"); } } } } } }
3,287
0.648097
0.647489
100
31.85
31.664293
143
false
false
0
0
0
0
0
0
1.77
false
false
12
4d7a348249f4103ffbcc52dfbf3f5aceeca6a74b
10,436,770,544,036
62a2c9696711b9c2bfc970f40ebe72f80275dcdf
/Java/Tasks/src/ru/spbau/kononenko/task4/comparators/ZeroModException.java
1f728de9135f489ac267afb6c1910b44e2ce2088
[]
no_license
vasily-knk/homeworks-au-2sem
https://github.com/vasily-knk/homeworks-au-2sem
614f200b60c354e3e58af6d8d39c658f354c7a09
adf6f8225ecc799d08871855297d188a98d3ca3b
refs/heads/master
2021-01-23T21:42:33.929000
2012-08-28T05:38:39
2012-08-28T05:38:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.spbau.kononenko.task4.comparators; public class ZeroModException extends RuntimeException { public ZeroModException(String message) { super(message); } }
UTF-8
Java
189
java
ZeroModException.java
Java
[]
null
[]
package ru.spbau.kononenko.task4.comparators; public class ZeroModException extends RuntimeException { public ZeroModException(String message) { super(message); } }
189
0.719577
0.714286
7
25
21.928455
56
false
false
0
0
0
0
0
0
0.285714
false
false
12
4d52842b9d4b26b60f8a0c2a0aa99da73342603e
3,204,045,647,866
02526ff9775a03b49632379b9ee40568d0738c1b
/Java/560_SubarraySumEqualsK.java
3437e25da341e77ad2a22c25cbc7919906e6ea9f
[]
no_license
optimisea/Leetcode
https://github.com/optimisea/Leetcode
81db272a66b3525a7b0768b463adb93fbebd0dc4
4050813d0ecfffeb47690c305bd696a8d34d8b3b
refs/heads/master
2023-01-29T15:26:18.317000
2023-01-22T23:25:26
2023-01-22T23:25:26
114,144,315
7
6
null
null
null
null
null
null
null
null
null
null
null
null
null
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 Note: The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. This is the same as Question 930 https://github.com/optimisea/Leetcode/blob/master/Java/974_Subarray.java Method 1: Best solution class Solution { public int subarraySum(int[] nums, int k) { int count = 0; int preSum = 0; Map<Integer, Integer> map = new HashMap<>(); map.put(0, 1); for (int i = 0; i < nums.length; i++){ preSum += nums[i]; if (map.containsKey(preSum-k)){ count += map.get(preSum-k); } map.put(preSum, map.getOrDefault(preSum, 0) + 1); } return count; } } Method 2: Time complexity: O(n) class Solution { public int subarraySum(int[] nums, int k) { int[] prefixSum = new int[nums.length + 1]; prefixSum[0] = 0; for (int i = 1; i <= nums.length; i++){ prefixSum[i] = prefixSum[i-1] + nums[i-1]; } Map<Integer, Integer> map = new HashMap<>(); int count = 0; for (int i = 0; i <= nums.length; i++){ if (map.containsKey(prefixSum[i] - k)){ count += map.get(prefixSum[i] - k); } map.put(prefixSum[i], map.getOrDefault(prefixSum[i], 0) + 1); } return count; } }
UTF-8
Java
1,580
java
560_SubarraySumEqualsK.java
Java
[ { "context": "s the same as Question 930\n https://github.com/optimisea/Leetcode/blob/master/Java/974_Subarray.java\nMetho", "end": 395, "score": 0.9996300339698792, "start": 386, "tag": "USERNAME", "value": "optimisea" } ]
null
[]
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 Note: The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. This is the same as Question 930 https://github.com/optimisea/Leetcode/blob/master/Java/974_Subarray.java Method 1: Best solution class Solution { public int subarraySum(int[] nums, int k) { int count = 0; int preSum = 0; Map<Integer, Integer> map = new HashMap<>(); map.put(0, 1); for (int i = 0; i < nums.length; i++){ preSum += nums[i]; if (map.containsKey(preSum-k)){ count += map.get(preSum-k); } map.put(preSum, map.getOrDefault(preSum, 0) + 1); } return count; } } Method 2: Time complexity: O(n) class Solution { public int subarraySum(int[] nums, int k) { int[] prefixSum = new int[nums.length + 1]; prefixSum[0] = 0; for (int i = 1; i <= nums.length; i++){ prefixSum[i] = prefixSum[i-1] + nums[i-1]; } Map<Integer, Integer> map = new HashMap<>(); int count = 0; for (int i = 0; i <= nums.length; i++){ if (map.containsKey(prefixSum[i] - k)){ count += map.get(prefixSum[i] - k); } map.put(prefixSum[i], map.getOrDefault(prefixSum[i], 0) + 1); } return count; } }
1,580
0.55443
0.523418
50
30.6
26.330971
125
false
false
0
0
0
0
0
0
0.78
false
false
12
43c94351d72a2fb5f4b211ae9dc2714f348fb9c7
18,408,229,867,600
9cdcc9e5437f7c2b9fdbe5135016ce63e6f5c688
/src/main/java/dr/web/basis/service/impl/BasisTiyan_profit_schedul_resultServiceImpl.java
5944db213daf0ee3b6b6a29cb06c04cc15c99231
[]
no_license
DreamInception/pc1.0
https://github.com/DreamInception/pc1.0
a0307cf5e2355a63ba8de562952e3902aacfc80c
1a1db34762a4d3f70d45d47c09f92e7c5fb98af3
refs/heads/master
2021-01-13T07:38:20.166000
2016-10-20T14:54:12
2016-10-20T14:54:12
71,473,454
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dr.web.basis.service.impl; import java.util.Map; import org.springframework.stereotype.Service; import dr.web.basis.service.BasisTiyan_profit_schedul_resultService; import dr.web.common.base.InterfaceServiceImpl; /** * * @包名 :dr.web.basis.service.impl * @文件名 :BasisTiyan_profit_schedul_resultServiceImpl.java * @系统名称 : 上海景源金服PC端 * @Author: 陈吉秋特 * @Date: 2016-3-16下午5:00:00 * @版本号 :v0.0.01 */ @Service(value = "basisTiyan_profit_schedul_resultService") public class BasisTiyan_profit_schedul_resultServiceImpl extends InterfaceServiceImpl<Map<String, Object>> implements BasisTiyan_profit_schedul_resultService { public static final String nameSpace = "basis_tiyan_profit_schedul_result"; @Override public String getNamespace() { return nameSpace; } }
UTF-8
Java
829
java
BasisTiyan_profit_schedul_resultServiceImpl.java
Java
[ { "context": "ServiceImpl.java\n * @系统名称 : 上海景源金服PC端\n * @Author: 陈吉秋特\n * @Date: 2016-3-16下午5:00:00\n * @版本号 :v0.0.01\n */", "end": 361, "score": 0.9998571276664734, "start": 357, "tag": "NAME", "value": "陈吉秋特" } ]
null
[]
package dr.web.basis.service.impl; import java.util.Map; import org.springframework.stereotype.Service; import dr.web.basis.service.BasisTiyan_profit_schedul_resultService; import dr.web.common.base.InterfaceServiceImpl; /** * * @包名 :dr.web.basis.service.impl * @文件名 :BasisTiyan_profit_schedul_resultServiceImpl.java * @系统名称 : 上海景源金服PC端 * @Author: 陈吉秋特 * @Date: 2016-3-16下午5:00:00 * @版本号 :v0.0.01 */ @Service(value = "basisTiyan_profit_schedul_resultService") public class BasisTiyan_profit_schedul_resultServiceImpl extends InterfaceServiceImpl<Map<String, Object>> implements BasisTiyan_profit_schedul_resultService { public static final String nameSpace = "basis_tiyan_profit_schedul_result"; @Override public String getNamespace() { return nameSpace; } }
829
0.770218
0.749679
26
28.961538
34.575981
160
false
false
0
0
0
0
0
0
0.538462
false
false
12
3ef4caa11a20356d286a0e04bc35237c441d16ac
23,433,341,572,853
50b2cb363ca931a32f4dd3b9cd5e3cff8949a107
/biemo-auth/biemo-auth-app/src/main/java/com/biemo/cloud/auth/modular/sso/model/AuthReq.java
63e264a4bef271db0e55b29671436a8b570f11a8
[ "Apache-2.0" ]
permissive
biemo8/bbs-cloud
https://github.com/biemo8/bbs-cloud
a5b3c50cef39edf1334a7b32cd7c5b14619abdc5
304af6ab2c212784b984230846d508a3c91b9fa1
refs/heads/master
2023-08-31T12:04:13.312000
2021-11-04T11:57:35
2021-11-04T11:57:35
415,247,848
80
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.biemo.cloud.auth.modular.sso.model; import com.biemo.cloud.core.util.ToolUtil; import com.biemo.cloud.kernel.model.validator.BaseValidatingParam; import lombok.Data; /** * 登录认证的请求 * * * @date 2019-04-19-14:21 */ @Data public class AuthReq extends SsoLoginReq implements BaseValidatingParam { /** * 账号 */ private String account; /** * 密码 */ private String password; @Override public String checkParam() { if (ToolUtil.isOneEmpty(account, password)) { return "账号密码为空!"; } if (ToolUtil.isOneEmpty(super.getClientId())) { return "参数不合法,应用id或url为空!"; } return null; } }
UTF-8
Java
762
java
AuthReq.java
Java
[]
null
[]
package com.biemo.cloud.auth.modular.sso.model; import com.biemo.cloud.core.util.ToolUtil; import com.biemo.cloud.kernel.model.validator.BaseValidatingParam; import lombok.Data; /** * 登录认证的请求 * * * @date 2019-04-19-14:21 */ @Data public class AuthReq extends SsoLoginReq implements BaseValidatingParam { /** * 账号 */ private String account; /** * 密码 */ private String password; @Override public String checkParam() { if (ToolUtil.isOneEmpty(account, password)) { return "账号密码为空!"; } if (ToolUtil.isOneEmpty(super.getClientId())) { return "参数不合法,应用id或url为空!"; } return null; } }
762
0.611111
0.594017
39
17
19.853308
73
false
false
0
0
0
0
0
0
0.25641
false
false
12
fed028f19625cafd88673dca59d0499375653110
23,673,859,752,184
eb272e85b37c158e88d0e50e2a14e5ad59bc12ad
/app/src/main/java/com/pinoymobileapps/mrtcctv/ApiService.java
1a46d047a22cfc6e21a328d66b847b01e314014f
[]
no_license
emc22/mrt-cctv-android
https://github.com/emc22/mrt-cctv-android
7969fd2b95f1f50234340bd43ac1b68a3dec9ecb
4f8132927ed595a55f0cb4db774c1edd2e66e79e
refs/heads/master
2016-09-06T09:22:34.381000
2015-10-06T00:26:07
2015-10-06T00:26:07
40,834,431
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pinoymobileapps.mrtcctv; import com.squareup.okhttp.ResponseBody; import retrofit.Call; import retrofit.http.GET; import retrofit.http.Query; public interface ApiService { @GET("/mrtcctv2/") Call<ResponseBody> streamV2(@Query("stationId") int stationId, @Query("cameraId") int cameraId); @GET("/mrtcctv/") Call<ResponseBody> streamV1(@Query("stationId") int stationId, @Query("cameraId") int cameraId); }
UTF-8
Java
438
java
ApiService.java
Java
[]
null
[]
package com.pinoymobileapps.mrtcctv; import com.squareup.okhttp.ResponseBody; import retrofit.Call; import retrofit.http.GET; import retrofit.http.Query; public interface ApiService { @GET("/mrtcctv2/") Call<ResponseBody> streamV2(@Query("stationId") int stationId, @Query("cameraId") int cameraId); @GET("/mrtcctv/") Call<ResponseBody> streamV1(@Query("stationId") int stationId, @Query("cameraId") int cameraId); }
438
0.737443
0.730594
15
28.133333
31.183044
100
false
false
0
0
0
0
0
0
0.6
false
false
12
0011a498347555aa4400b19cfa7f2979d97ae03a
22,462,679,019,033
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/eclipseswt_cluster/45186/tar_0.java
d41401f16ee4b84b17247c361e0bb16a5a4c9b95
[]
no_license
martinezmatias/GenPat-data-C3
https://github.com/martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905000
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.program; import org.eclipse.swt.internal.C; import org.eclipse.swt.internal.cocoa.*; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import java.util.Vector; /** * Instances of this class represent programs and * their associated file extensions in the operating * system. * * @see <a href="http://www.eclipse.org/swt/snippets/#program">Program snippets</a> * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> */ public final class Program { String name, fullPath, identifier; static final String PREFIX_FILE = "file://"; //$NON-NLS-1$ static final String PREFIX_HTTP = "http://"; //$NON-NLS-1$ static final String PREFIX_HTTPS = "https://"; //$NON-NLS-1$ /** * Prevents uninitialized instances from being created outside the package. */ Program () { } /** * Finds the program that is associated with an extension. * The extension may or may not begin with a '.'. Note that * a <code>Display</code> must already exist to guarantee that * this method returns an appropriate result. * * @param extension the program extension * @return the program or <code>null</code> * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT when extension is null</li> * </ul> */ public static Program findProgram (String extension) { if (extension == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); if (extension.length () == 0) return null; if (extension.charAt(0) != '.') extension = "." + extension; NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { NSWorkspace workspace = NSWorkspace.sharedWorkspace(); int /*long*/ appName = OS.malloc(C.PTR_SIZEOF); int /*long*/ type = OS.malloc(C.PTR_SIZEOF); NSString temp = new NSString(OS.NSTemporaryDirectory()); NSString fileName = NSString.stringWith("swt" + System.currentTimeMillis() + extension); NSString fullPath = temp.stringByAppendingPathComponent(fileName); NSFileManager fileManager = NSFileManager.defaultManager(); fileManager.createFileAtPath(fullPath, null, null); workspace.getInfoForFile(fullPath, appName, type); fileManager.removeItemAtPath(fullPath, 0); int /*long*/ [] buffer = new int /*long*/[1]; OS.memmove(buffer, appName, C.PTR_SIZEOF); OS.free(appName); OS.free(type); if (buffer [0] != 0) { NSString appPath = new NSString(buffer[0]); NSBundle bundle = NSBundle.bundleWithPath(appPath); if (bundle != null) return getProgram(bundle); } return null; } finally { pool.release(); } } /** * Answer all program extensions in the operating system. Note * that a <code>Display</code> must already exist to guarantee * that this method returns an appropriate result. * * @return an array of extensions */ public static String [] getExtensions () { NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { NSMutableSet supportedDocumentTypes = (NSMutableSet)NSMutableSet.set(); NSWorkspace workspace = NSWorkspace.sharedWorkspace(); NSString CFBundleDocumentTypes = NSString.stringWith("CFBundleDocumentTypes"); NSString CFBundleTypeExtensions = NSString.stringWith("CFBundleTypeExtensions"); NSArray array = new NSArray(OS.NSSearchPathForDirectoriesInDomains(OS.NSAllApplicationsDirectory, OS.NSAllDomainsMask, true)); int count = (int)/*64*/array.count(); for (int i = 0; i < count; i++) { NSString path = new NSString(array.objectAtIndex(i)); NSFileManager fileManager = NSFileManager.defaultManager(); NSDirectoryEnumerator enumerator = fileManager.enumeratorAtPath(path); if (enumerator != null) { id id; while ((id = enumerator.nextObject()) != null) { enumerator.skipDescendents(); NSString filePath = new NSString(id.id); NSString fullPath = path.stringByAppendingPathComponent(filePath); if (workspace.isFilePackageAtPath(fullPath)) { NSBundle bundle = NSBundle.bundleWithPath(fullPath); id = bundle.infoDictionary().objectForKey(CFBundleDocumentTypes); if (id != null) { NSDictionary documentTypes = new NSDictionary(id.id); NSEnumerator documentTypesEnumerator = documentTypes.objectEnumerator(); while ((id = documentTypesEnumerator.nextObject()) != null) { NSDictionary documentType = new NSDictionary(id.id); id = documentType.objectForKey(CFBundleTypeExtensions); if (id != null) { supportedDocumentTypes.addObjectsFromArray(new NSArray(id.id)); } } } } } } } int i = 0; String[] exts = new String[(int)/*64*/supportedDocumentTypes.count()]; NSEnumerator enumerator = supportedDocumentTypes.objectEnumerator(); id id; while ((id = enumerator.nextObject()) != null) { String ext = new NSString(id.id).getString(); if (!ext.equals("*")) exts[i++] = "." + ext; } if (i != exts.length) { String[] temp = new String[i]; System.arraycopy(exts, 0, temp, 0, i); exts = temp; } return exts; } finally { pool.release(); } } static Program getProgram(NSBundle bundle) { NSString CFBundleName = NSString.stringWith("CFBundleName"); NSString CFBundleDisplayName = NSString.stringWith("CFBundleDisplayName"); NSString fullPath = bundle.bundlePath(); NSString identifier = bundle.bundleIdentifier(); id bundleName = bundle.objectForInfoDictionaryKey(CFBundleDisplayName); if (bundleName == null) { bundleName = bundle.objectForInfoDictionaryKey(CFBundleName); } if (bundleName == null) { bundleName = fullPath.lastPathComponent().stringByDeletingPathExtension(); } NSString name = new NSString(bundleName.id); Program program = new Program(); program.name = name.getString(); program.fullPath = fullPath.getString(); program.identifier = identifier != null ? identifier.getString() : ""; return program; } /** * Answers all available programs in the operating system. Note * that a <code>Display</code> must already exist to guarantee * that this method returns an appropriate result. * * @return an array of programs */ public static Program [] getPrograms () { NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { Vector vector = new Vector(); NSWorkspace workspace = NSWorkspace.sharedWorkspace(); NSArray array = new NSArray(OS.NSSearchPathForDirectoriesInDomains(OS.NSAllApplicationsDirectory, OS.NSAllDomainsMask, true)); int count = (int)/*64*/array.count(); for (int i = 0; i < count; i++) { NSString path = new NSString(array.objectAtIndex(i)); NSFileManager fileManager = NSFileManager.defaultManager(); NSDirectoryEnumerator enumerator = fileManager.enumeratorAtPath(path); if (enumerator != null) { id id; while ((id = enumerator.nextObject()) != null) { enumerator.skipDescendents(); NSString fullPath = path.stringByAppendingPathComponent(new NSString(id.id)); if (workspace.isFilePackageAtPath(fullPath)) { NSBundle bundle = NSBundle.bundleWithPath(fullPath); vector.addElement(getProgram(bundle)); } } } } Program[] programs = new Program[vector.size()]; vector.copyInto(programs); return programs; } finally { pool.release(); } } /** * Launches the operating system executable associated with the file or * URL (http:// or https://). If the file is an executable then the * executable is launched. Note that a <code>Display</code> must already * exist to guarantee that this method returns an appropriate result. * * @param fileName the file or program name or URL (http:// or https://) * @return <code>true</code> if the file is launched, otherwise <code>false</code> * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT when fileName is null</li> * </ul> */ public static boolean launch (String fileName) { if (fileName == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { NSString unescapedStr = NSString.stringWith("%"); //$NON-NLS-1$ if (fileName.indexOf(':') == -1) { fileName = PREFIX_FILE + fileName; } else { String lowercaseName = fileName.toLowerCase (); if (lowercaseName.startsWith (PREFIX_HTTP) || lowercaseName.startsWith (PREFIX_HTTPS)) { unescapedStr = NSString.stringWith("%#"); //$NON-NLS-1$ } } NSString fullPath = NSString.stringWith(fileName); int /*long*/ ptr = OS.CFURLCreateStringByAddingPercentEscapes(0, fullPath.id, unescapedStr.id, 0, OS.kCFStringEncodingUTF8); NSString escapedString = new NSString(ptr); NSWorkspace workspace = NSWorkspace.sharedWorkspace(); boolean result = workspace.openURL(NSURL.URLWithString(escapedString)); OS.CFRelease(ptr); return result; } finally { pool.release(); } } /** * Executes the program with the file as the single argument * in the operating system. It is the responsibility of the * programmer to ensure that the file contains valid data for * this program. * * @param fileName the file or program name * @return <code>true</code> if the file is launched, otherwise <code>false</code> * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT when fileName is null</li> * </ul> */ public boolean execute (String fileName) { if (fileName == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { NSWorkspace workspace = NSWorkspace.sharedWorkspace(); NSString fullPath = NSString.stringWith(fileName); if (fileName.indexOf(':') == -1) { return workspace.openFile(fullPath, NSString.stringWith(name)); } NSString unescapedStr = NSString.stringWith("%"); //$NON-NLS-1$ String lowercaseName = fileName.toLowerCase (); if (lowercaseName.startsWith (PREFIX_HTTP) || lowercaseName.startsWith (PREFIX_HTTPS)) { unescapedStr = NSString.stringWith("%#"); //$NON-NLS-1$ } int /*long*/ ptr = OS.CFURLCreateStringByAddingPercentEscapes(0, fullPath.id, unescapedStr.id, 0, OS.kCFStringEncodingUTF8); NSString escapedString = new NSString(ptr); NSArray urls = NSArray.arrayWithObject(NSURL.URLWithString(escapedString)); OS.CFRelease(ptr); return workspace.openURLs(urls, NSString.stringWith(identifier), 0, null, 0); } finally { pool.release(); } } /** * Returns the receiver's image data. This is the icon * that is associated with the receiver in the operating * system. * * @return the image data for the program, may be null */ public ImageData getImageData () { NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { NSWorkspace workspace = NSWorkspace.sharedWorkspace(); NSString fullPath; if (this.fullPath != null) { fullPath = NSString.stringWith(this.fullPath); } else { fullPath = workspace.fullPathForApplication(NSString.stringWith(name)); } if (fullPath != null) { NSImage nsImage = workspace.iconForFile(fullPath); if (nsImage != null) { NSSize size = new NSSize(); size.width = size.height = 16; nsImage.setSize(size); NSBitmapImageRep imageRep = null; NSImageRep rep = nsImage.bestRepresentationForDevice(null); if (rep.isKindOfClass(OS.class_NSBitmapImageRep)) { imageRep = new NSBitmapImageRep(rep.id); } if (imageRep != null) { int width = (int)/*64*/imageRep.pixelsWide(); int height = (int)/*64*/imageRep.pixelsHigh(); int bpr = (int)/*64*/imageRep.bytesPerRow(); int bpp = (int)/*64*/imageRep.bitsPerPixel(); int dataSize = height * bpr; byte[] srcData = new byte[dataSize]; OS.memmove(srcData, imageRep.bitmapData(), dataSize); //TODO check color info PaletteData palette = new PaletteData(0xFF000000, 0xFF0000, 0xFF00); ImageData data = new ImageData(width, height, bpp, palette, 4, srcData); data.bytesPerLine = bpr; data.alphaData = new byte[width * height]; for (int i = 3, o = 0; i < srcData.length; i+= 4, o++) { data.alphaData[o] = srcData[i]; } return data; } } } return null; } finally { pool.release(); } } /** * Returns the receiver's name. This is as short and * descriptive a name as possible for the program. If * the program has no descriptive name, this string may * be the executable name, path or empty. * * @return the name of the program */ public String getName () { return name; } /** * Compares the argument to the receiver, and returns true * if they represent the <em>same</em> object using a class * specific comparison. * * @param other the object to compare with this object * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise * * @see #hashCode() */ public boolean equals(Object other) { if (this == other) return true; if (other instanceof Program) { final Program program = (Program) other; return name.equals(program.name); } return false; } /** * Returns an integer hash code for the receiver. Any two * objects that return <code>true</code> when passed to * <code>equals</code> must return the same value for this * method. * * @return the receiver's hash * * @see #equals(Object) */ public int hashCode() { return name.hashCode(); } /** * Returns a string containing a concise, human-readable * description of the receiver. * * @return a string representation of the program */ public String toString () { return "Program {" + name + "}"; } }
UTF-8
Java
14,023
java
tar_0.java
Java
[]
null
[]
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.program; import org.eclipse.swt.internal.C; import org.eclipse.swt.internal.cocoa.*; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import java.util.Vector; /** * Instances of this class represent programs and * their associated file extensions in the operating * system. * * @see <a href="http://www.eclipse.org/swt/snippets/#program">Program snippets</a> * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> */ public final class Program { String name, fullPath, identifier; static final String PREFIX_FILE = "file://"; //$NON-NLS-1$ static final String PREFIX_HTTP = "http://"; //$NON-NLS-1$ static final String PREFIX_HTTPS = "https://"; //$NON-NLS-1$ /** * Prevents uninitialized instances from being created outside the package. */ Program () { } /** * Finds the program that is associated with an extension. * The extension may or may not begin with a '.'. Note that * a <code>Display</code> must already exist to guarantee that * this method returns an appropriate result. * * @param extension the program extension * @return the program or <code>null</code> * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT when extension is null</li> * </ul> */ public static Program findProgram (String extension) { if (extension == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); if (extension.length () == 0) return null; if (extension.charAt(0) != '.') extension = "." + extension; NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { NSWorkspace workspace = NSWorkspace.sharedWorkspace(); int /*long*/ appName = OS.malloc(C.PTR_SIZEOF); int /*long*/ type = OS.malloc(C.PTR_SIZEOF); NSString temp = new NSString(OS.NSTemporaryDirectory()); NSString fileName = NSString.stringWith("swt" + System.currentTimeMillis() + extension); NSString fullPath = temp.stringByAppendingPathComponent(fileName); NSFileManager fileManager = NSFileManager.defaultManager(); fileManager.createFileAtPath(fullPath, null, null); workspace.getInfoForFile(fullPath, appName, type); fileManager.removeItemAtPath(fullPath, 0); int /*long*/ [] buffer = new int /*long*/[1]; OS.memmove(buffer, appName, C.PTR_SIZEOF); OS.free(appName); OS.free(type); if (buffer [0] != 0) { NSString appPath = new NSString(buffer[0]); NSBundle bundle = NSBundle.bundleWithPath(appPath); if (bundle != null) return getProgram(bundle); } return null; } finally { pool.release(); } } /** * Answer all program extensions in the operating system. Note * that a <code>Display</code> must already exist to guarantee * that this method returns an appropriate result. * * @return an array of extensions */ public static String [] getExtensions () { NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { NSMutableSet supportedDocumentTypes = (NSMutableSet)NSMutableSet.set(); NSWorkspace workspace = NSWorkspace.sharedWorkspace(); NSString CFBundleDocumentTypes = NSString.stringWith("CFBundleDocumentTypes"); NSString CFBundleTypeExtensions = NSString.stringWith("CFBundleTypeExtensions"); NSArray array = new NSArray(OS.NSSearchPathForDirectoriesInDomains(OS.NSAllApplicationsDirectory, OS.NSAllDomainsMask, true)); int count = (int)/*64*/array.count(); for (int i = 0; i < count; i++) { NSString path = new NSString(array.objectAtIndex(i)); NSFileManager fileManager = NSFileManager.defaultManager(); NSDirectoryEnumerator enumerator = fileManager.enumeratorAtPath(path); if (enumerator != null) { id id; while ((id = enumerator.nextObject()) != null) { enumerator.skipDescendents(); NSString filePath = new NSString(id.id); NSString fullPath = path.stringByAppendingPathComponent(filePath); if (workspace.isFilePackageAtPath(fullPath)) { NSBundle bundle = NSBundle.bundleWithPath(fullPath); id = bundle.infoDictionary().objectForKey(CFBundleDocumentTypes); if (id != null) { NSDictionary documentTypes = new NSDictionary(id.id); NSEnumerator documentTypesEnumerator = documentTypes.objectEnumerator(); while ((id = documentTypesEnumerator.nextObject()) != null) { NSDictionary documentType = new NSDictionary(id.id); id = documentType.objectForKey(CFBundleTypeExtensions); if (id != null) { supportedDocumentTypes.addObjectsFromArray(new NSArray(id.id)); } } } } } } } int i = 0; String[] exts = new String[(int)/*64*/supportedDocumentTypes.count()]; NSEnumerator enumerator = supportedDocumentTypes.objectEnumerator(); id id; while ((id = enumerator.nextObject()) != null) { String ext = new NSString(id.id).getString(); if (!ext.equals("*")) exts[i++] = "." + ext; } if (i != exts.length) { String[] temp = new String[i]; System.arraycopy(exts, 0, temp, 0, i); exts = temp; } return exts; } finally { pool.release(); } } static Program getProgram(NSBundle bundle) { NSString CFBundleName = NSString.stringWith("CFBundleName"); NSString CFBundleDisplayName = NSString.stringWith("CFBundleDisplayName"); NSString fullPath = bundle.bundlePath(); NSString identifier = bundle.bundleIdentifier(); id bundleName = bundle.objectForInfoDictionaryKey(CFBundleDisplayName); if (bundleName == null) { bundleName = bundle.objectForInfoDictionaryKey(CFBundleName); } if (bundleName == null) { bundleName = fullPath.lastPathComponent().stringByDeletingPathExtension(); } NSString name = new NSString(bundleName.id); Program program = new Program(); program.name = name.getString(); program.fullPath = fullPath.getString(); program.identifier = identifier != null ? identifier.getString() : ""; return program; } /** * Answers all available programs in the operating system. Note * that a <code>Display</code> must already exist to guarantee * that this method returns an appropriate result. * * @return an array of programs */ public static Program [] getPrograms () { NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { Vector vector = new Vector(); NSWorkspace workspace = NSWorkspace.sharedWorkspace(); NSArray array = new NSArray(OS.NSSearchPathForDirectoriesInDomains(OS.NSAllApplicationsDirectory, OS.NSAllDomainsMask, true)); int count = (int)/*64*/array.count(); for (int i = 0; i < count; i++) { NSString path = new NSString(array.objectAtIndex(i)); NSFileManager fileManager = NSFileManager.defaultManager(); NSDirectoryEnumerator enumerator = fileManager.enumeratorAtPath(path); if (enumerator != null) { id id; while ((id = enumerator.nextObject()) != null) { enumerator.skipDescendents(); NSString fullPath = path.stringByAppendingPathComponent(new NSString(id.id)); if (workspace.isFilePackageAtPath(fullPath)) { NSBundle bundle = NSBundle.bundleWithPath(fullPath); vector.addElement(getProgram(bundle)); } } } } Program[] programs = new Program[vector.size()]; vector.copyInto(programs); return programs; } finally { pool.release(); } } /** * Launches the operating system executable associated with the file or * URL (http:// or https://). If the file is an executable then the * executable is launched. Note that a <code>Display</code> must already * exist to guarantee that this method returns an appropriate result. * * @param fileName the file or program name or URL (http:// or https://) * @return <code>true</code> if the file is launched, otherwise <code>false</code> * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT when fileName is null</li> * </ul> */ public static boolean launch (String fileName) { if (fileName == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { NSString unescapedStr = NSString.stringWith("%"); //$NON-NLS-1$ if (fileName.indexOf(':') == -1) { fileName = PREFIX_FILE + fileName; } else { String lowercaseName = fileName.toLowerCase (); if (lowercaseName.startsWith (PREFIX_HTTP) || lowercaseName.startsWith (PREFIX_HTTPS)) { unescapedStr = NSString.stringWith("%#"); //$NON-NLS-1$ } } NSString fullPath = NSString.stringWith(fileName); int /*long*/ ptr = OS.CFURLCreateStringByAddingPercentEscapes(0, fullPath.id, unescapedStr.id, 0, OS.kCFStringEncodingUTF8); NSString escapedString = new NSString(ptr); NSWorkspace workspace = NSWorkspace.sharedWorkspace(); boolean result = workspace.openURL(NSURL.URLWithString(escapedString)); OS.CFRelease(ptr); return result; } finally { pool.release(); } } /** * Executes the program with the file as the single argument * in the operating system. It is the responsibility of the * programmer to ensure that the file contains valid data for * this program. * * @param fileName the file or program name * @return <code>true</code> if the file is launched, otherwise <code>false</code> * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT when fileName is null</li> * </ul> */ public boolean execute (String fileName) { if (fileName == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { NSWorkspace workspace = NSWorkspace.sharedWorkspace(); NSString fullPath = NSString.stringWith(fileName); if (fileName.indexOf(':') == -1) { return workspace.openFile(fullPath, NSString.stringWith(name)); } NSString unescapedStr = NSString.stringWith("%"); //$NON-NLS-1$ String lowercaseName = fileName.toLowerCase (); if (lowercaseName.startsWith (PREFIX_HTTP) || lowercaseName.startsWith (PREFIX_HTTPS)) { unescapedStr = NSString.stringWith("%#"); //$NON-NLS-1$ } int /*long*/ ptr = OS.CFURLCreateStringByAddingPercentEscapes(0, fullPath.id, unescapedStr.id, 0, OS.kCFStringEncodingUTF8); NSString escapedString = new NSString(ptr); NSArray urls = NSArray.arrayWithObject(NSURL.URLWithString(escapedString)); OS.CFRelease(ptr); return workspace.openURLs(urls, NSString.stringWith(identifier), 0, null, 0); } finally { pool.release(); } } /** * Returns the receiver's image data. This is the icon * that is associated with the receiver in the operating * system. * * @return the image data for the program, may be null */ public ImageData getImageData () { NSAutoreleasePool pool = (NSAutoreleasePool) new NSAutoreleasePool().alloc().init(); try { NSWorkspace workspace = NSWorkspace.sharedWorkspace(); NSString fullPath; if (this.fullPath != null) { fullPath = NSString.stringWith(this.fullPath); } else { fullPath = workspace.fullPathForApplication(NSString.stringWith(name)); } if (fullPath != null) { NSImage nsImage = workspace.iconForFile(fullPath); if (nsImage != null) { NSSize size = new NSSize(); size.width = size.height = 16; nsImage.setSize(size); NSBitmapImageRep imageRep = null; NSImageRep rep = nsImage.bestRepresentationForDevice(null); if (rep.isKindOfClass(OS.class_NSBitmapImageRep)) { imageRep = new NSBitmapImageRep(rep.id); } if (imageRep != null) { int width = (int)/*64*/imageRep.pixelsWide(); int height = (int)/*64*/imageRep.pixelsHigh(); int bpr = (int)/*64*/imageRep.bytesPerRow(); int bpp = (int)/*64*/imageRep.bitsPerPixel(); int dataSize = height * bpr; byte[] srcData = new byte[dataSize]; OS.memmove(srcData, imageRep.bitmapData(), dataSize); //TODO check color info PaletteData palette = new PaletteData(0xFF000000, 0xFF0000, 0xFF00); ImageData data = new ImageData(width, height, bpp, palette, 4, srcData); data.bytesPerLine = bpr; data.alphaData = new byte[width * height]; for (int i = 3, o = 0; i < srcData.length; i+= 4, o++) { data.alphaData[o] = srcData[i]; } return data; } } } return null; } finally { pool.release(); } } /** * Returns the receiver's name. This is as short and * descriptive a name as possible for the program. If * the program has no descriptive name, this string may * be the executable name, path or empty. * * @return the name of the program */ public String getName () { return name; } /** * Compares the argument to the receiver, and returns true * if they represent the <em>same</em> object using a class * specific comparison. * * @param other the object to compare with this object * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise * * @see #hashCode() */ public boolean equals(Object other) { if (this == other) return true; if (other instanceof Program) { final Program program = (Program) other; return name.equals(program.name); } return false; } /** * Returns an integer hash code for the receiver. Any two * objects that return <code>true</code> when passed to * <code>equals</code> must return the same value for this * method. * * @return the receiver's hash * * @see #equals(Object) */ public int hashCode() { return name.hashCode(); } /** * Returns a string containing a concise, human-readable * description of the receiver. * * @return a string representation of the program */ public String toString () { return "Program {" + name + "}"; } }
14,023
0.695001
0.689581
391
34.864449
28.155752
128
false
false
0
0
0
0
0
0
2.092072
false
false
12
5084e49423beb0527ea7c6f713ef42079f258934
15,479,062,190,377
1ef0eedba35f0f3868cf404b66d3e8299fabb080
/EjerciciosTema4/src/Bombilla/Bombilla.java
d955df60d590b529238154daaffe1f21c21e16ed
[]
no_license
Mersprec/Java
https://github.com/Mersprec/Java
03ed12ce6eef622afc18e2636c967c7f15f4d829
94fd167f487f036f2b408b82d8455f695bdbb6aa
refs/heads/master
2020-04-02T02:28:05.658000
2019-07-15T15:10:14
2019-07-15T15:10:14
153,910,863
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Bombilla; public class Bombilla { private boolean encendida, fundida; private int contadorEncendido; public Bombilla() { encendida = false; fundida = false; contadorEncendido = 0; } public Bombilla(boolean encendida, boolean fundida, int contadorEncendido) { this.encendida = encendida; this.fundida = fundida; this.contadorEncendido = contadorEncendido; } public boolean Apagar() { return encendida = false; } public boolean Encender() { return encendida = true; } public boolean isEncendida() { return encendida; } public void setEncendida(boolean encendida) { this.encendida = encendida; } public boolean isFundida() { return fundida; } public void setFundida(boolean fundida) { this.fundida = fundida; } public int getContadorEncendido() { return contadorEncendido; } public void setContadorEncendido(int contadorEncendido) { this.contadorEncendido = contadorEncendido; } public void cambiarAEncendida() { this.encendida = true; this.contadorEncendido++; if (this.contadorEncendido == 100) { this.fundida = true; } } }
UTF-8
Java
1,295
java
Bombilla.java
Java
[]
null
[]
package Bombilla; public class Bombilla { private boolean encendida, fundida; private int contadorEncendido; public Bombilla() { encendida = false; fundida = false; contadorEncendido = 0; } public Bombilla(boolean encendida, boolean fundida, int contadorEncendido) { this.encendida = encendida; this.fundida = fundida; this.contadorEncendido = contadorEncendido; } public boolean Apagar() { return encendida = false; } public boolean Encender() { return encendida = true; } public boolean isEncendida() { return encendida; } public void setEncendida(boolean encendida) { this.encendida = encendida; } public boolean isFundida() { return fundida; } public void setFundida(boolean fundida) { this.fundida = fundida; } public int getContadorEncendido() { return contadorEncendido; } public void setContadorEncendido(int contadorEncendido) { this.contadorEncendido = contadorEncendido; } public void cambiarAEncendida() { this.encendida = true; this.contadorEncendido++; if (this.contadorEncendido == 100) { this.fundida = true; } } }
1,295
0.619305
0.616216
58
21.327587
18.776716
80
false
false
0
0
0
0
0
0
0.396552
false
false
12
8ef8f3d34ea17593a262c3069c79bdc6106b009d
360,777,299,232
09ed08b066790930cf0b35fad18962fc11841976
/app/src/main/java/app/mawared/alhayat/cities/Data.java
b4d38b15b19583d50e5ca5a9db80fdefe12e54c2
[]
no_license
zamalex/Mawared
https://github.com/zamalex/Mawared
1bf19a4e68a8bce40fd732e422b481895c56a0de
697d2435629cee78dcffba1b7a4bff7d1bc5da69
refs/heads/master
2023-09-04T19:03:34.197000
2021-10-31T21:12:49
2021-10-31T21:12:49
288,940,050
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.mawared.alhayat.cities; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Data { @Expose @SerializedName("longitude") private String longitude; @Expose @SerializedName("latitude") private String latitude; @Expose @SerializedName("slug") private String slug; @Expose @SerializedName("name") private String name; @Expose @SerializedName("active") private String active; @Expose @SerializedName("code") private String code; @Expose @SerializedName("region_id") private String region_id; @Expose @SerializedName("country_code") private String country_code; @Expose @SerializedName("id") private String id; public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getActive() { return active; } public void setActive(String active) { this.active = active; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getRegion_id() { return region_id; } public void setRegion_id(String region_id) { this.region_id = region_id; } public String getCountry_code() { return country_code; } public void setCountry_code(String country_code) { this.country_code = country_code; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
UTF-8
Java
2,085
java
Data.java
Java
[]
null
[]
package app.mawared.alhayat.cities; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Data { @Expose @SerializedName("longitude") private String longitude; @Expose @SerializedName("latitude") private String latitude; @Expose @SerializedName("slug") private String slug; @Expose @SerializedName("name") private String name; @Expose @SerializedName("active") private String active; @Expose @SerializedName("code") private String code; @Expose @SerializedName("region_id") private String region_id; @Expose @SerializedName("country_code") private String country_code; @Expose @SerializedName("id") private String id; public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getActive() { return active; } public void setActive(String active) { this.active = active; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getRegion_id() { return region_id; } public void setRegion_id(String region_id) { this.region_id = region_id; } public String getCountry_code() { return country_code; } public void setCountry_code(String country_code) { this.country_code = country_code; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
2,085
0.607194
0.607194
106
18.669811
14.914044
54
false
false
0
0
0
0
0
0
0.283019
false
false
12
bae68ad2b61ad2536f02547585e788283b03b7aa
2,482,491,123,996
a14e9253a3de6264322caf94325b3e4f70f9c95a
/DynamicProgramming/MinCostPathBF.java
6fc651d89f6f55a2572ad39403ca115f772a5069
[]
no_license
davekartik24/Algorithms
https://github.com/davekartik24/Algorithms
124543d4e9d27522402b9efbac94ec62b2e46c43
de6cbfe9c8543507166290a46684f392339a235d
refs/heads/master
2021-04-24T19:57:21.294000
2018-12-27T18:30:40
2018-12-27T18:30:40
117,389,346
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; public class MinCostPathBF { public static int pathFinder(int[][] path, int m, int n) { if(m < 0 || n < 0) { return Integer.MAX_VALUE; } else if (m == 0 && n == 0) { return path[m][n]; } else { return path[m][n] + Math.min(pathFinder(path, m - 1, n - 1), Math.min(pathFinder(path, m - 1, n), pathFinder(path, m, n - 1))); } } public static void main(String[] args) { int[][] path = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; System.out.println(pathFinder(path, 2, 2)); } }
UTF-8
Java
599
java
MinCostPathBF.java
Java
[]
null
[]
import java.util.*; public class MinCostPathBF { public static int pathFinder(int[][] path, int m, int n) { if(m < 0 || n < 0) { return Integer.MAX_VALUE; } else if (m == 0 && n == 0) { return path[m][n]; } else { return path[m][n] + Math.min(pathFinder(path, m - 1, n - 1), Math.min(pathFinder(path, m - 1, n), pathFinder(path, m, n - 1))); } } public static void main(String[] args) { int[][] path = {{1, 2, 3}, {4, 8, 2}, {1, 5, 3} }; System.out.println(pathFinder(path, 2, 2)); } }
599
0.479132
0.447412
33
17.151516
25.954647
129
false
false
0
0
0
0
0
0
1.575758
false
false
12
e1ffa588f36937b997ee664d4a5ee1141c90dbe0
26,594,437,509,180
2034a25215690698e15880a0c0d62289852678e8
/src/main/java/com/miros/testproject/view/BaseView.java
1943d5b02d1176c2351727e2a392085707dba5eb
[]
no_license
Softwerke-Java-School-2018/demin
https://github.com/Softwerke-Java-School-2018/demin
c7061fea299d1b8ffe2124d464d41a50496702be
58afb690df9ca5b7e8260357c4beb621f74ecfc5
refs/heads/master
2020-03-09T12:07:06.178000
2018-06-01T09:55:52
2018-06-01T09:55:52
128,778,001
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.miros.testproject.view; import com.miros.testproject.BaseClass; /** * All View classes extends from this class */ public class BaseView extends BaseClass { }
UTF-8
Java
176
java
BaseView.java
Java
[]
null
[]
package com.miros.testproject.view; import com.miros.testproject.BaseClass; /** * All View classes extends from this class */ public class BaseView extends BaseClass { }
176
0.755682
0.755682
10
16.5
18.901058
43
false
false
0
0
0
0
0
0
0.2
false
false
12
47342a41de5e98e2cb3cb0333727772b27d1ff1d
28,200,755,333,792
2ba1cf8eb2219e37400758c85b2b6178c663ceeb
/src/com/btvn02/Main.java
d6724e16cb73651e5004eefe8d0430a435489e63
[]
no_license
TienDuy031197/TienDuy_BTVN02
https://github.com/TienDuy031197/TienDuy_BTVN02
0013261db58e4d11977ee91bff538bcbbf0580ba
9afd5b72caf306d5861b809aaba008b43bc651d8
refs/heads/master
2020-06-07T06:47:53.569000
2019-06-22T08:57:13
2019-06-22T08:57:13
192,953,351
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.btvn02; import java.util.Calendar; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub long start = Calendar.getInstance().getTimeInMillis(); Process process = new Process(); process.readFile(Constant.PATH); process.sort(); long end = Calendar.getInstance().getTimeInMillis(); System.out.println(end - start); } }
UTF-8
Java
396
java
Main.java
Java
[]
null
[]
package com.btvn02; import java.util.Calendar; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub long start = Calendar.getInstance().getTimeInMillis(); Process process = new Process(); process.readFile(Constant.PATH); process.sort(); long end = Calendar.getInstance().getTimeInMillis(); System.out.println(end - start); } }
396
0.707071
0.70202
19
19.842106
18.801632
56
false
false
0
0
0
0
0
0
1.473684
false
false
12
dcd30190b0cd6724eb0205815aa6b19bd2166cdc
2,946,347,614,878
48b7e40ee791e124aeceb2d06268d21eb0b4028f
/br.unioeste.sisra/src/br/unioeste/sisra/controle/validacao/PedidoValidacao.java
e8f506a6d498cd8460dc1c3a2ad91afc1a4a7a70
[]
no_license
jclazzarim/Sisra
https://github.com/jclazzarim/Sisra
88ac680fd21eb7e5fb5cc4210517a31d8f8235d7
b413d718694db76471b4fb7bf011125b612ebef6
refs/heads/master
2020-07-03T13:03:49.380000
2013-11-12T22:33:13
2013-11-12T22:33:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.unioeste.sisra.controle.validacao; import br.unioeste.sisra.modelo.execao.ValidacaoException; import br.unioeste.sisra.modelo.to.FuncionarioTO; import br.unioeste.sisra.utils.DataUtils; import br.unioeste.sisra.utils.NumericoUtils; /** * * @author Tharle J. Camargo */ public class PedidoValidacao extends Validacao { public static final String CHAVE_CAMPO_CONTA_ID = "idConta"; @Override public void validar(Object to) throws ValidacaoException { } }
UTF-8
Java
517
java
PedidoValidacao.java
Java
[ { "context": ".sisra.utils.NumericoUtils;\r\n\r\n/**\r\n *\r\n * @author Tharle J. Camargo\r\n */\r\npublic class PedidoValidacao extends Valida", "end": 289, "score": 0.9998812079429626, "start": 272, "tag": "NAME", "value": "Tharle J. Camargo" } ]
null
[]
package br.unioeste.sisra.controle.validacao; import br.unioeste.sisra.modelo.execao.ValidacaoException; import br.unioeste.sisra.modelo.to.FuncionarioTO; import br.unioeste.sisra.utils.DataUtils; import br.unioeste.sisra.utils.NumericoUtils; /** * * @author <NAME> */ public class PedidoValidacao extends Validacao { public static final String CHAVE_CAMPO_CONTA_ID = "idConta"; @Override public void validar(Object to) throws ValidacaoException { } }
506
0.719536
0.719536
21
22.619047
23.965206
64
false
false
0
0
0
0
0
0
0.285714
false
false
12
b672aceed03454e99ca50ec3c0d9de3cd80c48ed
16,441,134,849,035
dc5803fa48a510fcf6320eae06038c83a6605e2d
/src/test/java/Run_Demo/RunnerableDemo.java
d6e03f1290ff82b5ce736d6ad7fba5ca0d125dbb
[]
no_license
sudiprai10/cucumber_java_pom
https://github.com/sudiprai10/cucumber_java_pom
af9ca5067772380795862fe4ce7638314d2c20b6
fc975e94af69e0bd1720ffb1dd49af75bfa484ed
refs/heads/master
2018-04-03T17:02:36.746000
2017-04-20T02:13:41
2017-04-20T02:13:41
88,809,915
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Run_Demo; /** * Created by sudip on 4/19/17. */ import org.junit.BeforeClass; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features = "src/test/java", format = { "pretty","html:target/cucumber-html-report" }, glue = { "StepFile" }, tags = {}) public class RunnerableDemo { }
UTF-8
Java
426
java
RunnerableDemo.java
Java
[ { "context": "package Run_Demo;\n\n/**\n * Created by sudip on 4/19/17.\n */\n\nimport org.junit.BeforeClass;\nim", "end": 42, "score": 0.9943572878837585, "start": 37, "tag": "USERNAME", "value": "sudip" } ]
null
[]
package Run_Demo; /** * Created by sudip on 4/19/17. */ import org.junit.BeforeClass; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features = "src/test/java", format = { "pretty","html:target/cucumber-html-report" }, glue = { "StepFile" }, tags = {}) public class RunnerableDemo { }
426
0.666667
0.65493
21
19.285715
17.216114
65
false
false
0
0
0
0
0
0
0.428571
false
false
12
83fbf8cc387bf9be97853a475e81ce00411ce93b
14,293,651,172,579
4de65aa9d4a83d59ab102825507d00ff4d981a40
/src/HttpRequest.java
4dbd4ae253c1a0438b2a4afa78c90ad0d93d398f
[]
no_license
AlexAbraham1/AlexaBestRide
https://github.com/AlexAbraham1/AlexaBestRide
a153d389c3e2229cc9b362d5cf41c38212805b92
6bf64ddb38f464113b9a7881775dffff54ab3ec2
refs/heads/master
2021-01-01T03:49:51.855000
2016-04-17T22:40:17
2016-04-17T22:40:17
56,462,259
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.apache.commons.logging.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.lang.reflect.Type; import java.net.URL; import java.util.HashMap; import java.util.Map; import static org.apache.http.protocol.HTTP.USER_AGENT; /** * Created by alexabraham on 4/17/16. */ public class HttpRequest { private static Gson gson = new Gson(); public static String GET(String url) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpGet get = new HttpGet(url); get.setHeader("Authorization", "Bearer " + Config.Lyft.TOKEN); HttpResponse httpResponse = httpClient.execute(get); InputStream is = httpResponse.getEntity().getContent(); BufferedReader buffReader = new BufferedReader(new InputStreamReader(is)); StringBuffer response = new StringBuffer(); String line = null; try { line = buffReader.readLine(); } catch (IOException e) { e.printStackTrace(); } while (line != null) { response.append(line); response.append('\n'); try { line = buffReader.readLine(); } catch (IOException e) { System.out.println(" IOException: " + e.getMessage()); e.printStackTrace(); } } try { buffReader.close(); } catch (IOException e) { e.printStackTrace(); } return response.toString(); } public static Map<String, Object> parseJson(String json) { Gson gson = new Gson(); Map<String,Object> map = new HashMap<String,Object>(); map = (Map<String,Object>) gson.fromJson(json, map.getClass()); return map; } }
UTF-8
Java
2,332
java
HttpRequest.java
Java
[ { "context": ".http.protocol.HTTP.USER_AGENT;\n\n/**\n * Created by alexabraham on 4/17/16.\n */\npublic class HttpRequest {\n\n p", "end": 827, "score": 0.9962762594223022, "start": 816, "tag": "USERNAME", "value": "alexabraham" } ]
null
[]
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.apache.commons.logging.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.lang.reflect.Type; import java.net.URL; import java.util.HashMap; import java.util.Map; import static org.apache.http.protocol.HTTP.USER_AGENT; /** * Created by alexabraham on 4/17/16. */ public class HttpRequest { private static Gson gson = new Gson(); public static String GET(String url) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpGet get = new HttpGet(url); get.setHeader("Authorization", "Bearer " + Config.Lyft.TOKEN); HttpResponse httpResponse = httpClient.execute(get); InputStream is = httpResponse.getEntity().getContent(); BufferedReader buffReader = new BufferedReader(new InputStreamReader(is)); StringBuffer response = new StringBuffer(); String line = null; try { line = buffReader.readLine(); } catch (IOException e) { e.printStackTrace(); } while (line != null) { response.append(line); response.append('\n'); try { line = buffReader.readLine(); } catch (IOException e) { System.out.println(" IOException: " + e.getMessage()); e.printStackTrace(); } } try { buffReader.close(); } catch (IOException e) { e.printStackTrace(); } return response.toString(); } public static Map<String, Object> parseJson(String json) { Gson gson = new Gson(); Map<String,Object> map = new HashMap<String,Object>(); map = (Map<String,Object>) gson.fromJson(json, map.getClass()); return map; } }
2,332
0.650943
0.648799
77
29.285715
22.025286
82
false
false
0
0
0
0
0
0
0.636364
false
false
12
a00a0ad7ac9231c82a757a4725bf20ca5c3a6e37
23,880,018,191,880
43fc57e9078edcf5289ad81c7deeefad7d05daf7
/app/src/main/java/com/whzl/mengbi/chat/room/util/RoundSpan.java
7a728ddc5371d20a326b637a7cdf9993834c92b1
[]
no_license
tiangt/MB
https://github.com/tiangt/MB
51ac7ffb776e7a2ffded034d1a159e85f8fddbc5
45b551f0594aaea8fd1250b9861573cbbf30dd22
refs/heads/master
2021-01-02T15:50:39.674000
2019-12-11T03:07:10
2019-12-11T03:07:10
239,680,624
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.whzl.mengbi.chat.room.util; import android.content.Context; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.text.style.ReplacementSpan; import com.whzl.mengbi.util.UIUtil; /** * @author nobody * @date 2019/4/12 */ public class RoundSpan extends ReplacementSpan { private int bgColor; private int endColor; private int textColor; private Context context; private final Paint tvPaint; public RoundSpan(Context context, int bgColor, int endcolor, int textColor) { super(); this.textColor = textColor; this.context = context; this.bgColor = bgColor; this.endColor = endcolor; tvPaint = new Paint(); } @Override public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { paint.setTextSize(UIUtil.sp2px(context, 10)); return ((int) paint.measureText(text, start, end) + 24); } @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { LinearGradient lg = new LinearGradient(x, top, x + ((int) paint.measureText(text, start, end)) + 24, x + paint.measureText(text, start, end), bgColor, endColor, Shader.TileMode.CLAMP); paint.setShader(lg); canvas.drawRoundRect(new RectF(x, top + 5, x + ((int) paint.measureText(text, start, end)) + 24, bottom - 5), 30, 30, paint); paint.clearShadowLayer(); tvPaint.setColor(this.textColor); tvPaint.setTextSize(UIUtil.sp2px(context, 10)); canvas.drawText(text, start, end, x + 12, y - 3, tvPaint); } }
UTF-8
Java
1,788
java
RoundSpan.java
Java
[ { "context": "mport com.whzl.mengbi.util.UIUtil;\n\n/**\n * @author nobody\n * @date 2019/4/12\n */\npublic class RoundSpan ext", "end": 341, "score": 0.9991871118545532, "start": 335, "tag": "USERNAME", "value": "nobody" } ]
null
[]
package com.whzl.mengbi.chat.room.util; import android.content.Context; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.text.style.ReplacementSpan; import com.whzl.mengbi.util.UIUtil; /** * @author nobody * @date 2019/4/12 */ public class RoundSpan extends ReplacementSpan { private int bgColor; private int endColor; private int textColor; private Context context; private final Paint tvPaint; public RoundSpan(Context context, int bgColor, int endcolor, int textColor) { super(); this.textColor = textColor; this.context = context; this.bgColor = bgColor; this.endColor = endcolor; tvPaint = new Paint(); } @Override public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { paint.setTextSize(UIUtil.sp2px(context, 10)); return ((int) paint.measureText(text, start, end) + 24); } @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { LinearGradient lg = new LinearGradient(x, top, x + ((int) paint.measureText(text, start, end)) + 24, x + paint.measureText(text, start, end), bgColor, endColor, Shader.TileMode.CLAMP); paint.setShader(lg); canvas.drawRoundRect(new RectF(x, top + 5, x + ((int) paint.measureText(text, start, end)) + 24, bottom - 5), 30, 30, paint); paint.clearShadowLayer(); tvPaint.setColor(this.textColor); tvPaint.setTextSize(UIUtil.sp2px(context, 10)); canvas.drawText(text, start, end, x + 12, y - 3, tvPaint); } }
1,788
0.674497
0.658837
51
34.07843
33.619465
149
false
false
0
0
0
0
0
0
1.392157
false
false
12
ff71a0d93713daa081c8d32a1e98bd40f79fbe8d
24,197,845,750,294
e8ce75cadfc502dab2f5d853cf52cd024c64bf95
/src/app/src/main/java/com/example/staffmanagement/View/Staff/UserProfile/StaffUserProfileActivity.java
f0e6f3e20f52b44a73e191145739f4c87f3f136d
[]
no_license
wata-brucenguyen/StaffManagement
https://github.com/wata-brucenguyen/StaffManagement
6f20f4b481944428c06bce32b352974459b59024
7106a9dc2f4a9f7fb333065edf61252f145df23d
refs/heads/master
2022-12-12T10:23:02.262000
2020-09-08T13:28:58
2020-09-08T13:28:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.staffmanagement.View.Staff.UserProfile; import android.Manifest; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProviders; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.example.staffmanagement.Model.Entity.User; import com.example.staffmanagement.R; import com.example.staffmanagement.View.Data.UserSingleTon; import com.example.staffmanagement.View.Main.LoginActivity; import com.example.staffmanagement.View.Admin.SendNotificationActivity.Service.Broadcast; import com.example.staffmanagement.View.Ultils.CheckNetwork; import com.example.staffmanagement.View.Ultils.Constant; import com.example.staffmanagement.View.Ultils.GeneralFunc; import com.example.staffmanagement.View.Ultils.ImageHandler; import com.example.staffmanagement.ViewModel.Staff.StaffUserProfileVM; import java.util.Objects; import java.util.regex.Pattern; public class StaffUserProfileActivity extends AppCompatActivity { private CheckNetwork mCheckNetwork; private TextView txtName, txtRole, txtEmail, txtPhoneNumber, txtAddress, txtCloseDialog, txt_eup_accept; private EditText tv_eup_name, tv_eup_phone, tv_eup_email, tv_eup_address; private ImageView imvBack, imvEdit, imvChangeAvatarDialog, imvAvatar; private Dialog mDialog; private Bitmap mBitmap; private ProgressDialog mProgressDialog; private Broadcast mBroadcast; private boolean isChooseAvatar = false; private StaffUserProfileVM mViewModel; private static final int REQUEST_CODE_CAMERA = 1; private static final int REQUEST_CODE_GALLERY = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.StaffAppTheme); setContentView(R.layout.activity_user_profile); mapping(); mViewModel = ViewModelProviders.of(StaffUserProfileActivity.this).get(StaffUserProfileVM.class); eventRegister(); setDataOnView(mViewModel.getUser()); } @Override protected void onStart() { super.onStart(); mBroadcast = new Broadcast(); IntentFilter filter = new IntentFilter("Notification"); registerReceiver(mBroadcast, filter); mCheckNetwork = new CheckNetwork(this); mCheckNetwork.registerCheckingNetwork(); } @Override protected void onStop() { super.onStop(); unregisterReceiver(mBroadcast); mCheckNetwork.unRegisterCheckingNetwork(); } @Override protected void onDestroy() { super.onDestroy(); mDialog = null; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_GALLERY && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent, REQUEST_CODE_GALLERY); } else if (requestCode == REQUEST_CODE_CAMERA && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, REQUEST_CODE_CAMERA); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null) { isChooseAvatar = true; Uri uri = data.getData(); mBitmap = ImageHandler.getBitmapFromUriAndShowImage(this, uri, imvChangeAvatarDialog); } else if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK && data != null) { isChooseAvatar = true; mBitmap = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data"); imvChangeAvatarDialog.setImageBitmap(mBitmap); } } private void mapping() { txtName = findViewById(R.id.textView_name_userProfile); txtRole = findViewById(R.id.textView_role_userProfile); txtEmail = findViewById(R.id.textView_email_userProfile); txtPhoneNumber = findViewById(R.id.textView_phone_userProfile); txtAddress = findViewById(R.id.textView_address_userProfile); imvBack = findViewById(R.id.imv_backUserProfile); imvEdit = findViewById(R.id.editOptionsUserProfile); imvAvatar = findViewById(R.id.imvAvatarUserProfile); } private void setDataOnView(User user) { txtName.setText(user.getFullName()); txtEmail.setText(user.getEmail()); txtPhoneNumber.setText(user.getPhoneNumber()); txtAddress.setText(user.getAddress()); txtRole.setText(user.getRole().getName()); if (UserSingleTon.getInstance().getUser().getAvatar() != null) { RequestOptions options = new RequestOptions() .centerCrop() .placeholder(R.mipmap.ic_launcher_round) .error(R.mipmap.ic_launcher_round); Glide.with(this).load(UserSingleTon.getInstance(). getUser().getAvatar()).apply(options).into(imvAvatar); } } private void eventRegister() { imvBack.setOnClickListener(view -> finish()); imvEdit.setOnClickListener(view -> setUpBtnEditProfile()); imvAvatar.setOnClickListener(view -> openDialogOptionChangeAvatar()); mViewModel.getUserLD().observe(this, user -> { if (user != null) { setDataOnView(user); } if (mProgressDialog != null && mProgressDialog.isShowing()) dismissProgressDialog(); if (mDialog != null && mDialog.isShowing()){ mDialog.dismiss(); } }); } private void setUpBtnEditProfile() { PopupMenu popupMenu = new PopupMenu(this, imvEdit); popupMenu.getMenuInflater().inflate(R.menu.menu_edit_user_profile, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(item -> { switch (item.getItemId()) { case R.id.item_menu_editUserProfile_in_staff: activateEditUserProfile(); break; case R.id.item_menu_changePassword_in_staff: activateChangePassword(); break; case R.id.item_menu_change_avatar_in_staff: openDialogOptionChangeAvatar(); break; } return false; }); popupMenu.show(); } public void activateEditUserProfile() { newDialog(R.layout.dialog_edit_user_profile_staff); mappingEditUserProfile(); registerEventEditUserProfile(); } public void newDialog(int layoutRes) { mDialog = new Dialog(StaffUserProfileActivity.this); mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mDialog.setContentView(layoutRes); mDialog.setCanceledOnTouchOutside(false); Window window = mDialog.getWindow(); assert window != null; window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); } public void mappingEditUserProfile() { txtCloseDialog = mDialog.findViewById(R.id.textView_CloseEditUserProfile); tv_eup_name = mDialog.findViewById(R.id.tv_eup_Name); tv_eup_phone = mDialog.findViewById(R.id.tv_eup_Phone); tv_eup_address = mDialog.findViewById(R.id.tv_eup_Address); tv_eup_email = mDialog.findViewById(R.id.tv_eup_Email); txt_eup_accept = mDialog.findViewById(R.id.textView_accept_filter); tv_eup_name.setText(UserSingleTon.getInstance().getUser().getFullName()); tv_eup_phone.setText(UserSingleTon.getInstance().getUser().getPhoneNumber()); tv_eup_email.setText(UserSingleTon.getInstance().getUser().getEmail()); tv_eup_address.setText(UserSingleTon.getInstance().getUser().getAddress()); } private void registerEventEditUserProfile() { GeneralFunc.setHideKeyboardOnTouch(this, mDialog.findViewById(R.id.ProfileStaff)); txtCloseDialog.setOnClickListener(v -> mDialog.dismiss()); txt_eup_accept.setOnClickListener(v -> { if (!CheckNetwork.checkInternetConnection(StaffUserProfileActivity.this)) { return; } newProgressDialog(); showProgressDialog(); // check user name String name = tv_eup_name.getText().toString(); if (TextUtils.isEmpty(name)) { showMessage("Name field is empty"); tv_eup_name.requestFocus(); dismissProgressDialog(); return; } // check phone number String phone = tv_eup_phone.getText().toString(); if (phone.length() < 10 || phone.length() > 12) { showMessage("Phone number must be from 10 to 12"); tv_eup_phone.requestFocus(); dismissProgressDialog(); return; } // check String emailPattern = "^[a-z][a-z0-9_.]{1,32}@[a-z0-9]{2,}(\\.[a-z0-9]{2,4}){1,2}$"; String email = tv_eup_email.getText().toString(); if (email.length() > 0 && !Pattern.matches(emailPattern, email)) { showMessage("Email format is wrong"); tv_eup_email.requestFocus(); dismissProgressDialog(); return; } mViewModel.getUser().setFullName(name); mViewModel.getUser().setPhoneNumber(phone); mViewModel.getUser().setEmail(email); mViewModel.getUser().setAddress(tv_eup_address.getText().toString()); mViewModel.updateUserProfile(); GeneralFunc.setStateChangeProfile(StaffUserProfileActivity.this, true); }); mDialog.show(); } public void activateChangePassword() { newDialog(R.layout.dialog_change_user_password); final EditText edtOldPass = mDialog.findViewById(R.id.edt_oldPassword_non_admin), edtNewPass = mDialog.findViewById(R.id.edt_newPassword_non_admin), edtReNewPass = mDialog.findViewById(R.id.edt_reNewPassword_non_admin); TextView btnAccept = mDialog.findViewById(R.id.textView_acceptChangePassword_non_admin); TextView imvClose = mDialog.findViewById(R.id.textView_CloseChangePassword); imvClose.setOnClickListener(v -> mDialog.dismiss()); btnAccept.setOnClickListener(v -> { if (!CheckNetwork.checkInternetConnection(StaffUserProfileActivity.this)) { return; } newProgressDialog(); showProgressDialog(); String oldPass = edtOldPass.getText().toString(); String newPass = edtNewPass.getText().toString(); String confirmNewPass = edtReNewPass.getText().toString(); checkInfoChangePassword(oldPass, newPass, confirmNewPass); }); GeneralFunc.setHideKeyboardOnTouch(this, mDialog.findViewById(R.id.ChangePasswordStaff)); mDialog.show(); } private void openDialogOptionChangeAvatar() { mDialog = new Dialog(StaffUserProfileActivity.this); mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mDialog.setContentView(R.layout.dialog_change_avatar_staff); mDialog.setCanceledOnTouchOutside(false); imvChangeAvatarDialog = mDialog.findViewById(R.id.imageView_change_avatar_dialog); if (UserSingleTon.getInstance().getUser().getAvatar() != null) { RequestOptions options = new RequestOptions() .centerCrop() .placeholder(R.mipmap.ic_launcher_round) .error(R.mipmap.ic_launcher_round); Glide.with(this).load(UserSingleTon.getInstance().getUser().getAvatar()).apply(options).into(imvChangeAvatarDialog); } Window window = mDialog.getWindow(); assert window != null; window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); // close dialog TextView txtCloseDialog = mDialog.findViewById(R.id.textView_CloseDialog); txtCloseDialog.setOnClickListener(view -> { mDialog.dismiss(); isChooseAvatar = false; }); // accept change avatar TextView txtAccept = mDialog.findViewById(R.id.textView_ApplyDialog); txtAccept.setOnClickListener(view -> { if (isChooseAvatar) { if (!CheckNetwork.checkInternetConnection(StaffUserProfileActivity.this)) { return; } newProgressDialog(); showProgressDialog(); mViewModel.changeAvatar(mBitmap); isChooseAvatar = false; GeneralFunc.setStateChangeProfile(StaffUserProfileActivity.this, true); } else { showMessage("You haven't chosen image or captured image from camera"); } }); // choose from gallery LinearLayout llGallery = mDialog.findViewById(R.id.linearLayout_choose_gallery); llGallery.setOnClickListener(view -> requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_GALLERY)); //choose from camera LinearLayout llCamera = mDialog.findViewById(R.id.linearLayout_choose_camera); llCamera.setOnClickListener(view -> requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA)); mDialog.show(); } public void showMessage(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } private void logout() { showMessage("Password is changed"); Intent intent = new Intent(StaffUserProfileActivity.this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); SharedPreferences sharedPreferences = getSharedPreferences(Constant.SHARED_PREFERENCE_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.remove(Constant.SHARED_PREFERENCE_IS_LOGIN); editor.remove(Constant.SHARED_PREFERENCE_ID_USER); editor.apply(); startActivity(intent); finish(); } public void checkInfoChangePassword(String oldPass, String newPass, String confirmNewPass) { if (TextUtils.isEmpty(oldPass) || TextUtils.isEmpty(newPass) || TextUtils.isEmpty(confirmNewPass)) { showMessage("Some field is empty"); dismissProgressDialog(); return; } if (!UserSingleTon.getInstance().getUser().getPassword().equals(GeneralFunc.getMD5(oldPass))) { showMessage("Old password is wrong"); dismissProgressDialog(); return; } if (newPass.length() < 6) { showMessage("New password must more 6 characters"); dismissProgressDialog(); return; } if (!newPass.equals(confirmNewPass)) { showMessage("Confirm password is wrong"); dismissProgressDialog(); return; } mViewModel.getUser().setPassword(GeneralFunc.getMD5(newPass)); mViewModel.updateUserProfile(); logout(); } private void newProgressDialog() { mProgressDialog = new ProgressDialog(this); mProgressDialog.setCanceledOnTouchOutside(false); mProgressDialog.setMessage("Loading..."); } private void showProgressDialog() { if (mProgressDialog != null) mProgressDialog.show(); } private void dismissProgressDialog() { if (mProgressDialog != null && mProgressDialog.isShowing()) mProgressDialog.dismiss(); } }
UTF-8
Java
17,119
java
StaffUserProfileActivity.java
Java
[]
null
[]
package com.example.staffmanagement.View.Staff.UserProfile; import android.Manifest; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProviders; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.example.staffmanagement.Model.Entity.User; import com.example.staffmanagement.R; import com.example.staffmanagement.View.Data.UserSingleTon; import com.example.staffmanagement.View.Main.LoginActivity; import com.example.staffmanagement.View.Admin.SendNotificationActivity.Service.Broadcast; import com.example.staffmanagement.View.Ultils.CheckNetwork; import com.example.staffmanagement.View.Ultils.Constant; import com.example.staffmanagement.View.Ultils.GeneralFunc; import com.example.staffmanagement.View.Ultils.ImageHandler; import com.example.staffmanagement.ViewModel.Staff.StaffUserProfileVM; import java.util.Objects; import java.util.regex.Pattern; public class StaffUserProfileActivity extends AppCompatActivity { private CheckNetwork mCheckNetwork; private TextView txtName, txtRole, txtEmail, txtPhoneNumber, txtAddress, txtCloseDialog, txt_eup_accept; private EditText tv_eup_name, tv_eup_phone, tv_eup_email, tv_eup_address; private ImageView imvBack, imvEdit, imvChangeAvatarDialog, imvAvatar; private Dialog mDialog; private Bitmap mBitmap; private ProgressDialog mProgressDialog; private Broadcast mBroadcast; private boolean isChooseAvatar = false; private StaffUserProfileVM mViewModel; private static final int REQUEST_CODE_CAMERA = 1; private static final int REQUEST_CODE_GALLERY = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.StaffAppTheme); setContentView(R.layout.activity_user_profile); mapping(); mViewModel = ViewModelProviders.of(StaffUserProfileActivity.this).get(StaffUserProfileVM.class); eventRegister(); setDataOnView(mViewModel.getUser()); } @Override protected void onStart() { super.onStart(); mBroadcast = new Broadcast(); IntentFilter filter = new IntentFilter("Notification"); registerReceiver(mBroadcast, filter); mCheckNetwork = new CheckNetwork(this); mCheckNetwork.registerCheckingNetwork(); } @Override protected void onStop() { super.onStop(); unregisterReceiver(mBroadcast); mCheckNetwork.unRegisterCheckingNetwork(); } @Override protected void onDestroy() { super.onDestroy(); mDialog = null; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_GALLERY && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent, REQUEST_CODE_GALLERY); } else if (requestCode == REQUEST_CODE_CAMERA && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, REQUEST_CODE_CAMERA); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null) { isChooseAvatar = true; Uri uri = data.getData(); mBitmap = ImageHandler.getBitmapFromUriAndShowImage(this, uri, imvChangeAvatarDialog); } else if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK && data != null) { isChooseAvatar = true; mBitmap = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data"); imvChangeAvatarDialog.setImageBitmap(mBitmap); } } private void mapping() { txtName = findViewById(R.id.textView_name_userProfile); txtRole = findViewById(R.id.textView_role_userProfile); txtEmail = findViewById(R.id.textView_email_userProfile); txtPhoneNumber = findViewById(R.id.textView_phone_userProfile); txtAddress = findViewById(R.id.textView_address_userProfile); imvBack = findViewById(R.id.imv_backUserProfile); imvEdit = findViewById(R.id.editOptionsUserProfile); imvAvatar = findViewById(R.id.imvAvatarUserProfile); } private void setDataOnView(User user) { txtName.setText(user.getFullName()); txtEmail.setText(user.getEmail()); txtPhoneNumber.setText(user.getPhoneNumber()); txtAddress.setText(user.getAddress()); txtRole.setText(user.getRole().getName()); if (UserSingleTon.getInstance().getUser().getAvatar() != null) { RequestOptions options = new RequestOptions() .centerCrop() .placeholder(R.mipmap.ic_launcher_round) .error(R.mipmap.ic_launcher_round); Glide.with(this).load(UserSingleTon.getInstance(). getUser().getAvatar()).apply(options).into(imvAvatar); } } private void eventRegister() { imvBack.setOnClickListener(view -> finish()); imvEdit.setOnClickListener(view -> setUpBtnEditProfile()); imvAvatar.setOnClickListener(view -> openDialogOptionChangeAvatar()); mViewModel.getUserLD().observe(this, user -> { if (user != null) { setDataOnView(user); } if (mProgressDialog != null && mProgressDialog.isShowing()) dismissProgressDialog(); if (mDialog != null && mDialog.isShowing()){ mDialog.dismiss(); } }); } private void setUpBtnEditProfile() { PopupMenu popupMenu = new PopupMenu(this, imvEdit); popupMenu.getMenuInflater().inflate(R.menu.menu_edit_user_profile, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(item -> { switch (item.getItemId()) { case R.id.item_menu_editUserProfile_in_staff: activateEditUserProfile(); break; case R.id.item_menu_changePassword_in_staff: activateChangePassword(); break; case R.id.item_menu_change_avatar_in_staff: openDialogOptionChangeAvatar(); break; } return false; }); popupMenu.show(); } public void activateEditUserProfile() { newDialog(R.layout.dialog_edit_user_profile_staff); mappingEditUserProfile(); registerEventEditUserProfile(); } public void newDialog(int layoutRes) { mDialog = new Dialog(StaffUserProfileActivity.this); mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mDialog.setContentView(layoutRes); mDialog.setCanceledOnTouchOutside(false); Window window = mDialog.getWindow(); assert window != null; window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); } public void mappingEditUserProfile() { txtCloseDialog = mDialog.findViewById(R.id.textView_CloseEditUserProfile); tv_eup_name = mDialog.findViewById(R.id.tv_eup_Name); tv_eup_phone = mDialog.findViewById(R.id.tv_eup_Phone); tv_eup_address = mDialog.findViewById(R.id.tv_eup_Address); tv_eup_email = mDialog.findViewById(R.id.tv_eup_Email); txt_eup_accept = mDialog.findViewById(R.id.textView_accept_filter); tv_eup_name.setText(UserSingleTon.getInstance().getUser().getFullName()); tv_eup_phone.setText(UserSingleTon.getInstance().getUser().getPhoneNumber()); tv_eup_email.setText(UserSingleTon.getInstance().getUser().getEmail()); tv_eup_address.setText(UserSingleTon.getInstance().getUser().getAddress()); } private void registerEventEditUserProfile() { GeneralFunc.setHideKeyboardOnTouch(this, mDialog.findViewById(R.id.ProfileStaff)); txtCloseDialog.setOnClickListener(v -> mDialog.dismiss()); txt_eup_accept.setOnClickListener(v -> { if (!CheckNetwork.checkInternetConnection(StaffUserProfileActivity.this)) { return; } newProgressDialog(); showProgressDialog(); // check user name String name = tv_eup_name.getText().toString(); if (TextUtils.isEmpty(name)) { showMessage("Name field is empty"); tv_eup_name.requestFocus(); dismissProgressDialog(); return; } // check phone number String phone = tv_eup_phone.getText().toString(); if (phone.length() < 10 || phone.length() > 12) { showMessage("Phone number must be from 10 to 12"); tv_eup_phone.requestFocus(); dismissProgressDialog(); return; } // check String emailPattern = "^[a-z][a-z0-9_.]{1,32}@[a-z0-9]{2,}(\\.[a-z0-9]{2,4}){1,2}$"; String email = tv_eup_email.getText().toString(); if (email.length() > 0 && !Pattern.matches(emailPattern, email)) { showMessage("Email format is wrong"); tv_eup_email.requestFocus(); dismissProgressDialog(); return; } mViewModel.getUser().setFullName(name); mViewModel.getUser().setPhoneNumber(phone); mViewModel.getUser().setEmail(email); mViewModel.getUser().setAddress(tv_eup_address.getText().toString()); mViewModel.updateUserProfile(); GeneralFunc.setStateChangeProfile(StaffUserProfileActivity.this, true); }); mDialog.show(); } public void activateChangePassword() { newDialog(R.layout.dialog_change_user_password); final EditText edtOldPass = mDialog.findViewById(R.id.edt_oldPassword_non_admin), edtNewPass = mDialog.findViewById(R.id.edt_newPassword_non_admin), edtReNewPass = mDialog.findViewById(R.id.edt_reNewPassword_non_admin); TextView btnAccept = mDialog.findViewById(R.id.textView_acceptChangePassword_non_admin); TextView imvClose = mDialog.findViewById(R.id.textView_CloseChangePassword); imvClose.setOnClickListener(v -> mDialog.dismiss()); btnAccept.setOnClickListener(v -> { if (!CheckNetwork.checkInternetConnection(StaffUserProfileActivity.this)) { return; } newProgressDialog(); showProgressDialog(); String oldPass = edtOldPass.getText().toString(); String newPass = edtNewPass.getText().toString(); String confirmNewPass = edtReNewPass.getText().toString(); checkInfoChangePassword(oldPass, newPass, confirmNewPass); }); GeneralFunc.setHideKeyboardOnTouch(this, mDialog.findViewById(R.id.ChangePasswordStaff)); mDialog.show(); } private void openDialogOptionChangeAvatar() { mDialog = new Dialog(StaffUserProfileActivity.this); mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mDialog.setContentView(R.layout.dialog_change_avatar_staff); mDialog.setCanceledOnTouchOutside(false); imvChangeAvatarDialog = mDialog.findViewById(R.id.imageView_change_avatar_dialog); if (UserSingleTon.getInstance().getUser().getAvatar() != null) { RequestOptions options = new RequestOptions() .centerCrop() .placeholder(R.mipmap.ic_launcher_round) .error(R.mipmap.ic_launcher_round); Glide.with(this).load(UserSingleTon.getInstance().getUser().getAvatar()).apply(options).into(imvChangeAvatarDialog); } Window window = mDialog.getWindow(); assert window != null; window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); // close dialog TextView txtCloseDialog = mDialog.findViewById(R.id.textView_CloseDialog); txtCloseDialog.setOnClickListener(view -> { mDialog.dismiss(); isChooseAvatar = false; }); // accept change avatar TextView txtAccept = mDialog.findViewById(R.id.textView_ApplyDialog); txtAccept.setOnClickListener(view -> { if (isChooseAvatar) { if (!CheckNetwork.checkInternetConnection(StaffUserProfileActivity.this)) { return; } newProgressDialog(); showProgressDialog(); mViewModel.changeAvatar(mBitmap); isChooseAvatar = false; GeneralFunc.setStateChangeProfile(StaffUserProfileActivity.this, true); } else { showMessage("You haven't chosen image or captured image from camera"); } }); // choose from gallery LinearLayout llGallery = mDialog.findViewById(R.id.linearLayout_choose_gallery); llGallery.setOnClickListener(view -> requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_GALLERY)); //choose from camera LinearLayout llCamera = mDialog.findViewById(R.id.linearLayout_choose_camera); llCamera.setOnClickListener(view -> requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA)); mDialog.show(); } public void showMessage(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } private void logout() { showMessage("Password is changed"); Intent intent = new Intent(StaffUserProfileActivity.this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); SharedPreferences sharedPreferences = getSharedPreferences(Constant.SHARED_PREFERENCE_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.remove(Constant.SHARED_PREFERENCE_IS_LOGIN); editor.remove(Constant.SHARED_PREFERENCE_ID_USER); editor.apply(); startActivity(intent); finish(); } public void checkInfoChangePassword(String oldPass, String newPass, String confirmNewPass) { if (TextUtils.isEmpty(oldPass) || TextUtils.isEmpty(newPass) || TextUtils.isEmpty(confirmNewPass)) { showMessage("Some field is empty"); dismissProgressDialog(); return; } if (!UserSingleTon.getInstance().getUser().getPassword().equals(GeneralFunc.getMD5(oldPass))) { showMessage("Old password is wrong"); dismissProgressDialog(); return; } if (newPass.length() < 6) { showMessage("New password must more 6 characters"); dismissProgressDialog(); return; } if (!newPass.equals(confirmNewPass)) { showMessage("Confirm password is wrong"); dismissProgressDialog(); return; } mViewModel.getUser().setPassword(GeneralFunc.getMD5(newPass)); mViewModel.updateUserProfile(); logout(); } private void newProgressDialog() { mProgressDialog = new ProgressDialog(this); mProgressDialog.setCanceledOnTouchOutside(false); mProgressDialog.setMessage("Loading..."); } private void showProgressDialog() { if (mProgressDialog != null) mProgressDialog.show(); } private void dismissProgressDialog() { if (mProgressDialog != null && mProgressDialog.isShowing()) mProgressDialog.dismiss(); } }
17,119
0.656931
0.655003
415
40.253014
29.98877
144
false
false
0
0
0
0
0
0
0.725301
false
false
12
8cce600f91846cb19637f7d135554f5e94a05495
36,361,193,149,307
590417b46976c80f1c694e7d1d5d552b70ab7a9d
/src/java/com/icp/sigipro/produccion/modelos/Actividad_Apoyo.java
7b8e3f0421dc942ce1e6df0d075f5c42a20dddbb
[]
no_license
DNJJ1/SIGIPRO
https://github.com/DNJJ1/SIGIPRO
216a3873dba38dd5da1fc26555ae3ea9db3c0f23
3783625aafa3f39cb211a96a6795454d19439e50
refs/heads/master
2021-03-16T07:55:16.451000
2020-05-26T18:24:28
2020-05-26T18:24:28
27,406,819
0
2
null
false
2020-05-26T18:24:30
2014-12-02T00:17:10
2018-11-13T20:51:05
2020-05-26T18:24:29
23,135
0
2
0
Java
false
false
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.icp.sigipro.produccion.modelos; import java.lang.reflect.Field; import java.sql.SQLXML; import java.util.List; import org.json.JSONObject; /** * * @author Amed */ public class Actividad_Apoyo { private int id_actividad; private String nombre; private SQLXML estructura; private String estructuraString; private Categoria_AA categoria; private boolean aprobacion_calidad; private boolean aprobacion_direccion; private boolean aprobacion_regente; private boolean aprobacion_coordinador; private boolean aprobacion_gestion; private int version; private int id_historial; private String observaciones; private List<Actividad_Apoyo> historial; private boolean requiere_ap; private boolean estado; private boolean requiere_coordinacion; private boolean requiere_regencia; private int version_anterior; public Actividad_Apoyo() { } public int getVersion_anterior() { return version_anterior; } public void setVersion_anterior(int version_anterior) { this.version_anterior = version_anterior; } public boolean isRequiere_coordinacion() { return requiere_coordinacion; } public void setRequiere_coordinacion(boolean requiere_coordinacion) { this.requiere_coordinacion = requiere_coordinacion; } public boolean isRequiere_regencia() { return requiere_regencia; } public void setRequiere_regencia(boolean requiere_regencia) { this.requiere_regencia = requiere_regencia; } public boolean isEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } public boolean isRequiere_ap() { return requiere_ap; } public void setRequiere_ap(boolean requiere_ap) { this.requiere_ap = requiere_ap; } public boolean isAprobacion_gestion() { return aprobacion_gestion; } public void setAprobacion_gestion(boolean aprobacion_gestion) { this.aprobacion_gestion = aprobacion_gestion; } public String getObservaciones() { return observaciones; } public void setObservaciones(String observaciones) { this.observaciones = observaciones; } public int getId_actividad() { return id_actividad; } public void setId_actividad(int id_actividad) { this.id_actividad = id_actividad; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public SQLXML getEstructura() { return estructura; } public void setEstructura(SQLXML estructura) { this.estructura = estructura; } public String getEstructuraString() { return estructuraString; } public void setEstructuraString(String estructuraString) { this.estructuraString = estructuraString; } public Categoria_AA getCategoria() { return categoria; } public void setCategoria(Categoria_AA categoria) { this.categoria = categoria; } public boolean isAprobacion_calidad() { return aprobacion_calidad; } public void setAprobacion_calidad(boolean aprobacion_calidad) { this.aprobacion_calidad = aprobacion_calidad; } public boolean isAprobacion_direccion() { return aprobacion_direccion; } public void setAprobacion_direccion(boolean aprobacion_direccion) { this.aprobacion_direccion = aprobacion_direccion; } public boolean isAprobacion_regente() { return aprobacion_regente; } public void setAprobacion_regente(boolean aprobacion_regente) { this.aprobacion_regente = aprobacion_regente; } public boolean isAprobacion_coordinador() { return aprobacion_coordinador; } public void setAprobacion_coordinador(boolean aprobacion_coordinador) { this.aprobacion_coordinador = aprobacion_coordinador; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public int getId_historial() { return id_historial; } public void setId_historial(int id_historial) { this.id_historial = id_historial; } public List<Actividad_Apoyo> getHistorial() { return historial; } public void setHistorial(List<Actividad_Apoyo> historial) { this.historial = historial; } public String parseJSON() { Class _class = this.getClass(); JSONObject JSON = new JSONObject(); try { Field properties[] = _class.getDeclaredFields(); for (int i = 0; i < properties.length; i++) { Field field = properties[i]; if (i != 0) { JSON.put(field.getName(), field.get(this)); } else { JSON.put("id_objeto", field.get(this)); } }JSON.put("id_categoria_aa", this.getCategoria().getId_categoria_aa()); } catch (Exception e) { } return JSON.toString(); } }
UTF-8
Java
5,599
java
Actividad_Apoyo.java
Java
[ { "context": "import org.json.JSONObject;\r\n\r\n/**\r\n *\r\n * @author Amed\r\n */\r\npublic class Actividad_Apoyo {\r\n\r\n priva", "end": 374, "score": 0.9400326609611511, "start": 370, "tag": "NAME", "value": "Amed" }, { "context": "t org.json.JSONObject;\r\n\r\n/**\r\n *\r\n * @author Amed\r\n */\r\npublic class Actividad_Apoyo {\r\n\r\n private", "end": 374, "score": 0.6527982354164124, "start": 374, "tag": "USERNAME", "value": "" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.icp.sigipro.produccion.modelos; import java.lang.reflect.Field; import java.sql.SQLXML; import java.util.List; import org.json.JSONObject; /** * * @author Amed */ public class Actividad_Apoyo { private int id_actividad; private String nombre; private SQLXML estructura; private String estructuraString; private Categoria_AA categoria; private boolean aprobacion_calidad; private boolean aprobacion_direccion; private boolean aprobacion_regente; private boolean aprobacion_coordinador; private boolean aprobacion_gestion; private int version; private int id_historial; private String observaciones; private List<Actividad_Apoyo> historial; private boolean requiere_ap; private boolean estado; private boolean requiere_coordinacion; private boolean requiere_regencia; private int version_anterior; public Actividad_Apoyo() { } public int getVersion_anterior() { return version_anterior; } public void setVersion_anterior(int version_anterior) { this.version_anterior = version_anterior; } public boolean isRequiere_coordinacion() { return requiere_coordinacion; } public void setRequiere_coordinacion(boolean requiere_coordinacion) { this.requiere_coordinacion = requiere_coordinacion; } public boolean isRequiere_regencia() { return requiere_regencia; } public void setRequiere_regencia(boolean requiere_regencia) { this.requiere_regencia = requiere_regencia; } public boolean isEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } public boolean isRequiere_ap() { return requiere_ap; } public void setRequiere_ap(boolean requiere_ap) { this.requiere_ap = requiere_ap; } public boolean isAprobacion_gestion() { return aprobacion_gestion; } public void setAprobacion_gestion(boolean aprobacion_gestion) { this.aprobacion_gestion = aprobacion_gestion; } public String getObservaciones() { return observaciones; } public void setObservaciones(String observaciones) { this.observaciones = observaciones; } public int getId_actividad() { return id_actividad; } public void setId_actividad(int id_actividad) { this.id_actividad = id_actividad; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public SQLXML getEstructura() { return estructura; } public void setEstructura(SQLXML estructura) { this.estructura = estructura; } public String getEstructuraString() { return estructuraString; } public void setEstructuraString(String estructuraString) { this.estructuraString = estructuraString; } public Categoria_AA getCategoria() { return categoria; } public void setCategoria(Categoria_AA categoria) { this.categoria = categoria; } public boolean isAprobacion_calidad() { return aprobacion_calidad; } public void setAprobacion_calidad(boolean aprobacion_calidad) { this.aprobacion_calidad = aprobacion_calidad; } public boolean isAprobacion_direccion() { return aprobacion_direccion; } public void setAprobacion_direccion(boolean aprobacion_direccion) { this.aprobacion_direccion = aprobacion_direccion; } public boolean isAprobacion_regente() { return aprobacion_regente; } public void setAprobacion_regente(boolean aprobacion_regente) { this.aprobacion_regente = aprobacion_regente; } public boolean isAprobacion_coordinador() { return aprobacion_coordinador; } public void setAprobacion_coordinador(boolean aprobacion_coordinador) { this.aprobacion_coordinador = aprobacion_coordinador; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public int getId_historial() { return id_historial; } public void setId_historial(int id_historial) { this.id_historial = id_historial; } public List<Actividad_Apoyo> getHistorial() { return historial; } public void setHistorial(List<Actividad_Apoyo> historial) { this.historial = historial; } public String parseJSON() { Class _class = this.getClass(); JSONObject JSON = new JSONObject(); try { Field properties[] = _class.getDeclaredFields(); for (int i = 0; i < properties.length; i++) { Field field = properties[i]; if (i != 0) { JSON.put(field.getName(), field.get(this)); } else { JSON.put("id_objeto", field.get(this)); } }JSON.put("id_categoria_aa", this.getCategoria().getId_categoria_aa()); } catch (Exception e) { } return JSON.toString(); } }
5,599
0.623147
0.62279
214
24.163551
21.827839
83
false
false
0
0
0
0
0
0
0.364486
false
false
12
20eb8c63e07abe043a24e3f385a756323c3204bf
35,270,271,463,042
a5be356f8d364ef54ce43e6ca240f823f71e207c
/src/com/amarsoft/server/check/ErrorCheckMD5.java
556c82213078b16ce5b31bb383098b137904b29c
[]
no_license
alongyan/git_demo
https://github.com/alongyan/git_demo
aaf3959d6c5b5ec036c48c86429f3b85b8e90976
b421d736819c70d4f827a847d9a9a7d591959500
refs/heads/master
2021-01-09T20:38:52.756000
2016-06-15T02:30:29
2016-06-15T02:30:29
61,171,456
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amarsoft.server.check; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.amarsoft.server.dao.SQLQuery; import com.amarsoft.server.util.JMTimesEncrypt; public class ErrorCheckMD5 extends ErrorCheck { public boolean excute(Map<String, Object> requestMap, SQLQuery sqlQuery) { try { String sStartTime = (String) requestMap.get("StartTime"); String sEndTime = (String) requestMap.get("EndTime"); Map<String, String> md5Map = getMD5Map(requestMap); JMTimesEncrypt je = new JMTimesEncrypt(); String keyMD5j = je.initFingerprint(getItemName(sqlQuery),md5Map); String keyMD5 = (String)requestMap.get("key"); logger.info(keyMD5 + "\n" + keyMD5j); return keyMD5.equals(keyMD5j); } catch (Exception e) { printLog(e); return false; } } /** * @describe 该方法用于获取加密字符串 * @param sqlQuery * @return */ private String getItemName(SQLQuery sqlQuery){ String sItemDescribe = ""; String sSql = "select itemdescribe from code_library where codeno = 'JMTimesService' and itemno = '020'"; try { sItemDescribe = sqlQuery.getString(sSql); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return sItemDescribe; } private Map<String, String> getMD5Map(Map<String, Object> requestMap){ Map<String, String> retMap = new HashMap<String, String>(); for(Iterator<String> it = requestMap.keySet().iterator(); it.hasNext(); ){ String key = it.next(); if("Channel".equalsIgnoreCase(key) || "TradCode".equalsIgnoreCase(key) || "key".equalsIgnoreCase(key) ){ continue; } retMap.put(key, (requestMap.get(key) + "").replaceAll(" ", "+")); System.out.println("||||"+key+"="+retMap.get(key)); } return retMap; } }
GB18030
Java
1,781
java
ErrorCheckMD5.java
Java
[]
null
[]
package com.amarsoft.server.check; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.amarsoft.server.dao.SQLQuery; import com.amarsoft.server.util.JMTimesEncrypt; public class ErrorCheckMD5 extends ErrorCheck { public boolean excute(Map<String, Object> requestMap, SQLQuery sqlQuery) { try { String sStartTime = (String) requestMap.get("StartTime"); String sEndTime = (String) requestMap.get("EndTime"); Map<String, String> md5Map = getMD5Map(requestMap); JMTimesEncrypt je = new JMTimesEncrypt(); String keyMD5j = je.initFingerprint(getItemName(sqlQuery),md5Map); String keyMD5 = (String)requestMap.get("key"); logger.info(keyMD5 + "\n" + keyMD5j); return keyMD5.equals(keyMD5j); } catch (Exception e) { printLog(e); return false; } } /** * @describe 该方法用于获取加密字符串 * @param sqlQuery * @return */ private String getItemName(SQLQuery sqlQuery){ String sItemDescribe = ""; String sSql = "select itemdescribe from code_library where codeno = 'JMTimesService' and itemno = '020'"; try { sItemDescribe = sqlQuery.getString(sSql); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return sItemDescribe; } private Map<String, String> getMD5Map(Map<String, Object> requestMap){ Map<String, String> retMap = new HashMap<String, String>(); for(Iterator<String> it = requestMap.keySet().iterator(); it.hasNext(); ){ String key = it.next(); if("Channel".equalsIgnoreCase(key) || "TradCode".equalsIgnoreCase(key) || "key".equalsIgnoreCase(key) ){ continue; } retMap.put(key, (requestMap.get(key) + "").replaceAll(" ", "+")); System.out.println("||||"+key+"="+retMap.get(key)); } return retMap; } }
1,781
0.695504
0.687536
55
30.945454
27.05242
109
false
false
0
0
0
0
0
0
2.581818
false
false
12
6da85be616eebba6003003410ddfdfdbeb362172
15,633,681,015,226
d1a0fa982f3c4cbf61c89616768441747f45066b
/src/main/java/com/eastmoney/algorithm/PriceChangeCal.java
d44982a12fe69e572d7b1f9c8903b0fe26cc8b00
[]
no_license
huhuajian1989/calculator
https://github.com/huhuajian1989/calculator
96aecdf5700b9334fff88050c6098820829e4ae8
cc60748a1b50cb1e8202bf82c50047f383ba88dd
refs/heads/master
2016-09-23T07:04:12.381000
2016-07-19T06:30:59
2016-07-19T06:30:59
63,667,347
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eastmoney.algorithm; import com.eastmoney.datamodule.BaseIntIndex; import com.eastmoney.datamodule.BaseLongIndex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 13-11-19 * Time: 下午4:27 * To change this template use File | Settings | File Templates. * 涨跌计算 */ public class PriceChangeCal { private static Logger logger = LoggerFactory.getLogger(PriceChangeCal.class); private static class SingletonHolder { public final static PriceChangeCal instance = new PriceChangeCal(); } public static PriceChangeCal getInstance() { return SingletonHolder.instance; } public long getPriceChange(HashMap<Integer, BaseLongIndex> longfields,String emCode,int pcloseIndex){ try{ BaseLongIndex priceNow=longfields.get(6); BaseLongIndex pclose=longfields.get(pcloseIndex); if(priceNow==null){ return 0; } if(pclose==null){ return 0; } return priceNow.getNowValue() - pclose.getNowValue(); }catch(Exception e){ logger.error(e.getMessage(),e); } return 0; } }
UTF-8
Java
1,292
java
PriceChangeCal.java
Java
[ { "context": "hMap;\n\n/**\n * Created with IntelliJ IDEA.\n * User: Administrator\n * Date: 13-11-19\n * Time: 下午4:27\n * To change th", "end": 269, "score": 0.9251625537872314, "start": 256, "tag": "USERNAME", "value": "Administrator" } ]
null
[]
package com.eastmoney.algorithm; import com.eastmoney.datamodule.BaseIntIndex; import com.eastmoney.datamodule.BaseLongIndex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 13-11-19 * Time: 下午4:27 * To change this template use File | Settings | File Templates. * 涨跌计算 */ public class PriceChangeCal { private static Logger logger = LoggerFactory.getLogger(PriceChangeCal.class); private static class SingletonHolder { public final static PriceChangeCal instance = new PriceChangeCal(); } public static PriceChangeCal getInstance() { return SingletonHolder.instance; } public long getPriceChange(HashMap<Integer, BaseLongIndex> longfields,String emCode,int pcloseIndex){ try{ BaseLongIndex priceNow=longfields.get(6); BaseLongIndex pclose=longfields.get(pcloseIndex); if(priceNow==null){ return 0; } if(pclose==null){ return 0; } return priceNow.getNowValue() - pclose.getNowValue(); }catch(Exception e){ logger.error(e.getMessage(),e); } return 0; } }
1,292
0.647656
0.635938
54
22.703703
24.68515
105
false
false
0
0
0
0
0
0
0.407407
false
false
12
bf99a029f4b80a73fb572fe50dd3a6e7711bdeda
35,510,789,636,506
84fc749ef75ef09a27308cb3c45b4b5ff8680444
/src/day02/LinkedList/TestDrive.java
1fe1b777d7308605572db94789b9a715718cc7b5
[]
no_license
ca7erina/JavaSE1
https://github.com/ca7erina/JavaSE1
43914dca554cc7dbfb1d884c2b55811b265319f2
7fcce243e3fca26fa6c81e24a318af186e9a7047
refs/heads/master
2021-01-01T19:46:23.726000
2013-05-12T13:29:44
2013-05-12T13:29:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day02.LinkedList; import java.util.*; public class TestDrive { public static void main(String[] args) { Node head=new Node("91210"); head.next=new Node("Poker Face"); head.next.next=new Node("Picture to burn"); head.next.next.next=new Node("On to the next One"); System.out.println(head); LinkedList llist=new LinkedList(); llist.add("91210"); llist.add("Poker Face"); llist.add("Picture to burn"); llist.add("On to the next One"); System.out.println(llist); } }
UTF-8
Java
503
java
TestDrive.java
Java
[]
null
[]
package day02.LinkedList; import java.util.*; public class TestDrive { public static void main(String[] args) { Node head=new Node("91210"); head.next=new Node("Poker Face"); head.next.next=new Node("Picture to burn"); head.next.next.next=new Node("On to the next One"); System.out.println(head); LinkedList llist=new LinkedList(); llist.add("91210"); llist.add("Poker Face"); llist.add("Picture to burn"); llist.add("On to the next One"); System.out.println(llist); } }
503
0.677932
0.654076
21
22.952381
15.728276
53
false
false
0
0
0
0
0
0
1.952381
false
false
12
40752ebdb20bdfc6c9d73fc3b8c94cb25b53344b
12,111,807,832,111
16fc2e4abd86047a08218376c879fd03a42d0847
/app/src/main/java/com/boylab/example/bean/Student.java
e7dd26e64e3578f6e85d4777b6dd7958519f9c5a
[]
no_license
boylab/TableView
https://github.com/boylab/TableView
fa07bb8ee72f403a525f9f9bb4db9278b949227a
c1aa6b2c747258956fb83594fce0a614e503d27f
refs/heads/main
2023-03-21T05:42:29.244000
2021-03-13T12:04:38
2021-03-13T12:04:38
291,260,024
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.boylab.example.bean; import android.text.TextUtils; import com.boylab.tableview.protocol.ItemRow; public class Student implements ItemRow { private Long id; private String name; private int age; private String sex; private float height; private float weight; private float chinese; private float math; private float english; private String chineseTeacher; private String mathTeacher; private String englishTeacher; private String remark; public Student(int i) { /** * 模拟初始化数据 */ this.id = Long.valueOf(100 + i * i); this.name = "名字" + i; this.age = i * i; this.sex = (i % 3 == 0 ? "boy" : "girl"); this.height = 1.00f * i; this.weight = 5.00f * i; this.chinese = 600.00f; this.math = 10.00f * i; this.english = 5.00f; this.chineseTeacher = "语文老师" + i % 5; this.mathTeacher = "数学老师" + i % 5; this.englishTeacher = "英语老师" + i % 5; this.remark = ""; } public Student() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public float getChinese() { return chinese; } public void setChinese(float chinese) { this.chinese = chinese; } public float getMath() { return math; } public void setMath(float math) { this.math = math; } public float getEnglish() { return english; } public void setEnglish(float english) { this.english = english; } public String getChineseTeacher() { return chineseTeacher; } public void setChineseTeacher(String chineseTeacher) { this.chineseTeacher = chineseTeacher; } public String getMathTeacher() { return mathTeacher; } public void setMathTeacher(String mathTeacher) { this.mathTeacher = mathTeacher; } public String getEnglishTeacher() { return englishTeacher; } public void setEnglishTeacher(String englishTeacher) { this.englishTeacher = englishTeacher; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public int size() { return 12; } @Override public String get(int position) { /** * position 对应的值 与 Label的标签对应上即可 */ position = position % 12; if (position == 0) { return String.valueOf(id); } else if (position == 1) { return name; } else if (position == 2) { return String.valueOf(age); } else if (position == 3) { return sex; } else if (position == 4) { return String.format("%6.3f", this.height); } else if (position == 5) { return String.format("%6.3f", this.weight); } else if (position == 6) { return String.format("%6.3f", this.chinese); } else if (position == 7) { return String.format("%6.3f", this.math); } else if (position == 8) { return String.format("%6.3f", this.english); } else if (position == 9) { return chineseTeacher; } else if (position == 10) { return mathTeacher; } else if (position == 11) { return englishTeacher; } else if (position == 12) { return remark; } return "N/A"; } }
UTF-8
Java
4,297
java
Student.java
Java
[]
null
[]
package com.boylab.example.bean; import android.text.TextUtils; import com.boylab.tableview.protocol.ItemRow; public class Student implements ItemRow { private Long id; private String name; private int age; private String sex; private float height; private float weight; private float chinese; private float math; private float english; private String chineseTeacher; private String mathTeacher; private String englishTeacher; private String remark; public Student(int i) { /** * 模拟初始化数据 */ this.id = Long.valueOf(100 + i * i); this.name = "名字" + i; this.age = i * i; this.sex = (i % 3 == 0 ? "boy" : "girl"); this.height = 1.00f * i; this.weight = 5.00f * i; this.chinese = 600.00f; this.math = 10.00f * i; this.english = 5.00f; this.chineseTeacher = "语文老师" + i % 5; this.mathTeacher = "数学老师" + i % 5; this.englishTeacher = "英语老师" + i % 5; this.remark = ""; } public Student() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public float getChinese() { return chinese; } public void setChinese(float chinese) { this.chinese = chinese; } public float getMath() { return math; } public void setMath(float math) { this.math = math; } public float getEnglish() { return english; } public void setEnglish(float english) { this.english = english; } public String getChineseTeacher() { return chineseTeacher; } public void setChineseTeacher(String chineseTeacher) { this.chineseTeacher = chineseTeacher; } public String getMathTeacher() { return mathTeacher; } public void setMathTeacher(String mathTeacher) { this.mathTeacher = mathTeacher; } public String getEnglishTeacher() { return englishTeacher; } public void setEnglishTeacher(String englishTeacher) { this.englishTeacher = englishTeacher; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Override public int size() { return 12; } @Override public String get(int position) { /** * position 对应的值 与 Label的标签对应上即可 */ position = position % 12; if (position == 0) { return String.valueOf(id); } else if (position == 1) { return name; } else if (position == 2) { return String.valueOf(age); } else if (position == 3) { return sex; } else if (position == 4) { return String.format("%6.3f", this.height); } else if (position == 5) { return String.format("%6.3f", this.weight); } else if (position == 6) { return String.format("%6.3f", this.chinese); } else if (position == 7) { return String.format("%6.3f", this.math); } else if (position == 8) { return String.format("%6.3f", this.english); } else if (position == 9) { return chineseTeacher; } else if (position == 10) { return mathTeacher; } else if (position == 11) { return englishTeacher; } else if (position == 12) { return remark; } return "N/A"; } }
4,297
0.542209
0.528967
195
20.68718
16.394796
58
false
false
0
0
0
0
0
0
0.389744
false
false
12
2254cec423892b9bb5a1d12f9ebd3775aba9297f
11,914,239,303,490
a12e4b494182d015de0a927c34a9806e60f23033
/src/com/kx/dao/Department2Mapper.java
83561840274c0155ffab11e15ed4eef2d3d8f3d5
[]
no_license
kakrot-16/KxHealth
https://github.com/kakrot-16/KxHealth
75e0f84717b49a6a1d2a4a0f9e44a93167b83a98
5fa4ef2a0730a2a7ae0642e3fb06491847c5aac0
refs/heads/master
2020-03-27T05:21:11.884000
2018-09-06T09:25:09
2018-09-06T09:25:09
146,012,581
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kx.dao; import com.kx.pojo.Department2; import java.util.List; /** * 二级科室mapper接口 * @author 申静宇 * */ public interface Department2Mapper { //增加二级科室的方法(已测) int addDepartment2(Department2 department2); //删除二级科室的方法(已测) int deleteDepartment2(int d2_id); //修改二级科室的方法(已测) int updateDepartment2(Department2 department2); //查找二级科室的方法(已测) List<Department2> getDepartmentList(Department2 department2); //寻找二级科室的方法(已测) List<Department2> getDe1ListById(String id);//张帅 //查找二级科室简介 张帅 String getInfo(String d2_name); }
UTF-8
Java
727
java
Department2Mapper.java
Java
[ { "context": "t java.util.List;\n\n/**\n * 二级科室mapper接口\n * @author 申静宇\n *\n */\npublic interface Department2Mapper {\n /", "end": 112, "score": 0.9998207688331604, "start": 109, "tag": "NAME", "value": "申静宇" } ]
null
[]
package com.kx.dao; import com.kx.pojo.Department2; import java.util.List; /** * 二级科室mapper接口 * @author 申静宇 * */ public interface Department2Mapper { //增加二级科室的方法(已测) int addDepartment2(Department2 department2); //删除二级科室的方法(已测) int deleteDepartment2(int d2_id); //修改二级科室的方法(已测) int updateDepartment2(Department2 department2); //查找二级科室的方法(已测) List<Department2> getDepartmentList(Department2 department2); //寻找二级科室的方法(已测) List<Department2> getDe1ListById(String id);//张帅 //查找二级科室简介 张帅 String getInfo(String d2_name); }
727
0.70087
0.673043
27
20.296297
18.275291
65
false
false
0
0
0
0
0
0
0.333333
false
false
12
3919308877dc520231844472f60b2a915ba7c10f
515,396,107,669
340a321fbac9f342b272a5367701b369d267446b
/src/main/java/org/sample/protocols/transaction/Transfer.java
4c9b2b93b72c801fcec7970e0d2a5b5a83ea0f45
[ "MIT" ]
permissive
ulubeyn/transaction-web-api
https://github.com/ulubeyn/transaction-web-api
53d76c6263587c7beeb5c195c0a97aed35b38364
3716277ff14124890a6977679bef5d6da1b9191d
refs/heads/master
2020-07-09T05:31:43.758000
2019-08-23T00:37:33
2019-08-23T00:37:33
203,894,551
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.sample.protocols.transaction; import java.math.BigDecimal; public interface Transfer { enum Status { Zero, InProcess, Completed, Cancelled } String getTransferId(); String getSenderId(); String getReceiverId(); BigDecimal getAmount(); Status getStatus(); Transfer setStatus(Status status); }
UTF-8
Java
378
java
Transfer.java
Java
[]
null
[]
package org.sample.protocols.transaction; import java.math.BigDecimal; public interface Transfer { enum Status { Zero, InProcess, Completed, Cancelled } String getTransferId(); String getSenderId(); String getReceiverId(); BigDecimal getAmount(); Status getStatus(); Transfer setStatus(Status status); }
378
0.640212
0.640212
26
13.538462
13.350974
41
false
false
0
0
0
0
0
0
0.423077
false
false
12
c8f0ccb89f33ebe88c00d65deaa95e6cefd51bbc
30,150,670,437,469
e4fa7d5c5213982912bc5b657b18ba6f0e35b542
/AddressBook/src/edu/gac/mcs270/hvidsten/guslistgae/client/BlobService.java
12e1f0f87b1b29db997f28a4b2d10be32ab994e9
[]
no_license
mschroe2/project3
https://github.com/mschroe2/project3
f8be3eef84108fe83517798fcbd9f78501631e1d
760625b7ba8a76cfab0ec9e223152f3ec5b20e28
refs/heads/master
2020-04-24T20:51:38.173000
2014-03-24T18:49:43
2014-03-24T18:49:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * RPC Servlet to handle getting the BlobStore URL address for the Google * web site that will handle uploading the Blob. */ package edu.gac.mcs270.hvidsten.guslistgae.client; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /* This is extracted from code in the BlobStore Tutorial written by the blogger "fishbone": * http://www.fishbonecloud.com/2010/12/tutorial-gwt-application-for-storing.html * Note: March 2014 - this link is no longer active. * */ @RemoteServiceRelativePath("blobservice") public interface BlobService extends RemoteService { String getBlobStoreUploadUrl(); }
UTF-8
Java
675
java
BlobService.java
Java
[ { "context": "in the BlobStore Tutorial written by the blogger \"fishbone\":\n * http://www.fishbonecloud.com/2010/12/tutori", "end": 394, "score": 0.9945418238639832, "start": 386, "tag": "USERNAME", "value": "fishbone" } ]
null
[]
/* * RPC Servlet to handle getting the BlobStore URL address for the Google * web site that will handle uploading the Blob. */ package edu.gac.mcs270.hvidsten.guslistgae.client; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /* This is extracted from code in the BlobStore Tutorial written by the blogger "fishbone": * http://www.fishbonecloud.com/2010/12/tutorial-gwt-application-for-storing.html * Note: March 2014 - this link is no longer active. * */ @RemoteServiceRelativePath("blobservice") public interface BlobService extends RemoteService { String getBlobStoreUploadUrl(); }
675
0.773333
0.754074
20
32.799999
31.083115
91
false
false
0
0
0
0
0
0
0.2
false
false
12
9f5ff46b28a3d52288d15aaedbc55b58d6b40ab8
4,535,485,514,677
8470f93a71a985e92379aed309147c38a97b0e6f
/core/src/com/michaelcyau/overlays/LogoScreen.java
bc7571281136ddedd12198d6a8294e618ac60ace
[]
no_license
abmicyau/FrostyFriends
https://github.com/abmicyau/FrostyFriends
3468d1dc7a06e3c7bd5e812fdd90a6bdb4cf3fa0
4efc483f225acbef0d7a5dd86d4b0a4ad949b67a
refs/heads/master
2020-09-13T09:31:29.515000
2016-09-16T03:26:40
2016-09-16T03:26:40
67,331,167
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.michaelcyau.overlays; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.michaelcyau.gameworld.GameWorld; import com.michaelcyau.helpers.AssetLoader; public class LogoScreen implements ScreenOverlay { private float transparency = 0; private float fadeSpeed = 1; // 2 private float splashRunTime = 0; private float splashDuration = 2f; private GameWorld gameWorld; private TextureRegion overlay = AssetLoader.splashScreen; public LogoScreen(GameWorld gameWorld) { this.gameWorld = gameWorld; } public void update(float delta) { if (splashRunTime == 0 && transparency < 1) { if (transparency + (fadeSpeed * delta) < 1) { transparency += fadeSpeed * delta; } else { transparency = 1; } } else if (transparency == 1 && splashRunTime < splashDuration) { if (splashRunTime + delta < splashDuration) { splashRunTime += delta; } else { splashRunTime = splashDuration; } } else { if (transparency - (fadeSpeed * delta) > 0) { transparency -= fadeSpeed * delta; } else { transparency = 0; gameWorld.setOverlay(new InstructionsScreen(gameWorld)); gameWorld.setCurrentState(GameWorld.GameState.INSTRUCTIONS); } } } public void render(SpriteBatch batcher) { float splashWidth = overlay.getRegionWidth(); float splashHeight = overlay.getRegionHeight(); float aspectRatio = splashHeight / splashWidth; float sizeDifference = (Gdx.graphics.getWidth() * aspectRatio) - Gdx.graphics.getHeight(); batcher.begin(); batcher.enableBlending(); batcher.setColor(1, 1, 1, transparency); batcher.draw(overlay, 0, -(sizeDifference / 2), Gdx.graphics.getWidth(), Gdx.graphics.getWidth() * aspectRatio); batcher.setColor(1, 1, 1, 1); batcher.disableBlending(); batcher.end(); } public void render(ShapeRenderer renderer) { } }
UTF-8
Java
2,349
java
LogoScreen.java
Java
[]
null
[]
package com.michaelcyau.overlays; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.michaelcyau.gameworld.GameWorld; import com.michaelcyau.helpers.AssetLoader; public class LogoScreen implements ScreenOverlay { private float transparency = 0; private float fadeSpeed = 1; // 2 private float splashRunTime = 0; private float splashDuration = 2f; private GameWorld gameWorld; private TextureRegion overlay = AssetLoader.splashScreen; public LogoScreen(GameWorld gameWorld) { this.gameWorld = gameWorld; } public void update(float delta) { if (splashRunTime == 0 && transparency < 1) { if (transparency + (fadeSpeed * delta) < 1) { transparency += fadeSpeed * delta; } else { transparency = 1; } } else if (transparency == 1 && splashRunTime < splashDuration) { if (splashRunTime + delta < splashDuration) { splashRunTime += delta; } else { splashRunTime = splashDuration; } } else { if (transparency - (fadeSpeed * delta) > 0) { transparency -= fadeSpeed * delta; } else { transparency = 0; gameWorld.setOverlay(new InstructionsScreen(gameWorld)); gameWorld.setCurrentState(GameWorld.GameState.INSTRUCTIONS); } } } public void render(SpriteBatch batcher) { float splashWidth = overlay.getRegionWidth(); float splashHeight = overlay.getRegionHeight(); float aspectRatio = splashHeight / splashWidth; float sizeDifference = (Gdx.graphics.getWidth() * aspectRatio) - Gdx.graphics.getHeight(); batcher.begin(); batcher.enableBlending(); batcher.setColor(1, 1, 1, transparency); batcher.draw(overlay, 0, -(sizeDifference / 2), Gdx.graphics.getWidth(), Gdx.graphics.getWidth() * aspectRatio); batcher.setColor(1, 1, 1, 1); batcher.disableBlending(); batcher.end(); } public void render(ShapeRenderer renderer) { } }
2,349
0.628352
0.618561
68
33.544117
24.871099
120
false
false
0
0
0
0
0
0
0.661765
false
false
12
93645d9a1cdd1b3f9f3c9dfcf936ffe4481fa465
4,475,355,940,862
760beae99e0c60fbe37d82d96cb04600e97d61e9
/src/main/java/com/thoughtworks/yuchen/demo/abstractfactory/electronicproduct/apple/Apple.java
1f5203b9b8305832a8ddc3e9cda0e091e77afc2b
[]
no_license
tw-chenyu/Demo
https://github.com/tw-chenyu/Demo
156d42726de3df45a136ece7a051e2bdda45241b
03df500c34bf68255440bae29282a85f5e746686
refs/heads/master
2016-09-01T22:38:47.373000
2015-08-25T08:59:55
2015-08-25T08:59:55
41,286,086
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.thoughtworks.yuchen.demo.abstractfactory.electronicproduct.apple; public interface Apple { String AppleStyle(); }
UTF-8
Java
131
java
Apple.java
Java
[]
null
[]
package com.thoughtworks.yuchen.demo.abstractfactory.electronicproduct.apple; public interface Apple { String AppleStyle(); }
131
0.801527
0.801527
5
25.200001
27.952818
77
false
false
0
0
0
0
0
0
0.4
false
false
12
757240e69df04393f15f128ad3933561078df243
32,959,579,048,451
4dfa437de7c2e9ae642f6ab15315b566436a8336
/app/src/main/java/com/bytesci/plant/base/BaseModel.java
7010db6f1bc2168901aa29c5882479a6c206cc49
[]
no_license
byteluo/Plant
https://github.com/byteluo/Plant
358fdaa7cdece7a3dc3ca98eb185d247b76554be
c348752eb86059896b376ff02653919b19c326ec
refs/heads/master
2020-06-14T16:20:08.869000
2019-07-04T07:27:43
2019-07-04T07:27:43
195,053,589
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bytesci.plant.base; import android.content.Context; import com.bytesci.plant.APP; public class BaseModel { public Context getContext(){ return APP.getApplication(); } }
UTF-8
Java
200
java
BaseModel.java
Java
[]
null
[]
package com.bytesci.plant.base; import android.content.Context; import com.bytesci.plant.APP; public class BaseModel { public Context getContext(){ return APP.getApplication(); } }
200
0.715
0.715
11
17.181818
14.886346
36
false
false
0
0
0
0
0
0
0.363636
false
false
12
c42570fe327f3cdfede93b33074b01b8ffe7d8aa
25,503,515,872,764
aa284021f134fc3c0d3cfa7c55ce681f493162f9
/src/main/java/com/ls/http/proxy/HttpProxy.java
4583cd655e3c9854c4d5b37cf066e543a10e87a2
[]
no_license
liangsu/crawler
https://github.com/liangsu/crawler
a3073447cc592a5f3b3a79a5e671eb9e83c9ae36
2216359309d114ace67e989142fc46803be9c5c5
refs/heads/master
2022-09-20T12:43:45.251000
2021-03-10T09:04:34
2021-03-10T09:04:34
197,580,272
0
0
null
false
2022-09-01T23:10:06
2019-07-18T12:12:29
2021-03-10T09:04:48
2022-09-01T23:10:04
113
0
0
4
JavaScript
false
false
package com.ls.http.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Map; public class HttpProxy implements InvocationHandler { private Map<Method, HttpMethodHandler> methodMap; private HttpRequestContext httpRequestContext; public HttpProxy(Map<Method, HttpMethodHandler> methodMap) { this.methodMap = methodMap; this.httpRequestContext = new HttpRequestContext(); } public HttpProxy(Map<Method, HttpMethodHandler> methodMap, HttpRequestContext httpRequestContext) { this.methodMap = methodMap; this.httpRequestContext = httpRequestContext; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { HttpMethodHandler httpMethodHandler = methodMap.get(method); return httpMethodHandler.request(args, httpRequestContext); } }
UTF-8
Java
912
java
HttpProxy.java
Java
[]
null
[]
package com.ls.http.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Map; public class HttpProxy implements InvocationHandler { private Map<Method, HttpMethodHandler> methodMap; private HttpRequestContext httpRequestContext; public HttpProxy(Map<Method, HttpMethodHandler> methodMap) { this.methodMap = methodMap; this.httpRequestContext = new HttpRequestContext(); } public HttpProxy(Map<Method, HttpMethodHandler> methodMap, HttpRequestContext httpRequestContext) { this.methodMap = methodMap; this.httpRequestContext = httpRequestContext; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { HttpMethodHandler httpMethodHandler = methodMap.get(method); return httpMethodHandler.request(args, httpRequestContext); } }
912
0.741228
0.741228
34
25.82353
29.608694
103
false
false
0
0
0
0
0
0
0.558824
false
false
12
33e5ab4306c3ca6d6d3a0ee6e49cf634ca65f5e6
31,318,901,536,857
46ea16efdadfd088bb3c9eaf49d429d2e7fdb082
/src/grammar/Terminal.java
9a2a50349c10b055d7c6ce687828a1514de5fb38
[]
no_license
CawaEast/Parser-for-parser
https://github.com/CawaEast/Parser-for-parser
562168b870785c82152ddb7f88bc8b8723ad53b8
541fb98e143eab76e00183a8cc7aaa7cce8b8a26
refs/heads/master
2020-06-16T13:47:00.984000
2017-06-12T22:55:11
2017-06-12T22:55:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package grammar; import java.util.Vector; /** * Created by Cawa on 12.06.2017. */ public class Terminal { String name; RegexpToken regexp; public Terminal(String s, RegexpToken r) { name = s; regexp = r; } }
UTF-8
Java
245
java
Terminal.java
Java
[ { "context": "mmar;\n\nimport java.util.Vector;\n\n/**\n * Created by Cawa on 12.06.2017.\n */\npublic class Terminal {\n ", "end": 63, "score": 0.5283834338188171, "start": 62, "tag": "NAME", "value": "C" }, { "context": "ar;\n\nimport java.util.Vector;\n\n/**\n * Created by Cawa on 12.06.2017.\n */\npublic class Terminal {\n St", "end": 66, "score": 0.7562230229377747, "start": 63, "tag": "USERNAME", "value": "awa" } ]
null
[]
package grammar; import java.util.Vector; /** * Created by Cawa on 12.06.2017. */ public class Terminal { String name; RegexpToken regexp; public Terminal(String s, RegexpToken r) { name = s; regexp = r; } }
245
0.604082
0.571429
16
14.3125
13.15161
46
false
false
0
0
0
0
0
0
0.4375
false
false
12
e04c13df21ba82b80101e858bc11365ca35e6a99
13,606,456,422,355
ecae3e7313727f672da6fd0cf16b49b1eab18a50
/src/visual/jfCadastroFuncaoCargo.java
0f07367e3422f9c843f147787d245fe734f8df13
[]
no_license
machinesque/Cadun
https://github.com/machinesque/Cadun
f6c001a7410bee4c8cb4da6d0d67e437ab0a91c2
3f4d874ccdd8fab6d7b8563ad4fac55930a5989d
refs/heads/master
2020-05-16T23:04:34.822000
2019-04-25T04:15:52
2019-04-25T04:15:52
183,353,897
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * jfCadastroFuncaoCargo.java * * Created on 05/08/2010, 08:43:38 */ package visual; import conexao.Conexao; import controlador.ClasseGeral; import controlador.ControleImagem; import controlador.ControleVersao; import controlador.FixedLengthDocument; import dao.DAO; import excecoes.ExcCadastro; import java.awt.Image; import java.awt.Toolkit; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import modelo.FuncaoCargo; import modelo.Permissoes; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.view.JasperViewer; /** * * @author luizam */ public class jfCadastroFuncaoCargo extends javax.swing.JFrame { private static ControleVersao versao = new ControleVersao(); private DAO dao; private ClasseGeral classeGeral; private ControleImagem controleImagem = new ControleImagem(); private FuncaoCargo funcaoCargo; private jdBuscaFuncaoCargo jdbfc; private JasperPrint jPrint; private JasperViewer jViewer; private int codigo; private String nomeUsuario; private String opcao = "salvar"; private String funcaoCargoVerificado; private boolean cadastrarFuncaoCargo; /** Creates new form jfCadastroFuncaoCargo */ public jfCadastroFuncaoCargo() { super("Cadastro Função/Cargo - " + versao.getVersao() + " - " + versao.getAno()); initComponents(); //Altera icone na barra de titulo Toolkit kit = Toolkit.getDefaultToolkit(); Image img = kit.getImage(controleImagem.getIconeImagem()); this.setIconImage(img); //centraliza tela setSize(getWidth(), getHeight()); setLocationRelativeTo(null); setNumeroCaracteres(); desabilitaBotoes(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jpBotoes = new javax.swing.JPanel(); jbNovo = new javax.swing.JButton(); jbSalvar = new javax.swing.JButton(); jbBuscar = new javax.swing.JButton(); jbCancelar = new javax.swing.JButton(); jbExcluir = new javax.swing.JButton(); jbAlterar = new javax.swing.JButton(); jbImprimir = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jtfNomeFuncaoCargo = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jpBotoes.setBorder(new org.jdesktop.swingx.border.DropShadowBorder()); jbNovo.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/novo02.png"))); // NOI18N jbNovo.setText("Novo"); jbNovo.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbNovo.setEnabled(false); jbNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbNovoActionPerformed(evt); } }); jbSalvar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/OK.png"))); // NOI18N jbSalvar.setText("Salvar"); jbSalvar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbSalvarActionPerformed(evt); } }); jbBuscar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/pesquisar.png"))); // NOI18N jbBuscar.setText("Buscar"); jbBuscar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbBuscarActionPerformed(evt); } }); jbCancelar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/cancelar.png"))); // NOI18N jbCancelar.setText("Cancelar"); jbCancelar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbCancelarActionPerformed(evt); } }); jbExcluir.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/delete02.png"))); // NOI18N jbExcluir.setText("Excluir"); jbExcluir.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbExcluir.setEnabled(false); jbExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbExcluirActionPerformed(evt); } }); jbAlterar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/reload.png"))); // NOI18N jbAlterar.setText("Alterar"); jbAlterar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbAlterar.setEnabled(false); jbAlterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAlterarActionPerformed(evt); } }); jbImprimir.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/imprimir.png"))); // NOI18N jbImprimir.setText("Imprimir"); jbImprimir.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbImprimir.setEnabled(false); jbImprimir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbImprimirActionPerformed(evt); } }); javax.swing.GroupLayout jpBotoesLayout = new javax.swing.GroupLayout(jpBotoes); jpBotoes.setLayout(jpBotoesLayout); jpBotoesLayout.setHorizontalGroup( jpBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpBotoesLayout.createSequentialGroup() .addContainerGap(27, Short.MAX_VALUE) .addComponent(jbNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jpBotoesLayout.setVerticalGroup( jpBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpBotoesLayout.createSequentialGroup() .addContainerGap() .addGroup(jpBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(16, Short.MAX_VALUE)) ); jPanel1.setBorder(new org.jdesktop.swingx.border.DropShadowBorder()); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel1.setText("Nome da Funão / Cargo: "); jtfNomeFuncaoCargo.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jtfNomeFuncaoCargo.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED)); jtfNomeFuncaoCargo.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jtfNomeFuncaoCargoFocusLost(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(43, 43, 43) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtfNomeFuncaoCargo, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(194, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jtfNomeFuncaoCargo, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(36, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jpBotoes, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jpBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbNovoActionPerformed cancelar(); }//GEN-LAST:event_jbNovoActionPerformed private void jbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSalvarActionPerformed if (!jtfNomeFuncaoCargo.getText().isEmpty()) { verificaCadastroFuncaoCargo(); if (opcao.equals("salvar")) { if (!funcaoCargoVerificado.isEmpty()) { iniciaClasseGeral(); classeGeral.msgAtencao("Essa Função/Cargo já existe!"); } else { salvar(); opcao = "salvar"; } } else if (opcao.equals("alterar")) { atualizar(); opcao = "salvar"; } } else { iniciaClasseGeral(); classeGeral.msgAtencao("Complete o Campo com o Nome da Função/Cargo!"); } }//GEN-LAST:event_jbSalvarActionPerformed private void jbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBuscarActionPerformed if (jdbfc == null) { jdbfc = new jdBuscaFuncaoCargo(null, true); } jdbfc.setVisible(true); setFuncaoCargoBuscado(jdbfc.getFuncaoCargo()); jdbfc.setFuncaoCargo(); }//GEN-LAST:event_jbBuscarActionPerformed private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed cancelar(); }//GEN-LAST:event_jbCancelarActionPerformed private void jbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExcluirActionPerformed excluir(); }//GEN-LAST:event_jbExcluirActionPerformed private void jbAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAlterarActionPerformed abilitaCampos(); jbAlterar.setEnabled(false); opcao = "alterar"; jbSalvar.setEnabled(true); }//GEN-LAST:event_jbAlterarActionPerformed private void jbImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbImprimirActionPerformed //ADOGeral ag = new ADOGeral(); Conexao conexao = new Conexao(); HashMap parametros = new HashMap(); try { //System.out.println(codigoRegistro); //parametros.put("titulo", "Titulo Relatorio"); parametros.put("codigoFuncaoCargo", new Integer(codigo)); //parametros.put("codigo", lista.get(0).getNome(); //ADOGeral.conectar(); conexao.getConexao(); } catch (ExcCadastro ex) { Logger.getLogger(jfCadastroCmei.class.getName()).log(Level.SEVERE, null, ex); } // JRDataSource jrds = new JRBeanCollectionDataSource(lista); try { //jReport = JasperCompileManager.compileReport("E:/LUIZ/PROJETOS JAVA/CORPORATIVO/m2GestaoClinicas/FichaPaciente.jrxml"); //jPrint = JasperFillManager.fillReport("C:/m2GestaoClinicas/FichaPaciente.jasper", parametros, ADOGeral.getConexao()); jPrint = JasperFillManager.fillReport("FuncaoCargo.jasper", parametros, conexao.getConexao()); //jPrint = JasperFillManager.fillReport(jReport, parametros, jrds); //if (!(jViewer == null)) { //jViewer = new JasperViewer(jPrint, false); //jViewer.setExtendedState(JFrame.MAXIMIZED_BOTH); jViewer.viewReport(jPrint, false); //} } catch (Exception ex) { ex.printStackTrace(); } }//GEN-LAST:event_jbImprimirActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing fechar(); }//GEN-LAST:event_formWindowClosing private void jtfNomeFuncaoCargoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfNomeFuncaoCargoFocusLost jtfNomeFuncaoCargo.setText(jtfNomeFuncaoCargo.getText().toUpperCase()); }//GEN-LAST:event_jtfNomeFuncaoCargoFocusLost /** * @param args the command line arguments */ /*public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new jfCadastroFuncaoCargo().setVisible(true); } }); }*/ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JButton jbAlterar; private javax.swing.JButton jbBuscar; private javax.swing.JButton jbCancelar; private javax.swing.JButton jbExcluir; private javax.swing.JButton jbImprimir; private javax.swing.JButton jbNovo; private javax.swing.JButton jbSalvar; private javax.swing.JPanel jpBotoes; private javax.swing.JTextField jtfNomeFuncaoCargo; // End of variables declaration//GEN-END:variables //Outros Metodos =========================================================================================================================================== public void fechar() { if (!jtfNomeFuncaoCargo.getText().isEmpty()) { iniciaClasseGeral(); classeGeral.msgAtencao("Cancele ou Salve o Cadastro em Edição!"); } else { dao = null; this.dispose(); } } public void cancelar() { jtfNomeFuncaoCargo.setText(""); desabilitaBotoes(); jbSalvar.transferFocusBackward(); funcaoCargo = null; } public void abilitaCampos() { jtfNomeFuncaoCargo.setEditable(true); } public void abilitaBotoes() { jbNovo.setEnabled(true); jbCancelar.setEnabled(true); jbBuscar.setEnabled(true); if (cadastrarFuncaoCargo == true) { jbSalvar.setEnabled(false); jbExcluir.setEnabled(true); jbAlterar.setEnabled(true); } else { jbSalvar.setEnabled(false); jbExcluir.setEnabled(false); jbAlterar.setEnabled(false); } } public void desabilitaBotoes() { jbNovo.setEnabled(false); jbCancelar.setEnabled(true); jbBuscar.setEnabled(true); jbImprimir.setEnabled(false); if (cadastrarFuncaoCargo == true) { jbSalvar.setEnabled(true); jbExcluir.setEnabled(false); jbAlterar.setEnabled(false); } else { jbSalvar.setEnabled(false); jbExcluir.setEnabled(false); jbAlterar.setEnabled(false); } } //Geradores, Validadores=========================================================================================================================================== public void iniciaClasseGeral() { if (classeGeral == null) { classeGeral = new ClasseGeral(); } } public void iniciaDao() { if (dao == null) { dao = new DAO(); } } public void iniciaFuncaoCargo() { if (funcaoCargo == null) { funcaoCargo = new FuncaoCargo(); } } public void verificaCadastroFuncaoCargo() { iniciaDao(); //DAO dao = new DAO(); funcaoCargoVerificado = dao.verificarCadastroFuncaoCargo(jtfNomeFuncaoCargo.getText()); } //Getters and Setters=========================================================================================================================================== public void setFuncaoCargoBuscado(FuncaoCargo funcaoCargoBuscado) { if (funcaoCargoBuscado.getNomeFuncaoCargo().isEmpty()) { } else { iniciaFuncaoCargo(); int codigoAux; jtfNomeFuncaoCargo.setText(funcaoCargoBuscado.getNomeFuncaoCargo()); codigoAux = funcaoCargoBuscado.getCodigoFuncaoCargo(); codigo = funcaoCargoBuscado.getCodigoFuncaoCargo(); funcaoCargo.setCodigoFuncaoCargo(codigoAux); jtfNomeFuncaoCargo.setEditable(false); abilitaBotoes(); } } public void setNumeroCaracteres() { jtfNomeFuncaoCargo.setDocument(new FixedLengthDocument(60)); } public String getNomeUsuario() { return nomeUsuario; } public void setNomeUsuario(String nomeUsuario) { this.nomeUsuario = nomeUsuario; getPermissoes(); desabilitaBotoes(); } public void getPermissoes() { Permissoes permissoes; iniciaDao(); //DAO dao = new DAO(); permissoes = (Permissoes) dao.buscaPermissoes(getNomeUsuario()); cadastrarFuncaoCargo = permissoes.isCadastrarFuncaoCargo(); } //Metodos DAO=================================================================================================================================================== public void salvar() { if (!jtfNomeFuncaoCargo.getText().isEmpty()) { iniciaDao(); iniciaFuncaoCargo(); //DAO dao = new DAO(); funcaoCargo.setNomeFuncaoCargo(jtfNomeFuncaoCargo.getText()); dao.inserir(funcaoCargo, 7); cancelar(); } else { iniciaClasseGeral(); classeGeral.msgAtencao("Complete os Campos Obrigatórios, destacados em Azul!"); } } public void atualizar() { if (!jtfNomeFuncaoCargo.getText().isEmpty()) { iniciaDao(); iniciaFuncaoCargo(); //DAO dao = new DAO(); funcaoCargo.setNomeFuncaoCargo(jtfNomeFuncaoCargo.getText()); dao.atualizar(funcaoCargo, 7); cancelar(); } else { iniciaClasseGeral(); classeGeral.msgAtencao("Complete os Campos Obrigatórios, destacados em Azul!"); } } public void excluir() { iniciaClasseGeral(); if (classeGeral.msgConfirma("Deseja excluir esta Função/Cargo?")) { iniciaDao(); iniciaFuncaoCargo(); //DAO dao = new DAO(); dao.excluir(funcaoCargo, 7); cancelar(); } } }
UTF-8
Java
23,681
java
jfCadastroFuncaoCargo.java
Java
[ { "context": "asperreports.view.JasperViewer;\n\n/**\n *\n * @author luizam\n */\npublic class jfCadastroFuncaoCargo extends ja", "end": 770, "score": 0.9992231726646423, "start": 764, "tag": "USERNAME", "value": "luizam" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * jfCadastroFuncaoCargo.java * * Created on 05/08/2010, 08:43:38 */ package visual; import conexao.Conexao; import controlador.ClasseGeral; import controlador.ControleImagem; import controlador.ControleVersao; import controlador.FixedLengthDocument; import dao.DAO; import excecoes.ExcCadastro; import java.awt.Image; import java.awt.Toolkit; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import modelo.FuncaoCargo; import modelo.Permissoes; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.view.JasperViewer; /** * * @author luizam */ public class jfCadastroFuncaoCargo extends javax.swing.JFrame { private static ControleVersao versao = new ControleVersao(); private DAO dao; private ClasseGeral classeGeral; private ControleImagem controleImagem = new ControleImagem(); private FuncaoCargo funcaoCargo; private jdBuscaFuncaoCargo jdbfc; private JasperPrint jPrint; private JasperViewer jViewer; private int codigo; private String nomeUsuario; private String opcao = "salvar"; private String funcaoCargoVerificado; private boolean cadastrarFuncaoCargo; /** Creates new form jfCadastroFuncaoCargo */ public jfCadastroFuncaoCargo() { super("Cadastro Função/Cargo - " + versao.getVersao() + " - " + versao.getAno()); initComponents(); //Altera icone na barra de titulo Toolkit kit = Toolkit.getDefaultToolkit(); Image img = kit.getImage(controleImagem.getIconeImagem()); this.setIconImage(img); //centraliza tela setSize(getWidth(), getHeight()); setLocationRelativeTo(null); setNumeroCaracteres(); desabilitaBotoes(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jpBotoes = new javax.swing.JPanel(); jbNovo = new javax.swing.JButton(); jbSalvar = new javax.swing.JButton(); jbBuscar = new javax.swing.JButton(); jbCancelar = new javax.swing.JButton(); jbExcluir = new javax.swing.JButton(); jbAlterar = new javax.swing.JButton(); jbImprimir = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jtfNomeFuncaoCargo = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jpBotoes.setBorder(new org.jdesktop.swingx.border.DropShadowBorder()); jbNovo.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/novo02.png"))); // NOI18N jbNovo.setText("Novo"); jbNovo.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbNovo.setEnabled(false); jbNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbNovoActionPerformed(evt); } }); jbSalvar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/OK.png"))); // NOI18N jbSalvar.setText("Salvar"); jbSalvar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbSalvarActionPerformed(evt); } }); jbBuscar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/pesquisar.png"))); // NOI18N jbBuscar.setText("Buscar"); jbBuscar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbBuscarActionPerformed(evt); } }); jbCancelar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/cancelar.png"))); // NOI18N jbCancelar.setText("Cancelar"); jbCancelar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbCancelarActionPerformed(evt); } }); jbExcluir.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/delete02.png"))); // NOI18N jbExcluir.setText("Excluir"); jbExcluir.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbExcluir.setEnabled(false); jbExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbExcluirActionPerformed(evt); } }); jbAlterar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/reload.png"))); // NOI18N jbAlterar.setText("Alterar"); jbAlterar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbAlterar.setEnabled(false); jbAlterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAlterarActionPerformed(evt); } }); jbImprimir.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jbImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/imprimir.png"))); // NOI18N jbImprimir.setText("Imprimir"); jbImprimir.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbImprimir.setEnabled(false); jbImprimir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbImprimirActionPerformed(evt); } }); javax.swing.GroupLayout jpBotoesLayout = new javax.swing.GroupLayout(jpBotoes); jpBotoes.setLayout(jpBotoesLayout); jpBotoesLayout.setHorizontalGroup( jpBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpBotoesLayout.createSequentialGroup() .addContainerGap(27, Short.MAX_VALUE) .addComponent(jbNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jpBotoesLayout.setVerticalGroup( jpBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpBotoesLayout.createSequentialGroup() .addContainerGap() .addGroup(jpBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(16, Short.MAX_VALUE)) ); jPanel1.setBorder(new org.jdesktop.swingx.border.DropShadowBorder()); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel1.setText("Nome da Funão / Cargo: "); jtfNomeFuncaoCargo.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jtfNomeFuncaoCargo.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED)); jtfNomeFuncaoCargo.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jtfNomeFuncaoCargoFocusLost(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(43, 43, 43) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtfNomeFuncaoCargo, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(194, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jtfNomeFuncaoCargo, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(36, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jpBotoes, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jpBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbNovoActionPerformed cancelar(); }//GEN-LAST:event_jbNovoActionPerformed private void jbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSalvarActionPerformed if (!jtfNomeFuncaoCargo.getText().isEmpty()) { verificaCadastroFuncaoCargo(); if (opcao.equals("salvar")) { if (!funcaoCargoVerificado.isEmpty()) { iniciaClasseGeral(); classeGeral.msgAtencao("Essa Função/Cargo já existe!"); } else { salvar(); opcao = "salvar"; } } else if (opcao.equals("alterar")) { atualizar(); opcao = "salvar"; } } else { iniciaClasseGeral(); classeGeral.msgAtencao("Complete o Campo com o Nome da Função/Cargo!"); } }//GEN-LAST:event_jbSalvarActionPerformed private void jbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBuscarActionPerformed if (jdbfc == null) { jdbfc = new jdBuscaFuncaoCargo(null, true); } jdbfc.setVisible(true); setFuncaoCargoBuscado(jdbfc.getFuncaoCargo()); jdbfc.setFuncaoCargo(); }//GEN-LAST:event_jbBuscarActionPerformed private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed cancelar(); }//GEN-LAST:event_jbCancelarActionPerformed private void jbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExcluirActionPerformed excluir(); }//GEN-LAST:event_jbExcluirActionPerformed private void jbAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAlterarActionPerformed abilitaCampos(); jbAlterar.setEnabled(false); opcao = "alterar"; jbSalvar.setEnabled(true); }//GEN-LAST:event_jbAlterarActionPerformed private void jbImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbImprimirActionPerformed //ADOGeral ag = new ADOGeral(); Conexao conexao = new Conexao(); HashMap parametros = new HashMap(); try { //System.out.println(codigoRegistro); //parametros.put("titulo", "Titulo Relatorio"); parametros.put("codigoFuncaoCargo", new Integer(codigo)); //parametros.put("codigo", lista.get(0).getNome(); //ADOGeral.conectar(); conexao.getConexao(); } catch (ExcCadastro ex) { Logger.getLogger(jfCadastroCmei.class.getName()).log(Level.SEVERE, null, ex); } // JRDataSource jrds = new JRBeanCollectionDataSource(lista); try { //jReport = JasperCompileManager.compileReport("E:/LUIZ/PROJETOS JAVA/CORPORATIVO/m2GestaoClinicas/FichaPaciente.jrxml"); //jPrint = JasperFillManager.fillReport("C:/m2GestaoClinicas/FichaPaciente.jasper", parametros, ADOGeral.getConexao()); jPrint = JasperFillManager.fillReport("FuncaoCargo.jasper", parametros, conexao.getConexao()); //jPrint = JasperFillManager.fillReport(jReport, parametros, jrds); //if (!(jViewer == null)) { //jViewer = new JasperViewer(jPrint, false); //jViewer.setExtendedState(JFrame.MAXIMIZED_BOTH); jViewer.viewReport(jPrint, false); //} } catch (Exception ex) { ex.printStackTrace(); } }//GEN-LAST:event_jbImprimirActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing fechar(); }//GEN-LAST:event_formWindowClosing private void jtfNomeFuncaoCargoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfNomeFuncaoCargoFocusLost jtfNomeFuncaoCargo.setText(jtfNomeFuncaoCargo.getText().toUpperCase()); }//GEN-LAST:event_jtfNomeFuncaoCargoFocusLost /** * @param args the command line arguments */ /*public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new jfCadastroFuncaoCargo().setVisible(true); } }); }*/ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JButton jbAlterar; private javax.swing.JButton jbBuscar; private javax.swing.JButton jbCancelar; private javax.swing.JButton jbExcluir; private javax.swing.JButton jbImprimir; private javax.swing.JButton jbNovo; private javax.swing.JButton jbSalvar; private javax.swing.JPanel jpBotoes; private javax.swing.JTextField jtfNomeFuncaoCargo; // End of variables declaration//GEN-END:variables //Outros Metodos =========================================================================================================================================== public void fechar() { if (!jtfNomeFuncaoCargo.getText().isEmpty()) { iniciaClasseGeral(); classeGeral.msgAtencao("Cancele ou Salve o Cadastro em Edição!"); } else { dao = null; this.dispose(); } } public void cancelar() { jtfNomeFuncaoCargo.setText(""); desabilitaBotoes(); jbSalvar.transferFocusBackward(); funcaoCargo = null; } public void abilitaCampos() { jtfNomeFuncaoCargo.setEditable(true); } public void abilitaBotoes() { jbNovo.setEnabled(true); jbCancelar.setEnabled(true); jbBuscar.setEnabled(true); if (cadastrarFuncaoCargo == true) { jbSalvar.setEnabled(false); jbExcluir.setEnabled(true); jbAlterar.setEnabled(true); } else { jbSalvar.setEnabled(false); jbExcluir.setEnabled(false); jbAlterar.setEnabled(false); } } public void desabilitaBotoes() { jbNovo.setEnabled(false); jbCancelar.setEnabled(true); jbBuscar.setEnabled(true); jbImprimir.setEnabled(false); if (cadastrarFuncaoCargo == true) { jbSalvar.setEnabled(true); jbExcluir.setEnabled(false); jbAlterar.setEnabled(false); } else { jbSalvar.setEnabled(false); jbExcluir.setEnabled(false); jbAlterar.setEnabled(false); } } //Geradores, Validadores=========================================================================================================================================== public void iniciaClasseGeral() { if (classeGeral == null) { classeGeral = new ClasseGeral(); } } public void iniciaDao() { if (dao == null) { dao = new DAO(); } } public void iniciaFuncaoCargo() { if (funcaoCargo == null) { funcaoCargo = new FuncaoCargo(); } } public void verificaCadastroFuncaoCargo() { iniciaDao(); //DAO dao = new DAO(); funcaoCargoVerificado = dao.verificarCadastroFuncaoCargo(jtfNomeFuncaoCargo.getText()); } //Getters and Setters=========================================================================================================================================== public void setFuncaoCargoBuscado(FuncaoCargo funcaoCargoBuscado) { if (funcaoCargoBuscado.getNomeFuncaoCargo().isEmpty()) { } else { iniciaFuncaoCargo(); int codigoAux; jtfNomeFuncaoCargo.setText(funcaoCargoBuscado.getNomeFuncaoCargo()); codigoAux = funcaoCargoBuscado.getCodigoFuncaoCargo(); codigo = funcaoCargoBuscado.getCodigoFuncaoCargo(); funcaoCargo.setCodigoFuncaoCargo(codigoAux); jtfNomeFuncaoCargo.setEditable(false); abilitaBotoes(); } } public void setNumeroCaracteres() { jtfNomeFuncaoCargo.setDocument(new FixedLengthDocument(60)); } public String getNomeUsuario() { return nomeUsuario; } public void setNomeUsuario(String nomeUsuario) { this.nomeUsuario = nomeUsuario; getPermissoes(); desabilitaBotoes(); } public void getPermissoes() { Permissoes permissoes; iniciaDao(); //DAO dao = new DAO(); permissoes = (Permissoes) dao.buscaPermissoes(getNomeUsuario()); cadastrarFuncaoCargo = permissoes.isCadastrarFuncaoCargo(); } //Metodos DAO=================================================================================================================================================== public void salvar() { if (!jtfNomeFuncaoCargo.getText().isEmpty()) { iniciaDao(); iniciaFuncaoCargo(); //DAO dao = new DAO(); funcaoCargo.setNomeFuncaoCargo(jtfNomeFuncaoCargo.getText()); dao.inserir(funcaoCargo, 7); cancelar(); } else { iniciaClasseGeral(); classeGeral.msgAtencao("Complete os Campos Obrigatórios, destacados em Azul!"); } } public void atualizar() { if (!jtfNomeFuncaoCargo.getText().isEmpty()) { iniciaDao(); iniciaFuncaoCargo(); //DAO dao = new DAO(); funcaoCargo.setNomeFuncaoCargo(jtfNomeFuncaoCargo.getText()); dao.atualizar(funcaoCargo, 7); cancelar(); } else { iniciaClasseGeral(); classeGeral.msgAtencao("Complete os Campos Obrigatórios, destacados em Azul!"); } } public void excluir() { iniciaClasseGeral(); if (classeGeral.msgConfirma("Deseja excluir esta Função/Cargo?")) { iniciaDao(); iniciaFuncaoCargo(); //DAO dao = new DAO(); dao.excluir(funcaoCargo, 7); cancelar(); } } }
23,681
0.637892
0.63109
610
37.798359
36.440838
172
false
false
0
0
0
0
151
0.024887
0.591803
false
false
12
9cb5c54b93b54bfdf7057f8b03b0b887408bfbf8
7,301,444,423,201
f94ba6dec597b12b3c3294ff699a2c77888bb1e4
/src/main/java/br/edu/unoesc/dao/PessoaDAO.java
6191f5749bbb10c13421e382fae8e040f79689d9
[]
no_license
Nata07/planilha-online
https://github.com/Nata07/planilha-online
f38c411739295813cbc9193c9a14ae765bf5f56e
fc6e3cce249201e4769804a02661ec88fb8c8917
refs/heads/master
2021-01-23T13:42:40.322000
2017-07-18T20:11:43
2017-07-18T20:11:43
61,449,548
0
0
null
true
2016-06-18T19:38:07
2016-06-18T19:38:07
2016-06-16T23:11:21
2016-06-18T19:34:37
2,196
0
0
0
null
null
null
package br.edu.unoesc.dao; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import br.edu.unoesc.model.MovimentacaoFinanceira; import br.edu.unoesc.model.Pessoa; @RequestScoped public class PessoaDAO extends HibernateDAO<Pessoa> { @Inject private PessoaDAO pessoaDAO; public Pessoa buscarPorUsuario(String usuario) { this.conectar(); try { TypedQuery<Pessoa> query = em.createNamedQuery(Pessoa.FILTRA_POR_USUARIO, Pessoa.class); query.setParameter(1, usuario); Pessoa p = query.getSingleResult(); return p; } catch (NoResultException nre) { return null; } finally { this.finalizar(); } } public Pessoa validarUsuario(Pessoa pessoa) { Pessoa p = pessoaDAO.buscarPorUsuario(pessoa.getCpf()); if (p != null) { return p; } else { return null; } } public MovimentacaoFinanceira retornaMF(Long id) { this.conectar(); try { TypedQuery<MovimentacaoFinanceira> query = em.createNamedQuery(Pessoa.RETORNA_MF, MovimentacaoFinanceira.class); query.setParameter(1, id); MovimentacaoFinanceira mf = query.getSingleResult(); return mf; } catch (NoResultException nre) { return null; } finally { this.finalizar(); } } }
UTF-8
Java
1,531
java
PessoaDAO.java
Java
[]
null
[]
package br.edu.unoesc.dao; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import br.edu.unoesc.model.MovimentacaoFinanceira; import br.edu.unoesc.model.Pessoa; @RequestScoped public class PessoaDAO extends HibernateDAO<Pessoa> { @Inject private PessoaDAO pessoaDAO; public Pessoa buscarPorUsuario(String usuario) { this.conectar(); try { TypedQuery<Pessoa> query = em.createNamedQuery(Pessoa.FILTRA_POR_USUARIO, Pessoa.class); query.setParameter(1, usuario); Pessoa p = query.getSingleResult(); return p; } catch (NoResultException nre) { return null; } finally { this.finalizar(); } } public Pessoa validarUsuario(Pessoa pessoa) { Pessoa p = pessoaDAO.buscarPorUsuario(pessoa.getCpf()); if (p != null) { return p; } else { return null; } } public MovimentacaoFinanceira retornaMF(Long id) { this.conectar(); try { TypedQuery<MovimentacaoFinanceira> query = em.createNamedQuery(Pessoa.RETORNA_MF, MovimentacaoFinanceira.class); query.setParameter(1, id); MovimentacaoFinanceira mf = query.getSingleResult(); return mf; } catch (NoResultException nre) { return null; } finally { this.finalizar(); } } }
1,531
0.621163
0.619856
54
27.351852
24.547125
124
false
false
0
0
0
0
0
0
0.537037
false
false
12
1123caafef91a7727b5a404ccaae37be2787215b
20,169,166,447,189
6b937630d5c9f246a8c0bfc331189da42b36e5f1
/src/main/java/paulevs/skyworld/structures/features/StructureFeatures.java
a7d941f7ba57f9988201def020b0e0ddf3c49f44
[]
no_license
paulevsGitch/SkyWorld
https://github.com/paulevsGitch/SkyWorld
d5885e0d1c8a9f03ad95ca2d1cc236394fd098e3
4da6c18e2dd10d37f3b07ac3e507c57cc0f138ef
refs/heads/master
2023-06-06T04:23:06.639000
2020-06-17T09:21:49
2020-06-17T09:21:49
255,117,132
1
3
null
false
2021-06-20T10:50:15
2020-04-12T15:51:34
2020-06-17T09:21:57
2021-06-19T12:33:57
294
0
2
2
Java
false
false
package paulevs.skyworld.structures.features; import java.util.ArrayList; import java.util.List; import net.minecraft.util.registry.Registry; import net.minecraft.world.gen.GenerationStep; import net.minecraft.world.gen.decorator.Decorator; import net.minecraft.world.gen.decorator.DecoratorConfig; import net.minecraft.world.gen.feature.DefaultFeatureConfig; import net.minecraft.world.gen.feature.Feature; import net.minecraft.world.gen.feature.FeatureConfig; import net.minecraft.world.gen.feature.StructureFeature; import paulevs.skyworld.SkyWorld; public class StructureFeatures { private static final List<StructureFeature<?>> FEATURES = new ArrayList<StructureFeature<?>>(); public static final StructureFeature<DefaultFeatureConfig> SKY_ISLAND = register("sky_island", new IslandFeature(DefaultFeatureConfig::deserialize)); public static void register() {} private static StructureFeature<DefaultFeatureConfig> register(String id, StructureFeature<DefaultFeatureConfig> feature) { FEATURES.add(feature); Feature.STRUCTURES.put(id, feature); Registry.BIOME.forEach((biome) -> { biome.getFeaturesForStep(GenerationStep.Feature.RAW_GENERATION).add(0, feature.configure(FeatureConfig.DEFAULT).createDecoratedFeature(Decorator.NOPE.configure(DecoratorConfig.DEFAULT))); biome.addStructureFeature(feature.configure(FeatureConfig.DEFAULT)); }); return Registry.register(Registry.STRUCTURE_FEATURE, SkyWorld.getID(id), feature); } public static boolean hasFeature(StructureFeature<?> feature) { return FEATURES.contains(feature); } }
UTF-8
Java
1,608
java
StructureFeatures.java
Java
[]
null
[]
package paulevs.skyworld.structures.features; import java.util.ArrayList; import java.util.List; import net.minecraft.util.registry.Registry; import net.minecraft.world.gen.GenerationStep; import net.minecraft.world.gen.decorator.Decorator; import net.minecraft.world.gen.decorator.DecoratorConfig; import net.minecraft.world.gen.feature.DefaultFeatureConfig; import net.minecraft.world.gen.feature.Feature; import net.minecraft.world.gen.feature.FeatureConfig; import net.minecraft.world.gen.feature.StructureFeature; import paulevs.skyworld.SkyWorld; public class StructureFeatures { private static final List<StructureFeature<?>> FEATURES = new ArrayList<StructureFeature<?>>(); public static final StructureFeature<DefaultFeatureConfig> SKY_ISLAND = register("sky_island", new IslandFeature(DefaultFeatureConfig::deserialize)); public static void register() {} private static StructureFeature<DefaultFeatureConfig> register(String id, StructureFeature<DefaultFeatureConfig> feature) { FEATURES.add(feature); Feature.STRUCTURES.put(id, feature); Registry.BIOME.forEach((biome) -> { biome.getFeaturesForStep(GenerationStep.Feature.RAW_GENERATION).add(0, feature.configure(FeatureConfig.DEFAULT).createDecoratedFeature(Decorator.NOPE.configure(DecoratorConfig.DEFAULT))); biome.addStructureFeature(feature.configure(FeatureConfig.DEFAULT)); }); return Registry.register(Registry.STRUCTURE_FEATURE, SkyWorld.getID(id), feature); } public static boolean hasFeature(StructureFeature<?> feature) { return FEATURES.contains(feature); } }
1,608
0.792289
0.791667
38
40.315788
42.790867
190
false
false
0
0
0
0
0
0
1.5
false
false
12
c7fe955173207eab5c8517bcdf6a8d8394cc144b
4,861,903,020,502
6cb54eee44c4629ab028da119afde5ec9c8e3ed2
/app/src/main/java/com/example/retrofit2/pk/retrofit2/DataClient.java
763e1734673e2a84b8b6be8947499f2c753084cc
[]
no_license
tienhoai/Retrofit2
https://github.com/tienhoai/Retrofit2
de9ff3f57164c81e33fa40d776304d58a8795ad0
64341e658193130f340a8483e7c2387739ae4558
refs/heads/master
2022-07-11T01:50:51.504000
2020-05-12T06:34:28
2020-05-12T06:34:28
262,267,484
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.retrofit2.pk.retrofit2; import com.example.retrofit2.pk.model.ProductData; import java.util.List; import okhttp3.MultipartBody; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Part; public interface DataClient { @GET("get-product.php") Call<List<ProductData>> getProduct(); @Multipart @POST("upload-image.php") Call<String> uploadImage(@Part MultipartBody.Part photo); @FormUrlEncoded @POST("insert-product.php") Call<String> insertProduct(@Field("ten") String ten, @Field("gia") String gia, @Field("hinh") String hinh); }
UTF-8
Java
759
java
DataClient.java
Java
[]
null
[]
package com.example.retrofit2.pk.retrofit2; import com.example.retrofit2.pk.model.ProductData; import java.util.List; import okhttp3.MultipartBody; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Part; public interface DataClient { @GET("get-product.php") Call<List<ProductData>> getProduct(); @Multipart @POST("upload-image.php") Call<String> uploadImage(@Part MultipartBody.Part photo); @FormUrlEncoded @POST("insert-product.php") Call<String> insertProduct(@Field("ten") String ten, @Field("gia") String gia, @Field("hinh") String hinh); }
759
0.753623
0.737813
27
27.111111
22.732475
111
false
false
0
0
0
0
0
0
0.62963
false
false
12
2bb7c2246fa17378028f4c233fbe4d6a8bb13d50
3,530,463,162,579
be41b0d417594c4c1ed0a6325a00d546a1246180
/CH3_17/src/CH3_17.java
3479d1b1255b123d768b9b885681074cb4577356
[]
no_license
anomie7/JavaPractice02
https://github.com/anomie7/JavaPractice02
d3ea46dce65f3e01d4a1ece0a5503be59104c5a9
44cef26799683049f508f1095226bdc8390267d1
refs/heads/master
2021-01-20T02:30:49.766000
2017-07-21T13:23:56
2017-07-21T13:23:56
89,418,287
0
0
null
false
2017-06-24T03:41:02
2017-04-26T00:09:22
2017-06-16T11:29:21
2017-06-24T03:41:02
5,217
0
0
0
Java
null
null
import java.util.Random; import java.util.Scanner; public class CH3_17 { public static void main(String[] args){ Scanner stdIn = new Scanner(System.in); Random rand = new Random(); System.out.print("무엇을 내시겠습니까? "); int my_hand = stdIn.nextInt(); switch(my_hand) { case 0: System.out.println("가위"); break; case 1: System.out.println("바위"); break; case 2: System.out.println("보"); break; } int com_hand = rand.nextInt(3); switch(com_hand) { case 0: System.out.println("가위"); break; case 1: System.out.println("바위"); break; case 2: System.out.println("보"); break; } if (com_hand == my_hand){ System.out.println("비겼습니다."); } else if (com_hand == 0 && my_hand == 1){ System.out.println("당신이 이겼습니다."); } else if (com_hand == 1 && my_hand == 2){ System.out.println("당신이 이겼습니다."); } else if (com_hand == 2 && my_hand == 0){ System.out.println("당신이 이겼습니다."); } else if ( my_hand > 2 || my_hand < 0){ System.out.println("다시 입력해주세요."); } else { System.out.println("당신이 졌습니다."); } stdIn.close(); } }
UHC
Java
1,234
java
CH3_17.java
Java
[]
null
[]
import java.util.Random; import java.util.Scanner; public class CH3_17 { public static void main(String[] args){ Scanner stdIn = new Scanner(System.in); Random rand = new Random(); System.out.print("무엇을 내시겠습니까? "); int my_hand = stdIn.nextInt(); switch(my_hand) { case 0: System.out.println("가위"); break; case 1: System.out.println("바위"); break; case 2: System.out.println("보"); break; } int com_hand = rand.nextInt(3); switch(com_hand) { case 0: System.out.println("가위"); break; case 1: System.out.println("바위"); break; case 2: System.out.println("보"); break; } if (com_hand == my_hand){ System.out.println("비겼습니다."); } else if (com_hand == 0 && my_hand == 1){ System.out.println("당신이 이겼습니다."); } else if (com_hand == 1 && my_hand == 2){ System.out.println("당신이 이겼습니다."); } else if (com_hand == 2 && my_hand == 0){ System.out.println("당신이 이겼습니다."); } else if ( my_hand > 2 || my_hand < 0){ System.out.println("다시 입력해주세요."); } else { System.out.println("당신이 졌습니다."); } stdIn.close(); } }
1,234
0.58213
0.565884
54
19.518518
14.272144
44
false
false
0
0
0
0
0
0
2.611111
false
false
12
836154272222463bc4a0a05bb32eb318383ed9ed
22,041,772,203,327
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/14/14_b96c6c8e8f1f828bb5aa242830cab02affaab331/PingsClientSimulation/14_b96c6c8e8f1f828bb5aa242830cab02affaab331_PingsClientSimulation_t.java
66ab9e3311926abe6c3782964437e1076ca9eb98
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
import java.net.InetAddress; import java.util.Random; /** * This class defines a rather accurate simulation of PingsClient * * @author RaphaelBonaque */ public class PingsClientSimulation extends PingsClient{ //Simulation parameters //let's say the signal is 3 times slower than light speed double approximate_speed = 100000000; //Some random time due to any kind of factor (routers ...) double average_random_time = 0.025; //Some additional residual time (added on every network transmission) double residual_time = 0.1; //the fraction of the ping that randomly time out double timed_out_fraction = 0.05; double timed_out_delay = 5; //the fraction of ping that randomly refuse connection double connection_refused_fraction = 0.3; private Random prg; private static GeoipInfo server_location = new GeoipInfo("Montreal","Canada",-73.55f,45.5f); private static GeoipInfo client_geoip = server_location; public PingsClientSimulation() { super(); prg = new Random(); if (client_geoip == server_location) { client_geoip = take_next_geoip_from_list(); } subClients_pool = new subClient[subClient_number]; subClients_threads_pool = new Thread[subClient_number]; for (int i = 0; i < subClient_number; i++) { subClients_pool[i] = new subClientSimulation(); subClients_threads_pool[i] = new Thread(subClients_pool[i]); subClients_threads_pool[i].setName("SubClient "+ i); } } /** * A function simulating a wait from the network * * @param time the time to wait in second */ public void wait_for_network(double time) { long real_time = (long) ((residual_time+ time) * 1000); try { Thread.sleep((long) real_time ); } catch (InterruptedException e) {} } /** * Return a great-circle approximation of the distance between to points * * @return the approximate distance in meters */ private double approximate_distance(GeoipInfo x1, GeoipInfo x2) { double phi_1 = x1.latitude * Math.PI /180; double lambda_1 = x1.longitude * Math.PI /180; double phi_2 = x2.latitude * Math.PI /180; double lambda_2 = x2.longitude * Math.PI /180; double mb1 = Math.sin(phi_1) * Math.sin(phi_2); double mb2 = Math.cos(phi_1) * Math.cos(phi_2)*Math.cos(lambda_1 - lambda_2); double earth_radius = 6372800.; double approximate_dist = earth_radius * Math.acos(mb1 + mb2); return approximate_dist; } /** * A function simulating a ICMP ping (we don't need the address of the * target only the position) */ private String ping(GeoipInfo target) { int nb_tries = 31; String fake_header = "ICMP 255.0.255.0 "; double ping_estimation = 2 * (approximate_distance(client_geoip, target)/ approximate_speed) + (2 * average_random_time * prg.nextDouble()); double total_time = 0; int nb_succes = 0; double x = prg.nextDouble(); //Times out : if (x < timed_out_fraction){ total_time = nb_tries * timed_out_delay; nb_succes = 0; } //Connection refused : else if (x > 1 - connection_refused_fraction) { total_time = ping_estimation; nb_succes = 0 ; } //Success else{ total_time = nb_tries * ping_estimation; nb_succes = nb_tries; } wait_for_network(total_time); return fake_header + nb_tries + " " + nb_succes + " " +(int) (total_time * 1000) + "ms;"; } /** * Emulate the use of the next address in the list received from the server * * @return a random GeoipInfo */ private GeoipInfo take_next_geoip_from_list() { int index = prg.nextInt(worldCapital.length); return worldCapital[index]; } private InetAddress take_next_address_from_list() { byte[] bytes = new byte[4]; prg.nextBytes(bytes); try{ return InetAddress.getByAddress(bytes ); } catch (Exception _) { return null; } } private void talk_with_server() { ping(server_location); } public void run () { m_source_geoip.set(client_geoip); for (int pings_index = 0; pings_index < subClient_number; pings_index++) { subClients_threads_pool[pings_index].start(); } } /** * Simulate the subClient run thread */ public class subClientSimulation extends subClient { public void run () { while (true) { //Take the next address in the list received from the server current_ping_dest = take_next_address_from_list(); current_dest_geoip = take_next_geoip_from_list(); current_ping_result = null; //After all the addresses are submitted send the result to the //server if (prg.nextInt(15) == 0) talk_with_server(); notifyObserversOfChange(); //Ping this address current_ping_result = ping(current_dest_geoip); notifyObserversOfChange(); //In case the thread is paused here if (!m_is_running.get()) { while (!m_is_running.get()) { synchronized(pings_queue) { try {pings_queue.wait();} catch (InterruptedException e) {} } } } } } } public GeoipInfo[] worldCapital = { new GeoipInfo("Kabul", "Afghanistan", 69.11f, 34.28f), //E new GeoipInfo("Tirane", "Albania", 19.49f, 41.18f), //E new GeoipInfo("Algiers", "Algeria", 03.08f, 36.42f), //E new GeoipInfo("American Samoa", "Pago Pago",-14.16f, -170.43f), //w new GeoipInfo("Andorra", "Andorra la Vella", 01.32f, 42.31f), //E new GeoipInfo("Luanda", "Angola",-08.50f, 13.15f), //E new GeoipInfo("Antigua and Barbuda", "West Indies", -61.48f, 17.20f), //w new GeoipInfo("Argentina", "Buenos Aires",-36.30f, -60.00f), //w new GeoipInfo("Yerevan", "Armenia", 44.31f, 40.10f), //E new GeoipInfo("Oranjestad", "Aruba", -70.02f, 12.32f), //w new GeoipInfo("Canberra", "Australia",-35.15f, 149.08f), //E new GeoipInfo("Vienna", "Austria", 16.22f, 48.12f), //E new GeoipInfo("Baku", "Azerbaijan", 49.56f, 40.29f), //E new GeoipInfo("Nassau", "Bahamas", -77.20f, 25.05f), //w new GeoipInfo("Manama", "Bahrain", 50.30f, 26.10f), //E new GeoipInfo("Dhaka", "Bangladesh", 90.26f, 23.43f), //E new GeoipInfo("Bridgetown", "Barbados", -59.30f, 13.05f), //w new GeoipInfo("Minsk", "Belarus", 27.30f, 53.52f), //E new GeoipInfo("Brussels", "Belgium", 04.21f, 50.51f), //E new GeoipInfo("Belmopan", "Belize", -88.30f, 17.18f), //w new GeoipInfo("Benin", "Porto Novo (constitutional) / Cotonou (seat of government)", 02.42f, 06.23f), //E new GeoipInfo("Thimphu", "Bhutan", 89.45f, 27.31f), //E new GeoipInfo("Bolivia", "La Paz (administrative) / Sucre (legislative)",-16.20f, -68.10f), //w new GeoipInfo("Bosnia and Herzegovina", "Sarajevo", 18.26f, 43.52f), //E new GeoipInfo("Gaborone", "Botswana",-24.45f, 25.57f), //E new GeoipInfo("Brasilia", "Brazil",-15.47f, -47.55f), //w new GeoipInfo("British Virgin Islands", "Road Town", -64.37f, 18.27f), //w new GeoipInfo("Brunei Darussalam", "Bandar Seri Begawan", 115.00f, 04.52f), //E new GeoipInfo("Sofia", "Bulgaria", 23.20f, 42.45f), //E new GeoipInfo("Burkina Faso", "Ouagadougou", -01.30f, 12.15f), //w new GeoipInfo("Bujumbura", "Burundi",-03.16f, 29.18f), //E new GeoipInfo("Cambodia", "Phnom Penh", 104.55f, 11.33f), //E new GeoipInfo("Yaounde", "Cameroon", 11.35f, 03.50f), //E new GeoipInfo("Ottawa", "Canada", -75.42f, 45.27f), //w new GeoipInfo("Cape Verde", "Praia", -23.34f, 15.02f), //w new GeoipInfo("Cayman Islands", "George Town", -81.24f, 19.20f), //w new GeoipInfo("Central African Republic", "Bangui", 18.35f, 04.23f), //E new GeoipInfo("Chad", "N'Djamena", 14.59f, 12.10f), //E new GeoipInfo("Santiago", "Chile",-33.24f, -70.40f), //w new GeoipInfo("Beijing", "China", 116.20f, 39.55f), //E new GeoipInfo("Bogota", "Colombia", -74.00f, 04.34f), //w new GeoipInfo("Moroni", "Comros",-11.40f, 43.16f), //E new GeoipInfo("Brazzaville", "Congo",-04.09f, 15.12f), //E new GeoipInfo("Costa Rica", "San Jose", -84.02f, 09.55f), //w new GeoipInfo("Cote d'Ivoire", "Yamoussoukro", -05.17f, 06.49f), //w new GeoipInfo("Zagreb", "Croatia", 15.58f, 45.50f), //E new GeoipInfo("Havana", "Cuba", -82.22f, 23.08f), //w new GeoipInfo("Nicosia", "Cyprus", 33.25f, 35.10f), //E new GeoipInfo("Czech Republic", "Prague", 14.22f, 50.05f), //E new GeoipInfo("Democratic Republic of the Congo", "Kinshasa",-04.20f, 15.15f), //E new GeoipInfo("Copenhagen", "Denmark", 12.34f, 55.41f), //E new GeoipInfo("Djibouti", "Djibouti", 42.20f, 11.08f), //E new GeoipInfo("Roseau", "Dominica", -61.24f, 15.20f), //w new GeoipInfo("Dominica Republic", "Santo Domingo", -69.59f, 18.30f), //w new GeoipInfo("East Timor", "Dili",-08.29f, 125.34f), //E new GeoipInfo("Quito", "Ecuador",-00.15f, -78.35f), //w new GeoipInfo("Cairo", "Egypt", 31.14f, 30.01f), //E new GeoipInfo("El Salvador", "San Salvador", -89.10f, 13.40f), //w new GeoipInfo("Equatorial Guinea", "Malabo", 08.50f, 03.45f), //E new GeoipInfo("Asmara", "Eritrea", 38.55f, 15.19f), //E new GeoipInfo("Tallinn", "Estonia", 24.48f, 59.22f), //E new GeoipInfo("Ethiopia", "Addis Ababa", 38.42f, 09.02f), //E new GeoipInfo("Falkland Islands (Malvinas)", "Stanley",-51.40f, -59.51f), //w new GeoipInfo("Faroe Islands", "Torshavn", -06.56f, 62.05f), //w new GeoipInfo("Suva", "Fiji",-18.06f, 178.30f), //E new GeoipInfo("Helsinki", "Finland", 25.03f, 60.15f), //E new GeoipInfo("Paris", "France", 02.20f, 48.50f), //E new GeoipInfo("French Guiana", "Cayenne", -52.18f, 05.05f), //w new GeoipInfo("French Polynesia", "Papeete",-17.32f, -149.34f), //w new GeoipInfo("Libreville", "Gabon", 09.26f, 00.25f), //E new GeoipInfo("Banjul", "Gambia", -16.40f, 13.28f), //w new GeoipInfo("Georgia", "T'bilisi", 44.50f, 41.43f), //E new GeoipInfo("Berlin", "Germany", 13.25f, 52.30f), //E new GeoipInfo("Accra", "Ghana", -00.06f, 05.35f), //w new GeoipInfo("Athens", "Greece", 23.46f, 37.58f), //E new GeoipInfo("Nuuk", "Greenland", -51.35f, 64.10f), //w new GeoipInfo("Guadeloupe", "Basse-Terre", -61.44f, 16.00f), //w new GeoipInfo("Guatemala", "Guatemala", -90.22f, 14.40f), //w new GeoipInfo("Guernsey", "St. Peter Port", -02.33f, 49.26f), //w new GeoipInfo("Conakry", "Guinea", -13.49f, 09.29f), //w new GeoipInfo("Guinea-Bissau", "Bissau", -15.45f, 11.45f), //w new GeoipInfo("Georgetown", "Guyana", -58.12f, 06.50f), //w new GeoipInfo("Haiti", "Port-au-Prince", -72.20f, 18.40f), //w new GeoipInfo("Heard Island and McDonald Islands", " ",-53.00f, 74.00f), //E new GeoipInfo("Tegucigalpa", "Honduras", -87.14f, 14.05f), //w new GeoipInfo("Budapest", "Hungary", 19.05f, 47.29f), //E new GeoipInfo("Reykjavik", "Iceland", -21.57f, 64.10f), //w new GeoipInfo("India", "New Delhi", 77.13f, 28.37f), //E new GeoipInfo("Jakarta", "Indonesia",-06.09f, 106.49f), //E new GeoipInfo("Iran (Islamic Republic of)", "Tehran", 51.30f, 35.44f), //E new GeoipInfo("Baghdad", "Iraq", 44.30f, 33.20f), //E new GeoipInfo("Dublin", "Ireland", -06.15f, 53.21f), //w new GeoipInfo("Jerusalem", "Israel", -35.10f, 31.71f), //w new GeoipInfo("Rome", "Italy", 12.29f, 41.54f), //E new GeoipInfo("Kingston", "Jamaica", -76.50f, 18.00f), //w new GeoipInfo("Amman", "Jordan", 35.52f, 31.57f), //E new GeoipInfo("Astana", "Kazakhstan", 71.30f, 51.10f), //E new GeoipInfo("Nairobi", "Kenya",-01.17f, 36.48f), //E new GeoipInfo("Tarawa", "Kiribati", 173.00f, 01.30f), //E new GeoipInfo("Kuwait", "Kuwait", 48.00f, 29.30f), //E new GeoipInfo("Bishkek", "Kyrgyzstan", 74.46f, 42.54f), //E new GeoipInfo("Lao People's Democratic Republic", "Vientiane", 102.36f, 17.58f), //E new GeoipInfo("Riga", "Latvia", 24.08f, 56.53f), //E new GeoipInfo("Beirut", "Lebanon", 35.31f, 33.53f), //E new GeoipInfo("Maseru", "Lesotho",-29.18f, 27.30f), //E new GeoipInfo("Monrovia", "Liberia", -10.47f, 06.18f), //w new GeoipInfo("Libyan Arab Jamahiriya", "Tripoli", 13.07f, 32.49f), //E new GeoipInfo("Vaduz", "Liechtenstein", 09.31f, 47.08f), //E new GeoipInfo("Vilnius", "Lithuania", 25.19f, 54.38f), //E new GeoipInfo("Luxembourg", "Luxembourg", 06.09f, 49.37f), //E new GeoipInfo("Macao, China", "Macau", 113.33f, 22.12f), //E new GeoipInfo("Antananarivo", "Madagascar",-18.55f, 47.31f), //E new GeoipInfo("Macedonia (Former Yugoslav Republic)", "Skopje", 21.26f, 42.01f), //E new GeoipInfo("Lilongwe", "Malawi",-14.00f, 33.48f), //E new GeoipInfo("Malaysia", "Kuala Lumpur", 101.41f, 03.09f), //E new GeoipInfo("Male", "Maldives", 73.28f, 04.00f), //E new GeoipInfo("Bamako", "Mali", -07.55f, 12.34f), //w new GeoipInfo("Valletta", "Malta", 14.31f, 35.54f), //E new GeoipInfo("Martinique", "Fort-de-France", -61.02f, 14.36f), //w new GeoipInfo("Nouakchott", "Mauritania",-20.10f, 57.30f), //E new GeoipInfo("Mamoudzou", "Mayotte",-12.48f, 45.14f), //E new GeoipInfo("Mexico", "Mexico", -99.10f, 19.20f), //w new GeoipInfo("Micronesia (Federated States of)", "Palikir", 158.09f, 06.55f), //E new GeoipInfo("Moldova, Republic of", "Chisinau", 28.50f, 47.02f), //E new GeoipInfo("Maputo", "Mozambique",-25.58f, 32.32f), //E new GeoipInfo("Yangon", "Myanmar", 96.20f, 16.45f), //E new GeoipInfo("Windhoek", "Namibia",-22.35f, 17.04f), //E new GeoipInfo("Kathmandu", "Nepal", 85.20f, 27.45f), //E new GeoipInfo("Netherlands", "Amsterdam / The Hague (seat of Government)", 04.54f, 52.23f), //E new GeoipInfo("Netherlands Antilles", "Willemstad", -69.00f, 12.05f), //w new GeoipInfo("New Caledonia", "Noumea",-22.17f, 166.30f), //E new GeoipInfo("New Zealand", "Wellington",-41.19f, 174.46f), //E new GeoipInfo("Managua", "Nicaragua", -86.20f, 12.06f), //w new GeoipInfo("Niamey", "Niger", 02.06f, 13.27f), //E new GeoipInfo("Abuja", "Nigeria", 07.32f, 09.05f), //E new GeoipInfo("Norfolk Island", "Kingston",-45.20f, 168.43f), //E new GeoipInfo("North Korea", "Pyongyang", 125.30f, 39.09f), //E new GeoipInfo("Northern Mariana Islands", "Saipan", 145.45f, 15.12f), //E new GeoipInfo("Oslo", "Norway", 10.45f, 59.55f), //E new GeoipInfo("Masqat", "Oman", 58.36f, 23.37f), //E new GeoipInfo("Islamabad", "Pakistan", 73.10f, 33.40f), //E new GeoipInfo("Koror", "Palau", 134.28f, 07.20f), //E new GeoipInfo("Panama", "Panama", -79.25f, 09.00f), //w new GeoipInfo("Papua New Guinea", "Port Moresby",-09.24f, 147.08f), //E new GeoipInfo("Asuncion", "Paraguay",-25.10f, -57.30f), //w new GeoipInfo("Lima", "Peru",-12.00f, -77.00f), //w new GeoipInfo("Manila", "Philippines", 121.03f, 14.40f), //E new GeoipInfo("Warsaw", "Poland", 21.00f, 52.13f), //E new GeoipInfo("Lisbon", "Portugal", -09.10f, 38.42f), //w new GeoipInfo("Puerto Rico", "San Juan", -66.07f, 18.28f), //w new GeoipInfo("Doha", "Qatar", 51.35f, 25.15f), //E new GeoipInfo("Republic of Korea", "Seoul", 126.58f, 37.31f), //E new GeoipInfo("Bucuresti", "Romania", 26.10f, 44.27f), //E new GeoipInfo("Russian Federation", "Moskva", 37.35f, 55.45f), //E new GeoipInfo("Kigali", "Rawanda",-01.59f, 30.04f), //E new GeoipInfo("Saint Kitts and Nevis", "Basseterre", -62.43f, 17.17f), //w new GeoipInfo("Saint Lucia", "Castries", -60.58f, 14.02f), //w new GeoipInfo("Saint Pierre and Miquelon", "Saint-Pierre", -56.12f, 46.46f), //w new GeoipInfo("Saint Vincent and the Greenadines", "Kingstown", -61.10f, 13.10f), //w new GeoipInfo("Apia", "Samoa",-13.50f, -171.50f), //w new GeoipInfo("San Marino", "San Marino", 12.30f, 43.55f), //E new GeoipInfo("Sao Tome and Principe", "Sao Tome", 06.39f, 00.10f), //E new GeoipInfo("Saudi Arabia", "Riyadh", 46.42f, 24.41f), //E new GeoipInfo("Dakar", "Senegal", -17.29f, 14.34f), //w new GeoipInfo("Sierra Leone", "Freetown", -13.17f, 08.30f), //w new GeoipInfo("Bratislava", "Slovakia", 17.07f, 48.10f), //E new GeoipInfo("Ljubljana", "Slovenia", 14.33f, 46.04f), //E new GeoipInfo("Solomon Islands", "Honiara",-09.27f, 159.57f), //E new GeoipInfo("Mogadishu", "Somalia", 45.25f, 02.02f), //E new GeoipInfo("South Africa", "Pretoria (administrative) / Cape Town (legislative) / Bloemfontein (judicial)",-25.44f, 28.12f), //E new GeoipInfo("Madrid", "Spain", -03.45f, 40.25f), //w new GeoipInfo("Khartoum", "Sudan", 32.35f, 15.31f), //E new GeoipInfo("Paramaribo", "Suriname", -55.10f, 05.50f), //w new GeoipInfo("Swaziland", "Mbabane (administrative)",-26.18f, 31.06f), //E new GeoipInfo("Stockholm", "Sweden", 18.03f, 59.20f), //E new GeoipInfo("Bern", "Switzerland", 07.28f, 46.57f), //E new GeoipInfo("Syrian Arab Republic", "Damascus", 36.18f, 33.30f), //E new GeoipInfo("Dushanbe", "Tajikistan", 68.48f, 38.33f), //E new GeoipInfo("Bangkok", "Thailand", 100.35f, 13.45f), //E new GeoipInfo("Lome", "Togo", 01.20f, 06.09f), //E new GeoipInfo("Tonga", "Nuku'alofa",-21.10f, -174.00f), //w new GeoipInfo("Tunis", "Tunisia", 10.11f, 36.50f), //E new GeoipInfo("Ankara", "Turkey", 32.54f, 39.57f), //E new GeoipInfo("Ashgabat", "Turkmenistan", 57.50f, 38.00f), //E new GeoipInfo("Funafuti", "Tuvalu",-08.31f, 179.13f), //E new GeoipInfo("Kampala", "Uganda", 32.30f, 00.20f), //E new GeoipInfo("Ukraine", "Kiev (Russia)", 30.28f, 50.30f), //E new GeoipInfo("United Arab Emirates", "Abu Dhabi", 54.22f, 24.28f), //E new GeoipInfo("United Kingdom of Great Britain and Northern Ireland", "London", -00.05f, 51.36f), //w new GeoipInfo("United Republic of Tanzania", "Dodoma",-06.08f, 35.45f), //E new GeoipInfo("United States of America", "Washington DC", -77.02f, 39.91f), //w new GeoipInfo("United States of Virgin Islands", "Charlotte Amalie", -64.56f, 18.21f), //w new GeoipInfo("Montevideo", "Uruguay",-34.50f, -56.11f), //w new GeoipInfo("Tashkent", "Uzbekistan", 69.10f, 41.20f), //E new GeoipInfo("Vanuatu", "Port-Vila",-17.45f, 168.18f), //E new GeoipInfo("Caracas", "Venezuela", -66.55f, 10.30f), //w new GeoipInfo("Viet Nam", "Hanoi", 105.55f, 21.05f), //E new GeoipInfo("Belgrade", "Yugoslavia", 20.37f, 44.50f), //E new GeoipInfo("Lusaka", "Zambia",-15.28f, 28.16f), //E new GeoipInfo("Harare", "Zimbabwe",-17.43f, 31.02f), //E }; }
UTF-8
Java
20,583
java
14_b96c6c8e8f1f828bb5aa242830cab02affaab331_PingsClientSimulation_t.java
Java
[ { "context": "ccurate simulation of PingsClient\n * \n * @author RaphaelBonaque\n */\n public class PingsClientSimulation extends ", "end": 165, "score": 0.9996488690376282, "start": 151, "tag": "NAME", "value": "RaphaelBonaque" }, { "context": "b_tries = 31;\n String fake_header = \"ICMP 255.0.255.0 \";\n \n double ping_estimation =\n ", "end": 3035, "score": 0.9997304677963257, "start": 3024, "tag": "IP_ADDRESS", "value": "255.0.255.0" }, { "context": " new GeoipInfo(\"Bosnia and Herzegovina\", \"Sarajevo\", 18.26f, 43.52f), //E\n new GeoipInfo(\"", "end": 7957, "score": 0.5687015056610107, "start": 7954, "tag": "NAME", "value": "aje" }, { "context": " //w\n new GeoipInfo(\"Brunei Darussalam\", \"Bandar Seri Begawan\", 115.00f, 04.52f), //E\n new GeoipInfo(\"S", "end": 8266, "score": 0.8880013227462769, "start": 8247, "tag": "NAME", "value": "Bandar Seri Begawan" }, { "context": " 29.18f), //E\n new GeoipInfo(\"Cambodia\", \"Phnom Penh\", 104.55f, 11.33f), //E\n new GeoipInfo(\"Y", "end": 8546, "score": 0.8229408860206604, "start": 8536, "tag": "NAME", "value": "Phnom Penh" }, { "context": "\", 08.50f, 03.45f), //E\n new GeoipInfo(\"Asmara\", \"Eritrea\", 38.55f, 15.19f), //E\n new G", "end": 10493, "score": 0.6347378492355347, "start": 10490, "tag": "NAME", "value": "mar" }, { "context": " 59.22f), //E\n new GeoipInfo(\"Ethiopia\", \"Addis Ababa\", 38.42f, 09.02f), //E\n new GeoipInfo(\"Fa", "end": 10642, "score": 0.994629979133606, "start": 10631, "tag": "NAME", "value": "Addis Ababa" }, { "context": "13.28f), //w\n new GeoipInfo(\"Georgia\", \"T'bilisi\", 44.50f, 41.43f), //E\n new GeoipInfo(", "end": 11340, "score": 0.5746320486068726, "start": 11337, "tag": "NAME", "value": "bil" }, { "context": "a\", -90.22f, 14.40f), //w\n new GeoipInfo(\"Guernsey\", \"St. Peter Port\", -02.33f, 49.26f), //w\n ", "end": 11802, "score": 0.8738365769386292, "start": 11794, "tag": "NAME", "value": "Guernsey" }, { "context": "a\", -76.50f, 18.00f), //w\n new GeoipInfo(\"Amman\", \"Jordan\", 35.52f, 31.57f), //E\n new Geo", "end": 12992, "score": 0.9774808883666992, "start": 12987, "tag": "NAME", "value": "Amman" }, { "context": "0f, 18.00f), //w\n new GeoipInfo(\"Amman\", \"Jordan\", 35.52f, 31.57f), //E\n new GeoipInfo(\"As", "end": 13002, "score": 0.9897301197052002, "start": 12996, "tag": "NAME", "value": "Jordan" }, { "context": "f, 33.53f), //E\n new GeoipInfo(\"Maseru\", \"Lesotho\",-29.18f, 27.30f), //E\n new GeoipInfo(\"Mo", "end": 13620, "score": 0.8640214800834656, "start": 13613, "tag": "NAME", "value": "Lesotho" }, { "context": "ho\",-29.18f, 27.30f), //E\n new GeoipInfo(\"Monrovia\", \"Liberia\", -10.47f, 06.18f), //w\n new G", "end": 13676, "score": 0.7995207905769348, "start": 13668, "tag": "NAME", "value": "Monrovia" }, { "context": "li\", 13.07f, 32.49f), //E\n new GeoipInfo(\"Vaduz\", \"Liechtenstein\", 09.31f, 47.08f), //E\n ", "end": 13822, "score": 0.958244800567627, "start": 13817, "tag": "NAME", "value": "Vaduz" }, { "context": "7f, 32.49f), //E\n new GeoipInfo(\"Vaduz\", \"Liechtenstein\", 09.31f, 47.08f), //E\n new GeoipInfo(\"Vi", "end": 13839, "score": 0.9877046942710876, "start": 13826, "tag": "NAME", "value": "Liechtenstein" }, { "context": ", 09.31f, 47.08f), //E\n new GeoipInfo(\"Vilnius\", \"Lithuania\", 25.19f, 54.38f), //E\n n", "end": 13891, "score": 0.6061657667160034, "start": 13890, "tag": "NAME", "value": "n" }, { "context": "37f), //E\n new GeoipInfo(\"Macao, China\", \"Macau\", 113.33f, 22.12f), //E\n new GeoipInfo(\"A", "end": 14048, "score": 0.594296395778656, "start": 14043, "tag": "NAME", "value": "Macau" }, { "context": ", 03.09f), //E\n new GeoipInfo(\"Male\", \"Maldives\", 73.28f, 04.00f), //E\n new GeoipInfo(\"", "end": 14418, "score": 0.5144749879837036, "start": 14415, "tag": "NAME", "value": "div" }, { "context": "i\", -07.55f, 12.34f), //w\n new GeoipInfo(\"Valletta\", \"Malta\", 14.31f, 35.54f), //E\n new Geoi", "end": 14539, "score": 0.8629498481750488, "start": 14531, "tag": "NAME", "value": "Valletta" }, { "context": ".34f), //w\n new GeoipInfo(\"Valletta\", \"Malta\", 14.31f, 35.54f), //E\n new GeoipInfo(\"Ma", "end": 14548, "score": 0.5835289359092712, "start": 14546, "tag": "NAME", "value": "ta" }, { "context": "ta\", 14.31f, 35.54f), //E\n new GeoipInfo(\"Martinique\", \"Fort-de-France\", -61.02f, 14.36f), //w\n ", "end": 14606, "score": 0.8125073909759521, "start": 14596, "tag": "NAME", "value": "Martinique" }, { "context": "4.36f), //w\n new GeoipInfo(\"Nouakchott\", \"Mauritania\",-20.10f, 57.30f), //E\n new Geoi", "end": 14688, "score": 0.7346752882003784, "start": 14687, "tag": "NAME", "value": "M" }, { "context": "an\", 57.50f, 38.00f), //E\n new GeoipInfo(\"Funafuti\", \"Tuvalu\",-08.31f, 179.13f), //E\n new", "end": 19386, "score": 0.6907747983932495, "start": 19381, "tag": "NAME", "value": "Funaf" }, { "context": " 38.00f), //E\n new GeoipInfo(\"Funafuti\", \"Tuvalu\",-08.31f, 179.13f), //E\n new GeoipInfo(\"K", "end": 19399, "score": 0.6632908582687378, "start": 19393, "tag": "NAME", "value": "Tuvalu" } ]
null
[]
import java.net.InetAddress; import java.util.Random; /** * This class defines a rather accurate simulation of PingsClient * * @author RaphaelBonaque */ public class PingsClientSimulation extends PingsClient{ //Simulation parameters //let's say the signal is 3 times slower than light speed double approximate_speed = 100000000; //Some random time due to any kind of factor (routers ...) double average_random_time = 0.025; //Some additional residual time (added on every network transmission) double residual_time = 0.1; //the fraction of the ping that randomly time out double timed_out_fraction = 0.05; double timed_out_delay = 5; //the fraction of ping that randomly refuse connection double connection_refused_fraction = 0.3; private Random prg; private static GeoipInfo server_location = new GeoipInfo("Montreal","Canada",-73.55f,45.5f); private static GeoipInfo client_geoip = server_location; public PingsClientSimulation() { super(); prg = new Random(); if (client_geoip == server_location) { client_geoip = take_next_geoip_from_list(); } subClients_pool = new subClient[subClient_number]; subClients_threads_pool = new Thread[subClient_number]; for (int i = 0; i < subClient_number; i++) { subClients_pool[i] = new subClientSimulation(); subClients_threads_pool[i] = new Thread(subClients_pool[i]); subClients_threads_pool[i].setName("SubClient "+ i); } } /** * A function simulating a wait from the network * * @param time the time to wait in second */ public void wait_for_network(double time) { long real_time = (long) ((residual_time+ time) * 1000); try { Thread.sleep((long) real_time ); } catch (InterruptedException e) {} } /** * Return a great-circle approximation of the distance between to points * * @return the approximate distance in meters */ private double approximate_distance(GeoipInfo x1, GeoipInfo x2) { double phi_1 = x1.latitude * Math.PI /180; double lambda_1 = x1.longitude * Math.PI /180; double phi_2 = x2.latitude * Math.PI /180; double lambda_2 = x2.longitude * Math.PI /180; double mb1 = Math.sin(phi_1) * Math.sin(phi_2); double mb2 = Math.cos(phi_1) * Math.cos(phi_2)*Math.cos(lambda_1 - lambda_2); double earth_radius = 6372800.; double approximate_dist = earth_radius * Math.acos(mb1 + mb2); return approximate_dist; } /** * A function simulating a ICMP ping (we don't need the address of the * target only the position) */ private String ping(GeoipInfo target) { int nb_tries = 31; String fake_header = "ICMP 255.0.255.0 "; double ping_estimation = 2 * (approximate_distance(client_geoip, target)/ approximate_speed) + (2 * average_random_time * prg.nextDouble()); double total_time = 0; int nb_succes = 0; double x = prg.nextDouble(); //Times out : if (x < timed_out_fraction){ total_time = nb_tries * timed_out_delay; nb_succes = 0; } //Connection refused : else if (x > 1 - connection_refused_fraction) { total_time = ping_estimation; nb_succes = 0 ; } //Success else{ total_time = nb_tries * ping_estimation; nb_succes = nb_tries; } wait_for_network(total_time); return fake_header + nb_tries + " " + nb_succes + " " +(int) (total_time * 1000) + "ms;"; } /** * Emulate the use of the next address in the list received from the server * * @return a random GeoipInfo */ private GeoipInfo take_next_geoip_from_list() { int index = prg.nextInt(worldCapital.length); return worldCapital[index]; } private InetAddress take_next_address_from_list() { byte[] bytes = new byte[4]; prg.nextBytes(bytes); try{ return InetAddress.getByAddress(bytes ); } catch (Exception _) { return null; } } private void talk_with_server() { ping(server_location); } public void run () { m_source_geoip.set(client_geoip); for (int pings_index = 0; pings_index < subClient_number; pings_index++) { subClients_threads_pool[pings_index].start(); } } /** * Simulate the subClient run thread */ public class subClientSimulation extends subClient { public void run () { while (true) { //Take the next address in the list received from the server current_ping_dest = take_next_address_from_list(); current_dest_geoip = take_next_geoip_from_list(); current_ping_result = null; //After all the addresses are submitted send the result to the //server if (prg.nextInt(15) == 0) talk_with_server(); notifyObserversOfChange(); //Ping this address current_ping_result = ping(current_dest_geoip); notifyObserversOfChange(); //In case the thread is paused here if (!m_is_running.get()) { while (!m_is_running.get()) { synchronized(pings_queue) { try {pings_queue.wait();} catch (InterruptedException e) {} } } } } } } public GeoipInfo[] worldCapital = { new GeoipInfo("Kabul", "Afghanistan", 69.11f, 34.28f), //E new GeoipInfo("Tirane", "Albania", 19.49f, 41.18f), //E new GeoipInfo("Algiers", "Algeria", 03.08f, 36.42f), //E new GeoipInfo("American Samoa", "Pago Pago",-14.16f, -170.43f), //w new GeoipInfo("Andorra", "Andorra la Vella", 01.32f, 42.31f), //E new GeoipInfo("Luanda", "Angola",-08.50f, 13.15f), //E new GeoipInfo("Antigua and Barbuda", "West Indies", -61.48f, 17.20f), //w new GeoipInfo("Argentina", "Buenos Aires",-36.30f, -60.00f), //w new GeoipInfo("Yerevan", "Armenia", 44.31f, 40.10f), //E new GeoipInfo("Oranjestad", "Aruba", -70.02f, 12.32f), //w new GeoipInfo("Canberra", "Australia",-35.15f, 149.08f), //E new GeoipInfo("Vienna", "Austria", 16.22f, 48.12f), //E new GeoipInfo("Baku", "Azerbaijan", 49.56f, 40.29f), //E new GeoipInfo("Nassau", "Bahamas", -77.20f, 25.05f), //w new GeoipInfo("Manama", "Bahrain", 50.30f, 26.10f), //E new GeoipInfo("Dhaka", "Bangladesh", 90.26f, 23.43f), //E new GeoipInfo("Bridgetown", "Barbados", -59.30f, 13.05f), //w new GeoipInfo("Minsk", "Belarus", 27.30f, 53.52f), //E new GeoipInfo("Brussels", "Belgium", 04.21f, 50.51f), //E new GeoipInfo("Belmopan", "Belize", -88.30f, 17.18f), //w new GeoipInfo("Benin", "Porto Novo (constitutional) / Cotonou (seat of government)", 02.42f, 06.23f), //E new GeoipInfo("Thimphu", "Bhutan", 89.45f, 27.31f), //E new GeoipInfo("Bolivia", "La Paz (administrative) / Sucre (legislative)",-16.20f, -68.10f), //w new GeoipInfo("Bosnia and Herzegovina", "Sarajevo", 18.26f, 43.52f), //E new GeoipInfo("Gaborone", "Botswana",-24.45f, 25.57f), //E new GeoipInfo("Brasilia", "Brazil",-15.47f, -47.55f), //w new GeoipInfo("British Virgin Islands", "Road Town", -64.37f, 18.27f), //w new GeoipInfo("Brunei Darussalam", "<NAME>", 115.00f, 04.52f), //E new GeoipInfo("Sofia", "Bulgaria", 23.20f, 42.45f), //E new GeoipInfo("Burkina Faso", "Ouagadougou", -01.30f, 12.15f), //w new GeoipInfo("Bujumbura", "Burundi",-03.16f, 29.18f), //E new GeoipInfo("Cambodia", "<NAME>", 104.55f, 11.33f), //E new GeoipInfo("Yaounde", "Cameroon", 11.35f, 03.50f), //E new GeoipInfo("Ottawa", "Canada", -75.42f, 45.27f), //w new GeoipInfo("Cape Verde", "Praia", -23.34f, 15.02f), //w new GeoipInfo("Cayman Islands", "George Town", -81.24f, 19.20f), //w new GeoipInfo("Central African Republic", "Bangui", 18.35f, 04.23f), //E new GeoipInfo("Chad", "N'Djamena", 14.59f, 12.10f), //E new GeoipInfo("Santiago", "Chile",-33.24f, -70.40f), //w new GeoipInfo("Beijing", "China", 116.20f, 39.55f), //E new GeoipInfo("Bogota", "Colombia", -74.00f, 04.34f), //w new GeoipInfo("Moroni", "Comros",-11.40f, 43.16f), //E new GeoipInfo("Brazzaville", "Congo",-04.09f, 15.12f), //E new GeoipInfo("Costa Rica", "San Jose", -84.02f, 09.55f), //w new GeoipInfo("Cote d'Ivoire", "Yamoussoukro", -05.17f, 06.49f), //w new GeoipInfo("Zagreb", "Croatia", 15.58f, 45.50f), //E new GeoipInfo("Havana", "Cuba", -82.22f, 23.08f), //w new GeoipInfo("Nicosia", "Cyprus", 33.25f, 35.10f), //E new GeoipInfo("Czech Republic", "Prague", 14.22f, 50.05f), //E new GeoipInfo("Democratic Republic of the Congo", "Kinshasa",-04.20f, 15.15f), //E new GeoipInfo("Copenhagen", "Denmark", 12.34f, 55.41f), //E new GeoipInfo("Djibouti", "Djibouti", 42.20f, 11.08f), //E new GeoipInfo("Roseau", "Dominica", -61.24f, 15.20f), //w new GeoipInfo("Dominica Republic", "Santo Domingo", -69.59f, 18.30f), //w new GeoipInfo("East Timor", "Dili",-08.29f, 125.34f), //E new GeoipInfo("Quito", "Ecuador",-00.15f, -78.35f), //w new GeoipInfo("Cairo", "Egypt", 31.14f, 30.01f), //E new GeoipInfo("El Salvador", "San Salvador", -89.10f, 13.40f), //w new GeoipInfo("Equatorial Guinea", "Malabo", 08.50f, 03.45f), //E new GeoipInfo("Asmara", "Eritrea", 38.55f, 15.19f), //E new GeoipInfo("Tallinn", "Estonia", 24.48f, 59.22f), //E new GeoipInfo("Ethiopia", "<NAME>", 38.42f, 09.02f), //E new GeoipInfo("Falkland Islands (Malvinas)", "Stanley",-51.40f, -59.51f), //w new GeoipInfo("Faroe Islands", "Torshavn", -06.56f, 62.05f), //w new GeoipInfo("Suva", "Fiji",-18.06f, 178.30f), //E new GeoipInfo("Helsinki", "Finland", 25.03f, 60.15f), //E new GeoipInfo("Paris", "France", 02.20f, 48.50f), //E new GeoipInfo("French Guiana", "Cayenne", -52.18f, 05.05f), //w new GeoipInfo("French Polynesia", "Papeete",-17.32f, -149.34f), //w new GeoipInfo("Libreville", "Gabon", 09.26f, 00.25f), //E new GeoipInfo("Banjul", "Gambia", -16.40f, 13.28f), //w new GeoipInfo("Georgia", "T'bilisi", 44.50f, 41.43f), //E new GeoipInfo("Berlin", "Germany", 13.25f, 52.30f), //E new GeoipInfo("Accra", "Ghana", -00.06f, 05.35f), //w new GeoipInfo("Athens", "Greece", 23.46f, 37.58f), //E new GeoipInfo("Nuuk", "Greenland", -51.35f, 64.10f), //w new GeoipInfo("Guadeloupe", "Basse-Terre", -61.44f, 16.00f), //w new GeoipInfo("Guatemala", "Guatemala", -90.22f, 14.40f), //w new GeoipInfo("Guernsey", "St. Peter Port", -02.33f, 49.26f), //w new GeoipInfo("Conakry", "Guinea", -13.49f, 09.29f), //w new GeoipInfo("Guinea-Bissau", "Bissau", -15.45f, 11.45f), //w new GeoipInfo("Georgetown", "Guyana", -58.12f, 06.50f), //w new GeoipInfo("Haiti", "Port-au-Prince", -72.20f, 18.40f), //w new GeoipInfo("Heard Island and McDonald Islands", " ",-53.00f, 74.00f), //E new GeoipInfo("Tegucigalpa", "Honduras", -87.14f, 14.05f), //w new GeoipInfo("Budapest", "Hungary", 19.05f, 47.29f), //E new GeoipInfo("Reykjavik", "Iceland", -21.57f, 64.10f), //w new GeoipInfo("India", "New Delhi", 77.13f, 28.37f), //E new GeoipInfo("Jakarta", "Indonesia",-06.09f, 106.49f), //E new GeoipInfo("Iran (Islamic Republic of)", "Tehran", 51.30f, 35.44f), //E new GeoipInfo("Baghdad", "Iraq", 44.30f, 33.20f), //E new GeoipInfo("Dublin", "Ireland", -06.15f, 53.21f), //w new GeoipInfo("Jerusalem", "Israel", -35.10f, 31.71f), //w new GeoipInfo("Rome", "Italy", 12.29f, 41.54f), //E new GeoipInfo("Kingston", "Jamaica", -76.50f, 18.00f), //w new GeoipInfo("Amman", "Jordan", 35.52f, 31.57f), //E new GeoipInfo("Astana", "Kazakhstan", 71.30f, 51.10f), //E new GeoipInfo("Nairobi", "Kenya",-01.17f, 36.48f), //E new GeoipInfo("Tarawa", "Kiribati", 173.00f, 01.30f), //E new GeoipInfo("Kuwait", "Kuwait", 48.00f, 29.30f), //E new GeoipInfo("Bishkek", "Kyrgyzstan", 74.46f, 42.54f), //E new GeoipInfo("Lao People's Democratic Republic", "Vientiane", 102.36f, 17.58f), //E new GeoipInfo("Riga", "Latvia", 24.08f, 56.53f), //E new GeoipInfo("Beirut", "Lebanon", 35.31f, 33.53f), //E new GeoipInfo("Maseru", "Lesotho",-29.18f, 27.30f), //E new GeoipInfo("Monrovia", "Liberia", -10.47f, 06.18f), //w new GeoipInfo("Libyan Arab Jamahiriya", "Tripoli", 13.07f, 32.49f), //E new GeoipInfo("Vaduz", "Liechtenstein", 09.31f, 47.08f), //E new GeoipInfo("Vilnius", "Lithuania", 25.19f, 54.38f), //E new GeoipInfo("Luxembourg", "Luxembourg", 06.09f, 49.37f), //E new GeoipInfo("Macao, China", "Macau", 113.33f, 22.12f), //E new GeoipInfo("Antananarivo", "Madagascar",-18.55f, 47.31f), //E new GeoipInfo("Macedonia (Former Yugoslav Republic)", "Skopje", 21.26f, 42.01f), //E new GeoipInfo("Lilongwe", "Malawi",-14.00f, 33.48f), //E new GeoipInfo("Malaysia", "Kuala Lumpur", 101.41f, 03.09f), //E new GeoipInfo("Male", "Maldives", 73.28f, 04.00f), //E new GeoipInfo("Bamako", "Mali", -07.55f, 12.34f), //w new GeoipInfo("Valletta", "Malta", 14.31f, 35.54f), //E new GeoipInfo("Martinique", "Fort-de-France", -61.02f, 14.36f), //w new GeoipInfo("Nouakchott", "Mauritania",-20.10f, 57.30f), //E new GeoipInfo("Mamoudzou", "Mayotte",-12.48f, 45.14f), //E new GeoipInfo("Mexico", "Mexico", -99.10f, 19.20f), //w new GeoipInfo("Micronesia (Federated States of)", "Palikir", 158.09f, 06.55f), //E new GeoipInfo("Moldova, Republic of", "Chisinau", 28.50f, 47.02f), //E new GeoipInfo("Maputo", "Mozambique",-25.58f, 32.32f), //E new GeoipInfo("Yangon", "Myanmar", 96.20f, 16.45f), //E new GeoipInfo("Windhoek", "Namibia",-22.35f, 17.04f), //E new GeoipInfo("Kathmandu", "Nepal", 85.20f, 27.45f), //E new GeoipInfo("Netherlands", "Amsterdam / The Hague (seat of Government)", 04.54f, 52.23f), //E new GeoipInfo("Netherlands Antilles", "Willemstad", -69.00f, 12.05f), //w new GeoipInfo("New Caledonia", "Noumea",-22.17f, 166.30f), //E new GeoipInfo("New Zealand", "Wellington",-41.19f, 174.46f), //E new GeoipInfo("Managua", "Nicaragua", -86.20f, 12.06f), //w new GeoipInfo("Niamey", "Niger", 02.06f, 13.27f), //E new GeoipInfo("Abuja", "Nigeria", 07.32f, 09.05f), //E new GeoipInfo("Norfolk Island", "Kingston",-45.20f, 168.43f), //E new GeoipInfo("North Korea", "Pyongyang", 125.30f, 39.09f), //E new GeoipInfo("Northern Mariana Islands", "Saipan", 145.45f, 15.12f), //E new GeoipInfo("Oslo", "Norway", 10.45f, 59.55f), //E new GeoipInfo("Masqat", "Oman", 58.36f, 23.37f), //E new GeoipInfo("Islamabad", "Pakistan", 73.10f, 33.40f), //E new GeoipInfo("Koror", "Palau", 134.28f, 07.20f), //E new GeoipInfo("Panama", "Panama", -79.25f, 09.00f), //w new GeoipInfo("Papua New Guinea", "Port Moresby",-09.24f, 147.08f), //E new GeoipInfo("Asuncion", "Paraguay",-25.10f, -57.30f), //w new GeoipInfo("Lima", "Peru",-12.00f, -77.00f), //w new GeoipInfo("Manila", "Philippines", 121.03f, 14.40f), //E new GeoipInfo("Warsaw", "Poland", 21.00f, 52.13f), //E new GeoipInfo("Lisbon", "Portugal", -09.10f, 38.42f), //w new GeoipInfo("Puerto Rico", "San Juan", -66.07f, 18.28f), //w new GeoipInfo("Doha", "Qatar", 51.35f, 25.15f), //E new GeoipInfo("Republic of Korea", "Seoul", 126.58f, 37.31f), //E new GeoipInfo("Bucuresti", "Romania", 26.10f, 44.27f), //E new GeoipInfo("Russian Federation", "Moskva", 37.35f, 55.45f), //E new GeoipInfo("Kigali", "Rawanda",-01.59f, 30.04f), //E new GeoipInfo("Saint Kitts and Nevis", "Basseterre", -62.43f, 17.17f), //w new GeoipInfo("Saint Lucia", "Castries", -60.58f, 14.02f), //w new GeoipInfo("Saint Pierre and Miquelon", "Saint-Pierre", -56.12f, 46.46f), //w new GeoipInfo("Saint Vincent and the Greenadines", "Kingstown", -61.10f, 13.10f), //w new GeoipInfo("Apia", "Samoa",-13.50f, -171.50f), //w new GeoipInfo("San Marino", "San Marino", 12.30f, 43.55f), //E new GeoipInfo("Sao Tome and Principe", "Sao Tome", 06.39f, 00.10f), //E new GeoipInfo("Saudi Arabia", "Riyadh", 46.42f, 24.41f), //E new GeoipInfo("Dakar", "Senegal", -17.29f, 14.34f), //w new GeoipInfo("Sierra Leone", "Freetown", -13.17f, 08.30f), //w new GeoipInfo("Bratislava", "Slovakia", 17.07f, 48.10f), //E new GeoipInfo("Ljubljana", "Slovenia", 14.33f, 46.04f), //E new GeoipInfo("Solomon Islands", "Honiara",-09.27f, 159.57f), //E new GeoipInfo("Mogadishu", "Somalia", 45.25f, 02.02f), //E new GeoipInfo("South Africa", "Pretoria (administrative) / Cape Town (legislative) / Bloemfontein (judicial)",-25.44f, 28.12f), //E new GeoipInfo("Madrid", "Spain", -03.45f, 40.25f), //w new GeoipInfo("Khartoum", "Sudan", 32.35f, 15.31f), //E new GeoipInfo("Paramaribo", "Suriname", -55.10f, 05.50f), //w new GeoipInfo("Swaziland", "Mbabane (administrative)",-26.18f, 31.06f), //E new GeoipInfo("Stockholm", "Sweden", 18.03f, 59.20f), //E new GeoipInfo("Bern", "Switzerland", 07.28f, 46.57f), //E new GeoipInfo("Syrian Arab Republic", "Damascus", 36.18f, 33.30f), //E new GeoipInfo("Dushanbe", "Tajikistan", 68.48f, 38.33f), //E new GeoipInfo("Bangkok", "Thailand", 100.35f, 13.45f), //E new GeoipInfo("Lome", "Togo", 01.20f, 06.09f), //E new GeoipInfo("Tonga", "Nuku'alofa",-21.10f, -174.00f), //w new GeoipInfo("Tunis", "Tunisia", 10.11f, 36.50f), //E new GeoipInfo("Ankara", "Turkey", 32.54f, 39.57f), //E new GeoipInfo("Ashgabat", "Turkmenistan", 57.50f, 38.00f), //E new GeoipInfo("Funafuti", "Tuvalu",-08.31f, 179.13f), //E new GeoipInfo("Kampala", "Uganda", 32.30f, 00.20f), //E new GeoipInfo("Ukraine", "Kiev (Russia)", 30.28f, 50.30f), //E new GeoipInfo("United Arab Emirates", "Abu Dhabi", 54.22f, 24.28f), //E new GeoipInfo("United Kingdom of Great Britain and Northern Ireland", "London", -00.05f, 51.36f), //w new GeoipInfo("United Republic of Tanzania", "Dodoma",-06.08f, 35.45f), //E new GeoipInfo("United States of America", "Washington DC", -77.02f, 39.91f), //w new GeoipInfo("United States of Virgin Islands", "Charlotte Amalie", -64.56f, 18.21f), //w new GeoipInfo("Montevideo", "Uruguay",-34.50f, -56.11f), //w new GeoipInfo("Tashkent", "Uzbekistan", 69.10f, 41.20f), //E new GeoipInfo("Vanuatu", "Port-Vila",-17.45f, 168.18f), //E new GeoipInfo("Caracas", "Venezuela", -66.55f, 10.30f), //w new GeoipInfo("Viet Nam", "Hanoi", 105.55f, 21.05f), //E new GeoipInfo("Belgrade", "Yugoslavia", 20.37f, 44.50f), //E new GeoipInfo("Lusaka", "Zambia",-15.28f, 28.16f), //E new GeoipInfo("Harare", "Zimbabwe",-17.43f, 31.02f), //E }; }
20,561
0.561823
0.477821
390
51.774361
26.53117
140
false
false
0
0
0
0
0
0
2.241026
false
false
12
efe9f7fa3633eb3793d82d55a655a0dff3a23190
16,776,142,274,230
32a410977dbe221681f33850f8656573baf8e279
/subject-courses/src/main/java/com/szu/subject/course/serviceImpl/ClassTimeSerivceImpl.java
5a997530bf372b64906ec48e0db6202d4777114f
[]
no_license
CaiJialing/course
https://github.com/CaiJialing/course
d7f016659c53463d40751cb29ca96f3a7fab4d52
87865e90839259258de3225e93689f7acda35bcf
refs/heads/master
2020-06-14T11:41:04.119000
2016-11-29T01:30:22
2016-11-29T01:30:22
75,030,418
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.szu.subject.course.serviceImpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.szu.subject.course.mapper.ClassTimeMapper; import com.szu.subject.course.service.ClassTimeSerivce; import com.szu.subject.domains.ClassTime; @Service public class ClassTimeSerivceImpl implements ClassTimeSerivce { @Autowired private ClassTimeMapper classTimeMapper; @Override public List<ClassTime> getAllClassTime() { return classTimeMapper.getAllClassTime(); } }
UTF-8
Java
591
java
ClassTimeSerivceImpl.java
Java
[]
null
[]
package com.szu.subject.course.serviceImpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.szu.subject.course.mapper.ClassTimeMapper; import com.szu.subject.course.service.ClassTimeSerivce; import com.szu.subject.domains.ClassTime; @Service public class ClassTimeSerivceImpl implements ClassTimeSerivce { @Autowired private ClassTimeMapper classTimeMapper; @Override public List<ClassTime> getAllClassTime() { return classTimeMapper.getAllClassTime(); } }
591
0.791878
0.791878
23
23.695652
23.34325
63
false
false
0
0
0
0
0
0
0.73913
false
false
12
d571a8295187b78cf7323721cf9566f6c846d71b
31,421,980,784,279
a34e27929947e7051150a5169d1694daea4cf33a
/src/br/integrado/jnpereira/nutrimix/controle/CompraControl.java
7404cf193b7dc45f1a8fe5846a94477a31bc0e94
[]
no_license
joseviniciusnunes/sisgecom
https://github.com/joseviniciusnunes/sisgecom
d7021ddc1356bb5529545b9782cd670a32b62c3a
17c7d4f63779dcb20610ae8c8ba944a6a5495c7f
refs/heads/master
2022-08-18T23:17:11.725000
2017-12-06T22:55:57
2017-12-06T22:55:57
102,540,805
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.integrado.jnpereira.nutrimix.controle; import br.integrado.jnpereira.nutrimix.dao.Dao; import br.integrado.jnpereira.nutrimix.modelo.VendaCompra; import br.integrado.jnpereira.nutrimix.modelo.VendaCompraProduto; import br.integrado.jnpereira.nutrimix.modelo.CondicaoPagto; import br.integrado.jnpereira.nutrimix.modelo.ContasPagarReceber; import br.integrado.jnpereira.nutrimix.modelo.FechamentoCaixa; import br.integrado.jnpereira.nutrimix.modelo.Fornecedor; import br.integrado.jnpereira.nutrimix.modelo.MovtoEstoque; import br.integrado.jnpereira.nutrimix.modelo.Pedido; import br.integrado.jnpereira.nutrimix.modelo.PedidoProduto; import br.integrado.jnpereira.nutrimix.modelo.Pessoa; import br.integrado.jnpereira.nutrimix.modelo.Produto; import br.integrado.jnpereira.nutrimix.tools.Alerta; import br.integrado.jnpereira.nutrimix.tools.Data; import br.integrado.jnpereira.nutrimix.tools.FuncaoCampo; import br.integrado.jnpereira.nutrimix.tools.IconButtonHit; import br.integrado.jnpereira.nutrimix.tools.Numero; import br.integrado.jnpereira.nutrimix.tools.Tela; import br.integrado.jnpereira.nutrimix.tools.TrataCombo; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.ResourceBundle; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; /** * * @author Jose Vinicius */ public class CompraControl implements Initializable { @FXML AnchorPane painel; @FXML TextField nrNotaFiscal; @FXML TextField cdSerie; @FXML TextField dtEmissao; @FXML TextField cdPedido; @FXML TextField cdForne; @FXML TextField dsForne; @FXML TextField nrCpfCnpj; @FXML TextField vlTotalProds; @FXML ChoiceBox tpFormaPagto; @FXML ChoiceBox tpCondPagto; @FXML TextField vlDesconto; @FXML TextField vlAdicional; @FXML TextField vlFrete; @FXML TextField vlTotalCompra; @FXML AnchorPane painelProd; @FXML TextField cdProduto; @FXML Button btnPesqProd; @FXML TextField dsProduto; @FXML TextField qtUnitario; @FXML TextField vlUnitario; @FXML TextField vlTotalProd; @FXML Button btnAdd; @FXML Button btnRem; public Stage stage; public Object param; private final Dao dao = new Dao(); private Pessoa pessoa; private Fornecedor fornecedor; private Pedido pedido; ArrayList<CompraProdHit> listCompraProd = new ArrayList<>(); double LayoutY; boolean inAntiLoop = true; @Override public void initialize(URL location, ResourceBundle resources) { FuncaoCampo.mascaraNumeroInteiro(cdForne); FuncaoCampo.mascaraNumeroInteiro(nrNotaFiscal); FuncaoCampo.mascaraNumeroInteiro(cdPedido); TrataCombo.setValueComboTpCondicaoPagto(tpCondPagto, 1); TrataCombo.setValueComboTpFormaPagto(tpFormaPagto, 1); FuncaoCampo.mascaraNumeroDecimal(vlDesconto); FuncaoCampo.mascaraNumeroDecimal(vlAdicional); FuncaoCampo.mascaraNumeroDecimal(vlFrete); FuncaoCampo.mascaraTexto(cdSerie, 10); FuncaoCampo.mascaraData(dtEmissao); cdPedido.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { validaCodigoPedido(); } }); cdForne.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { validaCodigoForne(); } }); cdForne.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { validaCodigoForne(); } }); vlAdicional.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!vlAdicional.getText().equals("")) { Double valor = Double.parseDouble(vlAdicional.getText()); vlAdicional.setText(Numero.doubleToReal(valor, 2)); } calculaTotalProd(); } }); vlDesconto.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!vlDesconto.getText().equals("")) { Double valorTotal = Double.parseDouble(vlTotalCompra.getText()); Double valor = Double.parseDouble(vlDesconto.getText()); if (valorTotal < valor) { Alerta.AlertaError("Campo inválido!", "Valor do desconto maior que o valor de venda."); vlDesconto.requestFocus(); return; } vlDesconto.setText(Numero.doubleToReal(valor, 2)); } calculaTotalProd(); } }); vlFrete.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!vlFrete.getText().equals("")) { Double valor = Double.parseDouble(vlFrete.getText()); vlFrete.setText(Numero.doubleToReal(valor, 2)); } calculaTotalProd(); } }); dtEmissao.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!dtEmissao.getText().equals("")) { try { Data.autoComplete(dtEmissao); Date dataInicio = Data.StringToDate(dtEmissao.getText()); if (dataInicio.after(new Date())) { Alerta.AlertaError("Campo inválido", "Dt. Emissão não pode ser maior que a data atual."); dtEmissao.requestFocus(); return; } } catch (Exception ex) { Alerta.AlertaError("Campo inválido", ex.getMessage()); dtEmissao.requestFocus(); } } } }); } public void iniciaTela() { if (param != null) { pedido = (Pedido) param; } atualizaCompraProd(); } private void validaCodigoPedido() { if (!cdPedido.getText().equals("")) { try { if (pedido != null) { if (Integer.parseInt(cdPedido.getText()) == pedido.getCdPedido()) { return; } } pedido = new Pedido(); pedido.setCdPedido(Integer.parseInt(cdPedido.getText())); dao.get(pedido); if (!pedido.getStPedido().equals("1")) { Alerta.AlertaError("Campo inválido!", "Apenas permitido pedidos pendentes."); cdPedido.setText(""); pedido = null; return; } cdForne.setText(pedido.getCdFornecedor().toString()); validaCodigoForne(); atualizaCompraProd(); } catch (Exception ex) { Alerta.AlertaError("Campo inválido!", ex.getMessage()); } } else { limparTelaPedido(); } } @FXML public void pesquisarFornecedor() { Tela tela = new Tela(); String valor = tela.abrirListaPessoa(new Fornecedor(), true); if (valor != null) { cdForne.setText(valor); validaCodigoForne(); } } @FXML public void pesquisarPedidoCompra() { Tela tela = new Tela(); String valor = tela.abrirListaPedidoCompra(); if (valor != null) { cdPedido.setText(valor); validaCodigoPedido(); } } @FXML public void visualizarParcelas() { Double vlTotal = Double.parseDouble(vlTotalCompra.getText()); if (vlTotal > 0 && TrataCombo.getValueComboTpCondicaoPagto(tpCondPagto) != null) { ContasPagarReceber conta = new ContasPagarReceber(); conta.setCdCondicao(TrataCombo.getValueComboTpCondicaoPagto(tpCondPagto)); conta.setVlConta(vlTotal); Tela tela = new Tela(); tela.abrirTelaModalComParam(stage, Tela.CON_PARCELA, conta); } } public void abrirListaProduto(CompraProdHit movto) { if (movto.pedidoProd != null) { Alerta.AlertaError("Não permitido!", "Altere o item no pedido."); return; } Tela tela = new Tela(); String valor = tela.abrirListaGenerica(new Produto(), "cdProduto", "dsProduto", "AND $inAtivo$ = 'T'", "Lista de Produtos"); if (valor != null) { movto.cdProduto.setText(valor); validaCodigoProduto(movto); } } private void validaCodigoForne() { if (!cdForne.getText().equals("")) { boolean vInBusca = true; if (fornecedor != null) { if (fornecedor.getCdFornecedor() == Integer.parseInt(cdForne.getText())) { vInBusca = false; } } if (vInBusca) { try { fornecedor = new Fornecedor(); fornecedor.setCdFornecedor(Integer.parseInt(cdForne.getText())); dao.get(fornecedor); if (!fornecedor.getInAtivo()) { Alerta.AlertaError("Fornecedor inválido!", "Fornecedor está inativo."); fornecedor = null; dsForne.setText(""); nrCpfCnpj.setText(""); cdForne.requestFocus(); return; } pessoa = new Pessoa(); pessoa.setCdPessoa(fornecedor.getCdPessoa()); dao.get(pessoa); dsForne.setText(pessoa.getDsPessoa()); if (pessoa.getTpPessoa().equals("F")) { nrCpfCnpj.setText(Numero.NumeroToCPF(pessoa.getNrCpfCnpj())); } else { nrCpfCnpj.setText(Numero.NumeroToCNPJ(pessoa.getNrCpfCnpj())); } } catch (Exception ex) { Alerta.AlertaError("Notificação", ex.getMessage()); fornecedor = null; pessoa = null; dsForne.setText(""); nrCpfCnpj.setText(""); cdForne.requestFocus(); } } } else { fornecedor = null; pessoa = null; dsForne.setText(""); nrCpfCnpj.setText(""); } } private void validaCodigoProduto(CompraProdHit compraHit) { if (!compraHit.cdProduto.getText().equals("")) { try { Produto prod = new Produto(); prod.setCdProduto(Integer.parseInt(compraHit.cdProduto.getText())); dao.get(prod); if (inAntiLoop) { inAntiLoop = false; if (!prod.getInAtivo()) { Alerta.AlertaError("Inválido", "Produto está inativo."); compraHit.cdProduto.requestFocus(); inAntiLoop = true; return; } for (CompraProdHit movtoHit : listCompraProd) { if (movtoHit.cdProduto.getText().equals(compraHit.cdProduto.getText()) && !movtoHit.equals(compraHit)) { Alerta.AlertaError("Inválido", "Produto já está na lista"); compraHit.cdProduto.requestFocus(); inAntiLoop = true; return; } } inAntiLoop = true; } compraHit.dsProduto.setText(prod.getDsProduto()); if (pedido != null) { PedidoProduto pedidoProd = new PedidoProduto(); pedidoProd.setCdPedido(pedido.getCdPedido()); pedidoProd.setCdProduto(prod.getCdProduto()); try { dao.get(pedidoProd); if (pedidoProd.getQtProduto() == pedidoProd.getQtEntregue()) { Alerta.AlertaError("Notificação", "Produto: " + prod.getCdProduto() + " está como totalmente entregue no pedido."); compraHit.cdProduto.requestFocus(); return; } compraHit.pedidoProd = pedidoProd; compraHit.qtUnitario.setText(Numero.doubleToReal(pedidoProd.getQtProduto() - pedidoProd.getQtEntregue(), 2)); compraHit.vlUnitario.setText(Numero.doubleToReal(pedidoProd.getVlUnitario(), 2)); compraHit.vlUnitario.setEditable(false); compraHit.vlUnitario.getStyleClass().addAll("numero_estatico"); compraHit.cdProduto.setEditable(false); compraHit.cdProduto.getStyleClass().addAll("texto_estatico_center"); } catch (Exception ex) { } } calculaTotalProd(); } catch (Exception ex) { inAntiLoop = true; Alerta.AlertaError("Notificação", ex.getMessage()); compraHit.cdProduto.requestFocus(); } } else { compraHit.dsProduto.setText(""); } } public void calculaTotalProd() { Double totalProd = 0.00; Double total = 0.00; for (CompraProdHit compraHit : listCompraProd) { double vlUnit = 0.00; if (!compraHit.vlUnitario.getText().equals("")) { vlUnit = Double.parseDouble(compraHit.vlUnitario.getText()); } double qtUnit = 0.00; if (!compraHit.qtUnitario.getText().equals("")) { qtUnit = Double.parseDouble(compraHit.qtUnitario.getText()); } totalProd += qtUnit * vlUnit; compraHit.vlTotalProd.setText(Numero.doubleToReal(qtUnit * vlUnit, 2)); } double vVlDesconto = 0.00; if (!vlDesconto.getText().equals("")) { vVlDesconto = Double.parseDouble(vlDesconto.getText()); } double vVlAdicional = 0.00; if (!vlAdicional.getText().equals("")) { vVlAdicional = Double.parseDouble(vlAdicional.getText()); } double vVlFrete = 0.00; if (!vlFrete.getText().equals("")) { vVlFrete = Double.parseDouble(vlFrete.getText()); } vlTotalProds.setText(Numero.doubleToReal(totalProd, 2)); total += ((totalProd + vVlAdicional + vVlFrete) - vVlDesconto); if (total < 0.00) { Alerta.AlertaWarning("Alerta!", "Desconto maior que o total da venda, desconto removido."); vlDesconto.setText(""); calculaTotalProd(); return; } vlTotalCompra.setText(Numero.doubleToReal(total, 2)); } @FXML public void salvar() { if (cdForne.getText().equals("")) { Alerta.AlertaError("Campo inválido!", "Fornecedor é obrigatório."); tpCondPagto.requestFocus(); return; } if ((nrNotaFiscal.getText().equals("") && !cdSerie.getText().equals("")) || (!nrNotaFiscal.getText().equals("") && cdSerie.getText().equals(""))) { Alerta.AlertaError("Campo inválido!", "Caso tenha nota fiscal, Nª da Nota e Série são obrigatórios."); return; } for (CompraProdHit compraHit : listCompraProd) { if (compraHit.cdProduto.getText().equals("")) { Alerta.AlertaError("Campo inválido!", "Código do produto é obrigatório."); compraHit.cdProduto.requestFocus(); return; } if (compraHit.qtUnitario.getText().equals("")) { Alerta.AlertaError("Campo inválido!", "Quantidade da compra é obrigatório."); compraHit.qtUnitario.requestFocus(); return; } } if (TrataCombo.getValueComboTpFormaPagto(tpFormaPagto) == null) { Alerta.AlertaError("Campo inválido!", "Forma de pagamento é obrigatório."); tpCondPagto.requestFocus(); return; } if (TrataCombo.getValueComboTpCondicaoPagto(tpCondPagto) == null) { Alerta.AlertaError("Campo inválido!", "Condição de pagamento é obrigatório."); tpCondPagto.requestFocus(); return; } try { dao.autoCommit(false); CondicaoPagto cond = new CondicaoPagto(); cond.setCdCondicao(TrataCombo.getValueComboTpCondicaoPagto(tpCondPagto)); dao.get(cond); CaixaControl caixa = new CaixaControl(); FechamentoCaixa fechamento; try { fechamento = caixa.getCaixaAberto(Data.getAgora()); //pega caixa aberto } catch (Exception ex) { Alerta.AlertaWarning("Negado!", ex.getMessage()); return; } VendaCompra compra = new VendaCompra(); compra.setTpMovto(EstoqueControl.ENTRADA); compra.setCdPessoa(pessoa.getCdPessoa()); compra.setNrNota(!nrNotaFiscal.getText().equals("") ? nrNotaFiscal.getText() : null); compra.setCdSerie(!cdSerie.getText().equals("") ? cdSerie.getText() : null); compra.setCdPedido(!cdPedido.getText().equals("") ? Integer.parseInt(cdPedido.getText()) : null); compra.setDtEmissao(Data.StringToDate(dtEmissao.getText())); compra.setVlDesconto(!vlDesconto.getText().equals("") ? Double.parseDouble(vlDesconto.getText()) : 0.0); compra.setVlAdicional(!vlAdicional.getText().equals("") ? Double.parseDouble(vlAdicional.getText()) : 0.0); compra.setVlFrete(!vlFrete.getText().equals("") ? Double.parseDouble(vlFrete.getText()) : 0.0); compra.setCdUserCad(MenuControl.usuarioAtivo); compra.setDtCadastro(Data.getAgora()); if (pedido != null) { compra.setCdPedido(pedido.getCdPedido()); } compra.setVlTotal(Double.parseDouble(vlTotalCompra.getText())); compra.setInCancelado(false); dao.save(compra); for (CompraProdHit compraHit : listCompraProd) { //baixa do produto de um pedido VendaCompraProduto compraProd = new VendaCompraProduto(); Double qtCompra = Double.parseDouble(compraHit.qtUnitario.getText()); compraProd.setCdMovto(compra.getCdMovto()); compraProd.setCdProduto(Integer.parseInt(compraHit.cdProduto.getText())); Produto prod = new Produto(); prod.setCdProduto(compraProd.getCdProduto()); dao.get(prod); compraProd.setQtUnitario(qtCompra * prod.getQtConversao()); //Conversão conforme cadastro compraProd.setVlUnitario(divisao(Double.parseDouble(compraHit.vlUnitario.getText()), prod.getQtConversao())); dao.save(compraProd); if (compraHit.pedidoProd != null) { Double qtEntregue = compraHit.pedidoProd.getQtEntregue() + qtCompra; compraHit.pedidoProd.setQtEntregue(qtEntregue); dao.update(compraHit.pedidoProd); } //Gera movimento estoque MovtoEstoque movtoEstoque = new MovtoEstoque(); movtoEstoque.setCdMovCompVend(compra.getCdMovto()); movtoEstoque.setTpMovto(EstoqueControl.ENTRADA); movtoEstoque.setCdProduto(compraProd.getCdProduto()); movtoEstoque.setDtMovto(Data.getAgora()); movtoEstoque.setQtMovto(compraProd.getQtUnitario()); movtoEstoque.setVlItem(compraProd.getVlUnitario()); movtoEstoque.setInCancelado(false); EstoqueControl estq = new EstoqueControl(); estq.geraMovtoEstoque(movtoEstoque); } if (pedido != null) { //Encerra o pedido String where = "WHERE $cdPedido$ = " + pedido.getCdPedido(); ArrayList<Object> pedidoProds = dao.getAllWhere(new PedidoProduto(), where); boolean vInEncerrado = true; for (Object obj : pedidoProds) { PedidoProduto pedidoProd = (PedidoProduto) obj; if (pedidoProd.getQtProduto() > pedidoProd.getQtEntregue()) { vInEncerrado = false; } } if (vInEncerrado) { pedido.setStPedido("2"); dao.update(pedido); } } ContasPagarReceber conta = new ContasPagarReceber(); conta.setTpMovto("S"); conta.setDtMovto(Data.getAgora()); conta.setCdCondicao(TrataCombo.getValueComboTpCondicaoPagto(tpCondPagto)); conta.setCdForma(TrataCombo.getValueComboTpFormaPagto(tpFormaPagto)); conta.setCdMovto(compra.getCdMovto()); conta.setVlConta(Double.parseDouble(vlTotalCompra.getText())); conta.setStConta("1"); dao.save(conta); ParcelaControl parcela = new ParcelaControl(); parcela.gerarParcelas(conta, fechamento); ParcelaControl parcelaControl = new ParcelaControl(); parcelaControl.encerrarConta(conta); dao.commit(); } catch (Exception ex) { ex.printStackTrace(); dao.rollback(); Alerta.AlertaError("Erro!", ex.getMessage()); return; } if (Alerta.AlertaConfirmation("Confirmação", "Compra efetivada com sucesso.\nDeseja realizar uma nova compra?")) { param = null; limparTela(); } else { stage.close(); } } @FXML public void limpar() { limparTela(); } private void limparTela() { pedido = null; fornecedor = null; pessoa = null; listCompraProd = new ArrayList<>(); FuncaoCampo.limparCampos(painel); iniciaTela(); } private void limparTelaPedido() { String nrNotaFiscal = this.nrNotaFiscal.getText(); String cdSerie = this.cdSerie.getText(); String dtEmissao = this.dtEmissao.getText(); pedido = null; fornecedor = null; pessoa = null; listCompraProd = new ArrayList<>(); FuncaoCampo.limparCampos(painel); iniciaTela(); this.nrNotaFiscal.setText(nrNotaFiscal); this.cdSerie.setText(cdSerie); this.dtEmissao.setText(dtEmissao); } private Double divisao(Double v1, Double v2) { if (v1 == null | v2 == null) { return 0.00; } if (v1 == 0 | v2 == 0) { return 0.00; } return v1 / v2; } public void atualizaCompraProd() { try { ArrayList<Object> pedidosProd = new ArrayList<>(); if (pedido != null) { String where = "WHERE $cdPedido$ = " + pedido.getCdPedido() + " ORDER BY $cdProduto$ ASC"; pedidosProd = dao.getAllWhere(new PedidoProduto(), where); listCompraProd.clear(); } if (pedidosProd.isEmpty()) { CompraProdHit compraHit = new CompraProdHit(); listCompraProd.add(compraHit); } for (Object obj : pedidosProd) { PedidoProduto pedidoProd = (PedidoProduto) obj; boolean vInAdd = true; if (pedidoProd.getQtProduto() > pedidoProd.getQtEntregue()) { CompraProdHit compraHit = new CompraProdHit(); compraHit.cdProduto.setText(pedidoProd.getCdProduto().toString()); Produto produto = new Produto(); produto.setCdProduto(pedidoProd.getCdProduto()); dao.get(produto); compraHit.dsProduto.setText(produto.getDsProduto()); compraHit.qtUnitario.setText(Numero.doubleToReal(pedidoProd.getQtProduto() - pedidoProd.getQtEntregue(), 2)); compraHit.pedidoProd = pedidoProd; compraHit.vlUnitario.setText(Numero.doubleToReal(pedidoProd.getVlUnitario(), 2)); if (vInAdd) { listCompraProd.add(compraHit); } } } calculaTotalProd(); } catch (Exception ex) { ex.printStackTrace(); } atualizaLista(); } public void atualizaLista() { LayoutY = cdProduto.getLayoutY(); painelProd.getChildren().clear(); Iterator it = listCompraProd.iterator(); for (int i = 0; it.hasNext(); i++) { CompraProdHit b = (CompraProdHit) it.next(); b.cdProduto.setEditable(cdProduto.isEditable()); if (b.pedidoProd != null) { b.cdProduto.setEditable(false); b.cdProduto.getStyleClass().addAll("texto_estatico_center"); } b.cdProduto.setPrefHeight(cdProduto.getHeight()); b.cdProduto.setPrefWidth(cdProduto.getWidth()); b.cdProduto.setLayoutX(cdProduto.getLayoutX()); b.cdProduto.setLayoutY(LayoutY); b.cdProduto.getStyleClass().addAll(this.cdProduto.getStyleClass()); b.dsProduto.setEditable(dsProduto.isEditable()); b.dsProduto.setPrefHeight(dsProduto.getHeight()); b.dsProduto.setPrefWidth(dsProduto.getWidth()); b.dsProduto.setLayoutX(dsProduto.getLayoutX()); b.dsProduto.setLayoutY(LayoutY); b.dsProduto.getStyleClass().addAll(this.dsProduto.getStyleClass()); b.qtUnitario.setEditable(qtUnitario.isEditable()); b.qtUnitario.setPrefHeight(qtUnitario.getHeight()); b.qtUnitario.setPrefWidth(qtUnitario.getWidth()); b.qtUnitario.setLayoutX(qtUnitario.getLayoutX()); b.qtUnitario.setLayoutY(LayoutY); b.qtUnitario.getStyleClass().addAll(this.qtUnitario.getStyleClass()); b.vlUnitario.setEditable(vlUnitario.isEditable()); b.vlUnitario.setPrefHeight(vlUnitario.getHeight()); b.vlUnitario.setPrefWidth(vlUnitario.getWidth()); b.vlUnitario.setLayoutX(vlUnitario.getLayoutX()); b.vlUnitario.setLayoutY(LayoutY); b.vlUnitario.getStyleClass().addAll(this.vlUnitario.getStyleClass()); if (b.pedidoProd != null) { b.vlUnitario.setEditable(false); b.vlUnitario.getStyleClass().addAll("numero_estatico"); } b.vlTotalProd.setEditable(vlTotalProd.isEditable()); b.vlTotalProd.setPrefHeight(vlTotalProd.getHeight()); b.vlTotalProd.setPrefWidth(vlTotalProd.getWidth()); b.vlTotalProd.setLayoutX(vlTotalProd.getLayoutX()); b.vlTotalProd.setLayoutY(LayoutY); b.vlTotalProd.getStyleClass().addAll(this.vlTotalProd.getStyleClass()); b.btnPesqProd.setPrefHeight(btnPesqProd.getHeight()); b.btnPesqProd.setPrefWidth(btnPesqProd.getWidth()); b.btnPesqProd.setLayoutX(btnPesqProd.getLayoutX()); b.btnPesqProd.setLayoutY(LayoutY); IconButtonHit.setIcon(b.btnPesqProd, IconButtonHit.ICON_PESQUISA); b.btnAdd.setPrefHeight(btnAdd.getHeight()); b.btnAdd.setPrefWidth(btnAdd.getWidth()); b.btnAdd.setLayoutX(btnAdd.getLayoutX()); b.btnAdd.setLayoutY(LayoutY); IconButtonHit.setIcon(b.btnAdd, IconButtonHit.ICON_ADD); b.btnRem.setPrefHeight(btnRem.getHeight()); b.btnRem.setPrefWidth(btnRem.getWidth()); b.btnRem.setLayoutX(btnRem.getLayoutX()); b.btnRem.setLayoutY(LayoutY); IconButtonHit.setIcon(b.btnRem, IconButtonHit.ICON_EXCLUIR); painelProd.getChildren().add(b.cdProduto); painelProd.getChildren().add(b.btnPesqProd); painelProd.getChildren().add(b.dsProduto); painelProd.getChildren().add(b.qtUnitario); painelProd.getChildren().add(b.vlUnitario); painelProd.getChildren().add(b.vlTotalProd); painelProd.getChildren().add(b.btnAdd); painelProd.getChildren().add(b.btnRem); LayoutY += (cdProduto.getHeight() + 5); addValidacao(b, i, listCompraProd.size()); } painelProd.setPrefHeight(LayoutY + 10); } public void addValidacao(CompraProdHit compraProdHit, int posicao, int total) { FuncaoCampo.mascaraNumeroInteiro(compraProdHit.cdProduto); FuncaoCampo.mascaraNumeroDecimal(compraProdHit.qtUnitario); FuncaoCampo.mascaraNumeroDecimal(compraProdHit.vlUnitario); compraProdHit.cdProduto.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { validaCodigoProduto(compraProdHit); } }); compraProdHit.btnPesqProd.setOnAction((ActionEvent event) -> { abrirListaProduto(compraProdHit); }); compraProdHit.qtUnitario.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!compraProdHit.qtUnitario.getText().equals("")) { Double valor = Double.parseDouble(compraProdHit.qtUnitario.getText()); if (valor <= 0) { Alerta.AlertaError("Campo inválido", "Compra deve ser maior que 0.00!"); compraProdHit.qtUnitario.requestFocus(); return; } compraProdHit.qtUnitario.setText(Numero.doubleToReal(valor, 2)); } calculaTotalProd(); } }); compraProdHit.vlUnitario.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!compraProdHit.vlUnitario.getText().equals("")) { Double valor = Double.parseDouble(compraProdHit.vlUnitario.getText()); if (valor <= 0) { Alerta.AlertaError("Campo inválido", "Valor do produto deve ser maior que 0.00!"); compraProdHit.vlUnitario.requestFocus(); return; } compraProdHit.vlUnitario.setText(Numero.doubleToReal(valor, 2)); } calculaTotalProd(); } }); compraProdHit.btnAdd.setOnAction((ActionEvent event) -> { CompraProdHit b = new CompraProdHit(); listCompraProd.add(posicao + 1, b); atualizaLista(); }); compraProdHit.btnRem.setOnAction((ActionEvent event) -> { if (total == 1) { CompraProdHit b = new CompraProdHit(); listCompraProd.add(b); } listCompraProd.remove(compraProdHit); calculaTotalProd(); atualizaLista(); }); } public class CompraProdHit { PedidoProduto pedidoProd; TextField cdProduto = new TextField(); Button btnPesqProd = new Button(); TextField dsProduto = new TextField(); TextField qtUnitario = new TextField(); TextField vlUnitario = new TextField(); TextField vlTotalProd = new TextField(); Button btnAdd = new Button(); Button btnRem = new Button(); } }
UTF-8
Java
33,382
java
CompraControl.java
Java
[ { "context": "ane;\nimport javafx.stage.Stage;\n\n/**\n *\n * @author Jose Vinicius\n */\npublic class CompraControl implements Initial", "end": 1803, "score": 0.9998360872268677, "start": 1790, "tag": "NAME", "value": "Jose Vinicius" } ]
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 br.integrado.jnpereira.nutrimix.controle; import br.integrado.jnpereira.nutrimix.dao.Dao; import br.integrado.jnpereira.nutrimix.modelo.VendaCompra; import br.integrado.jnpereira.nutrimix.modelo.VendaCompraProduto; import br.integrado.jnpereira.nutrimix.modelo.CondicaoPagto; import br.integrado.jnpereira.nutrimix.modelo.ContasPagarReceber; import br.integrado.jnpereira.nutrimix.modelo.FechamentoCaixa; import br.integrado.jnpereira.nutrimix.modelo.Fornecedor; import br.integrado.jnpereira.nutrimix.modelo.MovtoEstoque; import br.integrado.jnpereira.nutrimix.modelo.Pedido; import br.integrado.jnpereira.nutrimix.modelo.PedidoProduto; import br.integrado.jnpereira.nutrimix.modelo.Pessoa; import br.integrado.jnpereira.nutrimix.modelo.Produto; import br.integrado.jnpereira.nutrimix.tools.Alerta; import br.integrado.jnpereira.nutrimix.tools.Data; import br.integrado.jnpereira.nutrimix.tools.FuncaoCampo; import br.integrado.jnpereira.nutrimix.tools.IconButtonHit; import br.integrado.jnpereira.nutrimix.tools.Numero; import br.integrado.jnpereira.nutrimix.tools.Tela; import br.integrado.jnpereira.nutrimix.tools.TrataCombo; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.ResourceBundle; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; /** * * @author <NAME> */ public class CompraControl implements Initializable { @FXML AnchorPane painel; @FXML TextField nrNotaFiscal; @FXML TextField cdSerie; @FXML TextField dtEmissao; @FXML TextField cdPedido; @FXML TextField cdForne; @FXML TextField dsForne; @FXML TextField nrCpfCnpj; @FXML TextField vlTotalProds; @FXML ChoiceBox tpFormaPagto; @FXML ChoiceBox tpCondPagto; @FXML TextField vlDesconto; @FXML TextField vlAdicional; @FXML TextField vlFrete; @FXML TextField vlTotalCompra; @FXML AnchorPane painelProd; @FXML TextField cdProduto; @FXML Button btnPesqProd; @FXML TextField dsProduto; @FXML TextField qtUnitario; @FXML TextField vlUnitario; @FXML TextField vlTotalProd; @FXML Button btnAdd; @FXML Button btnRem; public Stage stage; public Object param; private final Dao dao = new Dao(); private Pessoa pessoa; private Fornecedor fornecedor; private Pedido pedido; ArrayList<CompraProdHit> listCompraProd = new ArrayList<>(); double LayoutY; boolean inAntiLoop = true; @Override public void initialize(URL location, ResourceBundle resources) { FuncaoCampo.mascaraNumeroInteiro(cdForne); FuncaoCampo.mascaraNumeroInteiro(nrNotaFiscal); FuncaoCampo.mascaraNumeroInteiro(cdPedido); TrataCombo.setValueComboTpCondicaoPagto(tpCondPagto, 1); TrataCombo.setValueComboTpFormaPagto(tpFormaPagto, 1); FuncaoCampo.mascaraNumeroDecimal(vlDesconto); FuncaoCampo.mascaraNumeroDecimal(vlAdicional); FuncaoCampo.mascaraNumeroDecimal(vlFrete); FuncaoCampo.mascaraTexto(cdSerie, 10); FuncaoCampo.mascaraData(dtEmissao); cdPedido.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { validaCodigoPedido(); } }); cdForne.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { validaCodigoForne(); } }); cdForne.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { validaCodigoForne(); } }); vlAdicional.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!vlAdicional.getText().equals("")) { Double valor = Double.parseDouble(vlAdicional.getText()); vlAdicional.setText(Numero.doubleToReal(valor, 2)); } calculaTotalProd(); } }); vlDesconto.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!vlDesconto.getText().equals("")) { Double valorTotal = Double.parseDouble(vlTotalCompra.getText()); Double valor = Double.parseDouble(vlDesconto.getText()); if (valorTotal < valor) { Alerta.AlertaError("Campo inválido!", "Valor do desconto maior que o valor de venda."); vlDesconto.requestFocus(); return; } vlDesconto.setText(Numero.doubleToReal(valor, 2)); } calculaTotalProd(); } }); vlFrete.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!vlFrete.getText().equals("")) { Double valor = Double.parseDouble(vlFrete.getText()); vlFrete.setText(Numero.doubleToReal(valor, 2)); } calculaTotalProd(); } }); dtEmissao.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!dtEmissao.getText().equals("")) { try { Data.autoComplete(dtEmissao); Date dataInicio = Data.StringToDate(dtEmissao.getText()); if (dataInicio.after(new Date())) { Alerta.AlertaError("Campo inválido", "Dt. Emissão não pode ser maior que a data atual."); dtEmissao.requestFocus(); return; } } catch (Exception ex) { Alerta.AlertaError("Campo inválido", ex.getMessage()); dtEmissao.requestFocus(); } } } }); } public void iniciaTela() { if (param != null) { pedido = (Pedido) param; } atualizaCompraProd(); } private void validaCodigoPedido() { if (!cdPedido.getText().equals("")) { try { if (pedido != null) { if (Integer.parseInt(cdPedido.getText()) == pedido.getCdPedido()) { return; } } pedido = new Pedido(); pedido.setCdPedido(Integer.parseInt(cdPedido.getText())); dao.get(pedido); if (!pedido.getStPedido().equals("1")) { Alerta.AlertaError("Campo inválido!", "Apenas permitido pedidos pendentes."); cdPedido.setText(""); pedido = null; return; } cdForne.setText(pedido.getCdFornecedor().toString()); validaCodigoForne(); atualizaCompraProd(); } catch (Exception ex) { Alerta.AlertaError("Campo inválido!", ex.getMessage()); } } else { limparTelaPedido(); } } @FXML public void pesquisarFornecedor() { Tela tela = new Tela(); String valor = tela.abrirListaPessoa(new Fornecedor(), true); if (valor != null) { cdForne.setText(valor); validaCodigoForne(); } } @FXML public void pesquisarPedidoCompra() { Tela tela = new Tela(); String valor = tela.abrirListaPedidoCompra(); if (valor != null) { cdPedido.setText(valor); validaCodigoPedido(); } } @FXML public void visualizarParcelas() { Double vlTotal = Double.parseDouble(vlTotalCompra.getText()); if (vlTotal > 0 && TrataCombo.getValueComboTpCondicaoPagto(tpCondPagto) != null) { ContasPagarReceber conta = new ContasPagarReceber(); conta.setCdCondicao(TrataCombo.getValueComboTpCondicaoPagto(tpCondPagto)); conta.setVlConta(vlTotal); Tela tela = new Tela(); tela.abrirTelaModalComParam(stage, Tela.CON_PARCELA, conta); } } public void abrirListaProduto(CompraProdHit movto) { if (movto.pedidoProd != null) { Alerta.AlertaError("Não permitido!", "Altere o item no pedido."); return; } Tela tela = new Tela(); String valor = tela.abrirListaGenerica(new Produto(), "cdProduto", "dsProduto", "AND $inAtivo$ = 'T'", "Lista de Produtos"); if (valor != null) { movto.cdProduto.setText(valor); validaCodigoProduto(movto); } } private void validaCodigoForne() { if (!cdForne.getText().equals("")) { boolean vInBusca = true; if (fornecedor != null) { if (fornecedor.getCdFornecedor() == Integer.parseInt(cdForne.getText())) { vInBusca = false; } } if (vInBusca) { try { fornecedor = new Fornecedor(); fornecedor.setCdFornecedor(Integer.parseInt(cdForne.getText())); dao.get(fornecedor); if (!fornecedor.getInAtivo()) { Alerta.AlertaError("Fornecedor inválido!", "Fornecedor está inativo."); fornecedor = null; dsForne.setText(""); nrCpfCnpj.setText(""); cdForne.requestFocus(); return; } pessoa = new Pessoa(); pessoa.setCdPessoa(fornecedor.getCdPessoa()); dao.get(pessoa); dsForne.setText(pessoa.getDsPessoa()); if (pessoa.getTpPessoa().equals("F")) { nrCpfCnpj.setText(Numero.NumeroToCPF(pessoa.getNrCpfCnpj())); } else { nrCpfCnpj.setText(Numero.NumeroToCNPJ(pessoa.getNrCpfCnpj())); } } catch (Exception ex) { Alerta.AlertaError("Notificação", ex.getMessage()); fornecedor = null; pessoa = null; dsForne.setText(""); nrCpfCnpj.setText(""); cdForne.requestFocus(); } } } else { fornecedor = null; pessoa = null; dsForne.setText(""); nrCpfCnpj.setText(""); } } private void validaCodigoProduto(CompraProdHit compraHit) { if (!compraHit.cdProduto.getText().equals("")) { try { Produto prod = new Produto(); prod.setCdProduto(Integer.parseInt(compraHit.cdProduto.getText())); dao.get(prod); if (inAntiLoop) { inAntiLoop = false; if (!prod.getInAtivo()) { Alerta.AlertaError("Inválido", "Produto está inativo."); compraHit.cdProduto.requestFocus(); inAntiLoop = true; return; } for (CompraProdHit movtoHit : listCompraProd) { if (movtoHit.cdProduto.getText().equals(compraHit.cdProduto.getText()) && !movtoHit.equals(compraHit)) { Alerta.AlertaError("Inválido", "Produto já está na lista"); compraHit.cdProduto.requestFocus(); inAntiLoop = true; return; } } inAntiLoop = true; } compraHit.dsProduto.setText(prod.getDsProduto()); if (pedido != null) { PedidoProduto pedidoProd = new PedidoProduto(); pedidoProd.setCdPedido(pedido.getCdPedido()); pedidoProd.setCdProduto(prod.getCdProduto()); try { dao.get(pedidoProd); if (pedidoProd.getQtProduto() == pedidoProd.getQtEntregue()) { Alerta.AlertaError("Notificação", "Produto: " + prod.getCdProduto() + " está como totalmente entregue no pedido."); compraHit.cdProduto.requestFocus(); return; } compraHit.pedidoProd = pedidoProd; compraHit.qtUnitario.setText(Numero.doubleToReal(pedidoProd.getQtProduto() - pedidoProd.getQtEntregue(), 2)); compraHit.vlUnitario.setText(Numero.doubleToReal(pedidoProd.getVlUnitario(), 2)); compraHit.vlUnitario.setEditable(false); compraHit.vlUnitario.getStyleClass().addAll("numero_estatico"); compraHit.cdProduto.setEditable(false); compraHit.cdProduto.getStyleClass().addAll("texto_estatico_center"); } catch (Exception ex) { } } calculaTotalProd(); } catch (Exception ex) { inAntiLoop = true; Alerta.AlertaError("Notificação", ex.getMessage()); compraHit.cdProduto.requestFocus(); } } else { compraHit.dsProduto.setText(""); } } public void calculaTotalProd() { Double totalProd = 0.00; Double total = 0.00; for (CompraProdHit compraHit : listCompraProd) { double vlUnit = 0.00; if (!compraHit.vlUnitario.getText().equals("")) { vlUnit = Double.parseDouble(compraHit.vlUnitario.getText()); } double qtUnit = 0.00; if (!compraHit.qtUnitario.getText().equals("")) { qtUnit = Double.parseDouble(compraHit.qtUnitario.getText()); } totalProd += qtUnit * vlUnit; compraHit.vlTotalProd.setText(Numero.doubleToReal(qtUnit * vlUnit, 2)); } double vVlDesconto = 0.00; if (!vlDesconto.getText().equals("")) { vVlDesconto = Double.parseDouble(vlDesconto.getText()); } double vVlAdicional = 0.00; if (!vlAdicional.getText().equals("")) { vVlAdicional = Double.parseDouble(vlAdicional.getText()); } double vVlFrete = 0.00; if (!vlFrete.getText().equals("")) { vVlFrete = Double.parseDouble(vlFrete.getText()); } vlTotalProds.setText(Numero.doubleToReal(totalProd, 2)); total += ((totalProd + vVlAdicional + vVlFrete) - vVlDesconto); if (total < 0.00) { Alerta.AlertaWarning("Alerta!", "Desconto maior que o total da venda, desconto removido."); vlDesconto.setText(""); calculaTotalProd(); return; } vlTotalCompra.setText(Numero.doubleToReal(total, 2)); } @FXML public void salvar() { if (cdForne.getText().equals("")) { Alerta.AlertaError("Campo inválido!", "Fornecedor é obrigatório."); tpCondPagto.requestFocus(); return; } if ((nrNotaFiscal.getText().equals("") && !cdSerie.getText().equals("")) || (!nrNotaFiscal.getText().equals("") && cdSerie.getText().equals(""))) { Alerta.AlertaError("Campo inválido!", "Caso tenha nota fiscal, Nª da Nota e Série são obrigatórios."); return; } for (CompraProdHit compraHit : listCompraProd) { if (compraHit.cdProduto.getText().equals("")) { Alerta.AlertaError("Campo inválido!", "Código do produto é obrigatório."); compraHit.cdProduto.requestFocus(); return; } if (compraHit.qtUnitario.getText().equals("")) { Alerta.AlertaError("Campo inválido!", "Quantidade da compra é obrigatório."); compraHit.qtUnitario.requestFocus(); return; } } if (TrataCombo.getValueComboTpFormaPagto(tpFormaPagto) == null) { Alerta.AlertaError("Campo inválido!", "Forma de pagamento é obrigatório."); tpCondPagto.requestFocus(); return; } if (TrataCombo.getValueComboTpCondicaoPagto(tpCondPagto) == null) { Alerta.AlertaError("Campo inválido!", "Condição de pagamento é obrigatório."); tpCondPagto.requestFocus(); return; } try { dao.autoCommit(false); CondicaoPagto cond = new CondicaoPagto(); cond.setCdCondicao(TrataCombo.getValueComboTpCondicaoPagto(tpCondPagto)); dao.get(cond); CaixaControl caixa = new CaixaControl(); FechamentoCaixa fechamento; try { fechamento = caixa.getCaixaAberto(Data.getAgora()); //pega caixa aberto } catch (Exception ex) { Alerta.AlertaWarning("Negado!", ex.getMessage()); return; } VendaCompra compra = new VendaCompra(); compra.setTpMovto(EstoqueControl.ENTRADA); compra.setCdPessoa(pessoa.getCdPessoa()); compra.setNrNota(!nrNotaFiscal.getText().equals("") ? nrNotaFiscal.getText() : null); compra.setCdSerie(!cdSerie.getText().equals("") ? cdSerie.getText() : null); compra.setCdPedido(!cdPedido.getText().equals("") ? Integer.parseInt(cdPedido.getText()) : null); compra.setDtEmissao(Data.StringToDate(dtEmissao.getText())); compra.setVlDesconto(!vlDesconto.getText().equals("") ? Double.parseDouble(vlDesconto.getText()) : 0.0); compra.setVlAdicional(!vlAdicional.getText().equals("") ? Double.parseDouble(vlAdicional.getText()) : 0.0); compra.setVlFrete(!vlFrete.getText().equals("") ? Double.parseDouble(vlFrete.getText()) : 0.0); compra.setCdUserCad(MenuControl.usuarioAtivo); compra.setDtCadastro(Data.getAgora()); if (pedido != null) { compra.setCdPedido(pedido.getCdPedido()); } compra.setVlTotal(Double.parseDouble(vlTotalCompra.getText())); compra.setInCancelado(false); dao.save(compra); for (CompraProdHit compraHit : listCompraProd) { //baixa do produto de um pedido VendaCompraProduto compraProd = new VendaCompraProduto(); Double qtCompra = Double.parseDouble(compraHit.qtUnitario.getText()); compraProd.setCdMovto(compra.getCdMovto()); compraProd.setCdProduto(Integer.parseInt(compraHit.cdProduto.getText())); Produto prod = new Produto(); prod.setCdProduto(compraProd.getCdProduto()); dao.get(prod); compraProd.setQtUnitario(qtCompra * prod.getQtConversao()); //Conversão conforme cadastro compraProd.setVlUnitario(divisao(Double.parseDouble(compraHit.vlUnitario.getText()), prod.getQtConversao())); dao.save(compraProd); if (compraHit.pedidoProd != null) { Double qtEntregue = compraHit.pedidoProd.getQtEntregue() + qtCompra; compraHit.pedidoProd.setQtEntregue(qtEntregue); dao.update(compraHit.pedidoProd); } //Gera movimento estoque MovtoEstoque movtoEstoque = new MovtoEstoque(); movtoEstoque.setCdMovCompVend(compra.getCdMovto()); movtoEstoque.setTpMovto(EstoqueControl.ENTRADA); movtoEstoque.setCdProduto(compraProd.getCdProduto()); movtoEstoque.setDtMovto(Data.getAgora()); movtoEstoque.setQtMovto(compraProd.getQtUnitario()); movtoEstoque.setVlItem(compraProd.getVlUnitario()); movtoEstoque.setInCancelado(false); EstoqueControl estq = new EstoqueControl(); estq.geraMovtoEstoque(movtoEstoque); } if (pedido != null) { //Encerra o pedido String where = "WHERE $cdPedido$ = " + pedido.getCdPedido(); ArrayList<Object> pedidoProds = dao.getAllWhere(new PedidoProduto(), where); boolean vInEncerrado = true; for (Object obj : pedidoProds) { PedidoProduto pedidoProd = (PedidoProduto) obj; if (pedidoProd.getQtProduto() > pedidoProd.getQtEntregue()) { vInEncerrado = false; } } if (vInEncerrado) { pedido.setStPedido("2"); dao.update(pedido); } } ContasPagarReceber conta = new ContasPagarReceber(); conta.setTpMovto("S"); conta.setDtMovto(Data.getAgora()); conta.setCdCondicao(TrataCombo.getValueComboTpCondicaoPagto(tpCondPagto)); conta.setCdForma(TrataCombo.getValueComboTpFormaPagto(tpFormaPagto)); conta.setCdMovto(compra.getCdMovto()); conta.setVlConta(Double.parseDouble(vlTotalCompra.getText())); conta.setStConta("1"); dao.save(conta); ParcelaControl parcela = new ParcelaControl(); parcela.gerarParcelas(conta, fechamento); ParcelaControl parcelaControl = new ParcelaControl(); parcelaControl.encerrarConta(conta); dao.commit(); } catch (Exception ex) { ex.printStackTrace(); dao.rollback(); Alerta.AlertaError("Erro!", ex.getMessage()); return; } if (Alerta.AlertaConfirmation("Confirmação", "Compra efetivada com sucesso.\nDeseja realizar uma nova compra?")) { param = null; limparTela(); } else { stage.close(); } } @FXML public void limpar() { limparTela(); } private void limparTela() { pedido = null; fornecedor = null; pessoa = null; listCompraProd = new ArrayList<>(); FuncaoCampo.limparCampos(painel); iniciaTela(); } private void limparTelaPedido() { String nrNotaFiscal = this.nrNotaFiscal.getText(); String cdSerie = this.cdSerie.getText(); String dtEmissao = this.dtEmissao.getText(); pedido = null; fornecedor = null; pessoa = null; listCompraProd = new ArrayList<>(); FuncaoCampo.limparCampos(painel); iniciaTela(); this.nrNotaFiscal.setText(nrNotaFiscal); this.cdSerie.setText(cdSerie); this.dtEmissao.setText(dtEmissao); } private Double divisao(Double v1, Double v2) { if (v1 == null | v2 == null) { return 0.00; } if (v1 == 0 | v2 == 0) { return 0.00; } return v1 / v2; } public void atualizaCompraProd() { try { ArrayList<Object> pedidosProd = new ArrayList<>(); if (pedido != null) { String where = "WHERE $cdPedido$ = " + pedido.getCdPedido() + " ORDER BY $cdProduto$ ASC"; pedidosProd = dao.getAllWhere(new PedidoProduto(), where); listCompraProd.clear(); } if (pedidosProd.isEmpty()) { CompraProdHit compraHit = new CompraProdHit(); listCompraProd.add(compraHit); } for (Object obj : pedidosProd) { PedidoProduto pedidoProd = (PedidoProduto) obj; boolean vInAdd = true; if (pedidoProd.getQtProduto() > pedidoProd.getQtEntregue()) { CompraProdHit compraHit = new CompraProdHit(); compraHit.cdProduto.setText(pedidoProd.getCdProduto().toString()); Produto produto = new Produto(); produto.setCdProduto(pedidoProd.getCdProduto()); dao.get(produto); compraHit.dsProduto.setText(produto.getDsProduto()); compraHit.qtUnitario.setText(Numero.doubleToReal(pedidoProd.getQtProduto() - pedidoProd.getQtEntregue(), 2)); compraHit.pedidoProd = pedidoProd; compraHit.vlUnitario.setText(Numero.doubleToReal(pedidoProd.getVlUnitario(), 2)); if (vInAdd) { listCompraProd.add(compraHit); } } } calculaTotalProd(); } catch (Exception ex) { ex.printStackTrace(); } atualizaLista(); } public void atualizaLista() { LayoutY = cdProduto.getLayoutY(); painelProd.getChildren().clear(); Iterator it = listCompraProd.iterator(); for (int i = 0; it.hasNext(); i++) { CompraProdHit b = (CompraProdHit) it.next(); b.cdProduto.setEditable(cdProduto.isEditable()); if (b.pedidoProd != null) { b.cdProduto.setEditable(false); b.cdProduto.getStyleClass().addAll("texto_estatico_center"); } b.cdProduto.setPrefHeight(cdProduto.getHeight()); b.cdProduto.setPrefWidth(cdProduto.getWidth()); b.cdProduto.setLayoutX(cdProduto.getLayoutX()); b.cdProduto.setLayoutY(LayoutY); b.cdProduto.getStyleClass().addAll(this.cdProduto.getStyleClass()); b.dsProduto.setEditable(dsProduto.isEditable()); b.dsProduto.setPrefHeight(dsProduto.getHeight()); b.dsProduto.setPrefWidth(dsProduto.getWidth()); b.dsProduto.setLayoutX(dsProduto.getLayoutX()); b.dsProduto.setLayoutY(LayoutY); b.dsProduto.getStyleClass().addAll(this.dsProduto.getStyleClass()); b.qtUnitario.setEditable(qtUnitario.isEditable()); b.qtUnitario.setPrefHeight(qtUnitario.getHeight()); b.qtUnitario.setPrefWidth(qtUnitario.getWidth()); b.qtUnitario.setLayoutX(qtUnitario.getLayoutX()); b.qtUnitario.setLayoutY(LayoutY); b.qtUnitario.getStyleClass().addAll(this.qtUnitario.getStyleClass()); b.vlUnitario.setEditable(vlUnitario.isEditable()); b.vlUnitario.setPrefHeight(vlUnitario.getHeight()); b.vlUnitario.setPrefWidth(vlUnitario.getWidth()); b.vlUnitario.setLayoutX(vlUnitario.getLayoutX()); b.vlUnitario.setLayoutY(LayoutY); b.vlUnitario.getStyleClass().addAll(this.vlUnitario.getStyleClass()); if (b.pedidoProd != null) { b.vlUnitario.setEditable(false); b.vlUnitario.getStyleClass().addAll("numero_estatico"); } b.vlTotalProd.setEditable(vlTotalProd.isEditable()); b.vlTotalProd.setPrefHeight(vlTotalProd.getHeight()); b.vlTotalProd.setPrefWidth(vlTotalProd.getWidth()); b.vlTotalProd.setLayoutX(vlTotalProd.getLayoutX()); b.vlTotalProd.setLayoutY(LayoutY); b.vlTotalProd.getStyleClass().addAll(this.vlTotalProd.getStyleClass()); b.btnPesqProd.setPrefHeight(btnPesqProd.getHeight()); b.btnPesqProd.setPrefWidth(btnPesqProd.getWidth()); b.btnPesqProd.setLayoutX(btnPesqProd.getLayoutX()); b.btnPesqProd.setLayoutY(LayoutY); IconButtonHit.setIcon(b.btnPesqProd, IconButtonHit.ICON_PESQUISA); b.btnAdd.setPrefHeight(btnAdd.getHeight()); b.btnAdd.setPrefWidth(btnAdd.getWidth()); b.btnAdd.setLayoutX(btnAdd.getLayoutX()); b.btnAdd.setLayoutY(LayoutY); IconButtonHit.setIcon(b.btnAdd, IconButtonHit.ICON_ADD); b.btnRem.setPrefHeight(btnRem.getHeight()); b.btnRem.setPrefWidth(btnRem.getWidth()); b.btnRem.setLayoutX(btnRem.getLayoutX()); b.btnRem.setLayoutY(LayoutY); IconButtonHit.setIcon(b.btnRem, IconButtonHit.ICON_EXCLUIR); painelProd.getChildren().add(b.cdProduto); painelProd.getChildren().add(b.btnPesqProd); painelProd.getChildren().add(b.dsProduto); painelProd.getChildren().add(b.qtUnitario); painelProd.getChildren().add(b.vlUnitario); painelProd.getChildren().add(b.vlTotalProd); painelProd.getChildren().add(b.btnAdd); painelProd.getChildren().add(b.btnRem); LayoutY += (cdProduto.getHeight() + 5); addValidacao(b, i, listCompraProd.size()); } painelProd.setPrefHeight(LayoutY + 10); } public void addValidacao(CompraProdHit compraProdHit, int posicao, int total) { FuncaoCampo.mascaraNumeroInteiro(compraProdHit.cdProduto); FuncaoCampo.mascaraNumeroDecimal(compraProdHit.qtUnitario); FuncaoCampo.mascaraNumeroDecimal(compraProdHit.vlUnitario); compraProdHit.cdProduto.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { validaCodigoProduto(compraProdHit); } }); compraProdHit.btnPesqProd.setOnAction((ActionEvent event) -> { abrirListaProduto(compraProdHit); }); compraProdHit.qtUnitario.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!compraProdHit.qtUnitario.getText().equals("")) { Double valor = Double.parseDouble(compraProdHit.qtUnitario.getText()); if (valor <= 0) { Alerta.AlertaError("Campo inválido", "Compra deve ser maior que 0.00!"); compraProdHit.qtUnitario.requestFocus(); return; } compraProdHit.qtUnitario.setText(Numero.doubleToReal(valor, 2)); } calculaTotalProd(); } }); compraProdHit.vlUnitario.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { if (!newPropertyValue) { if (!compraProdHit.vlUnitario.getText().equals("")) { Double valor = Double.parseDouble(compraProdHit.vlUnitario.getText()); if (valor <= 0) { Alerta.AlertaError("Campo inválido", "Valor do produto deve ser maior que 0.00!"); compraProdHit.vlUnitario.requestFocus(); return; } compraProdHit.vlUnitario.setText(Numero.doubleToReal(valor, 2)); } calculaTotalProd(); } }); compraProdHit.btnAdd.setOnAction((ActionEvent event) -> { CompraProdHit b = new CompraProdHit(); listCompraProd.add(posicao + 1, b); atualizaLista(); }); compraProdHit.btnRem.setOnAction((ActionEvent event) -> { if (total == 1) { CompraProdHit b = new CompraProdHit(); listCompraProd.add(b); } listCompraProd.remove(compraProdHit); calculaTotalProd(); atualizaLista(); }); } public class CompraProdHit { PedidoProduto pedidoProd; TextField cdProduto = new TextField(); Button btnPesqProd = new Button(); TextField dsProduto = new TextField(); TextField qtUnitario = new TextField(); TextField vlUnitario = new TextField(); TextField vlTotalProd = new TextField(); Button btnAdd = new Button(); Button btnRem = new Button(); } }
33,375
0.571313
0.568613
801
40.612984
29.743263
161
false
false
0
0
0
0
0
0
0.691635
false
false
12
c61b7148a9669f312b7b6eab11a8103a41359d33
15,891,379,020,848
bfab322e19330668588342d5fee284a6bbd231ef
/ShareCalendar/doc/android/AlarmTest/app/src/main/java/com/alarm/alarmtest/MainActivity.java
df29131ac70414270990f99603eb1f5baf6b3b7a
[]
no_license
chj1338/scheShare
https://github.com/chj1338/scheShare
020118f16b00f8b8243e6f118c78ab117e7d9505
588124a4d0491ee1904373d8b9c04c7326881305
refs/heads/master
2020-07-31T01:01:17.634000
2018-05-11T05:00:14
2018-05-11T05:00:14
73,613,020
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alarm.alarmtest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private int[] mlayout = new int[]{ R.id.layout01, R.id.layout02, R.id.layout03, R.id.layout04, R.id.layout05, R.id.layout06, R.id.layout07, R.id.layout08, R.id.layout09, R.id.layout10, R.id.layout11, R.id.layout12, R.id.layout13, R.id.layout14, R.id.layout15, R.id.layout16}; private runBuffer runBf; private TextView textView; private int gg= -1; private int alertCnt = 16; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); runBf = new runBuffer(); runBf.select = new boolean[alertCnt]; for (int i = 0; i < alertCnt; ++i) { runBf.select[i] = false; // unselect findViewById(mlayout[i]).setBackgroundResource(R.drawable.alarm_off); findViewById(mlayout[i]).setClickable(true); findViewById(mlayout[i]).setOnTouchListener(mTouchListener); } } private View.OnTouchListener mTouchListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (event.getAction()==MotionEvent.ACTION_DOWN) { v.setBackgroundResource(R.drawable.alarm_select); for (int i=0; i<16; ++i) { if (v.getId() == mlayout[i]) { gg=i; break; } } } else { if (event.getAction()==MotionEvent.ACTION_MOVE) { if (v.isPressed()==false) { for (int i=0; i<16; ++i) { if (v.getId()==mlayout[i]) { if (runBf.select[i] == true) { // selected? v.setBackgroundResource(R.drawable.alarm_run); } else { v.setBackgroundResource(R.drawable.alarm_off); } break; } } gg= -1; } } else { if (event.getAction()==MotionEvent.ACTION_UP) { if (gg != -1) { for (int i = 0; i < 16; ++i) { if (v.getId() == mlayout[i]) { if (runBf.select[i] == true) { // selected? runBf.select[i] = false; v.setBackgroundResource(R.drawable.alarm_run); } else { runBf.select[i] = true; v.setBackgroundResource(R.drawable.alarm_run); } break; } } } } } } return false; } }; private class runBuffer { public boolean[] select; }; }
UTF-8
Java
3,565
java
MainActivity.java
Java
[]
null
[]
package com.alarm.alarmtest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private int[] mlayout = new int[]{ R.id.layout01, R.id.layout02, R.id.layout03, R.id.layout04, R.id.layout05, R.id.layout06, R.id.layout07, R.id.layout08, R.id.layout09, R.id.layout10, R.id.layout11, R.id.layout12, R.id.layout13, R.id.layout14, R.id.layout15, R.id.layout16}; private runBuffer runBf; private TextView textView; private int gg= -1; private int alertCnt = 16; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); runBf = new runBuffer(); runBf.select = new boolean[alertCnt]; for (int i = 0; i < alertCnt; ++i) { runBf.select[i] = false; // unselect findViewById(mlayout[i]).setBackgroundResource(R.drawable.alarm_off); findViewById(mlayout[i]).setClickable(true); findViewById(mlayout[i]).setOnTouchListener(mTouchListener); } } private View.OnTouchListener mTouchListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (event.getAction()==MotionEvent.ACTION_DOWN) { v.setBackgroundResource(R.drawable.alarm_select); for (int i=0; i<16; ++i) { if (v.getId() == mlayout[i]) { gg=i; break; } } } else { if (event.getAction()==MotionEvent.ACTION_MOVE) { if (v.isPressed()==false) { for (int i=0; i<16; ++i) { if (v.getId()==mlayout[i]) { if (runBf.select[i] == true) { // selected? v.setBackgroundResource(R.drawable.alarm_run); } else { v.setBackgroundResource(R.drawable.alarm_off); } break; } } gg= -1; } } else { if (event.getAction()==MotionEvent.ACTION_UP) { if (gg != -1) { for (int i = 0; i < 16; ++i) { if (v.getId() == mlayout[i]) { if (runBf.select[i] == true) { // selected? runBf.select[i] = false; v.setBackgroundResource(R.drawable.alarm_run); } else { runBf.select[i] = true; v.setBackgroundResource(R.drawable.alarm_run); } break; } } } } } } return false; } }; private class runBuffer { public boolean[] select; }; }
3,565
0.428331
0.414867
90
37.566666
24.983128
86
false
false
0
0
0
0
0
0
0.655556
false
false
12
ac63e6bee878e0fba14af3bee266d4874c1f79c2
24,747,601,622,464
6cf77559687ae03249a6523bd25418bf14d950d8
/src/main/java/com/sda/zdjavapol68/example/zad39/Main.java
69249763f0ec3e828cf1a48a60af894e27130bbc
[]
no_license
pawelszpunar/java.zaaw.programowanie.projekty
https://github.com/pawelszpunar/java.zaaw.programowanie.projekty
2bfbded82b82821ebc9321a2e33f64b9190960ae
05c183c1881520de5c981fb61272cdce3a509c2e
refs/heads/master
2023-04-07T01:11:56.755000
2021-04-01T20:03:52
2021-04-01T20:03:52
353,813,242
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sda.zdjavapol68.example.zad39; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; public class Main { public static void main(String[] args) { AtomicInteger score = new AtomicInteger(0); ExecutorService screenPool = Executors.newFixedThreadPool(100); int screens = 100; for(int i = 0; i < screens; i++) { screenPool.execute(() -> System.out.println(score.get())); } int sensors = 5 ExecutorService sensorPool = Executors.newFixedThreadPool(sensors); } }
UTF-8
Java
631
java
Main.java
Java
[]
null
[]
package com.sda.zdjavapol68.example.zad39; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; public class Main { public static void main(String[] args) { AtomicInteger score = new AtomicInteger(0); ExecutorService screenPool = Executors.newFixedThreadPool(100); int screens = 100; for(int i = 0; i < screens; i++) { screenPool.execute(() -> System.out.println(score.get())); } int sensors = 5 ExecutorService sensorPool = Executors.newFixedThreadPool(sensors); } }
631
0.676704
0.656101
22
27.681818
25.429737
75
false
false
0
0
0
0
0
0
0.5
false
false
12
7d9291d7070a25083c885024e2a6050fc1047b41
2,731,599,263,365
991dc340fb41df1c65213054f90f6cba679cdb28
/src/main/java/io/renren/modules/mapper/SystemResourceMapper.java
7ab50f7c04fa7b016cfb172d06dc78765da195e9
[ "Apache-2.0" ]
permissive
la8457478/renrenDemo
https://github.com/la8457478/renrenDemo
6c9b95241ee9983f5b790101504c3ed0a53882c4
e6fd70564ec371774022ac92af5bbfae78501420
refs/heads/master
2022-07-23T12:35:39.688000
2018-12-14T09:08:57
2018-12-14T09:08:57
157,353,385
0
0
Apache-2.0
false
2022-07-06T20:30:30
2018-11-13T09:23:00
2018-12-14T09:09:04
2022-07-06T20:30:28
1,637
0
0
8
JavaScript
false
false
package io.renren.modules.mapper; import io.renren.modules.model.SystemResource; import tk.mybatis.mapper.common.Mapper; public interface SystemResourceMapper extends Mapper<SystemResource> { }
UTF-8
Java
195
java
SystemResourceMapper.java
Java
[]
null
[]
package io.renren.modules.mapper; import io.renren.modules.model.SystemResource; import tk.mybatis.mapper.common.Mapper; public interface SystemResourceMapper extends Mapper<SystemResource> { }
195
0.835897
0.835897
7
27
25.42215
70
false
false
0
0
0
0
0
0
0.428571
false
false
12
2e52eab6b7e1cc35f14a26093e556482ec514b5e
12,902,081,778,070
cfcaf63b3c25b30d3c383c9399b2f38c581eda86
/leetcode_notes/leetcode_cn/0113.路径总和II/0113-路径总和II.java
03bddf321ad58a0faafe44066b3f27afa42d1fa0
[ "BSD-3-Clause" ]
permissive
robinali/java_notes
https://github.com/robinali/java_notes
f361f525599495f8709691d60885a0a3faeb897b
b462c75851c1cd234b4027cd2b6181f0fbb0ef60
refs/heads/master
2021-06-18T09:23:33.244000
2021-04-13T02:32:33
2021-04-13T02:32:33
200,970,947
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); if(root == null) return res; pathSum(root, sum, new ArrayList<>(), res); return res; } private void pathSum(TreeNode node, int sum, List<Integer> out, List<List<Integer>> res) { if(node == null) return; out.add(node.val); if(sum == node.val && node.left == null && node.right == null) { res.add(new ArrayList<>(out)); } pathSum(node.left, sum - node.val, out, res); pathSum(node.right, sum - node.val, out, res); out.remove(out.size() -1); } }
UTF-8
Java
862
java
0113-路径总和II.java
Java
[]
null
[]
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); if(root == null) return res; pathSum(root, sum, new ArrayList<>(), res); return res; } private void pathSum(TreeNode node, int sum, List<Integer> out, List<List<Integer>> res) { if(node == null) return; out.add(node.val); if(sum == node.val && node.left == null && node.right == null) { res.add(new ArrayList<>(out)); } pathSum(node.left, sum - node.val, out, res); pathSum(node.right, sum - node.val, out, res); out.remove(out.size() -1); } }
862
0.551044
0.549884
28
29.821428
23.436928
94
false
false
0
0
0
0
0
0
0.964286
false
false
12
0c1827da3b8a122e4d0f244bdc87b1e494566c64
15,822,659,587,992
d589b150aae48b78f028066020988a7bf6b7472b
/collaborationpjtbackend/src/main/java/com/niit/collaborationpjtbackend/controller/friends_controller.java
e232587c1acea210b4536a3bbdcbd69b431c8039
[]
no_license
ANJUPANIL/Collaboration2NDPjt
https://github.com/ANJUPANIL/Collaboration2NDPjt
b575f59342aeb7acaadca89f49476a45f1283618
3ebf6f060b07ec25d29af5bf029e0f1731cb7303
refs/heads/master
2021-05-04T06:24:29.256000
2016-12-05T10:49:32
2016-12-05T10:49:32
70,461,337
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.niit.collaborationpjtbackend.controller; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.niit.collaborationpjtbackend.dao.friends_dao; import com.niit.collaborationpjtbackend.dao.register_dao; import com.niit.collaborationpjtbackend.model.friends; import com.niit.collaborationpjtbackend.model.jobbookmark; import com.niit.collaborationpjtbackend.model.register; @RestController public class friends_controller { @Autowired friends_dao friendsdao; friends frd; @Autowired register_dao regdao; @RequestMapping(value="/allfriends", method=RequestMethod.GET) public ResponseEntity<List<friends>> listallusers(HttpSession session) { register loggedInUser=(register) session.getAttribute("loggedInUser"); System.out.println("loggedInUser "+loggedInUser.getUser_id()); List<friends> friends =friendsdao.showallfriends(loggedInUser.getUser_id()); if(friends.size()==0) { return new ResponseEntity<List<friends>>(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<friends>>(friends,HttpStatus.OK); } @RequestMapping(value="/savefriends/{friendID}", method=RequestMethod.POST) public ResponseEntity<friends> createuser(@PathVariable("friendID") String friendID,HttpSession session) { System.out.println("Freind save controller"); System.out.println(" And FreindID " +friendID); String f=friendID + ".com"; //Bcoz .com is not acceptable System.out.println(" And FreindID " +f); friends friends=new friends(); String loggedInUserId=(String)session.getAttribute("loggedInUserId"); int flag=0; List<friends> t=friendsdao.showallfriends(loggedInUserId); for(int i=0;i<t.size();i++) { if(t.get(i).getRequestto().equals(f) && t.get(i).getUserid().equals(loggedInUserId)) { flag=1; } } if(flag==1) { friends.setErrorMessage("Already add friend...."); } else{ DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date)); String cdate=dateFormat.format(date); friends.setUserid(loggedInUserId); friends.setRequestto(f); friends.setRequesteddate(cdate); friends.setFollow("Yes"); friends.setStatus("New"); friendsdao.savefriends(friends); friends.setErrorMessage("Friend request send successfully....."); } return new ResponseEntity<friends>(friends,HttpStatus.OK); } @RequestMapping(value="/updatefriends",method=RequestMethod.PUT) public ResponseEntity<friends> updateuser(@RequestBody friends friends) { //System.out.println("Update user :" + id); System.out.println("Update user name :" + friends.getFid()); friendsdao.updatefriends(friends); return new ResponseEntity<friends>(friends,HttpStatus.OK); } @RequestMapping(value="/deletefriend/{id}", method=RequestMethod.DELETE) public ResponseEntity<friends> deleteuser(@PathVariable("id") String id) { //friendsdao.deletefriends(id,uid); return new ResponseEntity<friends>(HttpStatus.OK); } @RequestMapping(value="/acceptfriend/{id}", method=RequestMethod.PUT) public ResponseEntity<friends> acceptfriend(@PathVariable("id") String id) { System.out.println("Friend request id "+ id); friendsdao.acceptfriendrequest(id); return new ResponseEntity<friends>(HttpStatus.OK); } @RequestMapping(value="/rejectfriend/{id}", method=RequestMethod.PUT) public ResponseEntity<friends> rejectfriend(@PathVariable("id") String id) { System.out.println("Friend request id "+ id); friendsdao.deletefriendrequest(id); return new ResponseEntity<friends>(HttpStatus.OK); } @RequestMapping(value="/getmyfriendrequest", method=RequestMethod.GET) public ResponseEntity<List<friends>> listallfriendrequest(HttpSession session) { register loggedInUser=(register) session.getAttribute("loggedInUser"); System.out.println("loggedInUser "+loggedInUser.getUser_id()); List<friends> friends =friendsdao.shownewfriendrequests(loggedInUser.getUser_id()); if(friends.size()==0) { return new ResponseEntity<List<friends>>(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<friends>>(friends,HttpStatus.OK); } /*@RequestMapping(value="/getfriendbyid/{friendID}", method=RequestMethod.GET) public ResponseEntity<friends> getfriendbyid(@PathVariable("friendID") String friendID) { System.out.println(" And FreindID " +friendID); String f=friendID + ".com"; //Bcoz .com is not acceptable System.out.println(" And FreindID " +f); friends lsts =friendsdao.getfriendbyid(f); //System.out.println("GEt friend by id "+lsts.getUserid()); if(lsts==null) { return new ResponseEntity<friends>(HttpStatus.NO_CONTENT); } return new ResponseEntity<friends>(lsts,HttpStatus.OK); }*/ @RequestMapping(value="/friendprofile/{friendID}", method=RequestMethod.GET) public ResponseEntity<register> getuser(@PathVariable("friendID") String friendID) { System.out.println(" And FreindID " +friendID); String f=friendID + ".com"; //Bcoz .com is not acceptable System.out.println(" And FreindID " +f); //register u=regdao.getuserdetailsbyid(f); register regobj=regdao.getuserdetailsbyid(f); if(regobj==null) { regobj =new register(); regobj.setErrorMessage("User does not exist with id : "+regobj.getUser_id()); System.out.println("user not found"); return new ResponseEntity<register>(regobj,HttpStatus.NOT_FOUND); } System.out.println("user found " + regobj.getFname()); regobj.setErrorMessage("true"); return new ResponseEntity<register>(regobj,HttpStatus.OK); } @RequestMapping(value="/unfriend/{id}", method=RequestMethod.PUT) public ResponseEntity<friends> unfriend(@PathVariable("id") String id) { System.out.println("Friend request id "+ id); friendsdao.unfriend(id); return new ResponseEntity<friends>(HttpStatus.OK); } @RequestMapping(value="/unfollow/{id}", method=RequestMethod.PUT) public ResponseEntity<friends> unfollow(@PathVariable("id") String id) { System.out.println("Friend request id "+ id); friendsdao.unfollow(id); return new ResponseEntity<friends>(HttpStatus.OK); } }
UTF-8
Java
6,942
java
friends_controller.java
Java
[]
null
[]
package com.niit.collaborationpjtbackend.controller; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.niit.collaborationpjtbackend.dao.friends_dao; import com.niit.collaborationpjtbackend.dao.register_dao; import com.niit.collaborationpjtbackend.model.friends; import com.niit.collaborationpjtbackend.model.jobbookmark; import com.niit.collaborationpjtbackend.model.register; @RestController public class friends_controller { @Autowired friends_dao friendsdao; friends frd; @Autowired register_dao regdao; @RequestMapping(value="/allfriends", method=RequestMethod.GET) public ResponseEntity<List<friends>> listallusers(HttpSession session) { register loggedInUser=(register) session.getAttribute("loggedInUser"); System.out.println("loggedInUser "+loggedInUser.getUser_id()); List<friends> friends =friendsdao.showallfriends(loggedInUser.getUser_id()); if(friends.size()==0) { return new ResponseEntity<List<friends>>(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<friends>>(friends,HttpStatus.OK); } @RequestMapping(value="/savefriends/{friendID}", method=RequestMethod.POST) public ResponseEntity<friends> createuser(@PathVariable("friendID") String friendID,HttpSession session) { System.out.println("Freind save controller"); System.out.println(" And FreindID " +friendID); String f=friendID + ".com"; //Bcoz .com is not acceptable System.out.println(" And FreindID " +f); friends friends=new friends(); String loggedInUserId=(String)session.getAttribute("loggedInUserId"); int flag=0; List<friends> t=friendsdao.showallfriends(loggedInUserId); for(int i=0;i<t.size();i++) { if(t.get(i).getRequestto().equals(f) && t.get(i).getUserid().equals(loggedInUserId)) { flag=1; } } if(flag==1) { friends.setErrorMessage("Already add friend...."); } else{ DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date)); String cdate=dateFormat.format(date); friends.setUserid(loggedInUserId); friends.setRequestto(f); friends.setRequesteddate(cdate); friends.setFollow("Yes"); friends.setStatus("New"); friendsdao.savefriends(friends); friends.setErrorMessage("Friend request send successfully....."); } return new ResponseEntity<friends>(friends,HttpStatus.OK); } @RequestMapping(value="/updatefriends",method=RequestMethod.PUT) public ResponseEntity<friends> updateuser(@RequestBody friends friends) { //System.out.println("Update user :" + id); System.out.println("Update user name :" + friends.getFid()); friendsdao.updatefriends(friends); return new ResponseEntity<friends>(friends,HttpStatus.OK); } @RequestMapping(value="/deletefriend/{id}", method=RequestMethod.DELETE) public ResponseEntity<friends> deleteuser(@PathVariable("id") String id) { //friendsdao.deletefriends(id,uid); return new ResponseEntity<friends>(HttpStatus.OK); } @RequestMapping(value="/acceptfriend/{id}", method=RequestMethod.PUT) public ResponseEntity<friends> acceptfriend(@PathVariable("id") String id) { System.out.println("Friend request id "+ id); friendsdao.acceptfriendrequest(id); return new ResponseEntity<friends>(HttpStatus.OK); } @RequestMapping(value="/rejectfriend/{id}", method=RequestMethod.PUT) public ResponseEntity<friends> rejectfriend(@PathVariable("id") String id) { System.out.println("Friend request id "+ id); friendsdao.deletefriendrequest(id); return new ResponseEntity<friends>(HttpStatus.OK); } @RequestMapping(value="/getmyfriendrequest", method=RequestMethod.GET) public ResponseEntity<List<friends>> listallfriendrequest(HttpSession session) { register loggedInUser=(register) session.getAttribute("loggedInUser"); System.out.println("loggedInUser "+loggedInUser.getUser_id()); List<friends> friends =friendsdao.shownewfriendrequests(loggedInUser.getUser_id()); if(friends.size()==0) { return new ResponseEntity<List<friends>>(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<friends>>(friends,HttpStatus.OK); } /*@RequestMapping(value="/getfriendbyid/{friendID}", method=RequestMethod.GET) public ResponseEntity<friends> getfriendbyid(@PathVariable("friendID") String friendID) { System.out.println(" And FreindID " +friendID); String f=friendID + ".com"; //Bcoz .com is not acceptable System.out.println(" And FreindID " +f); friends lsts =friendsdao.getfriendbyid(f); //System.out.println("GEt friend by id "+lsts.getUserid()); if(lsts==null) { return new ResponseEntity<friends>(HttpStatus.NO_CONTENT); } return new ResponseEntity<friends>(lsts,HttpStatus.OK); }*/ @RequestMapping(value="/friendprofile/{friendID}", method=RequestMethod.GET) public ResponseEntity<register> getuser(@PathVariable("friendID") String friendID) { System.out.println(" And FreindID " +friendID); String f=friendID + ".com"; //Bcoz .com is not acceptable System.out.println(" And FreindID " +f); //register u=regdao.getuserdetailsbyid(f); register regobj=regdao.getuserdetailsbyid(f); if(regobj==null) { regobj =new register(); regobj.setErrorMessage("User does not exist with id : "+regobj.getUser_id()); System.out.println("user not found"); return new ResponseEntity<register>(regobj,HttpStatus.NOT_FOUND); } System.out.println("user found " + regobj.getFname()); regobj.setErrorMessage("true"); return new ResponseEntity<register>(regobj,HttpStatus.OK); } @RequestMapping(value="/unfriend/{id}", method=RequestMethod.PUT) public ResponseEntity<friends> unfriend(@PathVariable("id") String id) { System.out.println("Friend request id "+ id); friendsdao.unfriend(id); return new ResponseEntity<friends>(HttpStatus.OK); } @RequestMapping(value="/unfollow/{id}", method=RequestMethod.PUT) public ResponseEntity<friends> unfollow(@PathVariable("id") String id) { System.out.println("Friend request id "+ id); friendsdao.unfollow(id); return new ResponseEntity<friends>(HttpStatus.OK); } }
6,942
0.721694
0.72083
211
30.900475
28.701181
105
false
false
0
0
0
0
0
0
2.080569
false
false
12
70e743858083875049676f733e8469821d43f6b7
19,851,338,902,458
32a1792413b3ba5fe78e700808723832dd828734
/app/src/main/java/ricardo/android_files_gallery/Fragments/FileManagerFragment.java
e91a99fc2967b44f302e94130308adbb353f875c
[]
no_license
9riky6/Android_Files_Gallery
https://github.com/9riky6/Android_Files_Gallery
beb8186b327367d57d29bc4c20818e3465170163
fe4ec9b1ff6a168e2d85e62792d26910d3b6c89a
refs/heads/master
2021-01-20T04:43:13.354000
2017-05-28T23:02:29
2017-05-28T23:02:29
89,721,776
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ricardo.android_files_gallery.Fragments; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import java.util.ArrayList; import ricardo.android_files_gallery.MainActivity; import ricardo.android_files_gallery.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link FileManagerFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link FileManagerFragment#newInstance} factory method to * create an instance of this fragment. */ public class FileManagerFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; private ArrayList<String> ElementEliminar; private ImageButton bCrearCarpeta, bBorrarCarpeta, bCopiarCarpeta, selecteItemRemove; public FileManagerFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FileManagerFragment. */ // TODO: Rename and change types and number of parameters public static FileManagerFragment newInstance(String param1, String param2) { FileManagerFragment fragment = new FileManagerFragment(); Bundle args = new Bundle(); args.putString(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) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String pathtext = getArguments().getString("path"); String roottext = getArguments().getString("root"); // Inflate the layout for this fragment return inflater.inflate(R.layout.file_manager, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ElementEliminar = new ArrayList<String>(100); bCrearCarpeta = (ImageButton) getActivity().findViewById(R.id.imageButton_crear_carpeta); bBorrarCarpeta = (ImageButton) getActivity().findViewById(R.id.imageButton_borrar_carpeta); bCopiarCarpeta = (ImageButton) getActivity().findViewById(R.id.imageButton_copiar_carpeta); selecteItemRemove = (ImageButton) getActivity().findViewById(R.id.remove); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } private void getImatge(String name, ImageView imatge) { String extencionFile = name.substring(name.lastIndexOf(".") + 1); //Log.d("Contenido extencionFile", extencionFile); if (extencionFile.equalsIgnoreCase("jpg")) { imatge.setImageResource(R.drawable.jpg); } else if (extencionFile.equalsIgnoreCase(("ai"))) { imatge.setImageResource(R.drawable.ai); } else if (extencionFile.equalsIgnoreCase(("apk"))) { imatge.setImageResource(R.drawable.apk); } else if (extencionFile.equalsIgnoreCase(("avi"))) { imatge.setImageResource(R.drawable.avi); } else if (extencionFile.equalsIgnoreCase(("bmp"))) { imatge.setImageResource(R.drawable.bmp); } else if (extencionFile.equalsIgnoreCase(("cad"))) { imatge.setImageResource(R.drawable.cad); } else if (extencionFile.equalsIgnoreCase(("cdr"))) { imatge.setImageResource(R.drawable.cdr); } else if (extencionFile.equalsIgnoreCase(("css"))) { imatge.setImageResource(R.drawable.css); } else if (extencionFile.equalsIgnoreCase(("dat"))) { imatge.setImageResource(R.drawable.dat); } else if (extencionFile.equalsIgnoreCase(("dll"))) { imatge.setImageResource(R.drawable.dll); } else if (extencionFile.equalsIgnoreCase(("dmg"))) { imatge.setImageResource(R.drawable.dmg); } else if (extencionFile.equalsIgnoreCase(("doc"))) { imatge.setImageResource(R.drawable.doc); } else if (extencionFile.equalsIgnoreCase(("eps"))) { imatge.setImageResource(R.drawable.eps); } else if (extencionFile.equalsIgnoreCase(("fla"))) { imatge.setImageResource(R.drawable.fla); } else if (extencionFile.equalsIgnoreCase(("flv"))) { imatge.setImageResource(R.drawable.flv); } else if (extencionFile.equalsIgnoreCase(("gif"))) { imatge.setImageResource(R.drawable.gif); } else if (extencionFile.equalsIgnoreCase(("html"))) { imatge.setImageResource(R.drawable.html); } else if (extencionFile.equalsIgnoreCase(("indd"))) { imatge.setImageResource(R.drawable.indd); } else if (extencionFile.equalsIgnoreCase(("iso"))) { imatge.setImageResource(R.drawable.iso); } else if (extencionFile.equalsIgnoreCase(("js"))) { imatge.setImageResource(R.drawable.js); } else if (extencionFile.equalsIgnoreCase(("midi"))) { imatge.setImageResource(R.drawable.midi); } else if (extencionFile.equalsIgnoreCase(("mkv"))) { imatge.setImageResource(R.drawable.mkv); } else if (extencionFile.equalsIgnoreCase(("mov"))) { imatge.setImageResource(R.drawable.mov); } else if (extencionFile.equalsIgnoreCase(("mp3"))) { imatge.setImageResource(R.drawable.mp3); } else if (extencionFile.equalsIgnoreCase(("mpg"))) { imatge.setImageResource(R.drawable.mpg); } else if (extencionFile.equalsIgnoreCase(("php"))) { imatge.setImageResource(R.drawable.php); } else if (extencionFile.equalsIgnoreCase(("pdf"))) { imatge.setImageResource(R.drawable.pdf); } else if (extencionFile.equalsIgnoreCase(("png"))) { imatge.setImageResource(R.drawable.png); } else if (extencionFile.equalsIgnoreCase(("ppt"))) { imatge.setImageResource(R.drawable.ppt); } else if (extencionFile.equalsIgnoreCase(("ps"))) { imatge.setImageResource(R.drawable.ps); } else if (extencionFile.equalsIgnoreCase(("psd"))) { imatge.setImageResource(R.drawable.psd); } else if (extencionFile.equalsIgnoreCase(("rar"))) { imatge.setImageResource(R.drawable.rar); } else if (extencionFile.equalsIgnoreCase(("raw"))) { imatge.setImageResource(R.drawable.raw); } else if (extencionFile.equalsIgnoreCase(("sql"))) { imatge.setImageResource(R.drawable.sql); } else if (extencionFile.equalsIgnoreCase(("svg"))) { imatge.setImageResource(R.drawable.svg); } else if (extencionFile.equalsIgnoreCase(("tif"))) { imatge.setImageResource(R.drawable.tif); } else if (extencionFile.equalsIgnoreCase(("txt"))) { imatge.setImageResource(R.drawable.txt); } else if (extencionFile.equalsIgnoreCase(("wmv"))) { imatge.setImageResource(R.drawable.wmv); } else if (extencionFile.equalsIgnoreCase(("xls"))) { imatge.setImageResource(R.drawable.xls); } else if (extencionFile.equalsIgnoreCase(("xml"))) { imatge.setImageResource(R.drawable.xml); } else if (extencionFile.equalsIgnoreCase(("zip"))) { imatge.setImageResource(R.drawable.zip); } else if (extencionFile.equalsIgnoreCase(("aac"))) { imatge.setImageResource(R.drawable.aac); } else if (extencionFile.equalsIgnoreCase(("docx"))) { imatge.setImageResource(R.drawable.docx); } else if (extencionFile.equalsIgnoreCase(("odt"))) { imatge.setImageResource(R.drawable.odt); } else if (extencionFile.equalsIgnoreCase(("m4a"))) { imatge.setImageResource(R.drawable.m4a); } else if (extencionFile.equalsIgnoreCase(("jar"))) { imatge.setImageResource(R.drawable.jar); } else if (extencionFile.equalsIgnoreCase(("jad"))) { imatge.setImageResource(R.drawable.jad); } else if (extencionFile.equalsIgnoreCase(("vcf"))) { imatge.setImageResource(R.drawable.vcf); } else if (extencionFile.equalsIgnoreCase(("mp4"))) { imatge.setImageResource(R.drawable.mp4); } else if (extencionFile.equalsIgnoreCase(("jpeg"))) { imatge.setImageResource(R.drawable.jpeg); } else if (extencionFile.equalsIgnoreCase(("opus"))) { imatge.setImageResource(R.drawable.opus); } else { imatge.setImageResource(R.drawable.unknown); } } }
UTF-8
Java
10,977
java
FileManagerFragment.java
Java
[]
null
[]
package ricardo.android_files_gallery.Fragments; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import java.util.ArrayList; import ricardo.android_files_gallery.MainActivity; import ricardo.android_files_gallery.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link FileManagerFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link FileManagerFragment#newInstance} factory method to * create an instance of this fragment. */ public class FileManagerFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; private ArrayList<String> ElementEliminar; private ImageButton bCrearCarpeta, bBorrarCarpeta, bCopiarCarpeta, selecteItemRemove; public FileManagerFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FileManagerFragment. */ // TODO: Rename and change types and number of parameters public static FileManagerFragment newInstance(String param1, String param2) { FileManagerFragment fragment = new FileManagerFragment(); Bundle args = new Bundle(); args.putString(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) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String pathtext = getArguments().getString("path"); String roottext = getArguments().getString("root"); // Inflate the layout for this fragment return inflater.inflate(R.layout.file_manager, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ElementEliminar = new ArrayList<String>(100); bCrearCarpeta = (ImageButton) getActivity().findViewById(R.id.imageButton_crear_carpeta); bBorrarCarpeta = (ImageButton) getActivity().findViewById(R.id.imageButton_borrar_carpeta); bCopiarCarpeta = (ImageButton) getActivity().findViewById(R.id.imageButton_copiar_carpeta); selecteItemRemove = (ImageButton) getActivity().findViewById(R.id.remove); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } private void getImatge(String name, ImageView imatge) { String extencionFile = name.substring(name.lastIndexOf(".") + 1); //Log.d("Contenido extencionFile", extencionFile); if (extencionFile.equalsIgnoreCase("jpg")) { imatge.setImageResource(R.drawable.jpg); } else if (extencionFile.equalsIgnoreCase(("ai"))) { imatge.setImageResource(R.drawable.ai); } else if (extencionFile.equalsIgnoreCase(("apk"))) { imatge.setImageResource(R.drawable.apk); } else if (extencionFile.equalsIgnoreCase(("avi"))) { imatge.setImageResource(R.drawable.avi); } else if (extencionFile.equalsIgnoreCase(("bmp"))) { imatge.setImageResource(R.drawable.bmp); } else if (extencionFile.equalsIgnoreCase(("cad"))) { imatge.setImageResource(R.drawable.cad); } else if (extencionFile.equalsIgnoreCase(("cdr"))) { imatge.setImageResource(R.drawable.cdr); } else if (extencionFile.equalsIgnoreCase(("css"))) { imatge.setImageResource(R.drawable.css); } else if (extencionFile.equalsIgnoreCase(("dat"))) { imatge.setImageResource(R.drawable.dat); } else if (extencionFile.equalsIgnoreCase(("dll"))) { imatge.setImageResource(R.drawable.dll); } else if (extencionFile.equalsIgnoreCase(("dmg"))) { imatge.setImageResource(R.drawable.dmg); } else if (extencionFile.equalsIgnoreCase(("doc"))) { imatge.setImageResource(R.drawable.doc); } else if (extencionFile.equalsIgnoreCase(("eps"))) { imatge.setImageResource(R.drawable.eps); } else if (extencionFile.equalsIgnoreCase(("fla"))) { imatge.setImageResource(R.drawable.fla); } else if (extencionFile.equalsIgnoreCase(("flv"))) { imatge.setImageResource(R.drawable.flv); } else if (extencionFile.equalsIgnoreCase(("gif"))) { imatge.setImageResource(R.drawable.gif); } else if (extencionFile.equalsIgnoreCase(("html"))) { imatge.setImageResource(R.drawable.html); } else if (extencionFile.equalsIgnoreCase(("indd"))) { imatge.setImageResource(R.drawable.indd); } else if (extencionFile.equalsIgnoreCase(("iso"))) { imatge.setImageResource(R.drawable.iso); } else if (extencionFile.equalsIgnoreCase(("js"))) { imatge.setImageResource(R.drawable.js); } else if (extencionFile.equalsIgnoreCase(("midi"))) { imatge.setImageResource(R.drawable.midi); } else if (extencionFile.equalsIgnoreCase(("mkv"))) { imatge.setImageResource(R.drawable.mkv); } else if (extencionFile.equalsIgnoreCase(("mov"))) { imatge.setImageResource(R.drawable.mov); } else if (extencionFile.equalsIgnoreCase(("mp3"))) { imatge.setImageResource(R.drawable.mp3); } else if (extencionFile.equalsIgnoreCase(("mpg"))) { imatge.setImageResource(R.drawable.mpg); } else if (extencionFile.equalsIgnoreCase(("php"))) { imatge.setImageResource(R.drawable.php); } else if (extencionFile.equalsIgnoreCase(("pdf"))) { imatge.setImageResource(R.drawable.pdf); } else if (extencionFile.equalsIgnoreCase(("png"))) { imatge.setImageResource(R.drawable.png); } else if (extencionFile.equalsIgnoreCase(("ppt"))) { imatge.setImageResource(R.drawable.ppt); } else if (extencionFile.equalsIgnoreCase(("ps"))) { imatge.setImageResource(R.drawable.ps); } else if (extencionFile.equalsIgnoreCase(("psd"))) { imatge.setImageResource(R.drawable.psd); } else if (extencionFile.equalsIgnoreCase(("rar"))) { imatge.setImageResource(R.drawable.rar); } else if (extencionFile.equalsIgnoreCase(("raw"))) { imatge.setImageResource(R.drawable.raw); } else if (extencionFile.equalsIgnoreCase(("sql"))) { imatge.setImageResource(R.drawable.sql); } else if (extencionFile.equalsIgnoreCase(("svg"))) { imatge.setImageResource(R.drawable.svg); } else if (extencionFile.equalsIgnoreCase(("tif"))) { imatge.setImageResource(R.drawable.tif); } else if (extencionFile.equalsIgnoreCase(("txt"))) { imatge.setImageResource(R.drawable.txt); } else if (extencionFile.equalsIgnoreCase(("wmv"))) { imatge.setImageResource(R.drawable.wmv); } else if (extencionFile.equalsIgnoreCase(("xls"))) { imatge.setImageResource(R.drawable.xls); } else if (extencionFile.equalsIgnoreCase(("xml"))) { imatge.setImageResource(R.drawable.xml); } else if (extencionFile.equalsIgnoreCase(("zip"))) { imatge.setImageResource(R.drawable.zip); } else if (extencionFile.equalsIgnoreCase(("aac"))) { imatge.setImageResource(R.drawable.aac); } else if (extencionFile.equalsIgnoreCase(("docx"))) { imatge.setImageResource(R.drawable.docx); } else if (extencionFile.equalsIgnoreCase(("odt"))) { imatge.setImageResource(R.drawable.odt); } else if (extencionFile.equalsIgnoreCase(("m4a"))) { imatge.setImageResource(R.drawable.m4a); } else if (extencionFile.equalsIgnoreCase(("jar"))) { imatge.setImageResource(R.drawable.jar); } else if (extencionFile.equalsIgnoreCase(("jad"))) { imatge.setImageResource(R.drawable.jad); } else if (extencionFile.equalsIgnoreCase(("vcf"))) { imatge.setImageResource(R.drawable.vcf); } else if (extencionFile.equalsIgnoreCase(("mp4"))) { imatge.setImageResource(R.drawable.mp4); } else if (extencionFile.equalsIgnoreCase(("jpeg"))) { imatge.setImageResource(R.drawable.jpeg); } else if (extencionFile.equalsIgnoreCase(("opus"))) { imatge.setImageResource(R.drawable.opus); } else { imatge.setImageResource(R.drawable.unknown); } } }
10,977
0.653548
0.650724
294
36.336735
26.714773
99
false
false
0
0
0
0
0
0
0.397959
false
false
12
8afe7cc410586b1a71496ce1c119d4959284a4f6
19,851,338,902,956
8d6dd1e0cb7be3d950682427e169fce247c06158
/ItAnnouncementsPortal/src/main/java/radoslawlewandowski/portal/Configuration/SecurityConfig.java
f9b259505cdd1fee7b5103ae8ff170adbeeafd93
[]
no_license
lewandowski2004/It-Announcement-Portal
https://github.com/lewandowski2004/It-Announcement-Portal
33c97a6882eab944c633e175a3dce84dc5b2ced3
3978f4cd4c60ed08bb0ca6c62bcc288bde93a18f
refs/heads/master
2023-05-01T10:38:00.653000
2019-07-23T16:20:07
2019-07-23T16:20:07
176,362,082
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package radoslawlewandowski.portal.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import radoslawlewandowski.portal.Service.UserService; import javax.sql.DataSource; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled=true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private BCryptPasswordEncoder bcp; @Autowired private DataSource ds; @Value("select email, password, active from user where email=?") private String userQuery; @Value("select email, password, active from company where email=?") private String companyQuery; @Value("select u.email, r.role from user u inner join user_role ur on(u.user_id=ur.user_id) inner join role r on(ur.role_id=r.role_id) where u.email=?") private String rolesQueryUser; @Value("select c.email, r.role from company c inner join company_role cr on(c.company_id=cr.company_id) inner join role r on(cr.role_id=r.role_id) where c.email=?") private String rolesQueryCompany; protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().usersByUsernameQuery(userQuery) .authoritiesByUsernameQuery(rolesQueryUser) .dataSource(ds).passwordEncoder(bcp); auth.jdbcAuthentication().usersByUsernameQuery(companyQuery) .authoritiesByUsernameQuery(rolesQueryCompany) .dataSource(ds).passwordEncoder(bcp); } protected void configure(HttpSecurity http) throws Exception { http .httpBasic() .and() .authorizeRequests() .antMatchers("/registerUser").permitAll() .antMatchers("/registerCompany").permitAll() // .antMatchers("/addUser1").permitAll() // .antMatchers("/add").permitAll() // .antMatchers("/users").hasAuthority("ROLE_ADMIN") .anyRequest().authenticated(); http.csrf().disable(); } public void configure(WebSecurity webSec) throws Exception { webSec.ignoring() .antMatchers("/resources/**", "/statics/**", "/css/**", "/js/**", "/images/**", "/incl/**"); } }
UTF-8
Java
3,103
java
SecurityConfig.java
Java
[]
null
[]
package radoslawlewandowski.portal.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import radoslawlewandowski.portal.Service.UserService; import javax.sql.DataSource; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled=true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private BCryptPasswordEncoder bcp; @Autowired private DataSource ds; @Value("select email, password, active from user where email=?") private String userQuery; @Value("select email, password, active from company where email=?") private String companyQuery; @Value("select u.email, r.role from user u inner join user_role ur on(u.user_id=ur.user_id) inner join role r on(ur.role_id=r.role_id) where u.email=?") private String rolesQueryUser; @Value("select c.email, r.role from company c inner join company_role cr on(c.company_id=cr.company_id) inner join role r on(cr.role_id=r.role_id) where c.email=?") private String rolesQueryCompany; protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().usersByUsernameQuery(userQuery) .authoritiesByUsernameQuery(rolesQueryUser) .dataSource(ds).passwordEncoder(bcp); auth.jdbcAuthentication().usersByUsernameQuery(companyQuery) .authoritiesByUsernameQuery(rolesQueryCompany) .dataSource(ds).passwordEncoder(bcp); } protected void configure(HttpSecurity http) throws Exception { http .httpBasic() .and() .authorizeRequests() .antMatchers("/registerUser").permitAll() .antMatchers("/registerCompany").permitAll() // .antMatchers("/addUser1").permitAll() // .antMatchers("/add").permitAll() // .antMatchers("/users").hasAuthority("ROLE_ADMIN") .anyRequest().authenticated(); http.csrf().disable(); } public void configure(WebSecurity webSec) throws Exception { webSec.ignoring() .antMatchers("/resources/**", "/statics/**", "/css/**", "/js/**", "/images/**", "/incl/**"); } }
3,103
0.726072
0.725749
70
43.342857
37.270779
168
false
false
0
0
0
0
0
0
0.514286
false
false
12
37e834f04d2f832200b8d06aec9d0d25e2f6e76a
19,378,892,486,200
9eef25e9697910fb9b76e159f9ed8783d07d578f
/src/TestVehicle.java
26dee3be56aa00fa10f008b2470d7d02fac1d325
[]
no_license
XiaoliChen/vehicle
https://github.com/XiaoliChen/vehicle
0852c001a8795b109a4bb84c41e07e4f2e4d5b98
6a9dafdafec311de3c922b449763eda019427a55
refs/heads/master
2020-07-25T17:10:23.230000
2015-05-18T05:43:22
2015-05-18T05:43:22
35,798,991
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class TestVehicle { public static void main(String[] args){ Person a = new Person(); a.setFirstName("Tom"); Car camry = new Car(); camry.setOwner(a); camry.set_numDoors(4); Truck frontier = new Truck(); frontier.setOwner(a); frontier.set_axels(2); Person b = new Person(); b.setFirstName("Jarry"); b.setLastName("Cyrus"); frontier.transferOwnership(b); System.out.println(frontier.getOwner()); MotorCycle harley = new MotorCycle(false); harley.setHasSideCar(false); } }
UTF-8
Java
523
java
TestVehicle.java
Java
[ { "context": "gs){\n\t\tPerson a = new Person();\n\t\ta.setFirstName(\"Tom\");\n\t\tCar camry = new Car();\n\t\tcamry.setOwner(a);\n", "end": 119, "score": 0.9998694658279419, "start": 116, "tag": "NAME", "value": "Tom" }, { "context": ";\n\t\t\n\t\tPerson b = new Person();\n\t\tb.setFirstName(\"Jarry\");\n\t\tb.setLastName(\"Cyrus\");\n\t\tfrontier.transferO", "end": 331, "score": 0.9996192455291748, "start": 326, "tag": "NAME", "value": "Jarry" }, { "context": "on();\n\t\tb.setFirstName(\"Jarry\");\n\t\tb.setLastName(\"Cyrus\");\n\t\tfrontier.transferOwnership(b);\n\t\tSystem.out.", "end": 357, "score": 0.999623715877533, "start": 352, "tag": "NAME", "value": "Cyrus" } ]
null
[]
public class TestVehicle { public static void main(String[] args){ Person a = new Person(); a.setFirstName("Tom"); Car camry = new Car(); camry.setOwner(a); camry.set_numDoors(4); Truck frontier = new Truck(); frontier.setOwner(a); frontier.set_axels(2); Person b = new Person(); b.setFirstName("Jarry"); b.setLastName("Cyrus"); frontier.transferOwnership(b); System.out.println(frontier.getOwner()); MotorCycle harley = new MotorCycle(false); harley.setHasSideCar(false); } }
523
0.671128
0.667304
23
21.695652
13.099733
44
false
false
0
0
0
0
0
0
2.434783
false
false
12
b8b9a2f7514b7f87e251b45b4464d97b68fa82cb
16,226,386,474,333
9d70a95afb93d9ab89f8fae064749ebae9cb4bfc
/server-side/vo/SheetVO.java
2683ea39ca4c02a48b8e8d74bf040a6793b18175
[]
no_license
MaetDol/ACNH_Catalog_manager
https://github.com/MaetDol/ACNH_Catalog_manager
a2d594e12e00d3d3d12c868a83ef1f86d518d65c
df8cab9aefc7721ee49761e750c48ddea7d210e7
refs/heads/master
2022-11-05T11:58:22.977000
2020-06-19T08:57:30
2020-06-19T08:57:30
265,504,999
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kroject.acnh.domain; public class SheetVO { private Integer id; private String user_id; private String title; private Integer view; private Boolean is_need_update; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getView() { return view; } public void setView(Integer view) { this.view = view; } public Boolean getIs_need_update() { return is_need_update; } public void setIs_need_update(Boolean is_need_update) { this.is_need_update = is_need_update; } }
UTF-8
Java
803
java
SheetVO.java
Java
[]
null
[]
package com.kroject.acnh.domain; public class SheetVO { private Integer id; private String user_id; private String title; private Integer view; private Boolean is_need_update; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getView() { return view; } public void setView(Integer view) { this.view = view; } public Boolean getIs_need_update() { return is_need_update; } public void setIs_need_update(Boolean is_need_update) { this.is_need_update = is_need_update; } }
803
0.674969
0.674969
42
18.142857
14.536607
56
false
false
0
0
0
0
0
0
1.333333
false
false
12
aad71a73eb8b82f5b6c0688f8fc4832205f06315
7,017,976,628,859
9a114321c237fdb99893a33fad47ca6844bddc00
/src/java/dao/Logindao.java
2279ba022ea03573788230836fb1c80fd01df877
[]
no_license
PalaniRaj12/MHRD
https://github.com/PalaniRaj12/MHRD
bcfd6f531fef9f72ca2d75567ff910e17fe6057d
c77d581d51cfea643c2361ca066a7cdb392fe244
refs/heads/master
2021-01-19T22:43:29.216000
2017-04-20T10:52:48
2017-04-20T10:52:48
88,850,697
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao; import bean.Adminallschemeviewbean; import bean.Adminloginbean; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import util.DButil; public class Logindao { public Adminloginbean adminselect(String un, String pw) { Connection con=DButil.getDbconnection(); Adminloginbean lb=new Adminloginbean(); int i=0; try{ PreparedStatement ps=con.prepareStatement("select * from admin where username=? and password=?"); ps.setString(1,un); ps.setString(2,pw); ResultSet rs=ps.executeQuery(); while(rs.next()) { i=1; lb.setUsername(rs.getString(1)); lb.setPassword(rs.getString(2)); } } catch (SQLException e) { e.printStackTrace(); } if(i==0) { lb=null; } //System.out.println("length of password"+lb.getEmail()); return lb; } public ArrayList<Adminallschemeviewbean> allschemeview() { ArrayList<Adminallschemeviewbean> al=new ArrayList<Adminallschemeviewbean>(); Connection con=DButil.getDbconnection(); int i=0; try{ PreparedStatement ps=con.prepareStatement("select scheme_code,scheme_name from schema_admin"); ResultSet rs=ps.executeQuery(); while(rs.next()) { i=1; Adminallschemeviewbean lb=new Adminallschemeviewbean(); lb.setSchemecode(rs.getString(1)); lb.setSchemename(rs.getString(2)); al.add(lb); } } catch (SQLException e) { e.printStackTrace(); } return al; } }
UTF-8
Java
1,708
java
Logindao.java
Java
[]
null
[]
package dao; import bean.Adminallschemeviewbean; import bean.Adminloginbean; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import util.DButil; public class Logindao { public Adminloginbean adminselect(String un, String pw) { Connection con=DButil.getDbconnection(); Adminloginbean lb=new Adminloginbean(); int i=0; try{ PreparedStatement ps=con.prepareStatement("select * from admin where username=? and password=?"); ps.setString(1,un); ps.setString(2,pw); ResultSet rs=ps.executeQuery(); while(rs.next()) { i=1; lb.setUsername(rs.getString(1)); lb.setPassword(rs.getString(2)); } } catch (SQLException e) { e.printStackTrace(); } if(i==0) { lb=null; } //System.out.println("length of password"+lb.getEmail()); return lb; } public ArrayList<Adminallschemeviewbean> allschemeview() { ArrayList<Adminallschemeviewbean> al=new ArrayList<Adminallschemeviewbean>(); Connection con=DButil.getDbconnection(); int i=0; try{ PreparedStatement ps=con.prepareStatement("select scheme_code,scheme_name from schema_admin"); ResultSet rs=ps.executeQuery(); while(rs.next()) { i=1; Adminallschemeviewbean lb=new Adminallschemeviewbean(); lb.setSchemecode(rs.getString(1)); lb.setSchemename(rs.getString(2)); al.add(lb); } } catch (SQLException e) { e.printStackTrace(); } return al; } }
1,708
0.621194
0.614754
71
22.056337
23.660086
100
false
false
0
0
0
0
0
0
2.478873
false
false
12
6ac395332eafa13a3ccf18070ee43defcc2e89dd
3,513,283,250,758
b7b41a2df3430f63b17e7089015f795696e918c3
/bmys/src/com/yfm/adapter/YuYueAdapter.java
cb72fc1d87ad9914729379d89a84f2d70045c852
[]
no_license
yfm049/oldcode
https://github.com/yfm049/oldcode
87c3839529d2bc7d634a6fafce62e22ecdfcc4c5
eac280f716e798aee6b6a284c8a887fe38b3bdc0
refs/heads/master
2020-12-24T08:30:30.625000
2016-08-26T09:21:22
2016-08-26T09:21:22
33,308,446
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yfm.adapter; import java.util.ArrayList; import java.util.List; import com.yfm.adapter.ActiveAdapter.Getdata; import com.yfm.net.HttpDao; import com.yfm.net.OnClickListenerImpl; import com.yfm.pojo.Good; import com.yfm.pojo.YuYue; import com.yfm.pro.R; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class YuYueAdapter extends BaseAdapter { private List<YuYue> lg=new ArrayList<YuYue>(); public List<YuYue> getLg() { return lg; } private Context context; private Dialog dialog; private String url="/MobApp/ReservationList"; private static boolean isrun=false; public YuYueAdapter(Context context){ this.context=context; } @Override public int getCount() { // TODO Auto-generated method stub return lg.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return lg.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(int arg0, View view, ViewGroup arg2) { // TODO Auto-generated method stub if(view==null){ view=LayoutInflater.from(context).inflate(R.layout.yuyue_item, null); } TextView date=(TextView)view.findViewById(R.id.date); GridView gv=(GridView)view.findViewById(R.id.shuju); YuYue gd=lg.get(arg0); date.setText(gd.getData()); YuyueGridAdapter yga=new YuyueGridAdapter(context,gd.getLyg()); gv.setAdapter(yga); return view; } public void getData(){ if(!isrun){ if(dialog!=null){ dialog.cancel(); } dialog=new ProgressDialog(context); dialog.setTitle("正在加载..."); Log.i("--", "正在加载..."); dialog.show(); Getdata ga=new Getdata(url,dialog); ga.start(); } } public Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if(msg.what==0){ YuYueAdapter.this.notifyDataSetChanged(); }else{ Toast.makeText(context, "加载了0条数据", Toast.LENGTH_SHORT).show(); } isrun=false; } }; class Getdata extends Thread{ private Dialog dialog; private String url; public Getdata(String url,Dialog dialog){ this.url=url; this.dialog=dialog; } @Override public void run() { // TODO Auto-generated method stub Log.i("isrun", isrun+""); try { isrun=true; List<YuYue> lgs=HttpDao.getYuyueList(url, dialog); lg.addAll(lgs); Log.i("tiso", lgs.size()+"---"); if(lgs.size()>0){ handler.sendEmptyMessage(0); }else{ handler.sendEmptyMessage(1); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
GB18030
Java
3,137
java
YuYueAdapter.java
Java
[]
null
[]
package com.yfm.adapter; import java.util.ArrayList; import java.util.List; import com.yfm.adapter.ActiveAdapter.Getdata; import com.yfm.net.HttpDao; import com.yfm.net.OnClickListenerImpl; import com.yfm.pojo.Good; import com.yfm.pojo.YuYue; import com.yfm.pro.R; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class YuYueAdapter extends BaseAdapter { private List<YuYue> lg=new ArrayList<YuYue>(); public List<YuYue> getLg() { return lg; } private Context context; private Dialog dialog; private String url="/MobApp/ReservationList"; private static boolean isrun=false; public YuYueAdapter(Context context){ this.context=context; } @Override public int getCount() { // TODO Auto-generated method stub return lg.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return lg.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(int arg0, View view, ViewGroup arg2) { // TODO Auto-generated method stub if(view==null){ view=LayoutInflater.from(context).inflate(R.layout.yuyue_item, null); } TextView date=(TextView)view.findViewById(R.id.date); GridView gv=(GridView)view.findViewById(R.id.shuju); YuYue gd=lg.get(arg0); date.setText(gd.getData()); YuyueGridAdapter yga=new YuyueGridAdapter(context,gd.getLyg()); gv.setAdapter(yga); return view; } public void getData(){ if(!isrun){ if(dialog!=null){ dialog.cancel(); } dialog=new ProgressDialog(context); dialog.setTitle("正在加载..."); Log.i("--", "正在加载..."); dialog.show(); Getdata ga=new Getdata(url,dialog); ga.start(); } } public Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if(msg.what==0){ YuYueAdapter.this.notifyDataSetChanged(); }else{ Toast.makeText(context, "加载了0条数据", Toast.LENGTH_SHORT).show(); } isrun=false; } }; class Getdata extends Thread{ private Dialog dialog; private String url; public Getdata(String url,Dialog dialog){ this.url=url; this.dialog=dialog; } @Override public void run() { // TODO Auto-generated method stub Log.i("isrun", isrun+""); try { isrun=true; List<YuYue> lgs=HttpDao.getYuyueList(url, dialog); lg.addAll(lgs); Log.i("tiso", lgs.size()+"---"); if(lgs.size()>0){ handler.sendEmptyMessage(0); }else{ handler.sendEmptyMessage(1); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
3,137
0.699582
0.695722
136
21.860294
16.342913
72
false
false
0
0
0
0
0
0
2.338235
false
false
12
f106b57d0be7ad4c70240fc6e637c4ac062790f2
31,095,563,270,167
0deebd569c48a17c04c1fd952ea7de6044e1f877
/studyjava/src/practice017/TestArray08.java
5460cf72da03a817732c2ddd4dc8c9d8165c37d7
[]
no_license
neem693/workspace
https://github.com/neem693/workspace
7e28e7a0f9f649c3bbfc141fe906956b76953aa5
14b93c231fb3daf95adcf678e75793cdb135fead
refs/heads/master
2022-05-02T21:37:38.589000
2022-03-17T17:00:45
2022-03-17T17:00:45
125,331,638
0
0
null
false
2018-09-02T06:56:43
2018-03-15T07:55:48
2018-09-02T06:49:47
2018-09-02T06:56:43
271,837
0
0
0
HTML
false
null
package practice017; import java.util.Arrays; public class TestArray08 { public static int[] reverse(int[] array) { int[] result = new int[array.length]; for (int i = 0, j = result.length - 1; i < array.length; i++, j--) { result[i] = array[j]; } return result; } public static void main(String[] args) { int[] array = { 23, 45, 67, 43, 47, 31, 30, 27 }; System.out.println("오름차순 정렬하기"); Arrays.sort(array); for (int i : array) System.out.print(i + ","); System.out.println(); System.out.println("내림차순 정렬하기"); array = reverse(array); for (int i : array) System.out.print(i + ","); } }
UTF-8
Java
663
java
TestArray08.java
Java
[]
null
[]
package practice017; import java.util.Arrays; public class TestArray08 { public static int[] reverse(int[] array) { int[] result = new int[array.length]; for (int i = 0, j = result.length - 1; i < array.length; i++, j--) { result[i] = array[j]; } return result; } public static void main(String[] args) { int[] array = { 23, 45, 67, 43, 47, 31, 30, 27 }; System.out.println("오름차순 정렬하기"); Arrays.sort(array); for (int i : array) System.out.print(i + ","); System.out.println(); System.out.println("내림차순 정렬하기"); array = reverse(array); for (int i : array) System.out.print(i + ","); } }
663
0.603804
0.567353
32
18.71875
17.951731
70
false
false
0
0
0
0
0
0
1.96875
false
false
12
f03882bbbb774d1f17a453e7223e78c7792e7763
23,768,349,021,182
cc6d6c1cb4f250441350f88839f931e0541560ae
/JavaWebDevelopmentBasic/exam/src/main/java/services/UserServiceImpl.java
8acba9bdfd50549d2641c1fed662824fda2e6394
[]
no_license
cefothe/softuni
https://github.com/cefothe/softuni
a03a9fd1d510fc4871a52245e8e571e2f5e896ec
c684ae73e31695bc44efcbf115a92cabdb4404f2
refs/heads/master
2020-04-17T01:30:32.233000
2017-04-30T22:06:17
2017-04-30T22:06:17
53,979,583
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package services; import common.ApplicationUser; import entities.user.Role; import entities.user.User; import model.binding.CreateUserModel; import model.binding.LoginUserModel; import repositories.interfaces.UserRepository; import services.interfaces.UserService; import utils.parser.interfaces.ModelParser; import javax.ejb.Stateless; import javax.inject.Inject; import javax.servlet.http.HttpSession; /** * Created by cefothe on 05.03.17. */ @Stateless public class UserServiceImpl implements UserService{ @Inject private UserRepository userRepository; @Inject private ModelParser modelParser; @Override public void registeUser(CreateUserModel createUserModel) { User user = modelParser.convert(createUserModel, User.class); Role role= Role.USER; if(userRepository.numberOfUser()==0){ role = Role.ADMIN; } user.setRole(role); userRepository.createUser(user); } @Override public User findLoggedInUser(LoginUserModel loginUserModel) { String email = loginUserModel.getEmail(); String password = loginUserModel.getPassword(); return userRepository.findByUsernameAndPassword(email,password); } @Override public void createUserSession(User user, HttpSession httpSession) { httpSession.setAttribute("user",user); } }
UTF-8
Java
1,372
java
UserServiceImpl.java
Java
[ { "context": "avax.servlet.http.HttpSession;\n\n\n/**\n * Created by cefothe on 05.03.17.\n */\n@Stateless\npublic class UserServ", "end": 433, "score": 0.9996095299720764, "start": 426, "tag": "USERNAME", "value": "cefothe" } ]
null
[]
package services; import common.ApplicationUser; import entities.user.Role; import entities.user.User; import model.binding.CreateUserModel; import model.binding.LoginUserModel; import repositories.interfaces.UserRepository; import services.interfaces.UserService; import utils.parser.interfaces.ModelParser; import javax.ejb.Stateless; import javax.inject.Inject; import javax.servlet.http.HttpSession; /** * Created by cefothe on 05.03.17. */ @Stateless public class UserServiceImpl implements UserService{ @Inject private UserRepository userRepository; @Inject private ModelParser modelParser; @Override public void registeUser(CreateUserModel createUserModel) { User user = modelParser.convert(createUserModel, User.class); Role role= Role.USER; if(userRepository.numberOfUser()==0){ role = Role.ADMIN; } user.setRole(role); userRepository.createUser(user); } @Override public User findLoggedInUser(LoginUserModel loginUserModel) { String email = loginUserModel.getEmail(); String password = loginUserModel.getPassword(); return userRepository.findByUsernameAndPassword(email,password); } @Override public void createUserSession(User user, HttpSession httpSession) { httpSession.setAttribute("user",user); } }
1,372
0.728134
0.723032
54
24.407408
21.968428
72
false
false
0
0
0
0
0
0
0.5
false
false
12
90075b90e3a278cc2aee7c7e85a38c33f54ef2e9
9,345,848,886,124
41131d0c18da96c9cb30afb973b9ecd39c6983a1
/src/Problema1/Algoritmos.java
2214ac0bf7a87353e202dc03aa7a01c0cc9fea2b
[]
no_license
SergioAPaz/Tarea-52-problemas-Compiladores
https://github.com/SergioAPaz/Tarea-52-problemas-Compiladores
0aa617f67011102f0396e7f5f9e96cde4cdf8636
421718f8feaf90ae72c277ecedb86f225e182001
refs/heads/master
2020-05-02T12:13:23.886000
2015-05-14T05:26:45
2015-05-14T05:26:45
35,592,180
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Problema1; /** * * @author Sergio Alejandro Paz Holguin 264951 * @version 1.0 * @since 13/05/2015 */ public class Algoritmos { /** * @param args the command line arguments */ public static void main(String[] args) { int x=0; for (int i = 0; i <= 100; i++) { System.out.println(x); x++; } } }
UTF-8
Java
620
java
Algoritmos.java
Java
[ { "context": "r.\r\n */\r\npackage Problema1;\r\n\r\n/**\r\n *\r\n * @author Sergio Alejandro Paz Holguin 264951\r\n * @version 1.0\r\n * @since 13/05/2015\r\n *", "end": 260, "score": 0.999895453453064, "start": 232, "tag": "NAME", "value": "Sergio Alejandro Paz Holguin" } ]
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 Problema1; /** * * @author <NAME> 264951 * @version 1.0 * @since 13/05/2015 */ public class Algoritmos { /** * @param args the command line arguments */ public static void main(String[] args) { int x=0; for (int i = 0; i <= 100; i++) { System.out.println(x); x++; } } }
598
0.533871
0.498387
29
19.379311
20.012779
79
false
false
0
0
0
0
0
0
0.310345
false
false
12
714c1d594f76ad589c9cd81eaf8471f638a7d332
11,630,771,438,755
3ccbe3dacd6f9d749ca929527af7e9d1db4cfb23
/src/main/java/pro/bolshakov/stock/service/impl/DividendHistoryServiceImpl.java
1ed8443adf349ac17e2ff39eb89f4f494ca23ec6
[]
no_license
bolshakov-as/stock
https://github.com/bolshakov-as/stock
83c3394dbef8440d67f32ac874ef30cf849c3607
023f5795f4af2dc7c2f234837ee87b6379096b3c
refs/heads/master
2019-07-02T05:56:27.700000
2018-04-12T08:13:14
2018-04-12T08:13:14
80,832,327
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pro.bolshakov.stock.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pro.bolshakov.stock.api.intrinio.IntrinioApi; import pro.bolshakov.stock.api.yahoo.YahooFinance; import pro.bolshakov.stock.entity.domain.DividendHistory; import pro.bolshakov.stock.entity.domain.Item; import pro.bolshakov.stock.entity.domain.ServiceTask; import pro.bolshakov.stock.entity.domain.TypeServiceTask; import pro.bolshakov.stock.repository.DividendHistoryDAO; import pro.bolshakov.stock.service.DividendHistoryService; import pro.bolshakov.stock.service.ServiceTaskService; import java.io.IOException; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.List; @Service public class DividendHistoryServiceImpl implements DividendHistoryService { private final DividendHistoryDAO dividendHistoryDAO; private final ServiceTaskService serviceTaskService; @Autowired public DividendHistoryServiceImpl(DividendHistoryDAO dividendHistoryDAO, ServiceTaskService serviceTaskService) { this.dividendHistoryDAO = dividendHistoryDAO; this.serviceTaskService = serviceTaskService; } @Override public void createTaskImportDividendLastYear(Item item){ LocalDate endDate = LocalDate.now(); LocalDate startDate = endDate.minus(365, ChronoUnit.DAYS); serviceTaskService.save( new ServiceTask.Builder() .setDate(LocalDate.now()) .setType(TypeServiceTask.LOAD_DIVIDEND) .addProperites("id", item.getId().toString()) .addProperites("startDate", startDate.toString()) .addProperites("endDate", endDate.toString()) .setDescription("Import dividend for " + item.getCode() + " from " + startDate + " to " + endDate) .build() ); } @Override public void importDividendByPeriod(Item item, LocalDate startDate, LocalDate endDate){ List<DividendHistory> dividendHistoryByPeriod = getDividendHistoryByPeriod(item, startDate, endDate); dividendHistoryDAO.saveAll(dividendHistoryByPeriod); } @Override public List<DividendHistory> getAllByItem(Item item) { return dividendHistoryDAO.getAllByItem(item); } @Override public List<DividendHistory> getByLastYearByItem(Item item) { LocalDate endDate = LocalDate.now(); return dividendHistoryDAO.getByPeriodByItem(item, endDate.minusDays(365), endDate); } private List<DividendHistory> getDividendHistoryByPeriod(Item item, LocalDate startDate, LocalDate endDate){ List<DividendHistory> dividendHistory = Collections.emptyList(); try { dividendHistory = IntrinioApi.getDividendHistory(item, startDate, endDate); } catch (IOException e) { throw new RuntimeException(e); } return dividendHistory; } }
UTF-8
Java
3,065
java
DividendHistoryServiceImpl.java
Java
[]
null
[]
package pro.bolshakov.stock.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pro.bolshakov.stock.api.intrinio.IntrinioApi; import pro.bolshakov.stock.api.yahoo.YahooFinance; import pro.bolshakov.stock.entity.domain.DividendHistory; import pro.bolshakov.stock.entity.domain.Item; import pro.bolshakov.stock.entity.domain.ServiceTask; import pro.bolshakov.stock.entity.domain.TypeServiceTask; import pro.bolshakov.stock.repository.DividendHistoryDAO; import pro.bolshakov.stock.service.DividendHistoryService; import pro.bolshakov.stock.service.ServiceTaskService; import java.io.IOException; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.List; @Service public class DividendHistoryServiceImpl implements DividendHistoryService { private final DividendHistoryDAO dividendHistoryDAO; private final ServiceTaskService serviceTaskService; @Autowired public DividendHistoryServiceImpl(DividendHistoryDAO dividendHistoryDAO, ServiceTaskService serviceTaskService) { this.dividendHistoryDAO = dividendHistoryDAO; this.serviceTaskService = serviceTaskService; } @Override public void createTaskImportDividendLastYear(Item item){ LocalDate endDate = LocalDate.now(); LocalDate startDate = endDate.minus(365, ChronoUnit.DAYS); serviceTaskService.save( new ServiceTask.Builder() .setDate(LocalDate.now()) .setType(TypeServiceTask.LOAD_DIVIDEND) .addProperites("id", item.getId().toString()) .addProperites("startDate", startDate.toString()) .addProperites("endDate", endDate.toString()) .setDescription("Import dividend for " + item.getCode() + " from " + startDate + " to " + endDate) .build() ); } @Override public void importDividendByPeriod(Item item, LocalDate startDate, LocalDate endDate){ List<DividendHistory> dividendHistoryByPeriod = getDividendHistoryByPeriod(item, startDate, endDate); dividendHistoryDAO.saveAll(dividendHistoryByPeriod); } @Override public List<DividendHistory> getAllByItem(Item item) { return dividendHistoryDAO.getAllByItem(item); } @Override public List<DividendHistory> getByLastYearByItem(Item item) { LocalDate endDate = LocalDate.now(); return dividendHistoryDAO.getByPeriodByItem(item, endDate.minusDays(365), endDate); } private List<DividendHistory> getDividendHistoryByPeriod(Item item, LocalDate startDate, LocalDate endDate){ List<DividendHistory> dividendHistory = Collections.emptyList(); try { dividendHistory = IntrinioApi.getDividendHistory(item, startDate, endDate); } catch (IOException e) { throw new RuntimeException(e); } return dividendHistory; } }
3,065
0.715498
0.71354
76
39.328949
31.637081
122
false
false
0
0
0
0
0
0
0.631579
false
false
12
1a21b5cc03747bcb793b9d0bafa61ed770f53642
6,897,717,478,410
599448edf3d50ec0878584b39e4e08a3ecc57b42
/sbdem/sbdem/src/main/java/com/entr/sbdem/validation/PasswordMatchesValidator.java
1322ff0b163e27d7a70859af9ad1a0f5fce45bd1
[]
no_license
AlexSafonov/sbdem
https://github.com/AlexSafonov/sbdem
b0bc6532c839745662d30eb0dfee4f93dd032f4b
a6e848b26b12375ae2521b7bed46965bb59845a5
refs/heads/master
2020-04-17T08:32:37.519000
2019-05-22T11:57:19
2019-05-22T11:57:19
166,416,588
0
0
null
false
2019-01-18T14:43:35
2019-01-18T14:22:36
2019-01-18T14:22:38
2019-01-18T14:43:35
0
0
0
0
null
false
null
package com.entr.sbdem.validation; import com.entr.sbdem.model.UserRegisterForm; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches,Object> { @Override public void initialize(PasswordMatches constraintAnnotation){} @Override public boolean isValid(Object value, ConstraintValidatorContext context) { UserRegisterForm urf = (UserRegisterForm) value; return urf.getPassword().equals(urf.getMatchPassword()); } }
UTF-8
Java
581
java
PasswordMatchesValidator.java
Java
[]
null
[]
package com.entr.sbdem.validation; import com.entr.sbdem.model.UserRegisterForm; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches,Object> { @Override public void initialize(PasswordMatches constraintAnnotation){} @Override public boolean isValid(Object value, ConstraintValidatorContext context) { UserRegisterForm urf = (UserRegisterForm) value; return urf.getPassword().equals(urf.getMatchPassword()); } }
581
0.791738
0.791738
17
33.176472
30.561867
94
false
false
0
0
0
0
0
0
0.470588
false
false
12
1e380e4dcb431bd99ef339d11a59ddf81a55277b
28,965,259,494,681
49d9955ea714ff30b9d318b8901a19d85ea9d219
/Quiz2/src/pkgCore/CarPayment.java
ed533f00a16f74d182b444b73b5b26adee19c93b
[]
no_license
atalham1/Quiz2
https://github.com/atalham1/Quiz2
ea9ade0603c70cb5c619179a3037608529c2c616
6742da551dfa4f2e86b379275c43deb97f8b692e
refs/heads/master
2021-03-24T10:30:01.074000
2018-02-28T02:07:29
2018-02-28T02:07:29
123,214,610
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pkgCore; import java.util.Scanner; public class CarPayment { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the total price of the car: "); double totalPrice = sc.nextDouble(); System.out.println("Enter the down payment on the car: "); double downPayment = sc.nextDouble(); System.out.println("Enter the length of the loan (months): "); int loanLength = sc.nextInt(); System.out.println("Enter the interest rate (decimal): "); double interestRate = sc.nextDouble(); double paymentLeft = totalPrice - downPayment; double monthlyPay = monthlyPayment(paymentLeft,loanLength,interestRate); double totalIR = totalInterest(paymentLeft,monthlyPay,loanLength); System.out.println("Monthly payment: " + monthlyPay); System.out.println("Total interest paid: " + totalIR); } public static double monthlyPayment(double payLeft, int months, double rate) { double rpm = rate / 12; double powCalc = Math.pow((1+rpm), months); return payLeft * ((rpm*powCalc)/(powCalc-1)); } public static double totalInterest(double payLeft, double monthlyPay, int months) { return (monthlyPay * months) - payLeft; } }
UTF-8
Java
1,285
java
CarPayment.java
Java
[]
null
[]
package pkgCore; import java.util.Scanner; public class CarPayment { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the total price of the car: "); double totalPrice = sc.nextDouble(); System.out.println("Enter the down payment on the car: "); double downPayment = sc.nextDouble(); System.out.println("Enter the length of the loan (months): "); int loanLength = sc.nextInt(); System.out.println("Enter the interest rate (decimal): "); double interestRate = sc.nextDouble(); double paymentLeft = totalPrice - downPayment; double monthlyPay = monthlyPayment(paymentLeft,loanLength,interestRate); double totalIR = totalInterest(paymentLeft,monthlyPay,loanLength); System.out.println("Monthly payment: " + monthlyPay); System.out.println("Total interest paid: " + totalIR); } public static double monthlyPayment(double payLeft, int months, double rate) { double rpm = rate / 12; double powCalc = Math.pow((1+rpm), months); return payLeft * ((rpm*powCalc)/(powCalc-1)); } public static double totalInterest(double payLeft, double monthlyPay, int months) { return (monthlyPay * months) - payLeft; } }
1,285
0.677821
0.674708
47
25.340425
26.609291
84
false
false
0
0
0
0
0
0
2.042553
false
false
12
ec54a11479b54c92f2d49bc67e158093e31abc25
16,080,357,574,770
6035f7f949702f0642b7c25ee4e39e63eb0b66a9
/contas-bancarias/src/main/java/com/valmeida/contabancaria/api/controller/ContaController.java
edaf2242201cfcef7dc39821bdd042b408399f3b
[]
no_license
larolman/projeto-conta-bancaria
https://github.com/larolman/projeto-conta-bancaria
b56f9d02d7e76a745746180d16d9f1db267d9a9d
dc2bf2409e7778484ddadbf4c67b678986c045d4
refs/heads/master
2021-03-14T06:32:44.910000
2020-03-14T13:08:02
2020-03-14T13:08:02
246,746,153
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.valmeida.contabancaria.api.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.valmeida.contabancaria.api.assembler.ContaInputDisassembler; import com.valmeida.contabancaria.api.assembler.ContaModelAssembler; import com.valmeida.contabancaria.api.model.ContaModel; import com.valmeida.contabancaria.api.model.input.ContaAtualizaSaldoInput; import com.valmeida.contabancaria.api.model.input.ContaChequeEspecialInput; import com.valmeida.contabancaria.api.model.input.ContaInput; import com.valmeida.contabancaria.domain.exception.ContaNaoEncontradaException; import com.valmeida.contabancaria.domain.model.Conta; import com.valmeida.contabancaria.domain.repository.ContaRepository; import com.valmeida.contabancaria.domain.service.ContaService; @RestController @RequestMapping("/contas") public class ContaController { @Autowired ContaRepository repository; @Autowired ContaService service; @Autowired ContaModelAssembler contaAssembler; @Autowired ContaInputDisassembler contaDisassembler; @GetMapping public List<?> listarContas() { return contaAssembler.toCollection(repository.findAll()); } @GetMapping("/{numeroConta}") public ResponseEntity<?> buscarConta(@PathVariable int numeroConta) { try { Conta conta = service.buscarConta(numeroConta); if(conta.isChequeEspecialLiberado()) { return ResponseEntity.ok(contaAssembler.toContaModelChequeEspecial(conta)); } return ResponseEntity.ok(contaAssembler.toContaModel(conta)); } catch (ContaNaoEncontradaException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); } } @PostMapping @ResponseStatus(code = HttpStatus.CREATED) public ContaModel criarConta(@RequestBody @Valid ContaInput contaInput) { Conta conta = service.salvarConta(contaDisassembler.toDomainModel(contaInput)); return contaAssembler.toContaModel(conta); } @PutMapping("/{numeroConta}") public ResponseEntity<?> alterarConta(@PathVariable int numeroConta, @RequestBody ContaInput contaInput) { try { Conta contaAtual = service.buscarConta(numeroConta); contaDisassembler.copyProperties(contaInput, contaAtual); return ResponseEntity.ok(service.salvarConta(contaAtual)); } catch (ContaNaoEncontradaException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); } } @PutMapping("/{numeroConta}/saldo") public ResponseEntity<?> atualizarSaldo(@PathVariable int numeroConta, @RequestBody ContaAtualizaSaldoInput conta) { try { service.atualizarSaldo(numeroConta, conta); return ResponseEntity.noContent().build(); } catch (ContaNaoEncontradaException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); } } @PutMapping("/{numeroConta}/cheque-especial") public ResponseEntity<?> liberaChequeEspecial(@PathVariable int numeroConta, @RequestBody ContaChequeEspecialInput conta) { try { service.liberaChequeEspecial(numeroConta, conta); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } catch (ContaNaoEncontradaException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); } } @DeleteMapping("/{numeroConta}") public ResponseEntity<?> removerConta(@PathVariable int numeroConta) { try { service.removerConta(numeroConta); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } catch (ContaNaoEncontradaException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); } } }
UTF-8
Java
4,246
java
ContaController.java
Java
[]
null
[]
package com.valmeida.contabancaria.api.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.valmeida.contabancaria.api.assembler.ContaInputDisassembler; import com.valmeida.contabancaria.api.assembler.ContaModelAssembler; import com.valmeida.contabancaria.api.model.ContaModel; import com.valmeida.contabancaria.api.model.input.ContaAtualizaSaldoInput; import com.valmeida.contabancaria.api.model.input.ContaChequeEspecialInput; import com.valmeida.contabancaria.api.model.input.ContaInput; import com.valmeida.contabancaria.domain.exception.ContaNaoEncontradaException; import com.valmeida.contabancaria.domain.model.Conta; import com.valmeida.contabancaria.domain.repository.ContaRepository; import com.valmeida.contabancaria.domain.service.ContaService; @RestController @RequestMapping("/contas") public class ContaController { @Autowired ContaRepository repository; @Autowired ContaService service; @Autowired ContaModelAssembler contaAssembler; @Autowired ContaInputDisassembler contaDisassembler; @GetMapping public List<?> listarContas() { return contaAssembler.toCollection(repository.findAll()); } @GetMapping("/{numeroConta}") public ResponseEntity<?> buscarConta(@PathVariable int numeroConta) { try { Conta conta = service.buscarConta(numeroConta); if(conta.isChequeEspecialLiberado()) { return ResponseEntity.ok(contaAssembler.toContaModelChequeEspecial(conta)); } return ResponseEntity.ok(contaAssembler.toContaModel(conta)); } catch (ContaNaoEncontradaException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); } } @PostMapping @ResponseStatus(code = HttpStatus.CREATED) public ContaModel criarConta(@RequestBody @Valid ContaInput contaInput) { Conta conta = service.salvarConta(contaDisassembler.toDomainModel(contaInput)); return contaAssembler.toContaModel(conta); } @PutMapping("/{numeroConta}") public ResponseEntity<?> alterarConta(@PathVariable int numeroConta, @RequestBody ContaInput contaInput) { try { Conta contaAtual = service.buscarConta(numeroConta); contaDisassembler.copyProperties(contaInput, contaAtual); return ResponseEntity.ok(service.salvarConta(contaAtual)); } catch (ContaNaoEncontradaException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); } } @PutMapping("/{numeroConta}/saldo") public ResponseEntity<?> atualizarSaldo(@PathVariable int numeroConta, @RequestBody ContaAtualizaSaldoInput conta) { try { service.atualizarSaldo(numeroConta, conta); return ResponseEntity.noContent().build(); } catch (ContaNaoEncontradaException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); } } @PutMapping("/{numeroConta}/cheque-especial") public ResponseEntity<?> liberaChequeEspecial(@PathVariable int numeroConta, @RequestBody ContaChequeEspecialInput conta) { try { service.liberaChequeEspecial(numeroConta, conta); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } catch (ContaNaoEncontradaException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); } } @DeleteMapping("/{numeroConta}") public ResponseEntity<?> removerConta(@PathVariable int numeroConta) { try { service.removerConta(numeroConta); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } catch (ContaNaoEncontradaException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); } } }
4,246
0.798398
0.798398
118
34.983051
30.269127
124
false
false
0
0
0
0
0
0
1.728814
false
false
12
48716e5c17c97731d1688f0e06cdcb19cc952e25
10,531,259,845,564
0563c45c9ba07670a4538a6b023b54c9ef28662a
/src/test/java/com/sivtcev/distance/repository/CityRepositoryTest.java
2b40352bbe04e90b51b3e6860bfce4832868c1fd
[]
no_license
sivtcev/DistanceCalculator
https://github.com/sivtcev/DistanceCalculator
f02928f2f47d7515488ce2b11f43ecede720dd5c
d8b65ac26a40a27b3f6782deeb9458a5d5466b18
refs/heads/master
2023-04-09T08:37:53.026000
2021-04-28T19:34:06
2021-04-28T19:34:06
362,079,761
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sivtcev.distance.repository; import com.sivtcev.distance.model.City; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import static org.springframework.test.util.AssertionErrors.assertEquals; @DataJpaTest public class CityRepositoryTest { @Autowired CityRepository cityRepository; @Test void getCityByNameTest(){ cityRepository.save(new City(1L, "city", 1D, 1D, null)); cityRepository.save(new City(2L, "city", 2D, 2D, null)); City result = cityRepository.getFirstByName("city"); assertEquals("correct result", 1L, result.getCityId()); } }
UTF-8
Java
732
java
CityRepositoryTest.java
Java
[]
null
[]
package com.sivtcev.distance.repository; import com.sivtcev.distance.model.City; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import static org.springframework.test.util.AssertionErrors.assertEquals; @DataJpaTest public class CityRepositoryTest { @Autowired CityRepository cityRepository; @Test void getCityByNameTest(){ cityRepository.save(new City(1L, "city", 1D, 1D, null)); cityRepository.save(new City(2L, "city", 2D, 2D, null)); City result = cityRepository.getFirstByName("city"); assertEquals("correct result", 1L, result.getCityId()); } }
732
0.740437
0.730874
25
28.280001
26.676611
73
false
false
0
0
0
0
0
0
0.84
false
false
12
210594f6bda6706f4e9df71ba2d9b1ff29ce4663
10,531,259,844,817
957332be00088fba1cb827de49c15f4015157051
/DivionMining/1.0.0-A1/src/fr/Maxime3399/DivionMining/schedulers/AntiDamageScheduler.java
e2e80ee1fc336e83ffff9d79edee1a45daab3399
[]
no_license
Maxime3399/Divion
https://github.com/Maxime3399/Divion
7d9332e1b61cfd999df52c56caf1b0cca508d1f7
6060bffdc978485b03162accdf0cc8a8c60dd765
refs/heads/master
2017-11-01T22:48:22.754000
2017-07-03T11:36:21
2017-07-03T11:36:21
96,104,256
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.Maxime3399.DivionMining.schedulers; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.Sound; import org.bukkit.entity.Player; public class AntiDamageScheduler { public static HashMap<Player, Integer> invincible = new HashMap<>(); public static void startScheduler(){ Bukkit.getScheduler().scheduleSyncRepeatingTask(Bukkit.getPluginManager().getPlugin("DivionMining"), new Runnable() { @Override public void run() { for(Player pls : Bukkit.getOnlinePlayers()){ if(invincible.containsKey(pls)){ if(invincible.get(pls) <= 0){ invincible.remove(pls); pls.sendMessage("§4§l§k||§r §cVous êtes désormais sensible aux dégats §4§l§k||"); pls.playSound(pls.getLocation(), Sound.BLAZE_BREATH, 100, 1); }else{ invincible.put(pls, invincible.get(pls)-1); } } } } }, 20, 20); } }
ISO-8859-1
Java
978
java
AntiDamageScheduler.java
Java
[ { "context": "package fr.Maxime3399.DivionMining.schedulers;\n\nimport java.util.HashMa", "end": 21, "score": 0.9970993995666504, "start": 11, "tag": "USERNAME", "value": "Maxime3399" } ]
null
[]
package fr.Maxime3399.DivionMining.schedulers; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.Sound; import org.bukkit.entity.Player; public class AntiDamageScheduler { public static HashMap<Player, Integer> invincible = new HashMap<>(); public static void startScheduler(){ Bukkit.getScheduler().scheduleSyncRepeatingTask(Bukkit.getPluginManager().getPlugin("DivionMining"), new Runnable() { @Override public void run() { for(Player pls : Bukkit.getOnlinePlayers()){ if(invincible.containsKey(pls)){ if(invincible.get(pls) <= 0){ invincible.remove(pls); pls.sendMessage("§4§l§k||§r §cVous êtes désormais sensible aux dégats §4§l§k||"); pls.playSound(pls.getLocation(), Sound.BLAZE_BREATH, 100, 1); }else{ invincible.put(pls, invincible.get(pls)-1); } } } } }, 20, 20); } }
978
0.62151
0.604964
46
20.02174
25.575539
119
false
false
0
0
0
0
0
0
3.76087
false
false
12
2493efa3605a2a33ddbbe3aca6da895dc8d614b4
30,820,685,378,539
413f0132e6d4bf9c16dd5e8bea379e298bed5c02
/src/main/java/com/academy/moviesapi/repositories/ReleasesRepository.java
040e3b8b7b4829dc7e26df0595a78d8c17b1abff
[]
no_license
CarolinaChavezDavid/movies-api
https://github.com/CarolinaChavezDavid/movies-api
4174f431223b5f74864c38387eff33920578131d
1b0c0e0ca4a78ba41d54a6bd36b5323f35027eb7
refs/heads/main
2023-08-10T18:36:32.892000
2021-09-06T21:58:04
2021-09-06T21:58:04
387,937,436
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.academy.moviesapi.repositories; import com.academy.moviesapi.entities.Releases; import org.springframework.data.jpa.repository.JpaRepository; public interface ReleasesRepository extends JpaRepository<Releases, Long> { }
UTF-8
Java
234
java
ReleasesRepository.java
Java
[]
null
[]
package com.academy.moviesapi.repositories; import com.academy.moviesapi.entities.Releases; import org.springframework.data.jpa.repository.JpaRepository; public interface ReleasesRepository extends JpaRepository<Releases, Long> { }
234
0.846154
0.846154
7
32.42857
29.383461
75
false
false
0
0
0
0
0
0
0.571429
false
false
12
c994fc0ed013bce066a00936063a52c3e7f00a05
12,008,728,624,342
838711120d69d93b4b06a03e522b4d6fffbc9635
/Spring REST API/src/main/java/com/codecool/spring/controller/AirplaneModelControllerSimplePath.java
bfab94563b2b11b6c69272b0bd7b665ffcadfe0a
[]
no_license
Elzacodecool/airplanes-spring-boot
https://github.com/Elzacodecool/airplanes-spring-boot
45220cc8c77b9336e07d3fd68c29b081fc082c46
cdad8e1ebe3d6970930bf521ebe486d39abcfe0a
refs/heads/master
2020-04-04T00:04:43.853000
2018-11-01T00:29:56
2018-11-01T00:29:56
155,639,688
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codecool.spring.controller; import com.codecool.spring.exception.AirplaneModelNotFoundException; import com.codecool.spring.exception.AirplaneModelWrongDataException; import com.codecool.spring.model.AirplaneModel; import com.codecool.spring.service.AirplaneModelService; import org.hibernate.exception.JDBCConnectionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class AirplaneModelControllerSimplePath { @Autowired private AirplaneModelService airplaneModelService; @GetMapping("/airplanes") public List<AirplaneModel> getAllAirplaneModels() { return airplaneModelService.getAllAirplaneModels(); } @GetMapping("/airplanes/{id}") public AirplaneModel getAirplaneModel(@PathVariable long id) { return airplaneModelService.getAirplaneModel(id); } @PostMapping("/airplanes") public void addAirplaneModel(@RequestBody String airplaneModel) { airplaneModelService.addAirplaneModel(airplaneModel); } @PutMapping("/airplanes/{id}") public void updateAirplaneModel(@PathVariable long id, @RequestBody String airplaneModel) { airplaneModelService.updateAirplaneModel(id, airplaneModel); } @DeleteMapping("/airplanes/{id}") public void deleteAirplaneModel(@PathVariable long id) { airplaneModelService.deleteAirplaneModel(id); } }
UTF-8
Java
1,474
java
AirplaneModelControllerSimplePath.java
Java
[]
null
[]
package com.codecool.spring.controller; import com.codecool.spring.exception.AirplaneModelNotFoundException; import com.codecool.spring.exception.AirplaneModelWrongDataException; import com.codecool.spring.model.AirplaneModel; import com.codecool.spring.service.AirplaneModelService; import org.hibernate.exception.JDBCConnectionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class AirplaneModelControllerSimplePath { @Autowired private AirplaneModelService airplaneModelService; @GetMapping("/airplanes") public List<AirplaneModel> getAllAirplaneModels() { return airplaneModelService.getAllAirplaneModels(); } @GetMapping("/airplanes/{id}") public AirplaneModel getAirplaneModel(@PathVariable long id) { return airplaneModelService.getAirplaneModel(id); } @PostMapping("/airplanes") public void addAirplaneModel(@RequestBody String airplaneModel) { airplaneModelService.addAirplaneModel(airplaneModel); } @PutMapping("/airplanes/{id}") public void updateAirplaneModel(@PathVariable long id, @RequestBody String airplaneModel) { airplaneModelService.updateAirplaneModel(id, airplaneModel); } @DeleteMapping("/airplanes/{id}") public void deleteAirplaneModel(@PathVariable long id) { airplaneModelService.deleteAirplaneModel(id); } }
1,474
0.775441
0.775441
43
33.279068
27.374514
95
false
false
0
0
0
0
0
0
0.395349
false
false
12
26e54946bfe18ae39997c16a10e03c75a03c05f4
14,422,500,202,106
aed40deab0bcf46a70f211bf0c1399ddd9fe020e
/app/src/main/java/com/arkarzaw/asartaline/acitvities/BaseAcitvity.java
08ed78d003886d3c710d9edff29b2f4f44f8683f
[]
no_license
htetarkarzaw/ASarTaLine
https://github.com/htetarkarzaw/ASarTaLine
092b3fdc3b148d354c4299c0785c69e11c6e8c0e
6ec8bfc3738b59d4608434d52e00b1d220ff0724
refs/heads/master
2020-03-22T10:18:34.880000
2018-07-06T23:41:41
2018-07-06T23:41:41
139,894,941
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.arkarzaw.asartaline.acitvities; import android.support.v7.app.AppCompatActivity; public class BaseAcitvity extends AppCompatActivity{ // @Override // public void onCurrentItemClick() { // // } // // @Override // public void onCategoryItemClick(String categoryId, String programId) { // // } }
UTF-8
Java
327
java
BaseAcitvity.java
Java
[ { "context": "package com.arkarzaw.asartaline.acitvities;\n\nimport android.support.v7", "end": 20, "score": 0.6230208277702332, "start": 18, "tag": "USERNAME", "value": "aw" } ]
null
[]
package com.arkarzaw.asartaline.acitvities; import android.support.v7.app.AppCompatActivity; public class BaseAcitvity extends AppCompatActivity{ // @Override // public void onCurrentItemClick() { // // } // // @Override // public void onCategoryItemClick(String categoryId, String programId) { // // } }
327
0.706422
0.703364
17
18.235294
23.18856
76
false
false
0
0
0
0
0
0
0.176471
false
false
12
110468ad25d2c93340d02e3fb17dcb2325ba1e39
9,861,244,956,864
3789570b417f8fa2d102e0de1a9bdffe8bcdc417
/src/main/java/com/zyiot/gongzhonghao/mapper/WXReportMapper.java
ca040bc3c636755427a5aed2b44a272593f8af60
[]
no_license
forTribeforXuanmo/gongzhonghao
https://github.com/forTribeforXuanmo/gongzhonghao
adaadcf7144c73191188450aba8e1185312493db
3bc4f93f5428b541bf6d24dae4324ab44069262c
refs/heads/master
2021-01-01T06:30:19.091000
2017-08-01T02:05:46
2017-08-01T02:05:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zyiot.gongzhonghao.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.zyiot.gongzhonghao.model.WXReport; public interface WXReportMapper extends BaseMapper<WXReport> { }
UTF-8
Java
204
java
WXReportMapper.java
Java
[]
null
[]
package com.zyiot.gongzhonghao.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.zyiot.gongzhonghao.model.WXReport; public interface WXReportMapper extends BaseMapper<WXReport> { }
204
0.833333
0.833333
8
24.5
25.029982
62
false
false
0
0
0
0
0
0
0.375
false
false
12
d664b07b3f2b7d6f9eaf5c03bc1f9c5e14c5f1e6
15,152,644,672,199
010cb31f38a636b82a293b77b9b98cb10ff2e20c
/MainActivity.java
33c95223b01643ebda21221ab06b8607fe84e3db
[]
no_license
motwanikaran/T3
https://github.com/motwanikaran/T3
f10d3a7dc66f59b0cc519add6fdb7ca7821f2939
195db6c861331bc2e2fdb1949097d2b75b5acf4f
refs/heads/master
2021-01-11T01:57:33.831000
2016-10-20T08:03:20
2016-10-20T08:03:20
70,831,244
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package t3; /** * * @author USER */ public class MainActivity extends javax.swing.JFrame { int a[][]; int count=0; public MainActivity() { initComponents(); a = new int[3][3]; PlayerTurn(); for(int i=0; i<3;i++) for(int j=0; j<3; j++) a[i][j]=0; } public void PlayerTurn() { if(count<=9) if(count%2==0) jLabel2.setText("Player 1 Turn"); else jLabel2.setText("Player 2 Turn"); } public void Calculate() { if(((a[0][0] == 1) && (a[0][1] == 1) && (a[0][2] == 1)) || ((a[1][0] == 1) && (a[1][1] == 1) && (a[1][2] == 1)) || ((a[2][0] == 1) && (a[2][1] == 1) && (a[2][2] == 1)) || ((a[0][0] == 1) && (a[1][0] == 1) && (a[2][0] == 1)) || ((a[0][1] == 1) && (a[1][1] == 1) && (a[2][1] == 1)) || ((a[0][2] == 1) && (a[1][2] == 1) && (a[2][2] == 1)) || ((a[0][0] == 1) && (a[1][1] == 1) && (a[2][2] == 1)) || ((a[0][2] == 1) && (a[1][1] == 1) && (a[2][0] == 1))) { jLabel3.setText("Player 1 wins!"); jLabel2.setText("Player 1 Turn"); count=0; jButton1.setEnabled(true); jButton3.setEnabled(true); jButton4.setEnabled(true); jButton5.setEnabled(true); jButton6.setEnabled(true); jButton7.setEnabled(true); jButton8.setEnabled(true); jButton9.setEnabled(true); jButton10.setEnabled(true); jButton1.setText(""); jButton3.setText(""); jButton4.setText(""); jButton5.setText(""); jButton6.setText(""); jButton7.setText(""); jButton8.setText(""); jButton9.setText(""); jButton10.setText(""); for(int i=0; i<3;i++) for(int j=0; j<3; j++) a[i][j]=0; } else if(((a[0][0] == 2) && (a[0][1] == 2) && (a[0][2] == 2)) || ((a[1][0] == 2) && (a[1][1] == 2) && (a[1][2] == 2)) || ((a[2][0] == 2) && (a[2][1] == 2) && (a[2][2] == 2)) || ((a[0][0] == 2) && (a[1][0] == 2) && (a[2][0] == 2)) || ((a[0][1] == 2) && (a[1][1] == 2) && (a[2][1] == 2)) || ((a[0][2] == 2) && (a[1][2] == 2) && (a[2][2] == 2)) || ((a[0][0] == 2) && (a[1][1] == 2) && (a[2][2] == 2)) || ((a[0][2] == 2) && (a[1][1] == 2) && (a[2][0] == 2))) { jLabel3.setText("Player 2 wins!"); jLabel2.setText("Player 1 Turn"); count=0; jButton1.setEnabled(true); jButton3.setEnabled(true); jButton4.setEnabled(true); jButton5.setEnabled(true); jButton6.setEnabled(true); jButton7.setEnabled(true); jButton8.setEnabled(true); jButton9.setEnabled(true); jButton10.setEnabled(true); jButton1.setText(""); jButton3.setText(""); jButton4.setText(""); jButton5.setText(""); jButton6.setText(""); jButton7.setText(""); jButton8.setText(""); jButton9.setText(""); jButton10.setText(""); for(int i=0; i<3;i++) for(int j=0; j<3; j++) a[i][j]=0; } } public void Draw(){ if(count>=9) { jLabel3.setText("It's a Draw!"); jLabel2.setText("Player 1 Turn"); jButton1.setEnabled(true); jButton3.setEnabled(true); jButton4.setEnabled(true); jButton5.setEnabled(true); jButton6.setEnabled(true); jButton7.setEnabled(true); jButton8.setEnabled(true); jButton9.setEnabled(true); jButton10.setEnabled(true); jButton1.setText(""); jButton3.setText(""); jButton4.setText(""); jButton5.setText(""); jButton6.setText(""); jButton7.setText(""); jButton8.setText(""); jButton9.setText(""); jButton10.setText(""); count=0; for(int i=0; i<3;i++) for(int j=0; j<3; j++) a[i][j]=0; } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); jButton10 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel1.setText("jLabel1"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); jButton9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton9ActionPerformed(evt); } }); jButton10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton10ActionPerformed(evt); } }); jLabel2.setText("jLabel2"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3) .addGap(56, 56, 56)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(164, 164, 164) .addComponent(jLabel2)) .addGroup(layout.createSequentialGroup() .addGap(117, 117, 117) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(layout.createSequentialGroup() .addGap(118, 118, 118) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(117, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jLabel2) .addGap(41, 41, 41) .addComponent(jLabel3) .addGap(13, 13, 13) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(42, 42, 42)) .addComponent(jButton5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButton9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton10, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(78, 78, 78)) ); pack(); }// </editor-fold> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton1.getText().equals("")) { if(count%2==0) jButton1.setText("X"); else jButton1.setText("O"); count++; PlayerTurn(); jButton1.setEnabled(false); } else jButton1.setEnabled(false); if(jButton1.getText().equals("X")) a[0][0]=1; else a[0][0]=2; Calculate(); Draw(); } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton3.getText().equals("")) { if(count%2==0) jButton3.setText("X"); else jButton3.setText("O"); count++; PlayerTurn(); jButton3.setEnabled(false); } else jButton3.setEnabled(false); if(jButton3.getText().equals("X")) a[0][1]=1; else a[0][1]=2; Calculate(); Draw(); } private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton4.getText().equals("")) { if(count%2==0) jButton4.setText("X"); else jButton4.setText("O"); count++; PlayerTurn(); jButton4.setEnabled(false); } else jButton4.setEnabled(false); if(jButton4.getText().equals("X")) a[0][2]=1; else a[0][2]=2; Calculate(); Draw(); } private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton5.getText().equals("")) { if(count%2==0) jButton5.setText("X"); else jButton5.setText("O"); count++; PlayerTurn(); jButton5.setEnabled(false); } else jButton5.setEnabled(false); if(jButton5.getText().equals("X")) a[1][0]=1; else a[1][0]=2; Calculate(); Draw(); } private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton6.getText().equals("")) { if(count%2==0) jButton6.setText("X"); else jButton6.setText("O"); count++; PlayerTurn(); jButton6.setEnabled(false); } else jButton6.setEnabled(false);// TODO add your handling code here: if(jButton6.getText().equals("X")) a[1][1]=1; else a[1][1]=2; Calculate(); Draw(); } private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton7.getText().equals("")) { if(count%2==0) jButton7.setText("X"); else jButton7.setText("O"); count++; PlayerTurn(); jButton7.setEnabled(false); } else jButton7.setEnabled(false); if(jButton7.getText().equals("X")) a[1][2]=1; else a[1][2]=2; Calculate(); Draw();// TODO add your handling code here: } private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton8.getText().equals("")) { if(count%2==0) jButton8.setText("X"); else jButton8.setText("O"); count++; PlayerTurn(); jButton8.setEnabled(false); } else jButton8.setEnabled(false); if(jButton8.getText().equals("X")) a[2][0]=1; else a[2][0]=2; Calculate(); Draw();// TODO add your handling code here: } private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton9.getText().equals("")) { if(count%2==0) jButton9.setText("X"); else jButton9.setText("O"); count++; PlayerTurn(); jButton9.setEnabled(false); } else jButton9.setEnabled(false); if(jButton9.getText().equals("X")) a[2][1]=1; else a[2][1]=2; Calculate(); Draw();// TODO add your handling code here: } private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton10.getText().equals("")) { if(count%2==0) jButton10.setText("X"); else jButton10.setText("O"); count++; PlayerTurn(); jButton10.setEnabled(false); } else jButton10.setEnabled(false); if(jButton10.getText().equals("X")) a[2][2]=1; else a[2][2]=2; Calculate(); Draw();// TODO add your handling code here: } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainActivity.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainActivity.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainActivity.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainActivity.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton10; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; // End of variables declaration }
UTF-8
Java
20,543
java
MainActivity.java
Java
[ { "context": " in the editor.\n */\npackage t3;\n\n/**\n *\n * @author USER\n */\npublic class MainActivity extends javax.swing", "end": 220, "score": 0.9972309470176697, "start": 216, "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 t3; /** * * @author USER */ public class MainActivity extends javax.swing.JFrame { int a[][]; int count=0; public MainActivity() { initComponents(); a = new int[3][3]; PlayerTurn(); for(int i=0; i<3;i++) for(int j=0; j<3; j++) a[i][j]=0; } public void PlayerTurn() { if(count<=9) if(count%2==0) jLabel2.setText("Player 1 Turn"); else jLabel2.setText("Player 2 Turn"); } public void Calculate() { if(((a[0][0] == 1) && (a[0][1] == 1) && (a[0][2] == 1)) || ((a[1][0] == 1) && (a[1][1] == 1) && (a[1][2] == 1)) || ((a[2][0] == 1) && (a[2][1] == 1) && (a[2][2] == 1)) || ((a[0][0] == 1) && (a[1][0] == 1) && (a[2][0] == 1)) || ((a[0][1] == 1) && (a[1][1] == 1) && (a[2][1] == 1)) || ((a[0][2] == 1) && (a[1][2] == 1) && (a[2][2] == 1)) || ((a[0][0] == 1) && (a[1][1] == 1) && (a[2][2] == 1)) || ((a[0][2] == 1) && (a[1][1] == 1) && (a[2][0] == 1))) { jLabel3.setText("Player 1 wins!"); jLabel2.setText("Player 1 Turn"); count=0; jButton1.setEnabled(true); jButton3.setEnabled(true); jButton4.setEnabled(true); jButton5.setEnabled(true); jButton6.setEnabled(true); jButton7.setEnabled(true); jButton8.setEnabled(true); jButton9.setEnabled(true); jButton10.setEnabled(true); jButton1.setText(""); jButton3.setText(""); jButton4.setText(""); jButton5.setText(""); jButton6.setText(""); jButton7.setText(""); jButton8.setText(""); jButton9.setText(""); jButton10.setText(""); for(int i=0; i<3;i++) for(int j=0; j<3; j++) a[i][j]=0; } else if(((a[0][0] == 2) && (a[0][1] == 2) && (a[0][2] == 2)) || ((a[1][0] == 2) && (a[1][1] == 2) && (a[1][2] == 2)) || ((a[2][0] == 2) && (a[2][1] == 2) && (a[2][2] == 2)) || ((a[0][0] == 2) && (a[1][0] == 2) && (a[2][0] == 2)) || ((a[0][1] == 2) && (a[1][1] == 2) && (a[2][1] == 2)) || ((a[0][2] == 2) && (a[1][2] == 2) && (a[2][2] == 2)) || ((a[0][0] == 2) && (a[1][1] == 2) && (a[2][2] == 2)) || ((a[0][2] == 2) && (a[1][1] == 2) && (a[2][0] == 2))) { jLabel3.setText("Player 2 wins!"); jLabel2.setText("Player 1 Turn"); count=0; jButton1.setEnabled(true); jButton3.setEnabled(true); jButton4.setEnabled(true); jButton5.setEnabled(true); jButton6.setEnabled(true); jButton7.setEnabled(true); jButton8.setEnabled(true); jButton9.setEnabled(true); jButton10.setEnabled(true); jButton1.setText(""); jButton3.setText(""); jButton4.setText(""); jButton5.setText(""); jButton6.setText(""); jButton7.setText(""); jButton8.setText(""); jButton9.setText(""); jButton10.setText(""); for(int i=0; i<3;i++) for(int j=0; j<3; j++) a[i][j]=0; } } public void Draw(){ if(count>=9) { jLabel3.setText("It's a Draw!"); jLabel2.setText("Player 1 Turn"); jButton1.setEnabled(true); jButton3.setEnabled(true); jButton4.setEnabled(true); jButton5.setEnabled(true); jButton6.setEnabled(true); jButton7.setEnabled(true); jButton8.setEnabled(true); jButton9.setEnabled(true); jButton10.setEnabled(true); jButton1.setText(""); jButton3.setText(""); jButton4.setText(""); jButton5.setText(""); jButton6.setText(""); jButton7.setText(""); jButton8.setText(""); jButton9.setText(""); jButton10.setText(""); count=0; for(int i=0; i<3;i++) for(int j=0; j<3; j++) a[i][j]=0; } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); jButton10 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel1.setText("jLabel1"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); jButton9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton9ActionPerformed(evt); } }); jButton10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton10ActionPerformed(evt); } }); jLabel2.setText("jLabel2"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3) .addGap(56, 56, 56)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(164, 164, 164) .addComponent(jLabel2)) .addGroup(layout.createSequentialGroup() .addGap(117, 117, 117) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(layout.createSequentialGroup() .addGap(118, 118, 118) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(117, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jLabel2) .addGap(41, 41, 41) .addComponent(jLabel3) .addGap(13, 13, 13) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(42, 42, 42)) .addComponent(jButton5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButton9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton10, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(78, 78, 78)) ); pack(); }// </editor-fold> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton1.getText().equals("")) { if(count%2==0) jButton1.setText("X"); else jButton1.setText("O"); count++; PlayerTurn(); jButton1.setEnabled(false); } else jButton1.setEnabled(false); if(jButton1.getText().equals("X")) a[0][0]=1; else a[0][0]=2; Calculate(); Draw(); } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton3.getText().equals("")) { if(count%2==0) jButton3.setText("X"); else jButton3.setText("O"); count++; PlayerTurn(); jButton3.setEnabled(false); } else jButton3.setEnabled(false); if(jButton3.getText().equals("X")) a[0][1]=1; else a[0][1]=2; Calculate(); Draw(); } private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton4.getText().equals("")) { if(count%2==0) jButton4.setText("X"); else jButton4.setText("O"); count++; PlayerTurn(); jButton4.setEnabled(false); } else jButton4.setEnabled(false); if(jButton4.getText().equals("X")) a[0][2]=1; else a[0][2]=2; Calculate(); Draw(); } private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton5.getText().equals("")) { if(count%2==0) jButton5.setText("X"); else jButton5.setText("O"); count++; PlayerTurn(); jButton5.setEnabled(false); } else jButton5.setEnabled(false); if(jButton5.getText().equals("X")) a[1][0]=1; else a[1][0]=2; Calculate(); Draw(); } private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton6.getText().equals("")) { if(count%2==0) jButton6.setText("X"); else jButton6.setText("O"); count++; PlayerTurn(); jButton6.setEnabled(false); } else jButton6.setEnabled(false);// TODO add your handling code here: if(jButton6.getText().equals("X")) a[1][1]=1; else a[1][1]=2; Calculate(); Draw(); } private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton7.getText().equals("")) { if(count%2==0) jButton7.setText("X"); else jButton7.setText("O"); count++; PlayerTurn(); jButton7.setEnabled(false); } else jButton7.setEnabled(false); if(jButton7.getText().equals("X")) a[1][2]=1; else a[1][2]=2; Calculate(); Draw();// TODO add your handling code here: } private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton8.getText().equals("")) { if(count%2==0) jButton8.setText("X"); else jButton8.setText("O"); count++; PlayerTurn(); jButton8.setEnabled(false); } else jButton8.setEnabled(false); if(jButton8.getText().equals("X")) a[2][0]=1; else a[2][0]=2; Calculate(); Draw();// TODO add your handling code here: } private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton9.getText().equals("")) { if(count%2==0) jButton9.setText("X"); else jButton9.setText("O"); count++; PlayerTurn(); jButton9.setEnabled(false); } else jButton9.setEnabled(false); if(jButton9.getText().equals("X")) a[2][1]=1; else a[2][1]=2; Calculate(); Draw();// TODO add your handling code here: } private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) { if(jButton10.getText().equals("")) { if(count%2==0) jButton10.setText("X"); else jButton10.setText("O"); count++; PlayerTurn(); jButton10.setEnabled(false); } else jButton10.setEnabled(false); if(jButton10.getText().equals("X")) a[2][2]=1; else a[2][2]=2; Calculate(); Draw();// TODO add your handling code here: } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainActivity.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainActivity.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainActivity.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainActivity.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton10; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; // End of variables declaration }
20,543
0.540087
0.512389
507
39.518738
35.265312
179
false
false
0
0
0
0
0
0
0.706114
false
false
12
e2320e1c8a614d49d6bc1a95123f0d3cbcfa1065
31,456,340,486,431
e2f5aec463d31f1ad7aa588500131bce8f3606a8
/ambit2-tautomers/src/test/java/ambit2/tautomers/test/TestUtils.java
6b0ad35ffa9571d5751e31714f75253a6fdb6246
[]
no_license
egonw/ambit2-all
https://github.com/egonw/ambit2-all
8c46c48634970e6fa4099ccba2542d66c58af296
2b723d234c584941edee4d93898085152b574f41
refs/heads/master
2020-07-06T09:57:00.195000
2017-05-29T07:53:15
2017-05-29T07:53:15
66,829,035
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ambit2.tautomers.test; import ambit2.tautomers.tools.TautomerAnalysis; public class TestUtils { public static void main(String[] args) { testRanking(new double[] {2,3,3,0,45,1,3}); } public static void testRanking(double values[]) { double ranks[] = TautomerAnalysis.getRanks(values, true); System.out.println("Original values + ranks:"); for (int i = 0; i < ranks.length; i++) System.out.println(" " + values[i] + " rank = " + ranks[i]); int n = values.length; for (int i = 1; i < n; i++) for (int k = 0; k < n-i; k++) { if (ranks[k] > ranks[k+1]) { //swap ranks double tmp = ranks[k+1]; ranks[k+1] = ranks[k]; ranks[k] = tmp; //swap values tmp = values[k+1]; values[k+1] = values[k]; values[k] = tmp; } } System.out.println("\nValues sorted by ranking:"); for (int i = 0; i < ranks.length; i++) System.out.println(" " + values[i] + " rank = " + ranks[i]); System.out.println("\nNumber of distinct values = " + TautomerAnalysis.getNumberOfDistinctValues(values)); } }
UTF-8
Java
1,150
java
TestUtils.java
Java
[]
null
[]
package ambit2.tautomers.test; import ambit2.tautomers.tools.TautomerAnalysis; public class TestUtils { public static void main(String[] args) { testRanking(new double[] {2,3,3,0,45,1,3}); } public static void testRanking(double values[]) { double ranks[] = TautomerAnalysis.getRanks(values, true); System.out.println("Original values + ranks:"); for (int i = 0; i < ranks.length; i++) System.out.println(" " + values[i] + " rank = " + ranks[i]); int n = values.length; for (int i = 1; i < n; i++) for (int k = 0; k < n-i; k++) { if (ranks[k] > ranks[k+1]) { //swap ranks double tmp = ranks[k+1]; ranks[k+1] = ranks[k]; ranks[k] = tmp; //swap values tmp = values[k+1]; values[k+1] = values[k]; values[k] = tmp; } } System.out.println("\nValues sorted by ranking:"); for (int i = 0; i < ranks.length; i++) System.out.println(" " + values[i] + " rank = " + ranks[i]); System.out.println("\nNumber of distinct values = " + TautomerAnalysis.getNumberOfDistinctValues(values)); } }
1,150
0.56
0.543478
46
23
23.70929
108
false
false
0
0
0
0
0
0
3.021739
false
false
12
c230175bef40a24e8d4f16eaf6aa6f2ad5efee35
25,649,544,709,546
7c8d2d2791b63d49edaf464129849a585460c880
/3密钥卡发行系统/SAMMCS/src/com/goldsign/sammcs/service/IPSamIssueService.java
3ba934ad8900e7facb27219cbebae08812c0d12c
[]
no_license
wuqq-20191129/wlmq
https://github.com/wuqq-20191129/wlmq
5cd3ebc50945bde41d0fd615ba93ca95ab1a2235
ae26d439af09097b65c90cad8d22954cd91fe5f5
refs/heads/master
2023-01-14T03:19:23.226000
2020-11-24T01:43:22
2020-11-24T02:09:41
315,494,185
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.goldsign.sammcs.service; import com.goldsign.csfrm.vo.CallResult; import com.goldsign.sammcs.vo.IssueVo; import com.goldsign.sammcs.vo.KmsCfgParam; /** * * @author lenovo */ public interface IPSamIssueService { CallResult author(KmsCfgParam param); CallResult issue(IssueVo issueVo); CallResult read(); CallResult isKMSConnected(KmsCfgParam param); }
UTF-8
Java
522
java
IPSamIssueService.java
Java
[ { "context": "sign.sammcs.vo.KmsCfgParam;\r\n\r\n/**\r\n *\r\n * @author lenovo\r\n */\r\npublic interface IPSamIssueService {\r\n\r\n ", "end": 300, "score": 0.9993115663528442, "start": 294, "tag": "USERNAME", "value": "lenovo" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.goldsign.sammcs.service; import com.goldsign.csfrm.vo.CallResult; import com.goldsign.sammcs.vo.IssueVo; import com.goldsign.sammcs.vo.KmsCfgParam; /** * * @author lenovo */ public interface IPSamIssueService { CallResult author(KmsCfgParam param); CallResult issue(IssueVo issueVo); CallResult read(); CallResult isKMSConnected(KmsCfgParam param); }
522
0.691571
0.691571
25
18.879999
19.058479
52
false
false
0
0
0
0
0
0
0.4
false
false
12
cd008be05f78e6445af2aea1dc1cbbb70a853af8
17,394,617,566,954
3bec66eedde51415f9a6f0b8e421a24e9adf9b90
/src/main/java/com/spring/movi/dto/MoviTypeDTO.java
64085ece505ad366fa07ae66019603c7acf1eecf
[]
no_license
EanDalin0012/movi
https://github.com/EanDalin0012/movi
be51624b944f5eadf290d79f7b07f89cb4d16889
eee3ac05151b444cc55ee2fdc69d6e1dc833a851
refs/heads/master
2022-05-01T18:02:55.632000
2019-10-28T16:08:41
2019-10-28T16:08:41
205,511,769
1
0
null
false
2022-03-31T18:56:28
2019-08-31T07:29:30
2019-10-28T16:09:24
2022-03-31T18:56:28
60,923
1
0
2
JavaScript
false
false
package com.spring.movi.dto; public class MoviTypeDTO { private int id; private String name; private String description; private String createDate; private String createBy; private String modifyDate; private String modifyBy; private int status; public MoviTypeDTO() { super(); // TODO Auto-generated constructor stub } public MoviTypeDTO(int id, String name, String description, String createDate, String createBy, String modifyDate, String modifyBy, int status) { super(); this.id = id; this.name = name; this.description = description; this.createDate = createDate; this.createBy = createBy; this.modifyDate = modifyDate; this.modifyBy = modifyBy; this.status = status; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public String getModifyDate() { return modifyDate; } public void setModifyDate(String modifyDate) { this.modifyDate = modifyDate; } public String getModifyBy() { return modifyBy; } public void setModifyBy(String modifyBy) { this.modifyBy = modifyBy; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } @Override public String toString() { return "MoviTypeController [id=" + id + ", name=" + name + ", description=" + description + ", createDate=" + createDate + ", createBy=" + createBy + ", modifyDate=" + modifyDate + ", modifyBy=" + modifyBy + ", status=" + status + "]"; } }
UTF-8
Java
2,007
java
MoviTypeDTO.java
Java
[]
null
[]
package com.spring.movi.dto; public class MoviTypeDTO { private int id; private String name; private String description; private String createDate; private String createBy; private String modifyDate; private String modifyBy; private int status; public MoviTypeDTO() { super(); // TODO Auto-generated constructor stub } public MoviTypeDTO(int id, String name, String description, String createDate, String createBy, String modifyDate, String modifyBy, int status) { super(); this.id = id; this.name = name; this.description = description; this.createDate = createDate; this.createBy = createBy; this.modifyDate = modifyDate; this.modifyBy = modifyBy; this.status = status; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public String getModifyDate() { return modifyDate; } public void setModifyDate(String modifyDate) { this.modifyDate = modifyDate; } public String getModifyBy() { return modifyBy; } public void setModifyBy(String modifyBy) { this.modifyBy = modifyBy; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } @Override public String toString() { return "MoviTypeController [id=" + id + ", name=" + name + ", description=" + description + ", createDate=" + createDate + ", createBy=" + createBy + ", modifyDate=" + modifyDate + ", modifyBy=" + modifyBy + ", status=" + status + "]"; } }
2,007
0.694071
0.694071
103
18.485437
20.530756
109
false
false
0
0
0
0
0
0
1.61165
false
false
12
13f5e4637f3976d3c8c3dc06ff8a2ead5175f05a
910,533,086,087
535aafa5183d6969689878e32c7def0d5fa6ef85
/app/src/main/java/com/janiszhang/myokhttp/okhttp/listener/ResponseDataListener.java
409ef324cdcd10fef9a3527d11851b12181ffefd
[ "Apache-2.0" ]
permissive
zhangbz/MyOkHttpTest
https://github.com/zhangbz/MyOkHttpTest
9a1512e9e56abe2b88bd69fa08f78caf4f4c232a
0a932ebe9c22dcf78cf60403392c6fe941dc3950
refs/heads/master
2020-03-09T06:49:40.836000
2018-04-08T14:43:51
2018-04-08T14:59:44
128,649,539
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.janiszhang.myokhttp.okhttp.listener; /** * * @author janiszhang * @date 2018/4/4 * * 业务逻辑真正处理的地方 * * 为什么不直接使用OkHttp的Callback,而是额外自定义一个listener? * 之所以这样做,是为了将业务逻辑和通用的网络处理完全分开, * 统一的网络处理可以统一放在Callback中处理, * 然后再调用自定义的listener对业务逻辑进行处理。 * 另外一个重要原因是:Callback的onFailure只针对网络请求的异常情况, * 而实际开发中,我们不仅要关注网络异常,还要关注业务逻辑异常, * 通过自定义listener可以做到一点,因为callback的接口由框架自身调用, * 而listener的接口我们可以自由调用。 */ public interface ResponseDataListener { /** * 请求成功回调事件处理 * @param responseObj */ void onSuccess(Object responseObj); /** * 请求失败回调时间处理 * @param reasonObj */ void onFailure(Object reasonObj); }
UTF-8
Java
1,064
java
ResponseDataListener.java
Java
[ { "context": "zhang.myokhttp.okhttp.listener;\n\n/**\n *\n * @author janiszhang\n * @date 2018/4/4\n *\n * 业务逻辑真正处理的地方\n *\n * 为什么不直接使", "end": 78, "score": 0.9995611906051636, "start": 68, "tag": "USERNAME", "value": "janiszhang" } ]
null
[]
package com.janiszhang.myokhttp.okhttp.listener; /** * * @author janiszhang * @date 2018/4/4 * * 业务逻辑真正处理的地方 * * 为什么不直接使用OkHttp的Callback,而是额外自定义一个listener? * 之所以这样做,是为了将业务逻辑和通用的网络处理完全分开, * 统一的网络处理可以统一放在Callback中处理, * 然后再调用自定义的listener对业务逻辑进行处理。 * 另外一个重要原因是:Callback的onFailure只针对网络请求的异常情况, * 而实际开发中,我们不仅要关注网络异常,还要关注业务逻辑异常, * 通过自定义listener可以做到一点,因为callback的接口由框架自身调用, * 而listener的接口我们可以自由调用。 */ public interface ResponseDataListener { /** * 请求成功回调事件处理 * @param responseObj */ void onSuccess(Object responseObj); /** * 请求失败回调时间处理 * @param reasonObj */ void onFailure(Object reasonObj); }
1,064
0.712308
0.703077
33
18.69697
15.83147
48
false
false
0
0
0
0
0
0
0.090909
false
false
12
272bfb85443fa7219d437960ac961eaf20328ec6
20,358,145,007,204
7a3535cc63ba08bedad580eb0188c5bdf5a1e3ec
/app/src/main/java/com/mileem/mileem/networking/SendMessageDataManager.java
bd6375d8c28fbe269084db2f57de8c8612d956cd
[]
no_license
juanimarchese/mileemgrupo6
https://github.com/juanimarchese/mileemgrupo6
ff274c7b0118c92be7ba3c04d21b9afdc1dfcbf9
4b4eb56665fbf22bf3c610d6fea7a4f0b20de8b2
refs/heads/master
2021-01-18T14:02:49.370000
2014-11-24T21:11:12
2014-11-24T21:11:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mileem.mileem.networking; import com.loopj.android.http.RequestParams; import org.apache.http.Header; import org.json.JSONException; import org.json.JSONObject; /** * Created by ramirodiaz on 10/10/14. */ public class SendMessageDataManager { public static abstract class SendMessageDataManagerCallbackHandler extends CallbackHandler { public abstract void onComplete(); } public void sendMessage(final int publicationId, String email, String telephone, String contactTimeInfo, String message, final SendMessageDataManagerCallbackHandler callbackHandler) throws JSONException { RequestParams params = new RequestParams(); params.put("propertyId", publicationId); params.put("name", email ); params.put("email", email); params.put("telephone", telephone != null && telephone.length() > 0 ? telephone : "Teléfono no especificado"); params.put("callAt", contactTimeInfo != null && contactTimeInfo.length() > 0 ? contactTimeInfo : "Horario de respuesta no especificado"); params.put("message", message); AsyncRestHttpClient.get("send-message", params, new MileenJsonResponseHandler(callbackHandler) { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); try { int error = response.getInt("error"); if (error == 0) { callbackHandler.onComplete(); } else { String message = response.getString("message"); callbackHandler.onFailure(new Error(message)); } } catch (Throwable e) { callbackHandler.onFailure(new Error(e)); } } }); } }
UTF-8
Java
1,895
java
SendMessageDataManager.java
Java
[ { "context": "on;\nimport org.json.JSONObject;\n\n/**\n * Created by ramirodiaz on 10/10/14.\n */\npublic class SendMessageDataMana", "end": 204, "score": 0.9996502995491028, "start": 194, "tag": "USERNAME", "value": "ramirodiaz" } ]
null
[]
package com.mileem.mileem.networking; import com.loopj.android.http.RequestParams; import org.apache.http.Header; import org.json.JSONException; import org.json.JSONObject; /** * Created by ramirodiaz on 10/10/14. */ public class SendMessageDataManager { public static abstract class SendMessageDataManagerCallbackHandler extends CallbackHandler { public abstract void onComplete(); } public void sendMessage(final int publicationId, String email, String telephone, String contactTimeInfo, String message, final SendMessageDataManagerCallbackHandler callbackHandler) throws JSONException { RequestParams params = new RequestParams(); params.put("propertyId", publicationId); params.put("name", email ); params.put("email", email); params.put("telephone", telephone != null && telephone.length() > 0 ? telephone : "Teléfono no especificado"); params.put("callAt", contactTimeInfo != null && contactTimeInfo.length() > 0 ? contactTimeInfo : "Horario de respuesta no especificado"); params.put("message", message); AsyncRestHttpClient.get("send-message", params, new MileenJsonResponseHandler(callbackHandler) { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); try { int error = response.getInt("error"); if (error == 0) { callbackHandler.onComplete(); } else { String message = response.getString("message"); callbackHandler.onFailure(new Error(message)); } } catch (Throwable e) { callbackHandler.onFailure(new Error(e)); } } }); } }
1,895
0.62566
0.620908
43
43.069767
41.764786
208
false
false
0
0
0
0
0
0
0.860465
false
false
12
6f88ed8554c60b1d3f2c4fb8187e9078c3c7210d
13,932,873,929,121
9dddc1c014708c3eefc53bbeb0ec92e3d237eae5
/src/com/lemon/java/interfaced/StringApi.java
208109f12891bc8aa285b870bcb78dd909bafd65
[]
no_license
gaoqiuye/FromEsclispe
https://github.com/gaoqiuye/FromEsclispe
e71e08bbed43047650e2edabf387a4403aef1388
691213f5544e8981869073df82e5d1ca7423c0fd
refs/heads/master
2023-03-03T17:32:38.476000
2021-02-04T10:59:59
2021-02-04T10:59:59
294,656,037
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lemon.java.interfaced; import java.awt.Window.Type; public class StringApi { public static void main(String[] args) { String address1="abc,DEF广东省,深圳市:南山区南"; String address2="广东省深圳市宝安区"; String address3=""; System.out.println(address1.substring(3,6)); //从第三个开始取,到第5个结束 System.out.println(address1.equals(address2)); System.out.println(address1.contains("深圳")); System.out.println(address1.indexOf("南")); System.out.println(address1.lastIndexOf("南")); System.out.println(address2.isEmpty());//false System.out.println(address3.isEmpty());//true System.out.println(address1.toUpperCase()); System.out.println(address1.toLowerCase()); System.out.println(address1.length()); System.out.println(address3.length()); System.out.println(address1.charAt(2)); String[] adss= address1.split(","); //切分之后是个一维数组 for(String a:adss) { System.out.println(a); } } } /* * equals():判断两个数据是否一样 * equalIgnoreCase:判断两个数据是否一样,并且忽略大小写 * contains():判断是否包含某个信息 * indexOf():获取字符串中某个内容第一次出现的索引位置 * lastIndexOf():字符串中某个内容最后一次出现的索引位置 * isEmplty():判断是否为空 * subString():截取字符串 * toUpperCase():将字符串转换为大写 * toLOwerCase():将字符串转化为小写 * length():获取字符串的长度 * split():按照某个正则表达式来切分字符串 * chatAt():获取指定位置上的字符 * */
UTF-8
Java
1,631
java
StringApi.java
Java
[]
null
[]
package com.lemon.java.interfaced; import java.awt.Window.Type; public class StringApi { public static void main(String[] args) { String address1="abc,DEF广东省,深圳市:南山区南"; String address2="广东省深圳市宝安区"; String address3=""; System.out.println(address1.substring(3,6)); //从第三个开始取,到第5个结束 System.out.println(address1.equals(address2)); System.out.println(address1.contains("深圳")); System.out.println(address1.indexOf("南")); System.out.println(address1.lastIndexOf("南")); System.out.println(address2.isEmpty());//false System.out.println(address3.isEmpty());//true System.out.println(address1.toUpperCase()); System.out.println(address1.toLowerCase()); System.out.println(address1.length()); System.out.println(address3.length()); System.out.println(address1.charAt(2)); String[] adss= address1.split(","); //切分之后是个一维数组 for(String a:adss) { System.out.println(a); } } } /* * equals():判断两个数据是否一样 * equalIgnoreCase:判断两个数据是否一样,并且忽略大小写 * contains():判断是否包含某个信息 * indexOf():获取字符串中某个内容第一次出现的索引位置 * lastIndexOf():字符串中某个内容最后一次出现的索引位置 * isEmplty():判断是否为空 * subString():截取字符串 * toUpperCase():将字符串转换为大写 * toLOwerCase():将字符串转化为小写 * length():获取字符串的长度 * split():按照某个正则表达式来切分字符串 * chatAt():获取指定位置上的字符 * */
1,631
0.708961
0.692308
47
25.723404
17.755672
66
false
false
0
0
0
0
0
0
1.553192
false
false
12
e19f3699382cd4494c3c74f1409f871e7fa8e6bd
2,645,699,877,346
1aa58c5ce22419fe55f9f41915bdeae31023803f
/core/src/main/java/org/infinispan/partionhandling/impl/PartitionContext.java
d20483634dddcbd909a397d6cf8ea0621fda5adf
[ "Apache-2.0" ]
permissive
elguardian/infinispan
https://github.com/elguardian/infinispan
cf6fd51f3a0bc6e88048a2316536581ece8db558
041cf26555645aac0b86442656be6fe92406318e
refs/heads/master
2020-12-29T00:25:47.181000
2014-09-05T15:47:49
2014-09-08T11:16:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.infinispan.partionhandling.impl; import org.infinispan.Cache; import org.infinispan.remoting.transport.Address; import java.util.List; /** * Contains the information {@link PartitionHandlingStrategy} needs to decide what to do on membership changes. * Also allows the strategy to proceed with a rebalance or enter degraded mode. */ public interface PartitionContext<K,V> { /** * Returns the list of members before the partition happened. */ List<Address> getOldMembers(); /** * Returns the list of members as seen within this partition. */ List<Address> getNewMembers(); /** * Returns true if this partition might not contain all the data present in the cluster before partitioning happened. * E.g. if numOwners=5 and only 3 nodes left in the other partition, then this method returns false. If 6 nodes left * this method returns true. */ boolean isMissingData(); /** * Marks the current partition as available or not (writes are rejected with a AvailabilityException). */ void enterDegradedMode(); /** * Invoking this method triggers rebalance. */ void rebalance(); }
UTF-8
Java
1,171
java
PartitionContext.java
Java
[]
null
[]
package org.infinispan.partionhandling.impl; import org.infinispan.Cache; import org.infinispan.remoting.transport.Address; import java.util.List; /** * Contains the information {@link PartitionHandlingStrategy} needs to decide what to do on membership changes. * Also allows the strategy to proceed with a rebalance or enter degraded mode. */ public interface PartitionContext<K,V> { /** * Returns the list of members before the partition happened. */ List<Address> getOldMembers(); /** * Returns the list of members as seen within this partition. */ List<Address> getNewMembers(); /** * Returns true if this partition might not contain all the data present in the cluster before partitioning happened. * E.g. if numOwners=5 and only 3 nodes left in the other partition, then this method returns false. If 6 nodes left * this method returns true. */ boolean isMissingData(); /** * Marks the current partition as available or not (writes are rejected with a AvailabilityException). */ void enterDegradedMode(); /** * Invoking this method triggers rebalance. */ void rebalance(); }
1,171
0.711358
0.708796
41
27.560976
34.903385
120
false
false
0
0
0
0
0
0
0.268293
false
false
12
bef179c0a13b135ae377d67b67b1cd7409ad00c4
29,197,187,700,633
72f2875544e499dc0f66d886bcf97eedbd134b2f
/src/main/java/minn/minnbot/entities/command/QRCodeCommand.java
eba9b39814d23d35fca65e75acf0488bf21294f6
[]
no_license
connor44566/minnbot-test
https://github.com/connor44566/minnbot-test
1eb2b0c0c6b559d08daadc91d37afa1219f35b4f
5f939f2ed5b74e662802a4a392a88a528d0fe59b
refs/heads/master
2021-01-20T18:27:35.349000
2016-07-03T15:22:15
2016-07-03T15:22:15
62,502,358
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package minn.minnbot.entities.command; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import minn.minnbot.entities.Logger; import minn.minnbot.entities.command.listener.CommandAdapter; import minn.minnbot.events.CommandEvent; import java.net.URLEncoder; public class QRCodeCommand extends CommandAdapter{ public QRCodeCommand(String prefix, Logger logger) { this.logger = logger; this.prefix = prefix; } @Override public void onCommand(CommandEvent event) { if(event.allArguments.isEmpty()) { event.sendMessage(usage()); return; } String method = event.arguments[0]; if(!method.equalsIgnoreCase("text") && !method.equalsIgnoreCase("url")) { event.sendMessage("Invalid method!" + usage()); return; } if(!(event.allArguments.length() > event.arguments[0].length() + 1)) { event.sendMessage("Invalid input!" + usage()); return; } @SuppressWarnings("deprecation") String input = URLEncoder.encode(event.allArguments.substring(method.length() + 1)); try { HttpResponse<String> response = Unirest.get("https://pierre2106j-qrcode.p.mashape.com/api?backcolor=ffffff&ecl=H&forecolor=000000&pixel=3+to+4&text=" + input + "&type=" + method) .header("X-Mashape-Key", "IlX3p3hnDRmsheyTT7z87aT1mrs9p1Qb4WkjsnGUnXKitYqhtf") .header("Accept", "text/plain") .asString(); event.sendMessage(response.getBody()); } catch (UnirestException e) { event.sendMessage("Something is wrong with my connection try again later."); } } public String usage() { return "\n**__Methods:__** `text`, `url`\n**__Examples:__** `QR text test`, `QR url http://discordapp.com`"; } @Override public String getAlias() { return "QR <method> <input>"; } @Override public String example() { return "QR text This is an example"; } }
UTF-8
Java
2,143
java
QRCodeCommand.java
Java
[ { "context": "od)\n .header(\"X-Mashape-Key\", \"IlX3p3hnDRmsheyTT7z87aT1mrs9p1Qb4WkjsnGUnXKitYqhtf\")\n .header(\"Accept\", \"text/pla", "end": 1520, "score": 0.9997618794441223, "start": 1470, "tag": "KEY", "value": "IlX3p3hnDRmsheyTT7z87aT1mrs9p1Qb4WkjsnGUnXKitYqhtf" } ]
null
[]
package minn.minnbot.entities.command; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import minn.minnbot.entities.Logger; import minn.minnbot.entities.command.listener.CommandAdapter; import minn.minnbot.events.CommandEvent; import java.net.URLEncoder; public class QRCodeCommand extends CommandAdapter{ public QRCodeCommand(String prefix, Logger logger) { this.logger = logger; this.prefix = prefix; } @Override public void onCommand(CommandEvent event) { if(event.allArguments.isEmpty()) { event.sendMessage(usage()); return; } String method = event.arguments[0]; if(!method.equalsIgnoreCase("text") && !method.equalsIgnoreCase("url")) { event.sendMessage("Invalid method!" + usage()); return; } if(!(event.allArguments.length() > event.arguments[0].length() + 1)) { event.sendMessage("Invalid input!" + usage()); return; } @SuppressWarnings("deprecation") String input = URLEncoder.encode(event.allArguments.substring(method.length() + 1)); try { HttpResponse<String> response = Unirest.get("https://pierre2106j-qrcode.p.mashape.com/api?backcolor=ffffff&ecl=H&forecolor=000000&pixel=3+to+4&text=" + input + "&type=" + method) .header("X-Mashape-Key", "<KEY>") .header("Accept", "text/plain") .asString(); event.sendMessage(response.getBody()); } catch (UnirestException e) { event.sendMessage("Something is wrong with my connection try again later."); } } public String usage() { return "\n**__Methods:__** `text`, `url`\n**__Examples:__** `QR text test`, `QR url http://discordapp.com`"; } @Override public String getAlias() { return "QR <method> <input>"; } @Override public String example() { return "QR text This is an example"; } }
2,098
0.627625
0.615959
59
35.322033
35.567287
190
false
false
0
0
0
0
0
0
0.491525
false
false
12
2e06e22fee9a9e3f837f418ab36a42417cbcb547
20,495,583,956,126
ad38fc2c410fafa28a714639501d31c6bb0212d2
/net/fortuna/ical4j/model/Iso8601.java
7bbcdf6bb88bfa52212e985d1f3d432d89867798
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
michael79bxl/de.int80.ics.reader
https://github.com/michael79bxl/de.int80.ics.reader
2ed0de81060051e86c4af4319e0a339007cb3ab0
fae10754ef76d0db06f8d10d4bbb49dfc980a611
refs/heads/master
2019-04-27T01:18:41.476000
2017-03-03T13:06:18
2017-03-03T13:06:18
83,796,836
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.fortuna.ical4j.model; import java.text.DateFormat; import java.util.Date; import java.util.TimeZone; import net.fortuna.ical4j.util.CompatibilityHints; import net.fortuna.ical4j.util.Dates; import net.fortuna.ical4j.util.TimeZones; public abstract class Iso8601 extends Date { private static final long serialVersionUID = -4290728005713946811L; private DateFormat format; private DateFormat gmtFormat; private int precision; public Iso8601(long time, String pattern, int precision, TimeZone tz) { super(Dates.round(time, precision, tz)); this.format = CalendarDateFormatFactory.getInstance(pattern); this.format.setTimeZone(tz); this.format.setLenient(CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING)); this.precision = precision; } public Iso8601(String pattern, int precision, TimeZone tz) { this(Dates.getCurrentTimeRounded(), pattern, precision, tz); } public Iso8601(Date time, String pattern, int precision, TimeZone tz) { this(time.getTime(), pattern, precision, tz); } public String toString() { TimeZone timeZone = this.format.getTimeZone(); if (timeZone instanceof TimeZone) { return this.format.format(this); } if (this.gmtFormat == null) { this.gmtFormat = (DateFormat) this.format.clone(); this.gmtFormat.setTimeZone(TimeZone.getTimeZone(TimeZones.GMT_ID)); } if (timeZone.inDaylightTime(this) && timeZone.inDaylightTime(new Date(getTime() - 1))) { return this.gmtFormat.format(new Date((getTime() + ((long) timeZone.getRawOffset())) + ((long) timeZone.getDSTSavings()))); } return this.gmtFormat.format(new Date(getTime() + ((long) timeZone.getRawOffset()))); } protected final DateFormat getFormat() { return this.format; } public void setTime(long time) { if (this.format != null) { super.setTime(Dates.round(time, this.precision, this.format.getTimeZone())); } else { super.setTime(time); } } }
UTF-8
Java
2,144
java
Iso8601.java
Java
[]
null
[]
package net.fortuna.ical4j.model; import java.text.DateFormat; import java.util.Date; import java.util.TimeZone; import net.fortuna.ical4j.util.CompatibilityHints; import net.fortuna.ical4j.util.Dates; import net.fortuna.ical4j.util.TimeZones; public abstract class Iso8601 extends Date { private static final long serialVersionUID = -4290728005713946811L; private DateFormat format; private DateFormat gmtFormat; private int precision; public Iso8601(long time, String pattern, int precision, TimeZone tz) { super(Dates.round(time, precision, tz)); this.format = CalendarDateFormatFactory.getInstance(pattern); this.format.setTimeZone(tz); this.format.setLenient(CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING)); this.precision = precision; } public Iso8601(String pattern, int precision, TimeZone tz) { this(Dates.getCurrentTimeRounded(), pattern, precision, tz); } public Iso8601(Date time, String pattern, int precision, TimeZone tz) { this(time.getTime(), pattern, precision, tz); } public String toString() { TimeZone timeZone = this.format.getTimeZone(); if (timeZone instanceof TimeZone) { return this.format.format(this); } if (this.gmtFormat == null) { this.gmtFormat = (DateFormat) this.format.clone(); this.gmtFormat.setTimeZone(TimeZone.getTimeZone(TimeZones.GMT_ID)); } if (timeZone.inDaylightTime(this) && timeZone.inDaylightTime(new Date(getTime() - 1))) { return this.gmtFormat.format(new Date((getTime() + ((long) timeZone.getRawOffset())) + ((long) timeZone.getDSTSavings()))); } return this.gmtFormat.format(new Date(getTime() + ((long) timeZone.getRawOffset()))); } protected final DateFormat getFormat() { return this.format; } public void setTime(long time) { if (this.format != null) { super.setTime(Dates.round(time, this.precision, this.format.getTimeZone())); } else { super.setTime(time); } } }
2,144
0.667444
0.648787
58
35.965519
31.170259
135
false
false
0
0
0
0
0
0
0.775862
false
false
12
bf29d49f05f5583816b08b88efa25e618bc63671
25,254,407,722,993
b022e4186b94e1e8bace4d5c9c61857850ed71d8
/src/main/java/Model/StorageUtil.java
fca3c14cf5a2671e5c4f14ecd9b22269795c06c8
[]
no_license
Tocico/book-library
https://github.com/Tocico/book-library
cf8b7a7c1794a61a3e11ea2337423c89e4b6cff6
a0cb3467fce516d86d1c3398f4e40eb39c407b7b
refs/heads/master
2023-01-30T15:41:33.660000
2020-12-14T08:01:52
2020-12-14T08:01:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Model; import java.io.*; import java.util.List; public class StorageUtil { String path; public StorageUtil(String dbName) throws FileNotFoundException, IOException { path = "data/" + dbName + ".ser"; File file = new File(path); file.createNewFile(); } public void serializeStoreList(List<?> list) throws IOException { FileOutputStream fileOutput = new FileOutputStream(path); ObjectOutputStream objOutput = new ObjectOutputStream(fileOutput); System.out.println("Recieved:" + list); objOutput.writeObject(list); System.out.println("List serialization and store success!"); objOutput.close(); fileOutput.close(); } public <T> List<T> deserializeReadList() throws ClassNotFoundException, IOException { List<T> list = null; FileInputStream fileInput = new FileInputStream(path); ObjectInputStream objInput = new ObjectInputStream(fileInput); list = (List<T>) objInput.readObject(); objInput.close(); fileInput.close(); System.out.println("List deserialization and read success!"); return list; } }
UTF-8
Java
1,204
java
StorageUtil.java
Java
[]
null
[]
package Model; import java.io.*; import java.util.List; public class StorageUtil { String path; public StorageUtil(String dbName) throws FileNotFoundException, IOException { path = "data/" + dbName + ".ser"; File file = new File(path); file.createNewFile(); } public void serializeStoreList(List<?> list) throws IOException { FileOutputStream fileOutput = new FileOutputStream(path); ObjectOutputStream objOutput = new ObjectOutputStream(fileOutput); System.out.println("Recieved:" + list); objOutput.writeObject(list); System.out.println("List serialization and store success!"); objOutput.close(); fileOutput.close(); } public <T> List<T> deserializeReadList() throws ClassNotFoundException, IOException { List<T> list = null; FileInputStream fileInput = new FileInputStream(path); ObjectInputStream objInput = new ObjectInputStream(fileInput); list = (List<T>) objInput.readObject(); objInput.close(); fileInput.close(); System.out.println("List deserialization and read success!"); return list; } }
1,204
0.64701
0.64701
35
33.400002
27.173727
89
false
false
0
0
0
0
0
0
0.685714
false
false
12
4fb5602b38fb49ce0e40f943950bcee3bcd350b3
13,116,830,151,652
773974a99a640474ef1aeb681ce0ff5e83f5eda6
/src/main/java/com/learningmicroservice/userrestaurantmapping/service/UserRestaurantMapping.java
262e3aab50822df3846d32b34f229b5f7b5b81b8
[]
no_license
swathysrinath/learningspringboot
https://github.com/swathysrinath/learningspringboot
cd88980caf30dcb379ff48aa3420474e6c730d35
2c486e30e50258f2a504488a47ad70d23e982ce9
refs/heads/main
2023-04-17T22:20:50.902000
2021-04-27T14:37:43
2021-04-27T14:37:43
360,780,271
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.learningmicroservice.userrestaurantmapping.service; import java.util.Arrays; import java.util.HashMap; import java.util.List; import com.learningmicroservice.userrestaurantmapping.model.UserDetails; public class UserRestaurantMapping { public UserDetails getMapping(String restaurantName){ return getUserIds(restaurantName); } private UserDetails getUserIds(String name){ HashMap<String,UserDetails> getUserIds = new HashMap(); getUserIds.put("annaporna", new UserDetails(Arrays.asList("swa123","sri89"))); getUserIds.put("creamcenter", new UserDetails(Arrays.asList("cha20"))); getUserIds.put("pind", new UserDetails(Arrays.asList("cha20","swa123"))); getUserIds.put("kailashparbath", new UserDetails(Arrays.asList("cha20","swa123","sri89"))); return getUserIds.get(name); } }
UTF-8
Java
829
java
UserRestaurantMapping.java
Java
[ { "context": "ls> getUserIds = new HashMap();\n\t\tgetUserIds.put(\"annaporna\", new UserDetails(Arrays.asList(\"swa123\",\"sri89\")", "end": 491, "score": 0.999434769153595, "start": 482, "tag": "USERNAME", "value": "annaporna" }, { "context": "ays.asList(\"swa123\",\"sri89\")));\n\t\tgetUserIds.put(\"creamcenter\", new UserDetails(Arrays.asList(\"cha20\")));\n\t\tget", "end": 574, "score": 0.8704173564910889, "start": 563, "tag": "USERNAME", "value": "creamcenter" }, { "context": "tails(Arrays.asList(\"cha20\")));\n\t\tgetUserIds.put(\"pind\", new UserDetails(Arrays.asList(\"cha20\",\"swa123\")", "end": 641, "score": 0.9162114262580872, "start": 637, "tag": "USERNAME", "value": "pind" }, { "context": "ays.asList(\"cha20\",\"swa123\")));\n\t\tgetUserIds.put(\"kailashparbath\", new UserDetails(Arrays.asList(\"cha20\",\"swa123\",", "end": 727, "score": 0.9993515014648438, "start": 713, "tag": "USERNAME", "value": "kailashparbath" } ]
null
[]
package com.learningmicroservice.userrestaurantmapping.service; import java.util.Arrays; import java.util.HashMap; import java.util.List; import com.learningmicroservice.userrestaurantmapping.model.UserDetails; public class UserRestaurantMapping { public UserDetails getMapping(String restaurantName){ return getUserIds(restaurantName); } private UserDetails getUserIds(String name){ HashMap<String,UserDetails> getUserIds = new HashMap(); getUserIds.put("annaporna", new UserDetails(Arrays.asList("swa123","sri89"))); getUserIds.put("creamcenter", new UserDetails(Arrays.asList("cha20"))); getUserIds.put("pind", new UserDetails(Arrays.asList("cha20","swa123"))); getUserIds.put("kailashparbath", new UserDetails(Arrays.asList("cha20","swa123","sri89"))); return getUserIds.get(name); } }
829
0.764777
0.741858
29
27.586206
30.217051
93
false
false
0
0
0
0
0
0
1.689655
false
false
12
a04c35cfb724483ae7d002a4260d3abbeb4e842c
14,757,507,632,087
c523b5705ab447cc2134473e531c45d63231749a
/src/observer/Subject.java
1d97a173b8337fd9072da88d82a9555eb0a5e2f8
[]
no_license
cclouds/design_pattern
https://github.com/cclouds/design_pattern
424a0d692f7ec2fd7f056de5750992f74d09ffcc
cb7f1bf6dd24eb83d026b63b9e556af6bef2a07d
refs/heads/master
2021-01-10T13:25:58.898000
2017-06-07T03:46:33
2017-06-07T03:46:33
49,691,957
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package observer; import java.util.ArrayList; import java.util.List; /** * 抽象主题(Subject)角色: * 抽象主题角色把所有对观察者对象的引用保存在一个聚集(比如ArrayList对象)里, * 每个主题都可以有任何数量的观察者。抽象主题提供一个接口, * 可以增加和删除观察者对象,抽象主题角色又叫做抽象被观察者(Observable)角色。 * @author user * */ public abstract class Subject { private List<Observer> list = new ArrayList<Observer>(); /* * 增加观察者对象 */ public void attach(Observer observer){ list.add(observer); System.out.println("attached an observer"); } /* * 删除观察者对象 */ public void detch(Observer observer){ list.remove(observer); System.out.println("detched an observer"); } /* * 通知所有的观察者对象 */ public void notifyObservers(String newState){ for(Observer o : list){ o.update(newState); } } }
UTF-8
Java
1,034
java
Subject.java
Java
[ { "context": "删除观察者对象,抽象主题角色又叫做抽象被观察者(Observable)角色。\r\n * @author user\r\n *\r\n */\r\npublic abstract class Subject {\r\n\tpriva", "end": 245, "score": 0.9974807500839233, "start": 241, "tag": "USERNAME", "value": "user" } ]
null
[]
package observer; import java.util.ArrayList; import java.util.List; /** * 抽象主题(Subject)角色: * 抽象主题角色把所有对观察者对象的引用保存在一个聚集(比如ArrayList对象)里, * 每个主题都可以有任何数量的观察者。抽象主题提供一个接口, * 可以增加和删除观察者对象,抽象主题角色又叫做抽象被观察者(Observable)角色。 * @author user * */ public abstract class Subject { private List<Observer> list = new ArrayList<Observer>(); /* * 增加观察者对象 */ public void attach(Observer observer){ list.add(observer); System.out.println("attached an observer"); } /* * 删除观察者对象 */ public void detch(Observer observer){ list.remove(observer); System.out.println("detched an observer"); } /* * 通知所有的观察者对象 */ public void notifyObservers(String newState){ for(Observer o : list){ o.update(newState); } } }
1,034
0.645939
0.645939
45
15.511111
16.541695
57
false
false
0
0
0
0
0
0
1.088889
false
false
12
c654e7115f26505f4aec144199ba4579f8b261ba
24,781,961,308,214
99e7e34054d67fde190f6a87001c801100f1b4a6
/JavaSE2/Method/src/method_reference/method_reference_01/PrintableImpl.java
732e33f451645c6608c2fa27065b6bc9bbc75abc
[]
no_license
GuangkunYu/Java
https://github.com/GuangkunYu/Java
759999b809ec62df44cb47386fa2ce031c27f92f
649aab562e4dd8f0ffea3ebdb05cce0a1d291b73
refs/heads/master
2023-01-12T15:37:46.298000
2020-11-17T11:27:52
2020-11-17T11:27:52
283,760,278
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package method_reference.method_reference_01; public class PrintableImpl implements Printable { @Override public void printString(String s) { System.out.println(s + "什么玩意"); } }
UTF-8
Java
207
java
PrintableImpl.java
Java
[]
null
[]
package method_reference.method_reference_01; public class PrintableImpl implements Printable { @Override public void printString(String s) { System.out.println(s + "什么玩意"); } }
207
0.698492
0.688442
8
23.875
19.694145
49
false
false
0
0
0
0
0
0
0.25
false
false
12
bf3d66dbd25b6bf5f790e59062128a45e78a7181
19,662,360,297,784
f8863c701650a764425d13b6e42be24615d10844
/rpc-core/src/main/java/com/amao/rpc/core/example/HelloService.java
7d139526f97f45b5daad6c283d6c7bee5c520bb9
[]
no_license
the200m/amao-rpc
https://github.com/the200m/amao-rpc
e9060e0d27e76b3ae4910ce996789301a635bda0
9c0f15d1787cae7dfbfb8e1f9d9fc7d5ec6b944e
refs/heads/master
2021-01-19T05:16:41.319000
2016-07-23T16:18:52
2016-07-23T16:18:52
64,024,842
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amao.rpc.core.example; import java.util.Date; /** * Created by 阿毛 on 2016/6/7. */ public interface HelloService { String hello(String content, Date date); }
UTF-8
Java
182
java
HelloService.java
Java
[ { "context": "ample;\n\nimport java.util.Date;\n\n/**\n * Created by 阿毛 on 2016/6/7.\n */\n\npublic interface HelloService {", "end": 80, "score": 0.9767810702323914, "start": 78, "tag": "NAME", "value": "阿毛" } ]
null
[]
package com.amao.rpc.core.example; import java.util.Date; /** * Created by 阿毛 on 2016/6/7. */ public interface HelloService { String hello(String content, Date date); }
182
0.696629
0.662921
11
15.181818
16.129128
44
false
false
0
0
0
0
0
0
0.363636
false
false
12
d46aead1d4e124ac9ddfdd9b26384e8b8f1e6829
14,362,370,665,164
ddd1be3eda74bd7ba2bafdc2fc5c52904702847f
/src/de/javafish/html/HtmlHidden.java
9bf16422089ad87d62c5ec5c508de1f277bc9f47
[]
no_license
javafish-de/tools
https://github.com/javafish-de/tools
ec0eab548480285db43e431517f9efb1f77b1153
2bc9f2b6afdfb62fa5a76e0b2ec02a756bd16431
refs/heads/master
2021-01-09T05:43:04.920000
2017-02-03T10:59:00
2017-02-03T10:59:00
80,817,279
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.javafish.html; import de.javafish.html.tags.*; public class HtmlHidden extends Html { private HtmlHidden() { tag = new HtmlTagInput(); tag.addAttribute("type", "hidden"); } public HtmlHidden(String name, String value) { this(); tag.addAttribute("name", name); tag.addAttribute("value", value); } }
UTF-8
Java
379
java
HtmlHidden.java
Java
[]
null
[]
package de.javafish.html; import de.javafish.html.tags.*; public class HtmlHidden extends Html { private HtmlHidden() { tag = new HtmlTagInput(); tag.addAttribute("type", "hidden"); } public HtmlHidden(String name, String value) { this(); tag.addAttribute("name", name); tag.addAttribute("value", value); } }
379
0.596306
0.596306
18
20
17.406895
50
false
false
0
0
0
0
0
0
0.611111
false
false
12
51717cb4a8ccaafcb185911b964de7e53acec344
14,362,370,662,822
5f13563b4e72b81106e494f54135e71c27088082
/src/main/java/com/cofface/b.java
795e6523dd1cf78c8160849a8cd11d5c0f052c5c
[ "MIT" ]
permissive
fstwsr/HiddenCore
https://github.com/fstwsr/HiddenCore
29a892bd2ba59d2823f692cd7ad15f6d267b115c
597b5c55628f8c7935a28a535638391cb6a557cc
refs/heads/master
2022-04-05T18:43:19.441000
2020-01-19T06:49:47
2020-01-19T06:49:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cofface; import android.content.Context; public class b { private int a; private String b; public b(int i, String str) { this.a = i; this.b = str; } public b(Context context) { } public String a() { return this.b; } public void a(int i) { this.a = i; } public void a(String str) { this.b = str; } public int b() { return 0; } }
UTF-8
Java
452
java
b.java
Java
[]
null
[]
package com.cofface; import android.content.Context; public class b { private int a; private String b; public b(int i, String str) { this.a = i; this.b = str; } public b(Context context) { } public String a() { return this.b; } public void a(int i) { this.a = i; } public void a(String str) { this.b = str; } public int b() { return 0; } }
452
0.5
0.497788
32
13.125
11.199191
33
false
false
0
0
0
0
0
0
0.34375
false
false
12
179aca4d66e46ae0d89e12cf7fa0c65e9fd1d28b
13,666,585,996,486
1544d4e5c3ec2cd9afdb00a1ba6d71d8cf9f19a2
/src/test/java/io/xlate/edi/internal/schema/SyntaxRestrictionTest.java
41829def59a68309108c8da114c08cec100edd6b
[ "Apache-2.0" ]
permissive
sandeepkumar101/staedi
https://github.com/sandeepkumar101/staedi
b82b2ee3d2b12c4deb90d6b18616cdbbc5d32004
9c7ca1b4340739974bd3aac123c1db31832173c1
refs/heads/master
2022-04-23T17:59:01.609000
2020-05-02T14:05:28
2020-05-02T14:05:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.xlate.edi.internal.schema; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Arrays; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDISyntaxRule; public class SyntaxRestrictionTest { @Test public void testConstructorEmptyList() { assertThrows(IllegalArgumentException.class, () -> new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList())); } @Test public void testToString() { EDISyntaxRule rule = new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList(1, 2)); assertEquals("type: PAIRED, positions: [1, 2]", rule.toString()); } @Test public void testGetType() { EDISyntaxRule rule = new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList(1, 2)); assertEquals(EDISyntaxRule.Type.PAIRED, rule.getType()); } @Test public void testGetPositions() { EDISyntaxRule rule = new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList(1, 2)); assertEquals(Arrays.asList(1, 2), rule.getPositions()); } }
UTF-8
Java
1,152
java
SyntaxRestrictionTest.java
Java
[]
null
[]
package io.xlate.edi.internal.schema; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Arrays; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDISyntaxRule; public class SyntaxRestrictionTest { @Test public void testConstructorEmptyList() { assertThrows(IllegalArgumentException.class, () -> new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList())); } @Test public void testToString() { EDISyntaxRule rule = new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList(1, 2)); assertEquals("type: PAIRED, positions: [1, 2]", rule.toString()); } @Test public void testGetType() { EDISyntaxRule rule = new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList(1, 2)); assertEquals(EDISyntaxRule.Type.PAIRED, rule.getType()); } @Test public void testGetPositions() { EDISyntaxRule rule = new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList(1, 2)); assertEquals(Arrays.asList(1, 2), rule.getPositions()); } }
1,152
0.711806
0.703125
37
30.135136
34.481613
126
false
false
0
0
0
0
0
0
0.72973
false
false
12
16a1ec4beba3d996a0c83b3b126c7f27c92dc3ec
5,471,788,335,428
6dbf86830ba19c90ffc2d9c7759fa2cca8ee3d96
/android/scteam/app/src/main/java/pt/pepdevils/scteam/activities/TVActivity.java
dad5dcbfa66a265c304bfc55ce225ce829e450ec
[]
no_license
PepDevils/SC-Team-App
https://github.com/PepDevils/SC-Team-App
3461cf827ed49eb7747dc7505535f43183be2147
22937e9a1863a5720695fb3925ad00a86e90fd3b
refs/heads/master
2020-03-23T15:18:12.090000
2018-07-20T17:12:02
2018-07-20T17:12:02
141,736,764
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pt.pepdevils.scteam.activities; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.drawable.AnimationDrawable; import android.net.http.SslError; import android.os.Build; import android.preference.PreferenceManager; import android.support.v4.widget.NestedScrollView; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.SslErrorHandler; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import pt.pepdevils.scteam.Helper; import pt.pepdevils.scteam.R; import pt.pepdevils.scteam.custom.PepeDialogBuilder; import pt.pepdevils.scteam.custom.PepeDialogTutorial; public class TVActivity extends AppCompatActivity { private WebView webView; private FrameLayout customViewContainer; private WebChromeClient.CustomViewCallback customViewCallback; private View mCustomView; private myWebChromeClient mWebChromeClient; private myWebViewClient mWebViewClient; private SwipeRefreshLayout swipeContainer; private View ll_header; private ImageView img; private ProgressBar pr_bar_rot; private float dens; private String video_url; private NestedScrollView scrollNested; private LinearLayout lili; private boolean isBigSized; private boolean isOpenFirstTime = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tv); if (getIntent().getExtras() != null) { video_url = getIntent().getExtras().getString("video"); } UI(); STARTVIDEOFROMWEBVIEW(); REFRESHVIEW(); } @Override protected void onResume() { super.onResume(); webView.onResume(); AnimateAndChangeLayout(); ChangeBackIfHeight(); Helper.WarningInternetSnack(this); TutorialForRefres(); } @Override protected void onPause() { super.onPause(); webView.onPause(); } @Override protected void onStop() { super.onStop(); if (inCustomView()) { hideCustomView(); } } @Override protected void onSaveInstanceState(Bundle outState) { webView.saveState(outState); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); AnimateAndChangeLayout(); TutorialForRefres(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (inCustomView()) { hideCustomView(); return true; } if ((mCustomView == null) && webView.canGoBack()) { webView.goBack(); return true; } } return super.onKeyDown(keyCode, event); } @Override public void onBackPressed() { String TitleColor = getResources().getString(0 + R.color.colorPrimary); String DividerColor = getResources().getString(0 + R.color.colorPrimary); String MessageColor = getResources().getString(0 + R.color.colorPrimary); String DialogColor_ = getResources().getString(0 + R.color.colorAccent); PepeDialogBuilder pepeDialogBuilder = PepeDialogBuilder.getInstance(TVActivity.this); pepeDialogBuilder .withTitle("Aviso") .withMessage("Deseja sair da TV ?") .withMessageCenter(true) .withTitleColor(TitleColor) .withDividerColor(DividerColor) .withMessageColor(MessageColor) .withDialogColor(DialogColor_) .withIcon(getResources().getDrawable(R.mipmap.ic_launcher)) .isCancelableOnTouchOutside(true) .withButton1Text("Sim") .setButton1Click(new View.OnClickListener() { @Override public void onClick(View v) { pepeDialogBuilder.dismiss(); finish(); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } }) .withButton2Text("Não") .setButton2Click(new View.OnClickListener() { @Override public void onClick(View v) { pepeDialogBuilder.dismiss(); } }) .show(); } private void UI() { webView = (WebView) findViewById(R.id.webView); swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer); scrollNested = (NestedScrollView) findViewById(R.id.scrollNested); lili = (LinearLayout) findViewById(R.id.lili); ll_header = findViewById(R.id.ll_header); img = (ImageView) findViewById(R.id.img); img.bringToFront(); pr_bar_rot = (ProgressBar) findViewById(R.id.pr_bar_rot); } private void STARTVIDEOFROMWEBVIEW() { mWebViewClient = new myWebViewClient(); mWebChromeClient = new myWebChromeClient(); webView.setWebViewClient(mWebViewClient); webView.setWebChromeClient(mWebChromeClient); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setAppCacheEnabled(true); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setSaveFormData(true); webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); webView.setScrollContainer(false); webView.setVerticalScrollBarEnabled(false); webView.setHorizontalScrollBarEnabled(false); // disable scroll on touch webView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return (event.getAction() == MotionEvent.ACTION_MOVE); } }); //load do video, novo ou antigo guardado na memoria SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (video_url != null) { if (video_url.equalsIgnoreCase("")) { video_url = appSharedPrefs.getString("VIDEO_URL", "https://mycujoo.tv/embed/260?vid=14363"); Helper.WarningInternetSnack(this); webView.loadUrl(video_url); } else { webView.loadUrl(video_url); } } else { video_url = appSharedPrefs.getString("VIDEO_URL", "https://mycujoo.tv/embed/260?vid=14363"); Helper.WarningInternetSnack(this); webView.loadUrl(video_url); } } private void REFRESHVIEW() { // https://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { swipeContainer.setColorSchemeColors(getResources().getColor(R.color.colorPrimary, null), getResources().getColor(android.R.color.white, null)); } else { swipeContainer.setColorSchemeColors(getResources().getColor(R.color.colorPrimary), getResources().getColor(android.R.color.white)); } swipeContainer.setProgressBackgroundColorSchemeResource(android.R.color.transparent); swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { webView.setVisibility(View.GONE); pr_bar_rot.setVisibility(View.VISIBLE); STARTVIDEOFROMWEBVIEW(); Helper.WarningInternetSnack(TVActivity.this); swipeContainer.setRefreshing(false); } }); } private void TutorialForRefres() { SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); isOpenFirstTime = appSharedPrefs.getBoolean("isOpenFirstTime", true); //open first time? if (isOpenFirstTime) { PepeDialogTutorial pepDT = PepeDialogTutorial.getInstance(this); pepDT.setButton1Click(new View.OnClickListener() { @Override public void onClick(View view) { pepDT.dismiss(); } }); pepDT.setButton2Click(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences.Editor prefsEditor = appSharedPrefs.edit(); prefsEditor.putBoolean("isOpenFirstTime", false); prefsEditor.apply(); pepDT.dismiss(); } }); pepDT.show(); } } private void ChangeBackIfHeight() { LinearLayout lili = (LinearLayout) findViewById(R.id.lili); NestedScrollView scrollNested = (NestedScrollView) findViewById(R.id.scrollNested); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int h = (int) (dm.heightPixels / dm.scaledDensity); int alt_dra = 0; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { alt_dra = getResources().getDrawable(R.drawable.backbtv, null).getIntrinsicHeight(); } else { alt_dra = getResources().getDrawable(R.drawable.backbtv).getIntrinsicHeight(); } if (h <= alt_dra) { isBigSized = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { lili.setBackground(getResources().getDrawable(R.drawable.croped_back, null)); } else { lili.setBackground(getResources().getDrawable(R.drawable.croped_back)); } } else { isBigSized = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { lili.setBackgroundColor(getResources().getColor(android.R.color.darker_gray, null)); scrollNested.setBackgroundColor(getResources().getColor(android.R.color.darker_gray, null)); } else { lili.setBackgroundColor(getResources().getColor(android.R.color.darker_gray)); scrollNested.setBackgroundColor(getResources().getColor(android.R.color.darker_gray)); } } } private void AnimateAndChangeLayout() { int orientation = getResources().getConfiguration().orientation; dens = getResources().getDisplayMetrics().density; int h_port = (int) (100 * dens); int h_land = (int) (48 * dens); int margin_top_port = (int) (10 * dens); int margin_land = (int) (6.5 * dens); int margin_web_top_land = (int) (110 * dens); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT); LinearLayout.LayoutParams ll_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT); if (orientation == 1) { //port if (!customViewContainer.isShown()) { params.addRule(RelativeLayout.CENTER_HORIZONTAL); params.setMargins(0, margin_top_port, 0, 0); img.setLayoutParams(params); img.getLayoutParams().height = h_port; img.getLayoutParams().width = h_port; ll_params.setMargins(0, margin_web_top_land, 0, 0); webView.setLayoutParams(ll_params); customViewContainer.setLayoutParams(ll_params); int width_screen = getResources().getDisplayMetrics().widthPixels; int aux = (int) (width_screen * 0.5625); webView.getLayoutParams().height = aux; } } else { //land if (!customViewContainer.isShown()) { params.addRule(RelativeLayout.ALIGN_BOTTOM | RelativeLayout.ALIGN_PARENT_RIGHT); params.setMargins(0, margin_land, margin_land, 0); img.setLayoutParams(params); img.getLayoutParams().height = h_land; img.getLayoutParams().width = h_land; ll_params.setMargins(0, (int) (10 * dens), 0, 0); webView.setLayoutParams(ll_params); customViewContainer.setLayoutParams(ll_params); int width_screen = getResources().getDisplayMetrics().widthPixels; int aux = (int) (width_screen * 0.5625); webView.getLayoutParams().height = aux; } } } public boolean inCustomView() { return (mCustomView != null); } public void hideCustomView() { mWebChromeClient.onHideCustomView(); } class myWebChromeClient extends WebChromeClient { private View mVideoProgressView; @Override public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { onShowCustomView(view, callback); //To change body of overridden methods use File | Settings | File Templates. } @Override public View getVideoLoadingProgressView() { if (mVideoProgressView == null) { LayoutInflater inflater = LayoutInflater.from(TVActivity.this); mVideoProgressView = inflater.inflate(R.layout.video_progress, null); } return mVideoProgressView; } @Override public void onHideCustomView() { super.onHideCustomView(); if (mCustomView == null) return; Helper.ShowStatusBar(TVActivity.this); webView.setVisibility(View.VISIBLE); ll_header.setVisibility(View.VISIBLE); img.setVisibility(View.VISIBLE); if (isBigSized) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { lili.setBackgroundColor(getResources().getColor(android.R.color.darker_gray, null)); } else { lili.setBackgroundColor(getResources().getColor(android.R.color.darker_gray)); } } else { lili.setBackground(getResources().getDrawable(R.drawable.croped_back)); } // Hide the custom view. customViewContainer.setVisibility(View.GONE); mCustomView.setVisibility(View.GONE); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // Remove the custom view from its container. customViewContainer.removeView(mCustomView); customViewContainer.setLayoutParams(params); customViewCallback.onCustomViewHidden(); AnimateAndChangeLayout(); mCustomView = null; FrameLayout.LayoutParams params_f = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); lili.setLayoutParams(params_f); } @Override public void onShowCustomView(View view, CustomViewCallback callback) { // if a view already exists then immediately terminate the new one if (mCustomView != null) { callback.onCustomViewHidden(); return; } mCustomView = view; webView.setVisibility(View.GONE); img.setVisibility(View.GONE); ll_header.setVisibility(View.GONE); customViewContainer.setVisibility(View.VISIBLE); customViewContainer.addView(view); customViewCallback = callback; LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); params.setMargins(0, 0, 0, 0); customViewContainer.setLayoutParams(params); FrameLayout.LayoutParams params_f = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); params_f.gravity = Gravity.CENTER; lili.setBackgroundColor(getResources().getColor(android.R.color.black)); lili.setLayoutParams(params_f); customViewContainer.setLayoutParams(params); Helper.HideStatusBar(TVActivity.this); } } class myWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return super.shouldOverrideUrlLoading(view, request); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); pr_bar_rot.setVisibility(View.GONE); webView.setVisibility(View.VISIBLE); } @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.onReceivedHttpError(view, request, errorResponse); //webView.setVisibility(View.INVISIBLE); } } }
UTF-8
Java
18,275
java
TVActivity.java
Java
[]
null
[]
package pt.pepdevils.scteam.activities; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.drawable.AnimationDrawable; import android.net.http.SslError; import android.os.Build; import android.preference.PreferenceManager; import android.support.v4.widget.NestedScrollView; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.SslErrorHandler; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import pt.pepdevils.scteam.Helper; import pt.pepdevils.scteam.R; import pt.pepdevils.scteam.custom.PepeDialogBuilder; import pt.pepdevils.scteam.custom.PepeDialogTutorial; public class TVActivity extends AppCompatActivity { private WebView webView; private FrameLayout customViewContainer; private WebChromeClient.CustomViewCallback customViewCallback; private View mCustomView; private myWebChromeClient mWebChromeClient; private myWebViewClient mWebViewClient; private SwipeRefreshLayout swipeContainer; private View ll_header; private ImageView img; private ProgressBar pr_bar_rot; private float dens; private String video_url; private NestedScrollView scrollNested; private LinearLayout lili; private boolean isBigSized; private boolean isOpenFirstTime = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tv); if (getIntent().getExtras() != null) { video_url = getIntent().getExtras().getString("video"); } UI(); STARTVIDEOFROMWEBVIEW(); REFRESHVIEW(); } @Override protected void onResume() { super.onResume(); webView.onResume(); AnimateAndChangeLayout(); ChangeBackIfHeight(); Helper.WarningInternetSnack(this); TutorialForRefres(); } @Override protected void onPause() { super.onPause(); webView.onPause(); } @Override protected void onStop() { super.onStop(); if (inCustomView()) { hideCustomView(); } } @Override protected void onSaveInstanceState(Bundle outState) { webView.saveState(outState); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); AnimateAndChangeLayout(); TutorialForRefres(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (inCustomView()) { hideCustomView(); return true; } if ((mCustomView == null) && webView.canGoBack()) { webView.goBack(); return true; } } return super.onKeyDown(keyCode, event); } @Override public void onBackPressed() { String TitleColor = getResources().getString(0 + R.color.colorPrimary); String DividerColor = getResources().getString(0 + R.color.colorPrimary); String MessageColor = getResources().getString(0 + R.color.colorPrimary); String DialogColor_ = getResources().getString(0 + R.color.colorAccent); PepeDialogBuilder pepeDialogBuilder = PepeDialogBuilder.getInstance(TVActivity.this); pepeDialogBuilder .withTitle("Aviso") .withMessage("Deseja sair da TV ?") .withMessageCenter(true) .withTitleColor(TitleColor) .withDividerColor(DividerColor) .withMessageColor(MessageColor) .withDialogColor(DialogColor_) .withIcon(getResources().getDrawable(R.mipmap.ic_launcher)) .isCancelableOnTouchOutside(true) .withButton1Text("Sim") .setButton1Click(new View.OnClickListener() { @Override public void onClick(View v) { pepeDialogBuilder.dismiss(); finish(); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } }) .withButton2Text("Não") .setButton2Click(new View.OnClickListener() { @Override public void onClick(View v) { pepeDialogBuilder.dismiss(); } }) .show(); } private void UI() { webView = (WebView) findViewById(R.id.webView); swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer); scrollNested = (NestedScrollView) findViewById(R.id.scrollNested); lili = (LinearLayout) findViewById(R.id.lili); ll_header = findViewById(R.id.ll_header); img = (ImageView) findViewById(R.id.img); img.bringToFront(); pr_bar_rot = (ProgressBar) findViewById(R.id.pr_bar_rot); } private void STARTVIDEOFROMWEBVIEW() { mWebViewClient = new myWebViewClient(); mWebChromeClient = new myWebChromeClient(); webView.setWebViewClient(mWebViewClient); webView.setWebChromeClient(mWebChromeClient); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setAppCacheEnabled(true); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setSaveFormData(true); webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); webView.setScrollContainer(false); webView.setVerticalScrollBarEnabled(false); webView.setHorizontalScrollBarEnabled(false); // disable scroll on touch webView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return (event.getAction() == MotionEvent.ACTION_MOVE); } }); //load do video, novo ou antigo guardado na memoria SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (video_url != null) { if (video_url.equalsIgnoreCase("")) { video_url = appSharedPrefs.getString("VIDEO_URL", "https://mycujoo.tv/embed/260?vid=14363"); Helper.WarningInternetSnack(this); webView.loadUrl(video_url); } else { webView.loadUrl(video_url); } } else { video_url = appSharedPrefs.getString("VIDEO_URL", "https://mycujoo.tv/embed/260?vid=14363"); Helper.WarningInternetSnack(this); webView.loadUrl(video_url); } } private void REFRESHVIEW() { // https://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { swipeContainer.setColorSchemeColors(getResources().getColor(R.color.colorPrimary, null), getResources().getColor(android.R.color.white, null)); } else { swipeContainer.setColorSchemeColors(getResources().getColor(R.color.colorPrimary), getResources().getColor(android.R.color.white)); } swipeContainer.setProgressBackgroundColorSchemeResource(android.R.color.transparent); swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { webView.setVisibility(View.GONE); pr_bar_rot.setVisibility(View.VISIBLE); STARTVIDEOFROMWEBVIEW(); Helper.WarningInternetSnack(TVActivity.this); swipeContainer.setRefreshing(false); } }); } private void TutorialForRefres() { SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); isOpenFirstTime = appSharedPrefs.getBoolean("isOpenFirstTime", true); //open first time? if (isOpenFirstTime) { PepeDialogTutorial pepDT = PepeDialogTutorial.getInstance(this); pepDT.setButton1Click(new View.OnClickListener() { @Override public void onClick(View view) { pepDT.dismiss(); } }); pepDT.setButton2Click(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences.Editor prefsEditor = appSharedPrefs.edit(); prefsEditor.putBoolean("isOpenFirstTime", false); prefsEditor.apply(); pepDT.dismiss(); } }); pepDT.show(); } } private void ChangeBackIfHeight() { LinearLayout lili = (LinearLayout) findViewById(R.id.lili); NestedScrollView scrollNested = (NestedScrollView) findViewById(R.id.scrollNested); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int h = (int) (dm.heightPixels / dm.scaledDensity); int alt_dra = 0; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { alt_dra = getResources().getDrawable(R.drawable.backbtv, null).getIntrinsicHeight(); } else { alt_dra = getResources().getDrawable(R.drawable.backbtv).getIntrinsicHeight(); } if (h <= alt_dra) { isBigSized = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { lili.setBackground(getResources().getDrawable(R.drawable.croped_back, null)); } else { lili.setBackground(getResources().getDrawable(R.drawable.croped_back)); } } else { isBigSized = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { lili.setBackgroundColor(getResources().getColor(android.R.color.darker_gray, null)); scrollNested.setBackgroundColor(getResources().getColor(android.R.color.darker_gray, null)); } else { lili.setBackgroundColor(getResources().getColor(android.R.color.darker_gray)); scrollNested.setBackgroundColor(getResources().getColor(android.R.color.darker_gray)); } } } private void AnimateAndChangeLayout() { int orientation = getResources().getConfiguration().orientation; dens = getResources().getDisplayMetrics().density; int h_port = (int) (100 * dens); int h_land = (int) (48 * dens); int margin_top_port = (int) (10 * dens); int margin_land = (int) (6.5 * dens); int margin_web_top_land = (int) (110 * dens); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT); LinearLayout.LayoutParams ll_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT); if (orientation == 1) { //port if (!customViewContainer.isShown()) { params.addRule(RelativeLayout.CENTER_HORIZONTAL); params.setMargins(0, margin_top_port, 0, 0); img.setLayoutParams(params); img.getLayoutParams().height = h_port; img.getLayoutParams().width = h_port; ll_params.setMargins(0, margin_web_top_land, 0, 0); webView.setLayoutParams(ll_params); customViewContainer.setLayoutParams(ll_params); int width_screen = getResources().getDisplayMetrics().widthPixels; int aux = (int) (width_screen * 0.5625); webView.getLayoutParams().height = aux; } } else { //land if (!customViewContainer.isShown()) { params.addRule(RelativeLayout.ALIGN_BOTTOM | RelativeLayout.ALIGN_PARENT_RIGHT); params.setMargins(0, margin_land, margin_land, 0); img.setLayoutParams(params); img.getLayoutParams().height = h_land; img.getLayoutParams().width = h_land; ll_params.setMargins(0, (int) (10 * dens), 0, 0); webView.setLayoutParams(ll_params); customViewContainer.setLayoutParams(ll_params); int width_screen = getResources().getDisplayMetrics().widthPixels; int aux = (int) (width_screen * 0.5625); webView.getLayoutParams().height = aux; } } } public boolean inCustomView() { return (mCustomView != null); } public void hideCustomView() { mWebChromeClient.onHideCustomView(); } class myWebChromeClient extends WebChromeClient { private View mVideoProgressView; @Override public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { onShowCustomView(view, callback); //To change body of overridden methods use File | Settings | File Templates. } @Override public View getVideoLoadingProgressView() { if (mVideoProgressView == null) { LayoutInflater inflater = LayoutInflater.from(TVActivity.this); mVideoProgressView = inflater.inflate(R.layout.video_progress, null); } return mVideoProgressView; } @Override public void onHideCustomView() { super.onHideCustomView(); if (mCustomView == null) return; Helper.ShowStatusBar(TVActivity.this); webView.setVisibility(View.VISIBLE); ll_header.setVisibility(View.VISIBLE); img.setVisibility(View.VISIBLE); if (isBigSized) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { lili.setBackgroundColor(getResources().getColor(android.R.color.darker_gray, null)); } else { lili.setBackgroundColor(getResources().getColor(android.R.color.darker_gray)); } } else { lili.setBackground(getResources().getDrawable(R.drawable.croped_back)); } // Hide the custom view. customViewContainer.setVisibility(View.GONE); mCustomView.setVisibility(View.GONE); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // Remove the custom view from its container. customViewContainer.removeView(mCustomView); customViewContainer.setLayoutParams(params); customViewCallback.onCustomViewHidden(); AnimateAndChangeLayout(); mCustomView = null; FrameLayout.LayoutParams params_f = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); lili.setLayoutParams(params_f); } @Override public void onShowCustomView(View view, CustomViewCallback callback) { // if a view already exists then immediately terminate the new one if (mCustomView != null) { callback.onCustomViewHidden(); return; } mCustomView = view; webView.setVisibility(View.GONE); img.setVisibility(View.GONE); ll_header.setVisibility(View.GONE); customViewContainer.setVisibility(View.VISIBLE); customViewContainer.addView(view); customViewCallback = callback; LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); params.setMargins(0, 0, 0, 0); customViewContainer.setLayoutParams(params); FrameLayout.LayoutParams params_f = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); params_f.gravity = Gravity.CENTER; lili.setBackgroundColor(getResources().getColor(android.R.color.black)); lili.setLayoutParams(params_f); customViewContainer.setLayoutParams(params); Helper.HideStatusBar(TVActivity.this); } } class myWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return super.shouldOverrideUrlLoading(view, request); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); pr_bar_rot.setVisibility(View.GONE); webView.setVisibility(View.VISIBLE); } @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.onReceivedHttpError(view, request, errorResponse); //webView.setVisibility(View.INVISIBLE); } } }
18,275
0.629528
0.625643
474
37.552742
31.232731
161
false
false
0
0
0
0
0
0
0.611814
false
false
12
68cecd4069903ad168cdbcd50b576aeab6ed339a
9,148,280,409,637
2c67a6ada47f4be6ae6c0155aa4c2ea5afda5718
/projects/javaspaces/src/test/org/springmodules/javaspaces/gigaspaces/app/SimpleDao.java
4245eb8347c13df96a8b313e9f509d3f57c086de
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
abashev/spring-modules
https://github.com/abashev/spring-modules
c7e6638b77a8414e30455fa0d22c29b8fb4aac52
26f719709974aa6f47eea88d004e23abf88f49e8
refs/heads/master
2021-01-17T07:08:19.549000
2010-07-09T12:38:37
2010-07-09T12:38:37
765,379
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2005 GigaSpaces Technologies Ltd. All rights reserved. * * THIS SOFTWARE IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED INCLUDING BUT NOT LIMITED TO WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE OR * NON-INFRINGEMENT. GIGASPACES WILL NOT BE LIABLE FOR ANY DAMAGE OR * LOSS IN CONNECTION WITH THE SOFTWARE. */ package org.springmodules.javaspaces.gigaspaces.app; import org.springmodules.javaspaces.gigaspaces.GigaSpacesDaoSupport; import com.j_spaces.core.client.Modifiers; public class SimpleDao extends GigaSpacesDaoSupport implements ISimpleDao { public void writeSimple(SimpleBean bean) throws Exception { getGigaSpaceTemplate().write(bean, -1, Modifiers.WRITE); } public SimpleBean takeIfExists(SimpleBean template) { return (SimpleBean)getGigaSpaceTemplate().takeIfExists(template, -1); } public SimpleBean writeAndTake(SimpleBean bean) throws Exception { writeSimple(bean); return takeIfExists(bean); } }
UTF-8
Java
1,004
java
SimpleDao.java
Java
[]
null
[]
/* * Copyright 2005 GigaSpaces Technologies Ltd. All rights reserved. * * THIS SOFTWARE IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED INCLUDING BUT NOT LIMITED TO WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE OR * NON-INFRINGEMENT. GIGASPACES WILL NOT BE LIABLE FOR ANY DAMAGE OR * LOSS IN CONNECTION WITH THE SOFTWARE. */ package org.springmodules.javaspaces.gigaspaces.app; import org.springmodules.javaspaces.gigaspaces.GigaSpacesDaoSupport; import com.j_spaces.core.client.Modifiers; public class SimpleDao extends GigaSpacesDaoSupport implements ISimpleDao { public void writeSimple(SimpleBean bean) throws Exception { getGigaSpaceTemplate().write(bean, -1, Modifiers.WRITE); } public SimpleBean takeIfExists(SimpleBean template) { return (SimpleBean)getGigaSpaceTemplate().takeIfExists(template, -1); } public SimpleBean writeAndTake(SimpleBean bean) throws Exception { writeSimple(bean); return takeIfExists(bean); } }
1,004
0.787849
0.781873
30
32.466667
29.721746
75
false
false
0
0
0
0
0
0
0.866667
false
false
12