blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
e029c6b94efc86075bfa54939207383f3a14b507
Java
kbmakevin/WhatMyGPA
/WhatMyGPA_Web/src/com/whatmygpa/servlets/LoginServlet.java
UTF-8
1,458
2.375
2
[]
no_license
package com.whatmygpa.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.whatmygpa.dao.UsersService; import com.whatmygpa.models.Users; /** * Servlet implementation class Login */ @WebServlet("/Login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub try { // request.getSession().removeAttribute("user"); request.getRequestDispatcher("login.jsp").forward(request, response); } catch (IOException e) { response.getWriter().append("500: Server error;\n" + e.getMessage()); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Users authenticatedUser = UsersService.authenticateUsers(request.getParameter("username"), request.getParameter("password")); if (authenticatedUser != null) { request.getSession().setAttribute("user", authenticatedUser); response.sendRedirect(request.getContextPath() + "/Home"); } else { request.setAttribute("error", "Invalid login. Please try again."); doGet(request, response); } } }
true
8971be6d743d2f711ef2509fdde75a6c335dadde
Java
LucaContri/dataanalysis
/Reporting/src/com/saiglobal/reporting/utility/KPIProcessorScheduling.java
UTF-8
16,053
2.09375
2
[]
no_license
package com.saiglobal.reporting.utility; import java.sql.ResultSet; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import org.apache.commons.lang.StringUtils; import com.saiglobal.reporting.model.KPIData; import com.saiglobal.sf.core.data.DbHelper; public class KPIProcessorScheduling extends AbstractKPIProcessor { public KPIProcessorScheduling(DbHelper db_certification, DbHelper db_tis,int periodsToReport) { super(db_certification, db_tis, periodsToReport); } public Object[][] getOnTargetRatios() throws Exception { Object[][] tableData = new Object[periodsToReport+1][5]; String query = "select t.`Scheduled Period`, round(sum(if(t.`Scheduled - Target`=0,1,0))/count(t.id)*100,2) as 'On Target %', round(sum(if(t.`Scheduled - Target`=1,1,0))/count(t.id)*100,2) as '1 month to Target %', round(sum(if(t.`Scheduled - Target`=2,1,0))/count(t.id)*100,2) as '2 month to Target %', round(sum(if(t.`Scheduled - Target`>=3,1,0))/count(t.id)*100,2) as '3+ month to Target %' from ( " + "SELECT " + "wi.id as 'id', " + "DATE_FORMAT(wi.Work_Item_Date__c, '%Y %m') as 'Scheduled Period', " + "DATE_FORMAT(wi.Service_target_date__c, '%Y %m') as 'Target Period', " + "abs(round(datediff(date_format(wi.Work_Item_Date__c, '%Y-%m-01'), date_format(wi.Service_target_date__c,'%Y-%m-01'))/(365/12))) as 'Scheduled - Target' " + "FROM `work_item__c` wi " + "LEFT JOIN `recordtype` rt ON wi.RecordTypeId = rt.Id " + "WHERE " + "rt.Name = 'Audit' " + "AND (wi.Revenue_Ownership__c LIKE 'AUS-Food%' OR wi.Revenue_Ownership__c LIKE 'AUS-Global%' OR wi.Revenue_Ownership__c LIKE 'AUS-Managed%' OR wi.Revenue_Ownership__c LIKE 'AUS-Direct%') " + "and wi.Status__c NOT IN ('Open', 'Service Change', 'Cancelled', 'Budget') " + "AND date_format(wi.Work_Item_Date__c, '%Y %m') >= date_format(date_add(now(), interval " + (-this.periodsToReport) + " month), '%Y %m') " + "AND date_format(wi.Work_Item_Date__c, '%Y %m') <= date_format(date_add(now(), interval -1 month), '%Y %m') " + ") t " + "group by `Scheduled Period` " + "order by `Scheduled Period`"; ResultSet rs = db_certification.executeSelect(query, -1); tableData[0] = new Object[] {"Scheduled Period", "On Target %", "1 month to Target %", "2 month to Target %", "3+ month to Target %"}; while (rs.next()) { tableData[rs.getRow()] = new Object[] { displayMonthFormat.format(mysqlPeriodFormat.parse(rs.getString("Scheduled Period"))), rs.getDouble("On Target %"), rs.getDouble("1 month to Target %"), rs.getDouble("2 month to Target %"), rs.getDouble("3+ month to Target %")}; } return tableData; } private String[] getAuditorsUtilisationPeriods() { String[] periods = new String[periodsToReport]; Calendar aux = Calendar.getInstance(); aux.add(Calendar.MONTH, -2); for (int i = 0; i < periodsToReport; i++) { periods[i] = mysqlPeriodFormat.format(aux.getTime()); aux.add(Calendar.MONTH, 1); } return periods; } private String getAuditorsUtilisationQuery(String stream) { String additionalWhere = "and RowName not like 'Food%' and RowName not like 'MS%' "; if (stream.equalsIgnoreCase(KPIData.MS)) { additionalWhere = "and RowName like 'MS%'"; } else if (stream.equalsIgnoreCase(KPIData.FOOD)) { additionalWhere = "and RowName like 'Food%'"; } return "select t2.ColumnName as 'Period'," + "round(sum(if(t2.RowName like '%BlankDaysCount', t2.Value,0)),0) as 'BlankDaysCount'," + "round(sum(if(t2.RowName like '%Utilisation', t2.Value,0))*100,2) as 'Utilisation'," + "round(sum(if(t2.RowName like '%FTEDays%', t2.Value,0))*100,2) as 'FTEDays', " + "round(100-sum(if(t2.RowName like '%FTEDays%', t2.Value,0))*100,2) as 'ContractorDays' " + "from (" + "select t.* from (" + "select * from sf_report_history " + "where ReportName='Scheduling Auditors Metrics' " + "and Region = 'Australia' " + additionalWhere + "and ColumnName in ('" + StringUtils.join(getAuditorsUtilisationPeriods(), "','") + "') " + "order by Date desc) t " + "group by t.Region,t.ColumnName, RowName) t2 " + "group by t2.Region,t2.ColumnName " + "order by t2.Region,t2.ColumnName"; } public HashMap<String, Object[][]> getAuditorsUtilisation() throws Exception { HashMap<String, Object[][]> returnValue = new HashMap<String, Object[][]>(); Object[][] tableDataFood = new Object[periodsToReport+1][4]; Object[][] tableDataMS = new Object[periodsToReport+1][4]; Object[][] tableDataMSPlusFood = new Object[periodsToReport+1][4]; tableDataFood[0] = new Object[] {"Period", "Employee %", "Contractors %", "Employee Utilisation %"}; tableDataMS[0] = new Object[] {"Period", "Employee %", "Contractors %", "Employee Utilisation %"}; tableDataMSPlusFood[0] = new Object[] {"Period", "FTE %", "Contractors %", "Employee Utilisation %"}; String query = getAuditorsUtilisationQuery(KPIData.MS); ResultSet rs = db_certification.executeSelect(query, -1); while (rs.next()) { tableDataMS[rs.getRow()] = new Object[] {displayMonthFormat.format(mysqlPeriodFormat.parse(rs.getString("Period"))), rs.getDouble("FTEDays"), rs.getDouble("ContractorDays"), rs.getDouble("Utilisation")}; } query = getAuditorsUtilisationQuery(KPIData.FOOD); rs = db_certification.executeSelect(query, -1); while (rs.next()) { tableDataFood[rs.getRow()] = new Object[] {displayMonthFormat.format(mysqlPeriodFormat.parse(rs.getString("Period"))), rs.getDouble("FTEDays"), rs.getDouble("ContractorDays"), rs.getDouble("Utilisation")}; } query = getAuditorsUtilisationQuery(KPIData.MS_PLUS_FOOD); rs = db_certification.executeSelect(query, -1); while (rs.next()) { tableDataMSPlusFood[rs.getRow()] = new Object[] {displayMonthFormat.format(mysqlPeriodFormat.parse(rs.getString("Period"))), rs.getDouble("FTEDays"), rs.getDouble("ContractorDays"), rs.getDouble("Utilisation")}; } returnValue.put(KPIData.FOOD, tableDataFood); returnValue.put(KPIData.MS, tableDataMS); returnValue.put(KPIData.MS_PLUS_FOOD, tableDataMSPlusFood); return returnValue; } public Calendar getAuditorsUtilisationLastUpdate() throws Exception { SimpleDateFormat mysqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar lastUpdate = Calendar.getInstance(); String query = "select max(t2.Date) as 'LastUpdate' from (" + "select t.* " + "from ( " + "select * from sf_report_history " + "where ReportName='Scheduling Auditors Metrics' " + "and Region = 'Australia' " + "and ColumnName in ('" + StringUtils.join(getAuditorsUtilisationPeriods(), "','") + "') " + "order by Date desc) t " + "group by t.Region,t.ColumnName, RowName) t2"; lastUpdate.setTime(mysqlDateFormat.parse(db_certification.executeScalar(query))); return lastUpdate; } /* * Returns Scheduled/Available, Confirmed/Available and Open/Available ratios * Scheduled as 'Scheduled' + 'Scheduled - Offered' * Open as 'Open' excluding work items with Open_Sub_Status__c * Confirmed all Statuses excluding 'Cancelled', 'Budget', 'Open', 'Scheduled', 'Scheduled - Offered' * Available as Confirmed, Scheduled, Open as above defined */ public HashMap<String, Object[][]> getConfirmedOpenRatios() throws Exception { Object[][] tableDataFood = new Object[periodsToReport+1][5]; Object[][] tableDataMS = new Object[periodsToReport+1][5]; Object[][] tableDataPS = new Object[periodsToReport+1][5]; HashMap<String, Object[][]> returnValue = new HashMap<String, Object[][]>(); String query = "select t2.Stream, t2.Period, " + "ROUND((t2.Confirmed + t2.Open + t2.Scheduled)) as 'Available'," + "ROUND(t2.Confirmed/(t2.Confirmed + t2.Open + t2.Scheduled)*100,2) as 'Confirmed %'," + "ROUND(t2.Scheduled/(t2.Confirmed + t2.Open + t2.Scheduled)*100,2) as 'Scheduled %'," + "ROUND(t2.Open/(t2.Confirmed + t2.Open + t2.Scheduled)*100,2) as 'Open %' " + "from (" + "select t.Period, " + "t.Stream, " + "sum(if(t.Status='Confirmed',t.Days,0)) as 'Confirmed'," + "sum(if(t.Status='Scheduled',t.Days,0)) as 'Scheduled'," + "sum(if(t.Status='Open',t.Days,0)) as 'Open' from " + "((SELECT " + "if (wi.Revenue_Ownership__c like '%Food%', 'Food', if (wi.Revenue_Ownership__c like '%Product%', 'PS', 'MS')) as 'Stream', " + "wi.Status__c AS 'Status', " + "DATE_FORMAT(wi.Work_Item_Date__c, '%Y %m') as 'Period', " + "SUM(wi.Required_Duration__c)/8 as 'Days' " + "FROM `work_item__c` wi " + "LEFT JOIN `recordtype` rt ON wi.RecordTypeId = rt.Id " + "WHERE " + "rt.Name = 'Audit' " + "and wi.IsDeleted=0 " + "and wi.Status__c ='Open' " + "and wi.Open_Sub_Status__c is null " //+ "AND (wi.Revenue_Ownership__c LIKE 'AUS-Food%' OR wi.Revenue_Ownership__c LIKE 'AUS-Global%' OR wi.Revenue_Ownership__c LIKE 'AUS-Managed%' OR wi.Revenue_Ownership__c LIKE 'AUS-Direct%') " + "AND wi.Revenue_Ownership__c LIKE 'AUS%' " + "AND date_format(wi.Work_Item_Date__c, '%Y %m') >= date_format(date_add(now(), interval -1 month), '%Y %m') " + "AND date_format(wi.Work_Item_Date__c, '%Y %m') <= date_format(date_add(now(), interval " + (this.periodsToReport-2) + " month), '%Y %m') " + "GROUP BY `Stream`, `Status`, `Period` " + ") UNION ( " + "SELECT " + "if (wi.Revenue_Ownership__c like '%Food%', 'Food', if (wi.Revenue_Ownership__c like '%Product%', 'PS', 'MS')) as 'Stream', " + "if (wi.Status__c in ('Scheduled - Offered', 'Scheduled'), 'Scheduled', if(wi.Status__c = 'Service Change', 'Open','Confirmed')) AS 'Status', " + "DATE_FORMAT(wird.FStartDate__c, '%Y %m') as 'Period', " + "sum(if(Budget_Days__c is null, wird.Scheduled_Duration__c / 8, wird.Scheduled_Duration__c / 8 + Budget_Days__c)) AS 'Value' " + "FROM `work_item__c` wi " + "LEFT JOIN `work_item_resource__c` wir ON wir.work_item__c = wi.Id " + "LEFT JOIN `work_item_resource_day__c` wird ON wird.Work_Item_Resource__c = wir.Id " + "LEFT JOIN `recordtype` rt ON wi.RecordTypeId = rt.Id " + "WHERE " + "rt.Name = 'Audit' " + "AND wir.IsDeleted = 0 " + "AND wird.IsDeleted = 0 " + "AND wir.Work_Item_Type__c IN ('Audit' , 'Audit Planning', 'Client Management', 'Budget') " //+ "AND (wi.Revenue_Ownership__c LIKE 'AUS-Food%' OR wi.Revenue_Ownership__c LIKE 'AUS-Global%' OR wi.Revenue_Ownership__c LIKE 'AUS-Managed%' OR wi.Revenue_Ownership__c LIKE 'AUS-Direct%') " + "AND wi.Revenue_Ownership__c LIKE 'AUS%' " + "AND wir.Role__c NOT IN ('Observer' , 'Verifying Auditor', 'Verifier') " + "and wi.Status__c NOT IN ('Open', 'Cancelled', 'Budget') " + "AND date_format(wird.FStartDate__c, '%Y %m') >= date_format(date_add(now(), interval -1 month), '%Y %m') " + "AND date_format(wird.FStartDate__c, '%Y %m') <= date_format(date_add(now(), interval " + (this.periodsToReport-2) + " month), '%Y %m') " + "GROUP BY `Stream`, `Status`, `Period`)) t " + "group by t.Stream, t.Period " + ") t2 order by t2.Period, t2.Stream"; ResultSet rs = db_certification.executeSelect(query, -1); tableDataFood[0] = new Object[] {"Period", "Available", "Confirmed %", "Scheduled %", "Open %"}; tableDataMS[0] = new Object[] {"Period", "Available", "Confirmed %", "Scheduled %", "Open %"}; tableDataPS[0] = new Object[] {"Period", "Available", "Confirmed %", "Scheduled %", "Open %"}; int row = 3; while (rs.next()) { if (rs.getString("Stream").equalsIgnoreCase("Food")) tableDataFood[row/3] = new Object[] {displayMonthFormat.format(mysqlPeriodFormat.parse(rs.getString("Period"))), rs.getDouble("Available"), rs.getDouble("Confirmed %"), rs.getDouble("Scheduled %"), rs.getDouble("Open %")}; else if (rs.getString("Stream").equalsIgnoreCase("MS")) tableDataMS[row/3] = new Object[] {displayMonthFormat.format(mysqlPeriodFormat.parse(rs.getString("Period"))), rs.getDouble("Available"), rs.getDouble("Confirmed %"), rs.getDouble("Scheduled %"), rs.getDouble("Open %")}; else tableDataPS[row/3] = new Object[] {displayMonthFormat.format(mysqlPeriodFormat.parse(rs.getString("Period"))), rs.getDouble("Available"), rs.getDouble("Confirmed %"), rs.getDouble("Scheduled %"), rs.getDouble("Open %")}; row++; } returnValue.put(KPIData.FOOD, tableDataFood); returnValue.put(KPIData.MS, tableDataMS); returnValue.put(KPIData.PS, tableDataPS); return returnValue; } /* * Returns SiteCertifications not in ('Application Unpaid','Applicant','De-registered','Concluded','Transferred') * by validated flag (i.e. Lifecycle_Validated__c * Data_Enrichment_Review_complete__c) by Revenue Stream * tableData[0] => Food * tableData[1] => MS * tableData[2] => PS */ public HashMap<String, Object[][]> getDataValidated() throws Exception { Object[][] tableDataFood = new Object[periodsToReport+1][3]; Object[][] tableDataMS = new Object[periodsToReport+1][3]; Object[][] tableDataPS = new Object[periodsToReport+1][3]; HashMap<String, Object[][]> returnValue = new HashMap<String, Object[][]>(); String query = "select t.Period," + "sum(if(t.`Data Validated` and t.Stream='Food', 1, 0)) as 'Food-Validated', sum(if(not(t.`Data Validated`) and t.Stream='Food', 1, 0)) as 'Food-Not Validated'," + "sum(if(t.`Data Validated` and t.Stream='MS', 1, 0)) as 'MS-Validated', sum(if(not(t.`Data Validated`) and t.Stream='MS', 1, 0)) as 'MS-Not Validated'," + "sum(if(t.`Data Validated` and t.Stream='PS', 1, 0)) as 'PS-Validated', sum(if(not(t.`Data Validated`) and t.Stream='PS', 1, 0)) as 'PS-Not Validated' from (" + "select date_format(sc.CreatedDate,'%Y %m') as 'Period'," + "if (sc.Operational_Ownership__c like '%Food%', 'Food', if (Operational_Ownership__c like '%Product%', 'PS', 'MS')) as 'Stream'," + "sc.Lifecycle_Validated__c," + "sc.Data_Enrichment_Review_complete__c," + "sc.Lifecycle_Validated__c*sc.Data_Enrichment_Review_complete__c as 'Data Validated' " + "from certification__c sc " + "inner join site_certification_standard_program__c scsp on scsp.Site_Certification__c = sc.Id " + "where " + "sc.IsDeleted = 0 " + "and scsp.IsDeleted = 0 " + "and scsp.Status__c not in ('Application Unpaid','Applicant','De-registered','Concluded','Transferred') " + "and sc.Primary_Certification__c is not null " + "and sc.Status__c = 'Active' " + "and (sc.Mandatory_Site__c=1 or (sc.Mandatory_Site__c=0 and sc.FSample_Site__c like '%unchecked%')) " + "and scsp.Administration_Ownership__c like 'AUS%' " + "and date_format(sc.CreatedDate,'%Y %m') >= date_format(date_add(now(), interval " + (1-this.periodsToReport) + " month), '%Y %m') " + "and date_format(sc.CreatedDate,'%Y %m') <= date_format(now(), '%Y %m') " + "group by sc.id ) t " + "group by t.Period"; ResultSet rs = db_certification.executeSelect(query, -1); tableDataFood[0] = new Object[] {"Period", "Validated", "Not Validated"}; tableDataMS[0] = new Object[] {"Period", "Validated", "Not Validated"}; tableDataPS[0] = new Object[] {"Period", "Validated", "Not Validated"}; for (int i = 1; i<tableDataFood.length; i++) { tableDataFood[i] = new Object[] {"",0.0,0.0}; tableDataMS[i] = new Object[] {"",0.0,0.0}; tableDataPS[i] = new Object[] {"",0.0,0.0}; } while (rs.next()) { tableDataFood[rs.getRow()] = new Object[] {displayMonthFormat.format(mysqlPeriodFormat.parse(rs.getString("Period"))), rs.getDouble("Food-Validated"), rs.getDouble("Food-Not Validated")}; tableDataMS[rs.getRow()] = new Object[] {displayMonthFormat.format(mysqlPeriodFormat.parse(rs.getString("Period"))), rs.getDouble("MS-Validated"), rs.getDouble("MS-Not Validated")}; tableDataPS[rs.getRow()] = new Object[] {displayMonthFormat.format(mysqlPeriodFormat.parse(rs.getString("Period"))), rs.getDouble("PS-Validated"), rs.getDouble("PS-Not Validated")}; } returnValue.put(KPIData.FOOD, tableDataFood); returnValue.put(KPIData.MS, tableDataMS); returnValue.put(KPIData.PS, tableDataPS); return returnValue; } }
true
d8e02273c635616257d0752a1d3134f90b98934d
Java
weirongxin/wrx
/se,数据库/se/code/Day15/src/com/qiancheng/tools2/Test.java
GB18030
399
3.125
3
[]
no_license
package com.qiancheng.tools2; public class Test { public static void main(String[] args) { Person p1 = new Person(123); Person p2 = new Person(123); System.out.println(p1); System.out.println(p2); //ͨequalsȽ(ĬϱȽϵַ) if(p1.equals(p2)){ System.out.println("ͬһ"); }else{ System.out.println("ͬ"); } } }
true
8d2a4c34225a5bcbe5de18f29596c5cf12d5f8a2
Java
Gorro-par/Java_Study
/app/src/app/BreakEx.java
UHC
397
3.25
3
[]
no_license
package app; public class BreakEx { public static void main(String[] args) { int i = 0; boolean result = true; do { i++; if(result) { System.out.println(" "); if(i == 5) { result = false; } if(! result) { System.out.println(" "); break; } }else { System.out.println("i = " + i); } }while(i < 10); } }
true
57cf6f1cf72931f35117b81954c8eaee8318dfe2
Java
pigatron-industries/xenharmonics-archived
/src/main/java/com/pigatron/xen/domain/entity/OutputControlVoltages.java
UTF-8
704
2.21875
2
[]
no_license
package com.pigatron.xen.domain.entity; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; public class OutputControlVoltages { private ControlVoltage[] controlVoltages; public OutputControlVoltages(int size) { controlVoltages = new ControlVoltage[size]; } public void setOutputVoltage(int outputId, ControlVoltage controlVoltage) { controlVoltages[outputId] = controlVoltage; } public ControlVoltage[] getControlVoltages() { return controlVoltages; } public void setControlVoltages(ControlVoltage[] controlVoltages) { this.controlVoltages = controlVoltages; } }
true
9dc60e3f81bf19d577be99570c52fdab12ada150
Java
Kowsi2712/HandsOnAssignment
/Day4(27th Aug 2020)/PlayerException.java
UTF-8
912
3.28125
3
[]
no_license
package com.kowsi; import java.util.Scanner; class InvalidAgeRangeException extends Exception { private int age; InvalidAgeRangeException(int a) { age=a; } @Override public String toString() { return "Custom Exception:InvalidAgeRangeException "; } } public class PlayerException { public static void check(int a) throws InvalidAgeRangeException { throw new InvalidAgeRangeException(a); } public static void main(String[] args) { try { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); System.out.println("Enter the player name"); String ply=s.nextLine(); System.out.println("Enter the player age"); int a=s.nextInt(); if(a>19) { System.out.println("Player name :" +ply+ " Player age :" +a); return; } check(a); } catch(InvalidAgeRangeException e) { System.out.println(e); } } }
true
0f7cf7eb2486fc0e74ff080b7e1074caa65a4b7c
Java
OttoZong/MyProject
/JDBC/JDBC/src/tw/com/lccnet/bean/Customer.java
UTF-8
977
2.453125
2
[]
no_license
/* * Copyright (c) 1994, 2018, lccnet and/or 偷我程式者,將受到神的制裁 */ package tw.com.lccnet.bean; /** * 專案名稱:JDBC * 建立時間:2018年10月18日 下午8:46:20 * @auther EricYang * Email:eric.tw.2015@gmail.com * @version 1.0V * * TODO */ public class Customer { //封裝 //bean id.name....tables private int id; private String name; private String age; private String email; private String address; public Customer() {} 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 getAge() { return age; } public void setAge(String age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
true
29bb049d00d1e53d3ec49e76bde5422dc0af24ad
Java
Ahmad-faroukh/Java-Applets-2
/prog3/Server.java
UTF-8
1,501
3.5
4
[]
no_license
package Archive.prog3; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Server { public Server(){ try { ServerSocket soket = new ServerSocket(4444);//chose a port that's not busy System.out.println("Server is Running ..."); while(true) { Socket socket = soket.accept(); System.out.println("Server is Connecting ..."); new Thread(new Runnable() { @Override public void run() { InputStream is = null; try { is = socket.getInputStream(); Scanner scanner = new Scanner(is); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } scanner.close(); is.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new Server(); } }
true
f0ddd8644e5b8897a8342ad7cf03f2d7475d3819
Java
GZK0329/OA_SYSTEM
/src/main/java/com/example/emos/wx/controller/form/LoginForm.java
UTF-8
381
1.710938
2
[]
no_license
package com.example.emos.wx.controller.form; import io.swagger.annotations.ApiModel; import lombok.Data; import javax.validation.constraints.NotBlank; /** * @Classname LoginForm * @Description TODO * @Date 2021/7/31 15:25 * @Created by GZK0329 */ @ApiModel @Data public class LoginForm { @NotBlank(message = "临时授权凭证不能为空") private String code; }
true
a9794f8263113edd5a49d04538e8c46916575bb2
Java
taana/mavenCucumberProtopyte
/src/test/java/com/cucumber/mavenCucumberProtopyte/StepsButtons.java
UTF-8
1,177
2.234375
2
[]
no_license
package com.cucumber.mavenCucumberProtopyte; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import cucumber.api.java.After; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; public class StepsButtons { private WebDriverSingleton automation = WebDriverSingleton.getInstance(); //private WebDriver driver; //WebDriver driver = null; @Given("^Homepage should be opened$") public void Homepage_should_be_opened() throws Throwable { automation.openBrowser(); automation.openBrowser().get("http://www.thetestroom.com/webapp/index.html"); automation.openBrowser().manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @When("^Navigate to \"([^\"]*)\" page$") public void Navigate_to_page(String link) throws Throwable { //driver.findElement(By.id(link.toLowerCase() + "_link")).click(); automation.openBrowser().findElement(By.id(link)).click(); } public void closeWebBrowser(){ automation.closeBrowser(); } @After() public void close(){ automation.closeBrowser(); } @And("^Close browser$") public void Close_browser() throws Throwable { closeWebBrowser(); } }
true
aa7d1506bb70249f9f4336636a4af1efc6a28722
Java
tiengaro/GoogleMap_Demo_Comp
/app/src/main/java/com/example/domaumaru/googlemap_demo_comp/Data/d_FourSquarePlaces.java
UTF-8
706
1.851563
2
[]
no_license
package com.example.domaumaru.googlemap_demo_comp.Data; import com.google.android.gms.maps.model.LatLng; /** * Created by Doma Umaru on 9/27/2016. */ public class d_FourSquarePlaces { public String id = "BVJMMLEX2FLG4UN2CMEABBK2XPAIPEFEGRMQAZFLJGRLI5HV"; public String secret = "JN33ZUSGAVQLT1IHW3YTI3I2VALWHZL0TY5OQRLHFBYT4QUF"; public String version = "20160923"; public LatLng latLng; public String latLngAcc; public String query; public String radius; public String limit; public d_FourSquarePlaces(LatLng latLng, String latLngAcc, String query, String radius, String limit) { this.latLng = latLng; this.latLngAcc = latLngAcc; this.query = query; this.radius = radius; this.limit = limit; } }
true
9697f50ae03dd4fe66d38ffdbb30111cbf86b177
Java
olbucaille/Android_Mobility_Project
/app/src/main/java/com/andoidapplicationisep/teammobility/android_mobility_project/BDD/Activity.java
UTF-8
1,267
2.234375
2
[]
no_license
package com.andoidapplicationisep.teammobility.android_mobility_project.BDD; import java.util.Date; /** * Created by apple on 25/11/2015. */ public class Activity { static public final int TYPE_HEARTBEAT = 1; static public final int TYPE_RUNNING = 2; private long id ; private String userFbID; private int type ; private String begin; private String end; public Activity(){ } public Activity(String userFbID,int type ,String begin, String end){ this.userFbID = userFbID; this.type = type; this.begin = begin; this.end = end; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUserFbID() { return userFbID; } public void setUserFbID(String userFbID) { this.userFbID = userFbID; } public String getBegin() { return begin; } public void setBegin(String begin) { this.begin = begin; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } }
true
b2125baee65a7f04a63b6522dd3105363c7dd40f
Java
PacktPublishing/Java-9-Cookbook
/Chapter11/5_1_apache_http_demo_response_handler/src/http.client.demo/com/packt/ApacheHttpClientResponseHandlerDemo.java
UTF-8
1,068
2.640625
3
[ "MIT" ]
permissive
package com.packt; import java.io.IOException; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.ResponseHandler; import org.apache.http.HttpEntity; import org.apache.http.util.EntityUtils; public class ApacheHttpClientResponseHandlerDemo{ public static void main(String [] args) throws Exception{ CloseableHttpClient client = HttpClients.createDefault(); try{ HttpGet request = new HttpGet("http://httpbin.org/get"); String responseBody = client.execute(request, response -> { int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; }); System.out.println("Response Body: " + responseBody); }finally{ client.close(); } } }
true
ed2d589536b56fc796790eb72b3875b297457641
Java
testingGlobalIndia/JavaRepository
/Thread/src/academy/learnprogramming/Main.java
UTF-8
797
3.390625
3
[]
no_license
package academy.learnprogramming; public class Main { public static void main(String[] args) { System.out.println("Hello from main thread."); Thread anotherThread = new AnotherThread(); anotherThread.setName("== Another Thread ==="); anotherThread.start(); new Thread(){ public void run(){ System.out.println("Hello from anonymous class thread"); } }.start(); Thread myRunnableThread = new Thread(new MyRunnable(){ public void run(){ System.out.println("Hello from My runnable thread class"); } }); myRunnableThread.start(); anotherThread.interrupt(); System.out.println("Hello again from the main thread"); } }
true
008f5da8bed986bccf2c16273732b650b61bf636
Java
lucasantonio12/esigproject
/src/main/java/dao/TarefaDao.java
UTF-8
1,511
2.421875
2
[]
no_license
package dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Query; import org.hibernate.Session; import org.hibernate.Transaction; import interfaces.ITarefaDao; import modelo.Tarefa; import util.HibernateUtil; public class TarefaDao extends GenericDaoImpl<Tarefa, Integer> implements ITarefaDao { public TarefaDao() { super(Tarefa.class); } @SuppressWarnings("unchecked") public List<Tarefa> listarTarefas() { String sql = "select t from Tarefa t order by titulo"; Session sessao = HibernateUtil.getSessionFactory().openSession(); Query consulta = sessao.createQuery(sql); List<Tarefa> tarefas = consulta.getResultList(); sessao.close(); return tarefas; } @SuppressWarnings("unchecked") public List<Tarefa> buscaGeral(String campo,String valor) { Session sessao = HibernateUtil.getSessionFactory().openSession(); Query consulta = sessao.createQuery("Select t from" + " Tarefa t where t."+ campo +"= :valor" ); List<Tarefa> tarefas = consulta.setParameter("valor", valor).getResultList(); sessao.close(); return tarefas; } @SuppressWarnings("unchecked") public List<Tarefa> buscaConcluida(String campo,Boolean concluida) { Session sessao = HibernateUtil.getSessionFactory().openSession(); Query consulta = sessao.createQuery("Select t from" + " Tarefa t where t.concluida="+campo); List tarefas = consulta.getResultList(); sessao.close(); return tarefas; } }
true
0647d32f11533a32b402ec006f75707152166d0e
Java
SantiagoBursese/AterrizarV3
/src/dataDummy/DataDummy.java
UTF-8
10,563
1.929688
2
[]
no_license
/* * 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 dataDummy; import aterrizarv2.AterrizarV2; import aterrizarv2.aerolinea.Aerolinea; import aterrizarv2.aerolinea.RequisitoCargaAsientos; import aterrizarv2.aerolinea.aerolineaLanchita.AerolineaLanchita; import aterrizarv2.aerolinea.aerolineaLanchita.AerolineaLanchitaI; import aterrizarv2.aerolinea.aerolineaOceanic.AerolineaOceanic; import aterrizarv2.aerolinea.aerolineaOceanic.AerolineaOceanicI; import aterrizarv2.aerolinea.aerolineaOceanic.TipoPedidoInvalidaException; import aterrizarv2.aerolinea.exceptionesAerolinea.DatosVueloIncorrectoException; import aterrizarv2.asientos.excepcionesAsiento.AsientoReservadoException; import aterrizarv2.asientos.excepcionesAsiento.CodigoAsientoException; import aterrizarv2.fecha.FechaFlexible; import aterrizarv2.fecha.excepcionesFecha.FechaNoValidaException; import aterrizarv2.fecha.excepcionesFecha.FormatoFechaIncorrectoException; import aterrizarv2.hora.Hora; import aterrizarv2.hora.excepcionesHora.FormatoHoraIncorrectoException; import aterrizarv2.hora.excepcionesHora.HoraInvalidaException; import aterrizarv2.usuarios.DniInvalidoException; import aterrizarv2.usuarios.UsuarioPaga; import aterrizarv2.vuelos.Vuelo; import org.mockito.Mockito; public class DataDummy { public UsuarioPaga nuevoUsuario() throws DniInvalidoException, AsientoReservadoException{ UsuarioPaga usuario = new UsuarioPaga("Juan Manuel", "Pardo", 1111111, 350); usuario.efectuarCompra(500000); AterrizarV2 aterrizar = this.setearAterrizarDummy(); efectuarTresCompras(aterrizar,usuario); reservarUnAsiento(aterrizar,usuario); return usuario; } public AterrizarV2 paginaAerolineas() throws DniInvalidoException, FechaNoValidaException, FormatoFechaIncorrectoException, FormatoHoraIncorrectoException, DatosVueloIncorrectoException, HoraInvalidaException, TipoPedidoInvalidaException{ AterrizarV2 aterrizar = this.setearAterrizarDummy(); return aterrizar; } public AterrizarV2 setearAterrizarDummy() throws FormatoFechaIncorrectoException, FechaNoValidaException, FormatoHoraIncorrectoException, HoraInvalidaException, DatosVueloIncorrectoException, TipoPedidoInvalidaException, DniInvalidoException{ Vuelo vueloRioLima; Vuelo vueloBsAsMadrid; AerolineaLanchita lanchitaNoMockeada; AerolineaLanchitaI lanchitaMockeada; FechaFlexible fechaSalida1Junio2018; FechaFlexible fechaSalida13Noviembre2018; FechaFlexible fechaLlegada2Junio2018; FechaFlexible fechaLlegada13Noviembre2018; String origenBuenosAires = "BUE"; String destinoMadrid = "MAD"; String origenRioJaneiro = "RIO"; String destinoLima = "LIM"; fechaSalida1Junio2018 = new FechaFlexible("01/06/2018"); fechaLlegada2Junio2018 = new FechaFlexible("02/06/2018"); fechaSalida13Noviembre2018 = new FechaFlexible("13/11/2018"); fechaLlegada13Noviembre2018 = new FechaFlexible("13/11/2018"); Hora horaSalida23hs = new Hora("23:05"); Hora horaLlegada11hs = new Hora("11:30"); Hora horaSalida12hs = new Hora("12:20"); Hora horaLlegada21hs = new Hora("21:15"); lanchitaMockeada = Mockito.mock(AerolineaLanchitaI.class); lanchitaNoMockeada = new AerolineaLanchita(lanchitaMockeada); String[][] asientosDisponiblesBueMad = {{"EC0344-42","565.60","P","P","D"}, {"EC0344-66","365.60","T","E","D"},{"EC0344-67","3265.60","T","E","D"},{"EC0344-44","565.60","P","P","D"}}; String[][] asientosDisponiblesRioLim = {{"EC0LAM-12","4555.60","P","P","D"}, {"EC0LAM-13","3665.60","T","E","D"}, {"EC0LAM-14","4555.60","P","P","D"},{"EC0LAM-15","4555.60","P","P","D"},{"EC0LAM-16","4555.60","P","P","D"},{"EC0LAM-17","4555.60","P","P","D"}}; Mockito.when(lanchitaMockeada.asientosDisponibles("BUE", "MAD", fechaSalida1Junio2018.representacionEnIso(), fechaLlegada2Junio2018.representacionEnIso(), horaSalida23hs.getHoraFormatoString(), horaLlegada11hs.getHoraFormatoString())).thenReturn(asientosDisponiblesBueMad); Mockito.when(lanchitaMockeada.asientosDisponibles("RIO", "LIM", fechaSalida13Noviembre2018.representacionEnIso(), fechaLlegada13Noviembre2018.representacionEnIso(), horaSalida12hs.getHoraFormatoString(), horaLlegada21hs.getHoraFormatoString())).thenReturn(asientosDisponiblesRioLim); vueloBsAsMadrid = new Vuelo(origenBuenosAires, destinoMadrid, fechaSalida1Junio2018, fechaLlegada2Junio2018, horaSalida23hs, horaLlegada11hs); vueloRioLima = new Vuelo(origenRioJaneiro, destinoLima, fechaSalida13Noviembre2018, fechaLlegada13Noviembre2018, horaSalida12hs, horaLlegada21hs); lanchitaNoMockeada.agregarVuelo(vueloBsAsMadrid, null); lanchitaNoMockeada.agregarVuelo(vueloRioLima, null); AterrizarV2 aterrizar = new AterrizarV2(); aterrizar.agregarAerolinea(lanchitaNoMockeada); aterrizar.agregarAerolinea(setearOceanicDummy()); return aterrizar; } public static AerolineaOceanic setearOceanicDummy() throws FormatoFechaIncorrectoException, FechaNoValidaException, FormatoHoraIncorrectoException, HoraInvalidaException, TipoPedidoInvalidaException, DatosVueloIncorrectoException{ Vuelo vueloRioLosAngeles; Vuelo vueloBsAsMadrid; AerolineaOceanic oceanic; AerolineaOceanicI oceanicMock; FechaFlexible fechaSalida1Junio2018; FechaFlexible fechaSalida13Noviembre2018; FechaFlexible fechaLlegada2Junio2018; FechaFlexible fechaLlegada13Noviembre2018; oceanicMock = Mockito.mock(AerolineaOceanicI.class); oceanic = new AerolineaOceanic(oceanicMock); /* CIUDADES */ String origenBuenosAires = "BUE"; String destinoMadrid = "MAD"; String origenRioJaneiro = "RIO"; String destinoLosAngeles = "LA"; String bueOceanic = oceanic.convertirFormatoCiudad(origenBuenosAires); String madOceanic = oceanic.convertirFormatoCiudad(destinoMadrid); String rioOceanic = oceanic.convertirFormatoCiudad(origenRioJaneiro); String losAngelesOceanic = oceanic.convertirFormatoCiudad(destinoLosAngeles); /* ----------------------------------------------------------------------------------------------*/ /* FECHAS */ fechaSalida1Junio2018 = new FechaFlexible("01/06/2018"); fechaLlegada2Junio2018 = new FechaFlexible("02/06/2018"); fechaSalida13Noviembre2018 = new FechaFlexible("13/11/2018"); fechaLlegada13Noviembre2018 = new FechaFlexible("13/11/2018"); String unoJunio = fechaSalida1Junio2018.representacionEnLatinoamericano(); String dosJunio = fechaLlegada2Junio2018.representacionEnLatinoamericano(); String treceNoviembre = fechaSalida13Noviembre2018.representacionEnLatinoamericano(); /* ----------------------------------------------------------------------------------------------*/ /* HORA */ Hora horaSalida23hs = new Hora("23:00"); Hora horaLlegada11hs = new Hora("11:00"); Hora horaSalida12hs = new Hora("12:00"); Hora horaLlegada00hs= new Hora("00:00"); String lasOnce = "11:00"; String lasVeintiTres = "23:00"; String lasDoce = "12:00"; String lasCeroCero = "00:00"; /* ----------------------------------------------------------------------------------------------*/ /* COMUNICACION CON OCEANICI MOCKEADA */ String[][] asientosBueLim = {{"LAM344","13",unoJunio,lasDoce,"565.60","P","P"},{"LAM344","23",unoJunio,lasDoce,"565.60","T","C"}}; String[][] asientosRioLA = {{"MLR123","67", treceNoviembre, lasVeintiTres, "872.50", "P", "P"},{"MLR123", "122", treceNoviembre, lasVeintiTres, "921.76", "T","C"}}; Mockito.when(oceanicMock.asientosDisponiblesParaOrigen(bueOceanic, unoJunio)).thenReturn(asientosBueLim); Mockito.when(oceanicMock.asientosDisponiblesParaOrigenYDestino(bueOceanic, unoJunio,madOceanic)).thenReturn(asientosBueLim); Mockito.when(oceanicMock.asientosDisponiblesParaOrigen(rioOceanic, treceNoviembre)).thenReturn(asientosRioLA); Mockito.when(oceanicMock.asientosDisponiblesParaOrigenYDestino(rioOceanic, treceNoviembre, losAngelesOceanic)).thenReturn(asientosRioLA); /* ----------------------------------------------------------------------------------------------*/ /* CREACION Y CARGA DE LOS VUELOS */ vueloBsAsMadrid = new Vuelo(bueOceanic, madOceanic, fechaSalida1Junio2018, fechaLlegada2Junio2018, horaSalida12hs, horaLlegada11hs); vueloRioLosAngeles = new Vuelo(rioOceanic, losAngelesOceanic, fechaSalida13Noviembre2018, fechaLlegada13Noviembre2018, horaSalida23hs, horaLlegada00hs); RequisitoCargaAsientos requisitoOrigen = new RequisitoCargaAsientos("Origen"); oceanic.agregarVuelo(vueloBsAsMadrid, requisitoOrigen); oceanic.agregarVuelo(vueloRioLosAngeles, requisitoOrigen); /* ----------------------------------------------------------------------------------------------*/ return oceanic; } public static void reservarUnAsiento(AterrizarV2 aterrizar, UsuarioPaga usuario) throws CodigoAsientoException, AsientoReservadoException{ Aerolinea aerolinea = aterrizar.getAerolineas().get(0); aerolinea.reservarAsiento("EC0LAM-12", usuario); } public static void efectuarTresCompras(AterrizarV2 aterrizar, UsuarioPaga usuario) throws CodigoAsientoException, AsientoReservadoException{ Aerolinea aerolinea = aterrizar.getAerolineas().get(0); aerolinea.comprarAsiento("EC0344-42", usuario); aerolinea.comprarAsiento("EC0344-66", usuario); Aerolinea aerolineaOc = aterrizar.getAerolineas().get(1); aerolineaOc.comprarAsiento("LAM344-13", usuario); } }
true
a5d1344e7085618d0a64a0977e98e0f3d44016d4
Java
ojourmel/csci331-team-red
/src/main/java/csci331/team/red/client/FieldDialogueCallback.java
UTF-8
781
2.328125
2
[]
no_license
package csci331.team.red.client; import csci331.team.red.shared.callbacks.FieldCallback; public class FieldDialogueCallback<T extends Callback> implements DialogueCallback<Callback> { protected FieldAgentScreen entity; public FieldDialogueCallback(FieldAgentScreen entity) { this.entity = entity; } @Override public void call(Callback cg) { FieldCallback c = (FieldCallback) cg; switch (c) { case approachPerson: entity.displayNewPerson(entity.currentIncident.getActor()); break; case giveDocuments: if(entity.currentIncident.getIncidentDocuments() != null) { entity.produceDocuments(entity.currentIncident.getIncidentDocuments()); } break; case endGame: entity.parentEngine.LeaveGame(); break; default: break; } } }
true
972d5722f009cd45a10a1f86b6d4c9aa2f603f28
Java
tifuigabriel1993/ACADEMIA_RAPID_PLATFORM
/fc-rapid-mvn/fc-rapid-web/src/main/java/com/companyname/web/controller/platform/TicketController.java
UTF-8
459
1.804688
2
[]
no_license
package com.companyname.web.controller.platform; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.companyname.web.util.Views; @Controller @RequestMapping("/platforma/bilete") public class TicketController { @RequestMapping(method=RequestMethod.GET) public String ticketView() { return Views.TICKETS_VIEW; } }
true
6267588301ae64d16cede0622fb83f6071f7edf9
Java
irfanYLDRM/JavaCamp
/homework_week_5_1_e-commerce/src/eCommerceDemo/core/abstracts/ConfirmEmailService.java
UTF-8
118
1.945313
2
[]
no_license
package eCommerceDemo.core.abstracts; public interface ConfirmEmailService { boolean confirmEmail(String email); }
true
1ea6feb682ecb85ece33698b3aaa49605f8be66d
Java
pavikumbhar/spring-boot-mqtt-integration
/src/main/java/com/pavikumbhar/mqtt/dto/MessageProducerRequest.java
UTF-8
808
1.96875
2
[ "Apache-2.0" ]
permissive
package com.pavikumbhar.mqtt.dto; import org.springframework.integration.mqtt.core.MqttPahoClientFactory; import org.springframework.integration.mqtt.support.MqttMessageConverter; import org.springframework.messaging.MessageChannel; import lombok.Getter; import lombok.Setter; /** * * @author pavikumbhar * */ @Getter @Setter public class MessageProducerRequest { private String clientId; private MqttPahoClientFactory clientFactory; private String[] subscriptionTopic; private MqttMessageConverter converter; private MessageChannel outputChannel; public MessageProducerRequest(String clientId, MqttPahoClientFactory clientFactory, String[] subscriptionTopic) { super(); this.clientId = clientId; this.clientFactory = clientFactory; this.subscriptionTopic = subscriptionTopic; } }
true
a4fed13ce22f3a4363aa994ecd1751bbd58a81fe
Java
Cristhian-WebProgram/ProyectoClinicaDental
/ClinicaSpring/src/main/java/pe/edu/upc/spring/entity/Promocion.java
UTF-8
2,253
2.484375
2
[]
no_license
package pe.edu.upc.spring.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name = "Promocion") public class Promocion implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int idPromocion; @NotNull @Past(message="No puedes seleccionar un dia que todavia NO existe") @Temporal(TemporalType.DATE) @Column(name="fechainicio") @DateTimeFormat(pattern="dd-MM-yyyy") private Date fechainicio; @NotNull @Past(message="No puedes seleccionar un dia que todavia NO existe") @Temporal(TemporalType.DATE) @Column(name="fechafin") @DateTimeFormat(pattern="dd-MM-yyyy") private Date fechafin; @NotEmpty(message = "No puede estar vacío") @NotBlank(message = "No puede estar en blanco") @Column(name="descuento",length=60,nullable=false) private double descuento; public Promocion(int idPromocion, Date fechainicio, Date fechafin, double descuento) { super(); this.idPromocion = idPromocion; this.fechainicio = fechainicio; this.fechafin = fechafin; this.descuento = descuento; } public Promocion() { super(); } public int getIdPromocion() { return idPromocion; } public void setIdPromocion(int idPromocion) { this.idPromocion = idPromocion; } public Date getFechainicio() { return fechainicio; } public void setFechainicio(Date fechainicio) { this.fechainicio = fechainicio; } public Date getFechafin() { return fechafin; } public void setFechafin(Date fechafin) { this.fechafin = fechafin; } public double getDescuento() { return descuento; } public void setDescuento(double descuento) { this.descuento = descuento; } }
true
79c848403f152685c05a1299b20e22b5bff2af05
Java
moutainhigh/vmi-openInstall
/vmi-video-service/src/test/java/com/tigerjoys/shark/miai/agent/test/UserVipAgentTest.java
UTF-8
2,045
1.914063
2
[]
no_license
package com.tigerjoys.shark.miai.agent.test; import java.time.LocalTime; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.tigerjoys.nbs.common.utils.Tools; import com.tigerjoys.shark.miai.agent.IAnchorDefendAgent; import com.tigerjoys.shark.miai.agent.IUserAgent; import com.tigerjoys.shark.miai.agent.IUserVipAgent; import com.tigerjoys.shark.miai.agent.IUserWeekCardAgent; import com.tigerjoys.shark.miai.agent.dto.UserBO; import com.tigerjoys.shark.miai.inter.entity.GuardVipCategoryEntity; import com.tigerjoys.shark.miai.utils.BaseTestConfig; /** * 测试vip的相关功能 * @author shiming * */ public class UserVipAgentTest extends BaseTestConfig { @Autowired private IUserVipAgent userVipAgent; @Autowired private IUserWeekCardAgent userWeekCardAgent; @Autowired private IAnchorDefendAgent anchorDefendAgent; @Autowired private IUserAgent userAgent; @Test public void increaseVipDayTest() throws Exception{ userVipAgent.increaseVipDay(157644262727549184L, 2); } @Test public void updateDailyWeekCardDuration() throws Exception{ userWeekCardAgent.updateDailyWeekCardDuration(160697009626480896L, 4); } @Test public void updateLocalTime() throws Exception{ LocalTime localTime = LocalTime.now(); System.out.println(localTime.getHour()); } @Test public void getWeekCardTotalDuration() throws Exception{ long totalMinute = userWeekCardAgent.getWeekCardTotalDuration(159805667281010944L,4); System.out.println("totalMinute:"+totalMinute); long cardId = userWeekCardAgent.getDailyWeekCard(159805667281010944L,4); System.out.println("cardId:"+cardId); } @Test public void anchorDefend() throws Exception{ UserBO userBO = userAgent.findById(162860191952470272L); System.out.println("VIP:"+userBO.vipValue()); GuardVipCategoryEntity guardList = anchorDefendAgent.getCurrentAnchorDefendByUser(162860191952470272L, 134831734503047424L); System.out.println(Tools.isNotNull(guardList)?"guardTure":"false"); } }
true
50ed97f6b76b762b002f2948f9411bd37417b646
Java
zhiyuan0226/JavaNotes
/Spring/03 Spring-aop/src/com/wzy/test/Demo.java
UTF-8
316
2.265625
2
[]
no_license
package com.wzy.test; public class Demo { public void demo1() { System.out.println("Demo1.demo1"); } public void demo2() { System.out.println("demo2"); } public void demo3() { System.out.println("demo3"); } public void demo4(String name) { System.out.println("demo4---"+name); // int i=5/0; } }
true
8633282a59238dd5820bfa3a266b1ac4240caa1e
Java
dstmath/OppoR15
/app/src/main/java/android/icu/impl/SoftCache.java
UTF-8
1,263
2.359375
2
[]
no_license
package android.icu.impl; import java.util.concurrent.ConcurrentHashMap; public abstract class SoftCache<K, V, D> extends CacheBase<K, V, D> { private ConcurrentHashMap<K, Object> map = new ConcurrentHashMap(); public final V getInstance(K key, D data) { CacheValue<V> mapValue = this.map.get(key); V value; if (mapValue == null) { value = createInstance(key, data); Object mapValue2 = (value == null || !CacheValue.futureInstancesWillBeStrong()) ? CacheValue.getInstance(value) : value; mapValue2 = this.map.putIfAbsent(key, mapValue2); if (mapValue2 == null) { return value; } if (mapValue2 instanceof CacheValue) { return ((CacheValue) mapValue2).resetIfCleared(value); } return mapValue2; } else if (!(mapValue instanceof CacheValue)) { return mapValue; } else { CacheValue<V> cv = mapValue; if (cv.isNull()) { return null; } value = cv.get(); if (value != null) { return value; } return cv.resetIfCleared(createInstance(key, data)); } } }
true
b2d639c16ddf38760e206a012bb9913d94c68358
Java
lat-lon/deegree2-base-2.3.1
/src/org/deegree/enterprise/servlet/LoggingFilter.java
UTF-8
6,171
1.828125
2
[]
no_license
//$HeadURL: svn+ssh://aerben@scm.wald.intevation.org/deegree/base/trunk/src/org/deegree/enterprise/servlet/LoggingFilter.java $ /*---------------- FILE HEADER ------------------------------------------ This file is part of deegree. Copyright (C) 2001-2008 by: EXSE, Department of Geography, University of Bonn http://www.giub.uni-bonn.de/deegree/ lat/lon GmbH http://www.lat-lon.de This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: Andreas Poth lat/lon GmbH Aennchenstr. 19 53177 Bonn Germany E-Mail: poth@lat-lon.de Prof. Dr. Klaus Greve Department of Geography University of Bonn Meckenheimer Allee 166 53115 Bonn Germany E-Mail: greve@giub.uni-bonn.de ---------------------------------------------------------------------------*/ package org.deegree.enterprise.servlet; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.deegree.framework.util.StringTools; /** * servlet filter for logging incoming requests and outgoing responses. Through the init-params a * user may limit logging to: * <ul> * <li>requests received from a list of defined source/remote addresses</li> * <li>returned mime types</li> * <li>meta informations about the incoming request</li> * </ul> * * * @version $Revision: 10660 $ * @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a> * @author last edited by: $Author: apoth $ * * @version 1.0. $Revision: 10660 $, $Date: 2008-03-24 22:39:54 +0100 (Mo, 24. Mär 2008) $ * * @since 2.0 */ public class LoggingFilter implements Filter { private List<String> remoteAddresses; private List<String> mimeTypes; private boolean metaInfo = false; /** * @param config * @throws ServletException */ public void init( FilterConfig config ) throws ServletException { try { if ( config.getInitParameter( "sourceAddresses" ) != null ) { remoteAddresses = StringTools.toList( config.getInitParameter( "sourceAddresses" ), ";", true ); } if ( config.getInitParameter( "mimeTypes" ) != null ) { mimeTypes = StringTools.toList( config.getInitParameter( "mimeTypes" ), ";", true ); } metaInfo = "true".equalsIgnoreCase( config.getInitParameter( "metaInfo" ) ); } catch ( Exception e ) { e.printStackTrace(); } } /** * @param request * @param response * @param chain * @throws IOException * @throws ServletException */ public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { synchronized ( this ) { System.out.println( "==========================================================" ); ServletResponseWrapper resWrap = new ServletResponseWrapper( (HttpServletResponse) response ); String url = ( (HttpServletRequest) request ).getRemoteAddr(); if ( remoteAddresses == null || remoteAddresses.contains( url ) ) { ServletRequestWrapper reqWrap = new ServletRequestWrapper( (HttpServletRequest) request ); // log request content System.out.println( reqWrap.getRequestURI() ); InputStream is = reqWrap.getInputStream(); int c = 0; while ( ( c = is.read() ) > -1 ) { System.out.print( (char) c ); } is.close(); if ( metaInfo ) { // log request meta information System.out.println( "getRemoteAddr " + reqWrap.getRemoteAddr() ); System.out.println( "getPort " + reqWrap.getServerPort() ); System.out.println( "getMethod " + reqWrap.getMethod() ); System.out.println( "getPathInfo " + reqWrap.getPathInfo() ); System.out.println( "getRequestURI " + reqWrap.getRequestURI() ); System.out.println( "getServerName " + reqWrap.getServerName() ); System.out.println( "getServerPort " + reqWrap.getServerPort() ); System.out.println( "getServletPath " + reqWrap.getServletPath() ); } chain.doFilter( reqWrap, resWrap ); } else { chain.doFilter( request, resWrap ); } OutputStream os = resWrap.getOutputStream(); byte[] b = ( (ServletResponseWrapper.ProxyServletOutputStream) os ).toByteArray(); os.close(); String mime = resWrap.getContentType(); System.out.println( "mime type: " + mime ); if ( mimeTypes == null || ( mime != null && mimeTypes.contains( mime ) ) ) { System.out.write( b ); } response.setContentType( mime ); response.setContentLength( b.length ); os = response.getOutputStream(); os.write( b ); os.close(); } } /** * */ public void destroy() { // TODO Auto-generated method stub } }
true
c67246d9747e5dc63b73b83a19ec4209cb791a28
Java
bestjss/fpush
/fpush-server/src/main/java/com/appjishu/fpush/server/model/PushParam.java
UTF-8
813
2.03125
2
[ "Apache-2.0" ]
permissive
package com.appjishu.fpush.server.model; import java.io.Serializable; public class PushParam implements Serializable { private String receiverAlias; private String title; private String desc; private String data; public String getReceiverAlias() { return receiverAlias; } public void setReceiverAlias(String receiverAlias) { this.receiverAlias = receiverAlias; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getData() { return data; } public void setData(String data) { this.data = data; } }
true
a8eba2f1d44dc82d77df0eb7187e8ea152b71848
Java
Islendingurinn/adventofcode
/advent/e2020/Day12.java
UTF-8
7,479
3.125
3
[]
no_license
package advent.e2020; import advent.Advent; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; public class Day12 extends Advent { public static void main(String[] args) throws IOException { new Day12(); } protected Day12() throws IOException { super(12); } ArrayList<Character> directions; @Override protected void setup() { directions = new ArrayList<>(Arrays.asList('N', 'E', 'S', 'W')); } @Override protected Object solveFirst() { int northsouth = 0; int eastwest = 0; char facing = 'E'; for(String in : getInput()){ char instruction = in.charAt(0); int value = Integer.parseInt(in.substring(1)); switch(instruction){ case 'N': northsouth += value; break; case 'S': northsouth -= value; break; case 'E': eastwest += value; break; case 'W': eastwest -= value; break; case 'F': switch(facing){ case 'N': northsouth += value; break; case 'S': northsouth -= value; break; case 'E': eastwest += value; break; case 'W': eastwest -= value; break; } break; case 'R': case 'L': int iterations = value / 90; int start = directions.indexOf(facing); while (iterations != 0){ if(instruction == 'R') if(start != 3) start++; else start = 0; else if(start != 0) start--; else start = 3; iterations--; } facing = directions.get(start); break; } } return Math.abs(northsouth) + Math.abs(eastwest); } @Override protected Object solveSecond() { int northsouthWP = 1; int eastwestWP = 10; int northsouth = 0; int eastwest = 0; for(String in : getInput()){ char instruction = in.charAt(0); int value = Integer.parseInt(in.substring(1)); switch(instruction){ case 'N': northsouthWP += value; break; case 'S': northsouthWP -= value; break; case 'E': eastwestWP += value; break; case 'W': eastwestWP -= value; break; case 'F': northsouth += (northsouthWP*value); eastwest += (eastwestWP*value); break; case 'R': case 'L': int iterations = value / 90; char initNS = northsouthWP > 0 ? 'N' : 'S'; char initEW = eastwestWP > 0 ? 'E' : 'W'; int ns = directions.indexOf(initNS); int ew = directions.indexOf(initEW); while (iterations != 0){ if(instruction == 'R'){ if(ns != 3) ns++; else ns = 0; if(ew != 3) ew++; else ew = 0; }else{ if(ns != 0) ns--; else ns = 3; if(ew != 0) ew--; else ew = 3; } iterations--; } int newNS = 0; int newEW = 0; if(initNS == 'N'){ switch(directions.get(ns)){ case 'N': newNS = northsouthWP; break; case 'S': newNS = -northsouthWP; break; case 'E': newEW = northsouthWP; break; case 'W': newEW = -northsouthWP; break; } }else{ switch(directions.get(ns)){ case 'S': newNS = northsouthWP; break; case 'N': newNS = -northsouthWP; break; case 'W': newEW = northsouthWP; break; case 'E': newEW = -northsouthWP; break; } } if(initEW == 'E'){ switch(directions.get(ew)){ case 'N': newNS = eastwestWP; break; case 'S': newNS = -eastwestWP; break; case 'E': newEW = eastwestWP; break; case 'W': newEW = -eastwestWP; break; } }else{ switch(directions.get(ew)){ case 'S': newNS = eastwestWP; break; case 'N': newNS = -eastwestWP; break; case 'W': newEW = eastwestWP; break; case 'E': newEW = -eastwestWP; break; } } northsouthWP = newNS; eastwestWP = newEW; break; } } return Math.abs(northsouth) + Math.abs(eastwest); } }
true
606ecf818e70f5904809b75ea741e4296cae9c7b
Java
VitaliiBashta/Trunk
/java/l2trunk/gameserver/network/serverpackets/PledgeReceiveSubPledgeCreated.java
UTF-8
639
2.25
2
[]
no_license
package l2trunk.gameserver.network.serverpackets; import l2trunk.gameserver.model.pledge.SubUnit; public class PledgeReceiveSubPledgeCreated extends L2GameServerPacket { private final int type; private final String _name; private final String leader_name; public PledgeReceiveSubPledgeCreated(SubUnit subPledge) { type = subPledge.type(); _name = subPledge.getName(); leader_name = subPledge.getLeaderName(); } @Override protected final void writeImpl() { writeEx(0x40); writeD(0x01); writeD(type); writeS(_name); writeS(leader_name); } }
true
defda08d450956ff1402361fe5b801b6352f5332
Java
alboteanud/Golf
/core/src/com/lutu/golf/ecrane/AbstractScreenWithFlipper.java
UTF-8
9,844
2.203125
2
[]
no_license
package com.lutu.golf.ecrane; import com.badlogic.gdx.Game; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.assets.loaders.TextureLoader.TextureParameter; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.lutu.golf.ScreenType; import com.lutu.golf.framework.AbstractFlipperViewAdapter; import com.lutu.golf.framework.FlipperView; import com.lutu.golf.framework.FlipperView.OnFlippingFinishListener; import com.lutu.golf.utils.Assets; import com.lutu.golf.utils.AudioPaths; import com.lutu.golf.utils.GolfAudioManager; /** * Abstract screen which contains FlipperView. * * * @param <A> * see {@link AbstractFlipperViewAdapter} * @param <T> * see {@link FlipperView} * @param <V> * see {@link FlipperView} */ public abstract class AbstractScreenWithFlipper<A extends AbstractFlipperViewAdapter<T, V>, T extends Actor, V> extends UiScreen implements InputProcessor { // Background private static final String BACKGROUND = "levelsmenu/menu_bg.png"; // Next button private static final String LEVELS_NEXT_BUTTON_DOWN = "levelsmenu/levels_next_button_down.png"; private static final String LEVELS_NEXT_BUTTON_UP = "levelsmenu/levels_next_button_up.png"; private static final String LEVELS_NEXT_BUTTON_DISABLE = "levelsmenu/levels_next_button_disable.png"; // Previous button private static final String LEVELS_PREV_BUTTON_DOWN = "levelsmenu/levels_prev_button_down.png"; private static final String LEVELS_PREV_BUTTON_UP = "levelsmenu/levels_prev_button_up.png"; private static final String LEVELS_PREV_BUTTON_DISABLE = "levelsmenu/levels_prev_button_disable.png"; private static final float BUTTON_SIZE = 80f; private static final float BUTTON_PADDING = 30f; private static final float TITLE_VIEW_HEIGHT = 60f; private static final float TITLE_VIEW_TOP_PADDING = 10f; private Stage mBackgroundStage; private int mIndexOfSelectedView = -1; /** * Constructs instance of {@link AbstractScreenWithFlipper}. * * @param game * instance of {@link Game} */ AbstractScreenWithFlipper(Game game, ScreenType screenType) { super(game, screenType); } @Override protected void onRender(float delta) { mBackgroundStage.act(); mBackgroundStage.draw(); super.onRender(delta); } /** * Sets index of selected page. * * @param index * index of selected page */ public void setIndexOfSelectedPage(int index) { mIndexOfSelectedView = index; } @Override public void resize(int width, int height) { mBackgroundStage.setViewport((float) width / height * LAYOUT_HEIGHT, LAYOUT_HEIGHT, false); getStage().getCamera().viewportHeight = LAYOUT_HEIGHT; getStage().getCamera().viewportWidth = (float) width / height * getStage().getCamera().viewportHeight; getStage().getCamera().update(); super.resize(width, height); } /** * Returns instance of {@link AbstractFlipperViewAdapter}. * * @return instance of {@link AbstractFlipperViewAdapter} */ abstract A getFlipperAdapter(); /** * Returns title view. It can be null. * * @return title view */ abstract Actor prepareTitleView(); @Override public void create() { super.create(); Assets.get().load(BACKGROUND, Texture.class); final TextureParameter param = new TextureParameter(); param.minFilter = TextureFilter.MipMapLinearLinear; param.magFilter = TextureFilter.Linear; param.genMipMaps = true; Assets.get().load(LEVELS_NEXT_BUTTON_DOWN, Texture.class, param); Assets.get().load(LEVELS_NEXT_BUTTON_UP, Texture.class, param); Assets.get().load(LEVELS_NEXT_BUTTON_DISABLE, Texture.class, param); Assets.get().load(LEVELS_PREV_BUTTON_UP, Texture.class, param); Assets.get().load(LEVELS_PREV_BUTTON_DOWN, Texture.class, param); Assets.get().load(LEVELS_PREV_BUTTON_DISABLE, Texture.class, param); } private Stage prepareBackgroundStage() { final Stage result = new Stage(); final Image image = new Image(Assets.get().getTextureRegionDrawable(BACKGROUND)); image.setFillParent(true); image.setSize(image.getWidth() / image.getHeight() * LAYOUT_HEIGHT, LAYOUT_HEIGHT); result.setCamera(getStage().getCamera()); result.addActor(image); return result; } @Override protected Actor onCreateLayout() { final Stack mainLayoutWidget = new Stack(); mainLayoutWidget.setFillParent(true); final FlipperView<AbstractFlipperViewAdapter<T, V>, T, V> flipper = prepareFlipper(); final Table menuHudTable = prepareHudTable(flipper); mainLayoutWidget.add(flipper); mainLayoutWidget.add(menuHudTable); return mainLayoutWidget; } private FlipperView<AbstractFlipperViewAdapter<T, V>, T, V> prepareFlipper() { // @formatter:off final AbstractFlipperViewAdapter<T, V> adapter = getFlipperAdapter(); final FlipperView<AbstractFlipperViewAdapter<T, V>, T, V> flipper = new FlipperView<AbstractFlipperViewAdapter<T, V>, T, V>( adapter); // @formatter:on if (mIndexOfSelectedView != -1) { adapter.setCurrentIndex(mIndexOfSelectedView); flipper.setPageAt(mIndexOfSelectedView); mIndexOfSelectedView = -1; } flipper.setFillParent(true); return flipper; } @Override public boolean keyDown(int keycode) { return false; } private Table prepareHudTable(final FlipperView<AbstractFlipperViewAdapter<T, V>, T, V> flipper) { final Table result = new Table(); result.setFillParent(true); final ButtonStyle nextBtnStyle = new ButtonStyle(); nextBtnStyle.down = Assets.get().getTextureRegionDrawable(LEVELS_NEXT_BUTTON_DOWN); nextBtnStyle.up = Assets.get().getTextureRegionDrawable(LEVELS_NEXT_BUTTON_UP); nextBtnStyle.disabled = Assets.get().getTextureRegionDrawable(LEVELS_NEXT_BUTTON_DISABLE); final Button nextPage = new Button(nextBtnStyle); final ButtonStyle prevBtnStyle = new ButtonStyle(); prevBtnStyle.down = Assets.get().getTextureRegionDrawable(LEVELS_PREV_BUTTON_DOWN); prevBtnStyle.up = Assets.get().getTextureRegionDrawable(LEVELS_PREV_BUTTON_UP); prevBtnStyle.disabled = Assets.get().getTextureRegionDrawable(LEVELS_PREV_BUTTON_DISABLE); final Button prevPage = new Button(prevBtnStyle); final ClickListener clickListener = new ClickListener() { @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { final Actor buttonSelected = event.getListenerActor(); if (!((Button) buttonSelected).isDisabled()) { GolfAudioManager.playSound(AudioPaths.CLICK); } return super.touchDown(event, x, y, pointer, button); } @Override public void clicked(InputEvent event, float x, float y) { final Button button = (Button) event.getListenerActor(); if (button.equals(nextPage) && !button.isDisabled()) { button.setDisabled(true); flipper.flippingRight(); } else if (button.equals(prevPage)) { button.setDisabled(true); flipper.flippingLeft(); } } }; setButtonsEnabled(flipper.getFlipperAdapter(), prevPage, nextPage); flipper.setOnFlippingFinishListener(new OnFlippingFinishListener() { @Override public void onFlippingFinish() { setButtonsEnabled(flipper.getFlipperAdapter(), prevPage, nextPage); } }); nextPage.addListener(clickListener); prevPage.addListener(clickListener); final Actor titleView = prepareTitleView(); float buttonsPadding = 0.0f; if (titleView != null) { result.add(titleView).fillX().height(TITLE_VIEW_HEIGHT).top().padTop(TITLE_VIEW_TOP_PADDING).colspan(2); buttonsPadding = TITLE_VIEW_HEIGHT + TITLE_VIEW_TOP_PADDING; } result.row().expand().center().padTop(-buttonsPadding); result.add(prevPage).size(BUTTON_SIZE, BUTTON_SIZE).padLeft(BUTTON_PADDING).left(); result.add(nextPage).size(BUTTON_SIZE, BUTTON_SIZE).padRight(BUTTON_PADDING).right(); return result; } private void setButtonsEnabled(AbstractFlipperViewAdapter<T, V> adapter, Button prevPageBtn, Button nextPageBtn) { final int currentIndex = adapter.getCurrentIndex(); final int countValue = adapter.getValueCount(); prevPageBtn.setDisabled(currentIndex == 0); nextPageBtn.setDisabled(currentIndex == countValue - 1); } @Override public boolean keyTyped(char character) { return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return false; } @Override public boolean mouseMoved(int screenX, int screenY) { return false; } @Override public boolean scrolled(int amount) { return false; } @Override protected void onShow() { mBackgroundStage = prepareBackgroundStage(); getInputMultiplexer().addProcessor(this); } @Override protected void onHide() { getInputMultiplexer().removeProcessor(this); } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { super.dispose(); Assets.get().unload(BACKGROUND); Assets.get().unload(LEVELS_NEXT_BUTTON_DOWN); Assets.get().unload(LEVELS_NEXT_BUTTON_UP); Assets.get().unload(LEVELS_NEXT_BUTTON_DISABLE); Assets.get().unload(LEVELS_PREV_BUTTON_UP); Assets.get().unload(LEVELS_PREV_BUTTON_DOWN); Assets.get().unload(LEVELS_PREV_BUTTON_DISABLE); } }
true
ac30f9801c158ca1c23bb5a902f4538386343c57
Java
wq907547122/design23-demo
/src/main/java/com/wu/qiang/mediator/DatingPlatform.java
UTF-8
325
2.328125
2
[ "Apache-2.0" ]
permissive
package com.wu.qiang.mediator; /** * @auth wq on 2019/12/11 16:18 **/ public class DatingPlatform { public static void main(String[] args) { Medium medium = new EstateMedium(); // 房屋中介 medium.register(new Seller("张三(卖方)")); medium.register(new Buyer("李四(买方)")); } }
true
571c2dd0c1ffa6e1f08f0fbed185d28cd9920dda
Java
dfdf0202/JavaStudy
/src/ch3/Ch3_Ex3.java
UTF-8
587
3.8125
4
[]
no_license
package ch3; public class Ch3_Ex3 { public static void main(String[] args) { int a = 10; int b = 4; System.out.println(a + b); System.out.println(a - b); System.out.println(a * b); System.out.println(a / b); System.out.println(a / (float)b); // 나누기 연산자의 두 피연산자가 모두 int 타입인 경우, 결과도 int // 그래서 연산결과가 2.5이여도 int 타입의 값인 2로 결과 반환. // 올바른 결과를 얻기 위해서는 어느 한쪽을 실수형으로 형변환 해야 올바른 결과를 얻을수 있음 } }
true
1abb2e44921ab23343f869d521360423aa0bf762
Java
dengkai1982/xhapp
/src/main/java/kaiyi/app/xhapp/controller/mgr/AccountController.java
UTF-8
18,949
1.789063
2
[]
no_license
package kaiyi.app.xhapp.controller.mgr; import kaiyi.app.xhapp.entity.access.*; import kaiyi.app.xhapp.entity.access.enums.MemberShip; import kaiyi.app.xhapp.service.access.*; import kaiyi.app.xhapp.service.log.LoginLogService; import kaiyi.puer.commons.access.AccessControl; import kaiyi.puer.commons.collection.Cascadeable; import kaiyi.puer.commons.collection.ProcessCascadeEachHandler; import kaiyi.puer.commons.collection.StreamCollection; import kaiyi.puer.commons.data.JavaDataTyper; import kaiyi.puer.commons.utils.CoderUtil; import kaiyi.puer.db.orm.ServiceException; import kaiyi.puer.h5ui.bean.DynamicGridInfo; import kaiyi.puer.json.JsonParserException; import kaiyi.puer.json.creator.JsonMessageCreator; import kaiyi.puer.json.parse.ArrayJsonParser; import kaiyi.puer.web.elements.ChosenElement; import kaiyi.puer.web.servlet.WebInteractive; import kaiyi.puer.web.springmvc.IWebInteractive; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; @Controller @RequestMapping(AccountController.rootPath) @AccessControl(name = "用户账户", weight = 1f, detail = "管理系统中用户账户", code = AccountController.rootPath) public class AccountController extends ManagerController { public static final String rootPath=prefix+"/account"; @Resource private VisitorRoleService visitorRoleService; @Resource private RoleAuthorizationMenuService roleAuthorizationMenuService; @Resource private VisitorUserService visitorUserService; @Resource private AccountService accountService; @Resource private InsideNoticeService insideNoticeService; @Resource private LoginLogService loginLogService; @RequestMapping("/insideNotice") @AccessControl(name = "消息管理", weight = 1.1f, detail = "管理系统消息", code = rootPath+ "/insideNotice", parent = rootPath) public String insideNotice(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ setDefaultPage(interactive,rootPath+"/insideNotice"); mainTablePage(interactive,insideNoticeService,null,null, new DynamicGridInfo(false,DynamicGridInfo.OperMenuType.popup)); return rootPath+"/insideNotice"; } @RequestMapping("/readInsideNotice") public void readInsideNotice(@IWebInteractive WebInteractive interactive, HttpServletResponse response) throws IOException { String entityId=interactive.getStringParameter("entityId",""); InsideNotice insideNotice=insideNoticeService.readMessage(entityId); response.sendRedirect(insideNotice.getActionUrl()); } @RequestMapping("/visitorRole") @AccessControl(name = "角色管理", weight = 1.2f, detail = "管理系统中的访问角色", code = rootPath+ "/visitorRole", parent = rootPath) public String visitorRole(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ setDefaultPage(interactive,rootPath+"/visitorRole"); mainTablePage(interactive,visitorRoleService,null,null, new DynamicGridInfo(false,DynamicGridInfo.OperMenuType.popup)); return rootPath+"/visitorRole"; } @RequestMapping("/visitorRole/new") @AccessControl(name = "新增角色", weight = 1.21f, detail = "添加新的角色", code = rootPath+ "/visitorRole/new", parent = rootPath+"/visitorRole") public String visitorRoleNew(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ newOrEditPage(interactive,visitorRoleService,3); setDefaultPage(interactive,rootPath+"/visitorRole"); return rootPath+"/visitorRoleForm"; } @RequestMapping("/visitorRole/modify") @AccessControl(name = "编辑角色", weight = 1.22f, detail = "编辑角色", code = rootPath+ "/visitorRole/modify", parent = rootPath+"/visitorRole") public String visitorRoleModify(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ newOrEditPage(interactive,visitorRoleService,3); setDefaultPage(interactive,rootPath+"/visitorRole"); return rootPath+"/visitorRoleForm"; } @RequestMapping("/visitorRole/detail") @AccessControl(name = "角色详情", weight = 1.23f, detail = "角色详情", code = rootPath+ "/visitorRole/detail", parent = rootPath+"/visitorRole") public String visitorRoleDetail(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ detailPage(interactive,visitorRoleService,3); setDefaultPage(interactive,rootPath+"/visitorRole"); return rootPath+"/visitorRoleDetail"; } @PostMapping("/visitorRole/commit") public void visitorRoleCommit(@IWebInteractive WebInteractive interactive, HttpServletResponse response) throws IOException { JsonMessageCreator msg=executeNewOrUpdate(interactive,visitorRoleService); interactive.writeUTF8Text(msg.build()); } @AccessControl(name = "访问权限", weight = 1.24f, detail = "修改部门后台操作访问权限", code = rootPath + "/visitorRole/privilegeDatas", parent = rootPath+"/visitorRole") @RequestMapping("/visitorRole/privilegeDatas") public String rolePrilivigeDatas(@IWebInteractive WebInteractive interactive){ String entityId=interactive.getStringParameter("entityId",""); VisitorRole role=visitorRoleService.findForPrimary(entityId); final StreamCollection<VisitorMenu> rootMenus=visitorMenuService.getRootMenus(); final Set<RoleAuthorizationMenu> authors=role.getAuthors(); final StringBuilder builder=new StringBuilder(); builder.append("<ul class='tree tree-lines' data-animate='true' data-ride='tree'>"); Cascadeable.forEachCascade(rootMenus.toList(), new ProcessCascadeEachHandler<Cascadeable>() { @Override public void beforeEach(Cascadeable t) { //if(t.getLevel()>1)return; builder.append("<li>"); } @Override public void beforeEachChild(Cascadeable t, Collection<? extends Cascadeable> collection) { //if(t.getLevel()==1)return; builder.append("<ul>"); } @Override public void afterEachChild(Cascadeable t, Collection<? extends Cascadeable> collection) { //if(t.getLevel()==1)return; builder.append("</ul>"); } @Override public void atferEach(Cascadeable t) { //if(t.getLevel()>1)return; builder.append("</li>"); } @Override public boolean each(int i, Cascadeable t) { //if(t.getLevel()>1)return true; VisitorMenu menu=(VisitorMenu)t; boolean hasAuth=false; for(RoleAuthorizationMenu auth:authors){ if(auth.getMenu().getEntityId().equals(menu.getEntityId())){ if(auth.isVisit()){ hasAuth=auth.isVisit(); break; } } } String parentId=""; if(menu.getParent()!=null){ parentId=menu.getParent().getEntityId(); } if(hasAuth){ builder.append("<input class='changePrivilege' type='checkbox' id='" +CoderUtil.stringToHex(menu.getEntityId(),"utf-8",true)+"' parent='"+ CoderUtil.stringToHex(parentId,"utf-8",true) +"' checked='checked'><span href='#' title='"+menu.getDetail()+"' >"+menu.getName()+"</span>"); }else{ builder.append("<input class='changePrivilege' type='checkbox' id='" +CoderUtil.stringToHex(menu.getEntityId(),"utf-8",true)+"' parent='"+ CoderUtil.stringToHex(parentId,"utf-8",true) +"'><span href='#' title='"+menu.getDetail()+"' >"+menu.getName()+"</span>"); } return true; } }); builder.append("</ul>"); interactive.setRequestAttribute("privilegeList", builder.toString()); interactive.setRequestAttribute("roleId",entityId); return rootPath+"/prilivigeDatas"; } @RequestMapping(value = "/visitorRole/changePrivilege",method = RequestMethod.POST) public void changePrivilege(@IWebInteractive WebInteractive interactive,HttpServletResponse response) throws IOException, JsonParserException { JsonMessageCreator msg=getSuccessMessage(); String roleId=interactive.getStringParameter("roleid", ""); String privileges=interactive.getHttpServletRequest().getParameter("privileges");//interactive.getStringParameter("privileges", ""); ArrayJsonParser jsonParsr=new ArrayJsonParser(privileges); StreamCollection<Map<String, JavaDataTyper>> maplist=jsonParsr.doParser(); List<VisitorMenu> trueMenus=new ArrayList<VisitorMenu>(); List<VisitorMenu> falseMenus=new ArrayList<VisitorMenu>(); maplist.forEachByOrder((i,d)->{ VisitorMenu menu=new VisitorMenu(); String menuId=d.get("menuid").stringValue(); menu.setEntityId(CoderUtil.hexToString(menuId,"utf-8")); if(d.get("auth").booleanValue(false)){ trueMenus.add(menu); }else{ falseMenus.add(menu); } }); roleAuthorizationMenuService.updateRoleAuthroity(roleId, trueMenus, true); roleAuthorizationMenuService.updateRoleAuthroity(roleId, falseMenus, false); interactive.writeUTF8Text(msg.build()); } @RequestMapping("/visitorUser") @AccessControl(name = "用户管理", weight = 1.3f, detail = "管理系统中的用户", code = rootPath + "/visitorUser", parent = rootPath) public String visitorUser(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ setDefaultPage(interactive,rootPath+"/visitorUser"); mainTablePage(interactive,visitorUserService,null,null, new DynamicGridInfo(false,DynamicGridInfo.OperMenuType.popup)); return rootPath+"/visitorUser"; } @RequestMapping("/visitorUser/new") @AccessControl(name = "新增用户", weight = 1.31f, detail = "新增用户", code = rootPath + "/visitorUser/new", parent = rootPath+"/visitorUser") public String visitorUserNew(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ newOrEditPage(interactive,visitorUserService,3); setDefaultPage(interactive,rootPath+"/visitorUser"); return rootPath+"/visitorUserForm"; } @AccessControl(name = "修改用户", weight = 1.32f, detail = "修改用户", code = rootPath + "/visitorUser/modify", parent = rootPath+"/visitorUser") @RequestMapping("/visitorUser/modify") public String visitorUserModify(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ newOrEditPage(interactive,visitorUserService,3); setDefaultPage(interactive,rootPath+"/visitorUser"); return rootPath+"/visitorUserForm"; } @AccessControl(name = "删除用户", weight = 1.33f, detail = "删除用户", code = rootPath + "/visitorUser/delete", parent = rootPath+"/visitorUser") @RequestMapping("/visitorUser/delete") public void visitorUserDelete(@IWebInteractive WebInteractive interactive, HttpServletResponse response) throws IOException { JsonMessageCreator msg=getSuccessMessage(); String entityId=interactive.getStringParameter("entityId",""); try { visitorUserService.deleteById(entityId); } catch (ServiceException e) { catchServiceException(msg,e); } interactive.writeUTF8Text(msg.build()); } @AccessControl(name = "重置密码", weight = 1.34f, detail = "重置用户密码", code = rootPath + "/visitorUser/resetPasswd", parent = rootPath+"/visitorUser") @RequestMapping("/visitorUser/resetPasswd") public void visitorUserResetPasswd(@IWebInteractive WebInteractive interactive, HttpServletResponse response) throws IOException { String entityId=interactive.getStringParameter("entityId",""); visitorUserService.resetPassword(entityId); interactive.writeUTF8Text(getSuccessMessage().build()); } @RequestMapping("/visitorUser/detail") @AccessControl(name = "用户详情", weight = 1.35f, detail = "用户详情", code = rootPath+ "/visitorUser/detail", parent = rootPath+"/visitorUser") public String visitorUserDetail(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ detailPage(interactive,visitorUserService,3); setDefaultPage(interactive,rootPath+"/visitorUser"); return rootPath+"/visitorUserDetail"; } @RequestMapping(value="/visitorUser/commit",method = RequestMethod.POST) public void visitorUserCommit(@IWebInteractive WebInteractive interactive, HttpServletResponse response) throws IOException { JsonMessageCreator msg=executeNewOrUpdate(interactive,visitorUserService); interactive.writeUTF8Text(msg.build()); } @RequestMapping("/account") @AccessControl(name = "会员管理", weight = 1.4f, detail = "管理系统中的会员", code = rootPath + "/account", parent = rootPath) public String account(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ setDefaultPage(interactive,rootPath+"/account"); mainTablePage(interactive,accountService,null,null, new DynamicGridInfo(false,DynamicGridInfo.OperMenuType.popup)); StreamCollection<ChosenElement> memberShips=ChosenElement.build(MemberShip.values()); interactive.setRequestAttribute("memberShips",memberShips); return rootPath+"/account"; } @RequestMapping("/account/detail") @AccessControl(name = "会员详情", weight = 1.41f, detail = "用户详情", code = rootPath+ "/account/detail", parent = rootPath+"/account") public String accountDetail(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ Account account=detailPage(interactive,accountService,3); Account insideMember=accountService.findParentInsideMember(account.getEntityId()); account.setParentInsideAccount(insideMember); setDefaultPage(interactive,rootPath+"/account"); return rootPath+"/accountDetail"; } @AccessControl(name = "重置密码", weight = 1.42f, detail = "重置会员密码", code = rootPath + "/account/resetPasswd", parent = rootPath+"/account") @RequestMapping("/account/resetPasswd") public void accountResetPasswd(@IWebInteractive WebInteractive interactive, HttpServletResponse response) throws IOException { String entityId=interactive.getStringParameter("entityId",""); Account account=accountService.findForPrimary(entityId); String newPassword="123456";//interactive.getStringParameter("newPassword",""); JsonMessageCreator jmc=getSuccessMessage(); if(Objects.nonNull(account)){ try { accountService.resetPassword(account.getPhone(),newPassword); } catch (ServiceException e) { catchServiceException(jmc,e); } } interactive.writeUTF8Text(jmc.build()); } @AccessControl(name = "修改会员类型", weight = 1.43f, detail = "改变会员类型", code = rootPath + "/account/changeMemberShip", parent = rootPath+"/account") @RequestMapping("/account/changeMemberShip") public void accountChangeMemberShip(@IWebInteractive WebInteractive interactive, HttpServletResponse response) throws IOException { String entityId=interactive.getStringParameter("entityId",""); MemberShip memberShip=interactive.getEnumParameterByOrdinal(MemberShip.class,"memberShip",MemberShip.normal); JsonMessageCreator jmc=getSuccessMessage(); accountService.changeMemberShip(entityId,memberShip); interactive.writeUTF8Text(jmc.build()); } @AccessControl(name = "设置内部会员", weight = 1.44f, detail = "设置会员是否为内部会员", code = rootPath + "/account/changeInsideMember", parent = rootPath+"/account") @RequestMapping("/account/changeInsideMember") public void accountChangeInsideMember(@IWebInteractive WebInteractive interactive, HttpServletResponse response) throws IOException { String entityId=interactive.getStringParameter("entityId",""); accountService.changeInsideMember(entityId); interactive.writeUTF8Text(getSuccessMessage().build()); } @AccessControl(name = "冻结/解锁", weight = 1.45f, detail = "冻结或者解锁会员", code = rootPath + "/account/changeActive", parent = rootPath+"/account") @RequestMapping("/account/changeActive") public void accountActive(@IWebInteractive WebInteractive interactive, HttpServletResponse response) throws IOException { String entityId=interactive.getStringParameter("entityId",""); accountService.changeActive(entityId); interactive.writeUTF8Text(getSuccessMessage().build()); } @AccessControl(name = "设置员工姓名", weight = 1.46f, detail = "设置员工姓名", code = rootPath + "/account/setMemberName", parent = rootPath+"/account") @RequestMapping("/account/setMemberName") public void accountMemberName(@IWebInteractive WebInteractive interactive, HttpServletResponse response) throws IOException { String entityId=interactive.getStringParameter("entityId",""); String memberName=interactive.getStringParameter("memberName",""); accountService.setMemberName(entityId,memberName); interactive.writeUTF8Text(getSuccessMessage().build()); } @RequestMapping("/loginLog") @AccessControl(name = "登录日志", weight = 1.5f, detail = "查看登录日志", code = rootPath + "/loginLog", parent = rootPath) public String loginLog(@IWebInteractive WebInteractive interactive, HttpServletResponse response){ setDefaultPage(interactive,rootPath+"/loginLog"); mainTablePage(interactive,loginLogService,null,null, new DynamicGridInfo(false,DynamicGridInfo.OperMenuType.none)); return rootPath+"/loginLog"; } }
true
7e761c6d7a24e3285a853a384ec3fa4fb07bddef
Java
tamlover/awesome-algorithm
/src/main/java/greedy/Solution881.java
UTF-8
486
2.84375
3
[]
no_license
package greedy; import java.util.Arrays; /** * @author luli * @date 2021/8/26 */ public class Solution881 { public int numRescueBoats(int[] people, int limit) { Arrays.sort(people); int left = 0; int right = people.length - 1; int ans = 0; while (left <= right) { if (people[left] + people[right] <= limit) { left++; } right--; ans++; } return ans; } }
true
15207243476060516955b30f4d6c71eb38003112
Java
cha63506/CompSecurity
/lyft-source/src/com/crashlytics/android/Crashlytics$2.java
UTF-8
790
1.703125
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.crashlytics.android; import io.fabric.sdk.android.Fabric; import io.fabric.sdk.android.Logger; import java.io.File; import java.util.concurrent.Callable; // Referenced classes of package com.crashlytics.android: // Crashlytics class a implements Callable { final Crashlytics a; public Void a() { Crashlytics.a(a).createNewFile(); Fabric.g().a("Fabric", "Initialization marker file created."); return null; } public Object call() { return a(); } (Crashlytics crashlytics) { a = crashlytics; super(); } }
true
384c953f91295c680e2d37a8a6faab637aa1ba9d
Java
xlagunas/StickyHeaders
/app/src/main/java/cat/xlagunas/stickyheaders/Groupable.java
UTF-8
93
1.585938
2
[]
no_license
package cat.xlagunas.stickyheaders; public interface Groupable<T> { T getGroupKey(); }
true
fe83d58c956ca274dda3352af364bd48f13fc659
Java
artnaseef/immutable-utils
/src/main/java/com/artnaseef/immutable/utils/MutationUtilsImmutableProperties.java
UTF-8
1,157
1.929688
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2021 Arthur Naseef * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.artnaseef.immutable.utils; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface MutationUtilsImmutableProperties { /** * List of property names, in the order they are passed to the constructor. * * The listed properties, and only the listed properties, are processed by ImmutableUtils. * * @return */ String[] properties(); }
true
fe667e6ee6a8b51e9dbfc2b9590881792a8a2600
Java
vklindukhov/crossover
/src/main/java/com/dev/server/controllers/CustomerController.java
UTF-8
3,779
2.3125
2
[]
no_license
package com.dev.server.controllers; import com.dev.domain.Customer; import com.dev.server.NotEnoughBalanceException; import com.dev.server.NotEnoughQuantityProductException; import com.dev.server.services.SalesResourcesService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; 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.RestController; import org.springframework.web.util.UriComponentsBuilder; import java.util.List; import static org.springframework.http.HttpStatus.*; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.web.bind.annotation.RequestMethod.*; @SuppressWarnings("unchecked") @RestController @RequestMapping(value = "/customers", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE) public class CustomerController { @Autowired private SalesResourcesService salesResourcesService; @RequestMapping(method = GET) public ResponseEntity<List<Customer>> getCustomers() { List<Customer> customers = salesResourcesService.findAll(Customer.class); if (customers.isEmpty()) return new ResponseEntity<>(NO_CONTENT); return new ResponseEntity<>(customers, OK); } @RequestMapping(method = POST) public ResponseEntity<Void> createCustomer(@RequestBody Customer customer, UriComponentsBuilder ucBuilder) { if (salesResourcesService.findOne(Customer.class, customer.getId()) != null) return new ResponseEntity<>(CONFLICT); salesResourcesService.save(customer); HttpHeaders headers = new HttpHeaders(); headers.setLocation(ucBuilder.path("/customers/{code}").buildAndExpand(customer.getId()).toUri()); return new ResponseEntity<>(headers, CREATED); } @RequestMapping(value = "/{code}", method = GET) public ResponseEntity<Customer> getCustomer(@PathVariable("code") String code) { Customer customer = (Customer) salesResourcesService.findOne(Customer.class, code); if (customer == null) return new ResponseEntity<>(NOT_FOUND); return new ResponseEntity<>(customer, OK); } @RequestMapping(value = "/{code}", method = PUT) public ResponseEntity<Customer> updateCustomer(@PathVariable("code") String code, @RequestBody Customer customer) { Customer currentCustomer = (Customer) salesResourcesService.findOne(Customer.class, code); if (currentCustomer == null) return new ResponseEntity<>(NOT_FOUND); currentCustomer.setOrganizationName(customer.getOrganizationName()); currentCustomer.setPhone1(customer.getPhone1()); currentCustomer.setPhone2(customer.getPhone2()); currentCustomer.setBalance(customer.getBalance()); Customer savedCustomer = (Customer) salesResourcesService.save(currentCustomer); return new ResponseEntity<>(savedCustomer, ACCEPTED); } @RequestMapping(value = "/{code}", method = DELETE) public ResponseEntity<Customer> deleteCustomer(@PathVariable("code") String code) { Customer customer = (Customer) salesResourcesService.findOne(Customer.class, code); if (customer == null) return new ResponseEntity<>(NOT_FOUND); salesResourcesService.delete(Customer.class, code); return new ResponseEntity<>(NO_CONTENT); } @RequestMapping(method = DELETE) public ResponseEntity<Customer> deleteAllCustomers() { salesResourcesService.deleteAll(Customer.class); return new ResponseEntity<>(NO_CONTENT); } }
true
7edbca054e4666249c82f345cac63abb17fa0a1b
Java
Dotsworthy/airline_lab_codeclan_week11_weekend_homework
/weekend_hw/src/main/java/Plane.java
UTF-8
481
3.046875
3
[]
no_license
public class Plane { private PlaneType type; private int capacity; private int totalWeightKG; public Plane(PlaneType type, int capacity, int totalWeightKG) { this.type = type; this.capacity = capacity; this.totalWeightKG = totalWeightKG; } public PlaneType getType() { return this.type; } public int getCapacity() { return this.capacity; } public int getWeight() { return this.totalWeightKG; } }
true
3370702893620cbb99afc8fe6e87be44e1de5e9e
Java
DestinyWarrior-Shen/Homelets
/app/src/main/java/com/example/homelessservices/Toilet.java
UTF-8
1,163
2.40625
2
[]
no_license
package com.example.homelessservices; import com.google.android.gms.maps.model.LatLng; import com.google.maps.android.clustering.ClusterItem; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; public class Toilet extends ToiletPlace implements ClusterItem,Serializable { private transient LatLng position; public Toilet() { position = new LatLng(-37.81303878836988,144.96597290039062); } public void setPosition(double lat,double lng) { this.position = new LatLng(lat,lng); } @Override public LatLng getPosition() { return position; } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeDouble(position.latitude); out.writeDouble(position.longitude); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); position = new LatLng(in.readDouble(), in.readDouble()); } }
true
315974414574867f1452844120979a95246b9ee5
Java
granudoz/hello-world
/src/main/java/br/com/alura/forum/controller/form/RespostaForm.java
UTF-8
946
2.25
2
[]
no_license
package br.com.alura.forum.controller.form; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import br.com.alura.forum.modelo.Resposta; import br.com.alura.forum.modelo.Topico; import br.com.alura.forum.repository.TopicoRepository; public class RespostaForm { @NotNull @NotEmpty @Length(min = 5) private String mensagem; @NotNull @NotEmpty @Length(min = 5) private String tituloTopico; public String getMensagem() { return mensagem; } public void setMensagem(String mensagem) { this.mensagem = mensagem; } public String getTituloTopico() { return tituloTopico; } public void setTituloTopico(String tituloTopico) { this.tituloTopico = tituloTopico; } public Resposta converter(TopicoRepository topicoRepository) { Topico topico = topicoRepository.findByTitulo(tituloTopico); return new Resposta(mensagem, topico); } }
true
86f2b70dc674d599e734e92670689e12ad8b7733
Java
binbird/babysagaapp
/src/com/zylbaby/app/bean/BabyDiaryByClass.java
UTF-8
609
2.109375
2
[]
no_license
package com.zylbaby.app.bean; import java.util.ArrayList; public class BabyDiaryByClass { private String BabyName; private String BabyPic; private ArrayList<DiaryDto> DiaryList; public String getBabyName() { return BabyName; } public void setBabyName(String babyName) { BabyName = babyName; } public String getBabyPic() { return BabyPic; } public void setBabyPic(String babyPic) { BabyPic = babyPic; } public ArrayList<DiaryDto> getDiaryList() { return DiaryList; } public void setDiaryList(ArrayList<DiaryDto> diaryList) { DiaryList = diaryList; } }
true
05439c4ba9505bf3b5a18b1f751b9e9fefcb987e
Java
bhagwatwadhe/adb
/MachineL.java
UTF-8
2,266
3.28125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package machinel; import java.util.Scanner; public class MachineL { public static void main(String[] args) { float m1=0,m2=0,sum1,sum2,a,b; int n=0,i=0,j=0,k=0; int items=0; boolean flag; Scanner get=new Scanner(System.in); System.out.println("Enter no.of data items :"); items=get.nextInt(); int[] cluster1=new int[items]; int[] cluster2=new int[items]; int[] data=new int[items]; System.out.println("Enter the data items :"); for(i=0;i<items;i++){ data[i]=get.nextInt(); } a=data[0]; b=data[1]; m1=a;m2=b; do{ sum1=0; sum2=0; n++; k=0;j=0; cluster1=new int[items]; cluster2=new int[items]; for(i=0;i<items;i++) { if(Math.abs(data[i]-m1) <= Math.abs(data[i]-m2)) { cluster1[k] = data[i]; k++; } else{ cluster2[j] = data[i]; j++; } } System.out.println(); for(i=0;i<k;i++) { sum1+=cluster1[i]; } for(i=0;i<j;i++) { sum2+=cluster2[i]; } System.out.println("Median1 :"+m1+ "and Median2 :"+m2); a=m1; b=m2; m1=Math.round(sum1/k); m2=Math.round(sum2/j); flag=!(m1==a && m2==b); System.out.println(); System.out.println("After iteration no."+n+" cluster 1 is "); for(i=0;i<cluster1.length;i++) { if(cluster1[i]!=0) System.out.print(" "+cluster1[i]); } System.out.println(); System.out.println("After iteration no."+n+" cluster 2 is "); for(i=0;i<cluster2.length;i++) { if(cluster2[i]!=0) System.out.print(" "+cluster2[i]); } }while(flag); System.out.println(); System.out.println("Final cluster1 is:"); for(i=0;i<cluster1.length;i++) { if(cluster1[i]!=0) System.out.print(" "+cluster1[i]); } System.out.println(); System.out.println("Final Cluster 2 is: "); for(i=0;i<cluster2.length;i++) { if(cluster2[i]!=0) System.out.print(" "+cluster2[i]); } } }
true
7c27ac0e45851e0897aed18b1c139989d3424bea
Java
dinhdangkhoa0201/LTWWWJAVA_DHKTPM13A_BAITAPLON_NHOM24
/LTWWWJAVA_DHKTPM13B_Group20/src/main/java/fit/se/main/service/supplier/SupplierService.java
UTF-8
342
1.976563
2
[]
no_license
package fit.se.main.service.supplier; import java.util.List; import fit.se.main.model.Supplier; public interface SupplierService { public void createSupplier(Supplier supplier); public void updateSupplier(Supplier supplier); public List<Supplier> findAll(); public void deleteById(int supplierId); public Supplier findById(int id); }
true
e585890b3fbc1fd04099b5306f426a0887d3bbc9
Java
Kealina-A/leetcode-log
/src/week8/E155MinStack/MinStack.java
UTF-8
1,953
4.25
4
[]
no_license
package week8.E155MinStack; import java.util.Stack; /** * ****************************************************************** * 日 期: 2020-01-30 星期四 * ****************************************************************** * 题 目: [155]Min Stack * //设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 * // * // * // push(x) -- 将元素 x 推入栈中。 * // pop() -- 删除栈顶的元素。 * // top() -- 获取栈顶元素。 * // getMin() -- 检索栈中的最小元素。 * // * // * // 示例: * // * // MinStack minStack = new MinStack(); * //minStack.push(-2); * //minStack.push(0); * //minStack.push(-3); * //minStack.getMin(); --> 返回 -3. * //minStack.pop(); * //minStack.top(); --> 返回 0. * //minStack.getMin(); --> 返回 -2. * // * // Related Topics 栈 设计 * ****************************************************************** * 执行耗时: 9ms,击败了 48.14% 的Java用户 * 内存消耗:40.6 MB,击败了 24.86% 的Java用户 * ****************************************************************** * 个人总结:无 * ****************************************************************** */ public class MinStack { private Stack<Integer> stack; private Stack<Integer> helper; /** * initialize your data structure here. */ public MinStack () { stack = new Stack<>(); helper = new Stack<>(); } public void push (int x) { stack.push(x); if (helper.isEmpty() || helper.peek() >= x) { helper.push(x); } } public void pop () { if (stack.size() <= 0) { return; } Integer pop = stack.pop(); if (pop.equals(helper.peek())) { helper.pop(); } } public int top () { return stack.peek(); } public int getMin () { return helper.peek(); } }
true
e6534aa7bd1fac11638ec00fd6dd1d1f2026b76e
Java
eugeniocortesi/Sagrada
/src/test/java/it/polimi/ingsw/LM26/controller/GamePhases/TestRound.java
UTF-8
15,255
2.28125
2
[]
no_license
package it.polimi.ingsw.LM26.controller.GamePhases; import it.polimi.ingsw.LM26.controller.Controller; import it.polimi.ingsw.LM26.model.Model; import it.polimi.ingsw.LM26.model.PlayArea.diceObjects.Bag; import it.polimi.ingsw.LM26.model.PlayArea.diceObjects.Die; import it.polimi.ingsw.LM26.model.PlayArea.diceObjects.DieInt; import it.polimi.ingsw.LM26.model.PlayArea.diceObjects.DraftPool; import it.polimi.ingsw.LM26.model.PublicPlayerZone.PlayerState; import it.polimi.ingsw.LM26.model.PublicPlayerZone.PlayerZone; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import static it.polimi.ingsw.LM26.controller.GamePhases.RoundState.FINISHED; import static it.polimi.ingsw.LM26.model.PublicPlayerZone.PlayerState.*; import static it.polimi.ingsw.LM26.model.SingletonModel.singletonModel; import static org.junit.Assert.*; public class TestRound { private DraftPool draftPool = new DraftPool("s"); private String name = "name"; private Round round; private int nrounds = 10, contEnd, contBeg, contSta; private int turn[] = {1, 2, 3, 4, 4, 3, 2, 1}; private Bag bag; private ArrayList<DieInt> dice = new ArrayList<DieInt>(); private PlayerZone player; private ArrayList<PlayerZone> playerZones = new ArrayList<PlayerZone>(); private Model model; private PhaseInt central; int standby=0, ending=0, begin=0; private Game game; @Before public void setup(){ Logger.getLogger(Controller.class.getPackage().getName()).getParent().getHandlers()[0].setLevel(Level.OFF); model= singletonModel(); model.reset(); PlayerZone player1 = new PlayerZone("eugenio", 0); PlayerZone player2 = new PlayerZone("Chiara", 1); PlayerZone player3 = new PlayerZone( "Claudia", 2); PlayerZone player4 = new PlayerZone("Tommaso", 3); player1.setPlayerState(ENDING); player2.setPlayerState(ENDING); player3.setPlayerState(ENDING); player4.setPlayerState(ENDING); player1.setNumberPlayer(1); player1.setWindowPatternCard(model.getDecks().getWindowPatternCardDeck().get(0)); player2.setNumberPlayer(2); player2.setWindowPatternCard(model.getDecks().getWindowPatternCardDeck().get(1)); player3.setNumberPlayer(3); player3.setWindowPatternCard(model.getDecks().getWindowPatternCardDeck().get(2)); player4.setNumberPlayer(4); player4.setWindowPatternCard(model.getDecks().getWindowPatternCardDeck().get(3)); ArrayList<PlayerZone> playerList = new ArrayList<PlayerZone>(); playerList.add(player1); playerList.add(player2); playerList.add(player3); playerList.add(player4); model.getDecks().getObjectivePrivateCardDeck().get(0).setPlayer(player1); model.getDecks().getObjectivePrivateCardDeck().get(1).setPlayer(player2); model.getDecks().getObjectivePrivateCardDeck().get(2).setPlayer(player3); model.getDecks().getObjectivePrivateCardDeck().get(3).setPlayer(player4); model.setPlayerList(playerList); playerZones = playerList; game=new Game(); //initialPhase game.getPhase().doAction(game); central=game.getPhase(); } @Test public void checkEndActionNextPlayer() { round = new Round(central.getTurn()); bag = new Bag(); round.nextPlayer(); for (int i = 0; i < (turn.length - 1); i++) { round.endAction(); round.nextPlayer(); contBeg = 0; contEnd = 0; for (PlayerZone j : playerZones) { if (j.getPlayerState().equals(PlayerState.ENDING)) contEnd++; else contBeg++; } assertEquals(3, contEnd); assertEquals(1, contBeg); assertEquals(RoundState.RUNNING, round.getRoundState()); } dice.add(bag.draw()); draftPool.setInDraft(dice); round.endAction(); assertEquals(RoundState.FINISHED, round.getRoundState()); assertEquals(1, model.getRoundTrackInt().getRoundTrackTurnList().size()); } @Test public void checkEndActionNextPlayerStandby() { round = new Round(central.getTurn()); model.getPlayerList().get(3).setPlayerState(PlayerState.STANDBY); bag = new Bag(); round = new Round(central.getTurn()); player = model.getPlayerList().get(0); player = round.nextPlayer(); while (round.getTurnCounter() < (turn.length - 1)) { round.endAction(); player = round.nextPlayer(); System.out.println(player.getNumber()); contBeg = 0; contEnd = 0; contSta = 0; for (PlayerZone j : model.getPlayerList()) { if (j.getPlayerState().equals(PlayerState.ENDING)) contEnd++; else if (j.getPlayerState().equals(PlayerState.BEGINNING)) contBeg++; else contSta++; } assertEquals(1, contBeg); assertEquals(1, contSta); assertEquals(2, contEnd); assertEquals(RoundState.RUNNING, round.getRoundState()); } dice.add(bag.draw()); draftPool.setInDraft(dice); round.endAction(); assertEquals(RoundState.FINISHED, round.getRoundState()); assertEquals(1, model.getRoundTrackInt().getRoundTrackTurnList().size()); } @Test public void checkNextPlayer() { int j=0; PlayerZone playing=null; playerZones = model.getPlayerList(); model.setBag(new Bag()); Game game=new Game(); //initialPhase game.getPhase().doAction(game); PlayerZone previous; while (!game.getPhase().getOnePlayer() && j < game.getPhase().getNrounds() ) { playing = game.getPhase().getCurrentRound().nextPlayer(); System.out.println(" NUOVO ROUND"); while (game.getPhase().getCurrentRound().getRoundState() != FINISHED) { System.out.println(" CHANGE TURN: " + playing.getName()); int n = game.getPhase().getCurrentRound().getTurnCounter(); if (n < (game.getPhase().getTurn().length / 2) - 1) { assertTrue(playing.getActionHistory().isFirstTurn()); assertFalse(playing.getActionHistory().isSecondTurn()); } if (n > (game.getPhase().getTurn().length / 2) - 1) { assertTrue(playing.getActionHistory().isSecondTurn()); assertFalse(playing.getActionHistory().isFirstTurn()); } playing.getActionHistory().setPlacement(true); playing.getActionHistory().setJump(true); playing.getActionHistory().setCardUsed(true); playing.getActionHistory().setDieUsed(true); playing.getActionHistory().setFreezed(true); model.getRestrictions().setNeedPlacement(true); model.getRestrictions().setFirstPart(true); model.getRestrictions().setTool8needPlacement(true); model.getRestrictions().setCurrentPlacement(true); model.getRestrictions().setColor("verde"); model.getRestrictions().setDie(new Die()); game.getPhase().getCurrentRound().endAction(); if (n < (game.getPhase().getTurn().length) - 1 && game.getPhase().getTurn()[n] == game.getPhase().getTurn()[n + 1]) { assertTrue(playing.getActionHistory().isSecondTurn()); assertFalse(playing.getActionHistory().isFirstTurn()); } //check reset partial action history after a turn && restrictions assertFalse(playing.getActionHistory().isPlacement() && playing.getActionHistory().isDieUsed() && playing.getActionHistory().isJump() && playing.getActionHistory().isCardUsed()); if (n < (game.getPhase().getTurn().length) - 1) assertTrue(playing.getActionHistory().isFreezed()); else { assertFalse(playing.getActionHistory().isFreezed()); assertFalse(playing.getActionHistory().isSecondTurn()); } assertFalse(model.getRestrictions().isNeedPlacement() && model.getRestrictions().isFirstPart() && model.getRestrictions().isTool8needPlacement() && model.getRestrictions().isCurrentPlacement()); assertEquals(model.getRestrictions().getDie(), null); assertEquals(model.getRestrictions().getColor(), null); playing = game.getPhase().getCurrentRound().nextPlayer(); } game.getPhase().nextRound(game.getPhase().getCurrentRound(), game); //check reset all action history after a round like rounds reset and freezing assertFalse(playing.getActionHistory().isSecondTurn() && playing.getActionHistory().isFreezed() ); if(j!=9)assertTrue(playing.getActionHistory().isFirstTurn()); j++; } } @Test public void checkStandby() { System.out.println(" ____________________________________ "); int j=0, i=0; PlayerZone playing; playerZones = model.getPlayerList(); model.setBag(new Bag()); Game game=new Game(); //initialPhase game.getPhase().doAction(game); int myStandBycounter=0; while (j < game.getPhase().getNrounds() && !game.getPhase().getOnePlayer()) { playing = game.getPhase().getCurrentRound().nextPlayer(); System.out.println(" NUOVO ROUND"); while (game.getPhase().getCurrentRound().getRoundState() != FINISHED) { System.out.println(" CHANGE TURN: " + playing.getName()); if (i == 5) { playerZones.get(1).setPlayerState(PlayerState.STANDBY); count(); System.out.println(playerZones.get(1).getName() + " went in STANDBY"); myStandBycounter++; assertEquals(standby,myStandBycounter); assertEquals(ending, 3-myStandBycounter); assertEquals(begin, 1); } if (i == 9) { playerZones.get(3).setPlayerState(PlayerState.STANDBY); count(); System.out.println(playerZones.get(3).getName() + " went in STANDBY"); myStandBycounter++; assertEquals(standby,myStandBycounter); assertEquals(ending, 3-myStandBycounter); assertEquals(begin, 1); } if (i == 12) { playerZones.get(0).setPlayerState(PlayerState.STANDBY); count(); System.out.println(playerZones.get(0).getName() + " went in STANDBY"); myStandBycounter++; assertEquals(standby,myStandBycounter); assertEquals(ending, 3-myStandBycounter); assertEquals(begin, 1); } if (i == 16) { if (playerZones.get(1).getPlayerState()!=BEGINNING) { playerZones.get(1).setPlayerState(PlayerState.ENDING); count(); System.out.println(playerZones.get(1).getName() + " exit STANDBY"); myStandBycounter--; assertEquals(standby,myStandBycounter); assertEquals(ending, 3-myStandBycounter); assertEquals(begin, 1); } } if (i == 19) { if (playerZones.get(3).getPlayerState()!=BEGINNING) { playerZones.get(3).setPlayerState(PlayerState.ENDING); count(); System.out.println(playerZones.get(3).getName() + "exit STANDBY"); myStandBycounter--; assertEquals(standby,myStandBycounter); assertEquals(ending, 3-myStandBycounter); assertEquals(begin, 1); } } if (i == 22) { playerZones.get(2).setPlayerState(PlayerState.STANDBY); count(); System.out.println(playerZones.get(2).getName() + " went in STANDBY"); myStandBycounter++; assertEquals(standby,myStandBycounter); assertEquals(ending, 3-myStandBycounter); assertEquals(begin, 1); } if (i == 23) { playerZones.get(3).setPlayerState(PlayerState.STANDBY); count(); System.out.println(playerZones.get(3).getName() + "went STANDBY"); myStandBycounter++; assertEquals(standby,myStandBycounter); assertEquals(ending, 3-myStandBycounter); assertEquals(begin, 1); } if (i == 26) { if (playerZones.get(1).getPlayerState()!=BEGINNING) { playerZones.get(1).setPlayerState(PlayerState.ENDING); count(); System.out.println(playerZones.get(1).getName() + " exit STANDBY"); myStandBycounter--; assertEquals(standby,myStandBycounter); assertEquals(ending, 3-myStandBycounter); assertEquals(begin, 1); } } i++; game.getPhase().getCurrentRound().endAction(); if(game.getPhase().getCurrentRound().getRoundState()!=FINISHED) playing = game.getPhase().getCurrentRound().nextPlayer(); } game.getPhase().nextRound(game.getPhase().getCurrentRound(), game); j++; } } public void count(){ standby=0; ending=0; begin=0; for(int i=0;i<model.getPlayerList().size();i++){ if (model.getPlayer(i).getPlayerState()==STANDBY)standby++; if (model.getPlayer(i).getPlayerState()==ENDING)ending++; if (model.getPlayer(i).getPlayerState()==BEGINNING)begin++; } } }
true
b7995f8e62d307c9de6a1293389079d6122a5ee8
Java
mincatsg/practiceone
/NThanN2.java
UTF-8
898
3.171875
3
[]
no_license
package NKTest; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Map; import java.util.HashMap; public class NThanN2 { // n个数里出现次数大于等于n/2的数 public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Map<String, Integer> map = new HashMap<>(); String[] line = br.readLine().split(" "); for(int i = 0; i < line.length; i++){ if(map.containsKey(line[i])){ int count = map.get(line[i]); map.put(line[i], count + 1); }else{ map.put(line[i], 1); } } for(String x : map.keySet()){ if(map.get(x) >= (line.length / 2)){ System.out.println(x); } } } }
true
5ca1aa9d009e14ccea66155d74163d576cda01b0
Java
zengzhaoxing/app
/app/src/main/java/com/example/admin/fastpay/view/GetCodeView.java
UTF-8
2,298
2.046875
2
[]
no_license
package com.example.admin.fastpay.view; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import com.example.admin.fastpay.R; import com.zhaoxing.view.sharpview.SharpTextView; import com.zxz.www.base.utils.ResUtil; import com.zxz.www.base.utils.SpecialTask; /** * Created by 曾宪梓 on 2018/1/1. */ public class GetCodeView extends SharpTextView { private SpecialTask mSpecialTask; private String mText; public void setEnableTime(int enableTime) { mEnableTime = enableTime; } private int mEnableTime = 60; public GetCodeView(Context context) { super(context); init(); } public GetCodeView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public GetCodeView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void setDisable() { if (isClickable()) { getRenderProxy().setBackgroundColor(R.color.bg_gray); mSpecialTask.start(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mSpecialTask != null) { mSpecialTask.stop(); } } private void init() { mText = getText().toString(); getRenderProxy().setBackgroundColor(ResUtil.getColor(R.color.blue)); mSpecialTask = new SpecialTask(new Handler(), new SpecialTask.OnEndListener() { @Override public void onEnd() { if (GetCodeView.this.getContext() != null) { setClickable(false); setClickable(true); getRenderProxy().setBackgroundColor(ResUtil.getColor(R.color.blue)); setText(mText); } } }, new SpecialTask.OnPeriodListener() { @Override public void onPeriod(int currentTime) { if (GetCodeView.this.getContext() != null) { int time = currentTime / 1000; setText(time + "s"); } } }, 1000, mEnableTime * 1000); } }
true
8e8111660b00ace6120f06f5746d7112fa48f87a
Java
XeonLyfe/Backdoored-1.7-Deobf-Source-Leak
/com/google/api/client/repackaged/com/google/common/base/CharMatcher$BreakingWhitespace.java
UTF-8
904
2.578125
3
[ "MIT" ]
permissive
package com.google.api.client.repackaged.com.google.common.base; final class CharMatcher$BreakingWhitespace extends CharMatcher { static final CharMatcher INSTANCE = new CharMatcher$BreakingWhitespace(); private CharMatcher$BreakingWhitespace() { } public boolean matches(char c) { switch(c) { case '\t': case '\n': case '\u000b': case '\f': case '\r': case ' ': case '\u0085': case '\u1680': case '\u2028': case '\u2029': case '\u205f': case '\u3000': return true; case '\u2007': return false; default: return c >= 8192 && c <= 8202; } } public String toString() { return "CharMatcher.breakingWhitespace()"; } // $FF: synthetic method // $FF: bridge method public boolean apply(Object x0) { return super.apply((Character)x0); } }
true
9c38d49e8c80303a0726c41849fa0a1556b8c12f
Java
kugomusic/leetcode-java
/src/firstPass/easy/_342/Solution.java
UTF-8
807
3.125
3
[ "MIT" ]
permissive
package firstPass.easy._342; /** * @description: * @author: tc * @create: 2019/07/12 09:47 */ /* 执行用时 :1 ms, 在所有 Java 提交中击败了100.00%的用户 内存消耗 :33.5 MB, 在所有 Java 提交中击败了13.56%的用户 */ public class Solution { public boolean isPowerOfFour(int num) { if (num <= 0) { return false; } if (num == 1) { return true; } while (num > 1) { if (num % 4 != 0) { return false; } num /= 4; } return true; } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.isPowerOfFour(16)); System.out.println(solution.isPowerOfFour(5)); } }
true
07eb651bd8336ea3e7445f396367659531887f7b
Java
sorinb97/tester
/src/main/java/com/license/tester/transfer/mapping/SubGroupMapper.java
UTF-8
1,120
2.359375
2
[]
no_license
package com.license.tester.transfer.mapping; import com.license.tester.db.model.SubGroup; import com.license.tester.db.model.Teacher; import com.license.tester.db.repo.TeacherRepository; import com.license.tester.transfer.dto.SubGroupDto; import org.springframework.stereotype.Component; import java.util.UUID; @Component public class SubGroupMapper { private final TeacherRepository teacherRepository; public SubGroupMapper(TeacherRepository teacherRepository) { this.teacherRepository = teacherRepository; } public SubGroupDto convertSubGroupToDto(SubGroup subGroup) { return new SubGroupDto(subGroup.getId().toString(), subGroup.getName(), subGroup.getTeacher().getId().toString()); } public SubGroup convertToSubGroupEntity(SubGroupDto dto) { Teacher teacher = teacherRepository.findById(UUID.fromString(dto.getTeacherId())).get(); SubGroup subGroup = new SubGroup(dto.getName(), teacher); if (dto.getId() != null && !dto.getId().isEmpty()) { subGroup.setId(UUID.fromString(dto.getId())); } return subGroup; } }
true
32d53c3053cfbc01e53ac8d603cff2ee4a84018e
Java
facetalk/facetalk_web
/springMVC/src/main/java/com/facehu/web/controller/FaceSmsController.java
UTF-8
4,791
1.96875
2
[]
no_license
package com.facehu.web.controller; import com.facehu.web.dao.UserDao; import com.facehu.web.model.User; import com.facehu.web.util.CtlHelp; import com.facehu.web.util.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by wadang on 14-8-23. */ @Controller @RequestMapping("/facesms") public class FaceSmsController { @Autowired private UserDao userDao; @Value("${faceSmsGifPath}") private String faceSmsGifPath; @Value("${onlineUserUrl}") private String onlineUserUrl; @ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/saveGif") public CtlHelp.AjaxResult saveGif(@RequestParam("picData") String picData, @RequestParam("gifId") String gifId) { String savefileName = new StringBuilder().append(faceSmsGifPath).append(File.separator) .append(gifId.substring(0, 2)).append(File.separator) .append(gifId.substring(2, 4)).append(File.separator) .append(gifId).append(".gif").toString(); try { CtlHelp.writePicToFile(picData.substring(22), savefileName); return new CtlHelp.AjaxResult(CtlHelp.AjaxResult.resultState.success, "成功"); } catch (IOException e) { e.printStackTrace(); return new CtlHelp.AjaxResult(CtlHelp.AjaxResult.resultState.failure, "失败" + e.getMessage()); } } @ResponseBody @RequestMapping(method = RequestMethod.GET, value = "/getUserList") public List<UserStatus> getUserList() { List<String> userlist = userDao.listUserNamesByComplete(1, true); List<UserStatus> userStatusList = filterUserList(userlist); return userStatusList; } @ResponseBody @RequestMapping(method = RequestMethod.GET, value = "/getUserListByPage/{userName}/{firstResult}/{maxResult}") public List<UserStatus> getUserListByPage(@PathVariable String userName, @PathVariable int firstResult, @PathVariable int maxResult) { if (firstResult < 0 || maxResult < 0) { return Collections.emptyList(); } User user = userDao.getUserByName(userName); if (user == null) { return null; } List<String> userlist = userDao.listUserNamesByCompleteAndGender(1, user.getGender() == 0 ? true : false); List<UserStatus> userStatusList = filterUserList(userlist); int size = firstResult + maxResult; if (size > userStatusList.size()) { size = userStatusList.size(); } if (firstResult > userStatusList.size()) { return Collections.emptyList(); } return userStatusList.subList(firstResult, size); } private List<UserStatus> filterUserList(List<String> userlist) { List<UserStatus> userStatusList = new ArrayList<UserStatus>(); try { String onlineUsers = CtlHelp.getPageHTML(onlineUserUrl, "GBK"); // String onlineUsers = "d84bf6862bd649b8@facetalk/5280,b9938b2bb78f1edc@facetalk/5280,956e0df66aa959b4@facetalk/5280,7189910abd51e75e@facetalk/5280,5c53931e0a9f6517@facetalk/5280"; Logger.debug(this, "获取在线用户: " + onlineUsers); String[] jid = onlineUsers.split(","); for (int i = 0; i < jid.length; i++) { String s = jid[i]; String userName = s.split("@")[0]; userlist.remove(userName); userStatusList.add(new UserStatus(userName, true)); } } catch (Exception e) { e.printStackTrace(); } for (String userName : userlist) { userStatusList.add(new UserStatus(userName, false)); } return userStatusList; } public static class UserStatus { String userName; boolean isOnline; public UserStatus(String userName, boolean isOnline) { this.userName = userName; this.isOnline = isOnline; } public UserStatus() { } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public boolean isOnline() { return isOnline; } public void setOnline(boolean isOnline) { this.isOnline = isOnline; } } }
true
9e635cd36e8df3f855cd7a13b327cfd7627bcf44
Java
linjunbobo/recruiting
/src/main/java/com/graduation/project/Controller/FileController.java
UTF-8
2,210
2.1875
2
[]
no_license
package com.graduation.project.Controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.Tag; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import springfox.documentation.annotations.ApiIgnore; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("/file") @Api(tags = "文件上传") public class FileController { @PostMapping("/upload") @ApiImplicitParams({ @ApiImplicitParam(name = "myFile", value = "文件"), }) public Map<String,String> file(@ApiIgnore HttpServletRequest request, @RequestParam("myFile") MultipartFile myFile) throws IllegalStateException, IOException { // System.out.println("myFile="+myFile); Map<String,String> map1 = new HashMap<>(); //获取保存文件的真实路径 //String savePath=request.getServletContext().getRealPath("/uploads"); String savePath = "C:\\uploads"; //获取文件上传名字 String filename =myFile.getOriginalFilename(); // System.out.println("filename="+filename); //创建File对象 File file =new File(savePath,filename); //System.out.println("file"+file); if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } try { //保存文件 myFile.transferTo(file); //绝对地址 String imgIrl=savePath+"\\"+filename; // 图片地址 String imgUrl = request.getContextPath() + "/uploads/" + filename; map1.put("src",imgIrl); map1.put("fileName",filename); return map1; } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } return map1; } }
true
a930b364248178531b2bdd29ac61ad2ad6ceb484
Java
majrul/ycp
/day14/spring-intro/TestIoC.java
UTF-8
502
2.234375
2
[]
no_license
package com.cdac.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.cdac.component.HelloWorld; public class TestIoC { public static void main(String[] args) { //Loading the IoC container of Spring ApplicationContext context = new ClassPathXmlApplicationContext("app-config.xml"); HelloWorld h = (HelloWorld) context.getBean("hw"); //id System.out.println(h.sayHello("Majrul")); } }
true
b72e2ab8e5bf988e9e3f922a290dd5e1a1044f3b
Java
forestsky1/Stockly
/app/src/main/java/com/larkspur/stockly/data/IDataCache.java
UTF-8
2,337
3.015625
3
[]
no_license
package com.larkspur.stockly.data; import com.larkspur.stockly.models.Category; import com.larkspur.stockly.models.IStock; import java.util.List; public interface IDataCache { /** * Add all stock to the cache * @param stocks : representing list of stocks to add to the cache */ void addAllStock(List<IStock> stocks); /** * Add a category stock to the cache. * @param category : category type of the stocks. * @param stocks : list of stocks that is of that category. */ void addCategoryStock(Category category, List<IStock> stocks); /** * Add most viewed stock to the category. * @param stocks : representing the most viewed stock. */ void addMostViewStock(IStock stocks); /** * -- UNUSED -- * Add list of most viewed stocks. * @param stocks : representing the list of most viewed stocks */ void addMostViewStocks(List<IStock> stocks); /** * Get all stocks that is currently in cache * @return List<IStock> : representing the list of stocks. */ List<IStock> getAllStock(); /** * Get top N most viewed stocks * @param n : number of stocks to get. * @return List<IStock> : representing the list of IStock. */ List<IStock> getTopNMostViewed(int n); /** * Get list of stocks for a specific category. (If there are any in cache) * @param category : Category to get stocks for. * @return List<IStock> : list of stocks that is of the input category. */ List<IStock> getCategoryStock(Category category); /** * Get a stock with the highest week gainer. (in terms of percentage change). * @return IStock : representing the top gained stock. */ IStock getTopGainer(); /** * Get a stock with the highest week loser. (in terms of percentage change). * @return IStock : representing the top stock stock. */ IStock getTopLoser(); /** * Add a stock with the highest week gainer. (in terms of percentage change). * @param stock : representing the top gained stock. */ void addTopGainer(IStock stock); /** * Add a stock with the highest week loser. (in terms of percentage change). * @param stock : representing the top lost stock. */ void addTopLoser(IStock stock); }
true
20e7bb43148e6d4f06755dffa82fdf27a3477346
Java
FEJonesYang/Algorithm
/ZuoChengYun/src/sort/BubbleSort.java
UTF-8
945
3.9375
4
[]
no_license
package sort; /** * @Author: JonesYang * @Data: 2021-06-16 * @Description: 冒泡排序算法 */ public class BubbleSort { private int[] bubbleSort(int[] arr) { // 检查是否有效 if (arr == null || arr.length < 2) { return arr; } // 开始进行冒泡排序 for (int i = 0; i < arr.length - 1; i++) { // 对冒泡排序的简单优化 boolean isChange = false; for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; isChange = true; } } // 如果没有发生数组元素交换,说明数组都是有序的,则跳出循环 if (!isChange) { break; } } return arr; } }
true
2938c970143ea044272eb2d27e7f9acff37d150e
Java
devonuu/GOJ
/src/org/basic/enums/Gender.java
UTF-8
845
3.515625
4
[]
no_license
package org.basic.enums; public enum Gender { MALE("M","남"), FEMALE("F","여"); //객체의 생성과 값의 할당까지 ENUM에서 한번에 진행함. //생성자의 개수에 따라 MALE이라는 객체는 남일수도 M일수도 //열거형이기 때문에 Runtime이 아닌 Compile 단계에서 이미 MALE에는 M과 남이라는 값이 할당됨 private String genderShort; private String genderKor; private Gender(){} private Gender(String genderShort, String genderKor){ this.genderShort = genderShort; this.genderKor = genderKor; } public String getGenderShort(){ return this.genderShort; } public String getGenderKor(){ return this.genderKor; } public String makeFullWordGender(){ return this.getGenderKor() + "성"; } }
true
cabc57715e33320a254e3b2fa2eee8fd5a46009c
Java
JilingLee462362/ssh_HR_V005
/src/com/tzhu/ssh/controller/EngageInterviewAction.java
GB18030
4,715
2.015625
2
[]
no_license
package com.tzhu.ssh.controller; import java.util.List; import javax.annotation.Resource; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ModelDriven; import com.tzhu.ssh.appcomm.base.BaseAction; import com.tzhu.ssh.appcomm.util.Page; import com.tzhu.ssh.biz.EngageInterviewBizI; import com.tzhu.ssh.entity.EngageInterview; /** * ˵Action * @author ˼ *2018-7-26 */ @ParentPackage(value="struts-default") @Controller @Namespace("/ei") public class EngageInterviewAction extends BaseAction implements ModelDriven<EngageInterview> { private EngageInterview engageInterview = new EngageInterview(); private EngageInterviewBizI engageInterviewBizI; private Page page; @Resource(name="engageInterviewBizI") public void setEngageInterviewBizI(EngageInterviewBizI engageInterviewBizI) { this.engageInterviewBizI = engageInterviewBizI; } //Խ¼ݿ @Action(value="save",results={@Result(name="success",location="/admin/engage/success.jsp")}) public String saveEngageInterview() { System.out.println(engageInterview.toString()); engageInterviewBizI.save(engageInterview); return "success"; } //ҳѯԽ @Action(value="search",results={@Result(name="engageInterview_search",location="/admin/engage/engage_interview_search.jsp")}) public String searchEngageInterview() { //ҳϢ Long count = engageInterviewBizI.count("select count(*) from EngageInterview"); page.setTotalCount(Integer.valueOf(count.toString())); System.out.println(page.toString()); System.out.println(engageInterview.toString()); StringBuffer hql = new StringBuffer(" from EngageInterview where 1=1 "); //жԲΪʱƴַ if(engageInterview.getHumanMajorKindName()!=null && !"".equals(engageInterview.getHumanMajorKindName())){ //parms[0] = engageInterview.getHumanMajorKindName(); hql.append(" and humanMajorKindName=" + "'" + engageInterview.getHumanMajorKindName() + "'"); }else if(engageInterview.getHumanMajorName()!=null && !"".equals(engageInterview.getHumanMajorName())){ //parms[1] = engageInterview.getHumanMajorName(); hql.append(" and humanMajorName=" + "'" + engageInterview.getHumanMajorName() + "'"); }else if(engageInterview.getCheckStatus()!=null && !"".equals(engageInterview.getCheckStatus())){ //parms[2] = String.valueOf(engageInterview.getCheckStatus()); hql.append(" and checkStatus=" + "'" + engageInterview.getCheckStatus() + "'"); } System.out.println(hql.toString()); //ѯԽ List<EngageInterview> listEngageInterview = engageInterviewBizI.find(hql.toString(), new String[]{}, page.getPageNo(), page.getPageSize()); requestMap.put("listEngageInterview", listEngageInterview); requestMap.put("page", page); return "engageInterview_search"; } //Ӳѯҳת޸ҳ @Action(value="toChange",results={@Result(name="toChange",location="/admin/engage/engage_interview_change.jsp")}) public String toChange() { //ȡҪ޸Ķid Integer einId = engageInterview.getEinId(); //idвѯ EngageInterview changeEngageInterview = engageInterviewBizI.get(" from EngageInterview where einId = " +"'"+einId+"'", new String[]{}); //Ҫ޸ĵĶsession requestMap.put("changeEngageInterview", changeEngageInterview); return "toChange"; } //޸Ϣύ @Action(value="change",results={@Result(name="changeSuccess",location="/admin/engage/success.jsp")}) public String change() { //ȡ EngageInterview toChangeEngageInterview = (EngageInterview) sessionMap.get("changeEngageInterview"); Integer ceinId = toChangeEngageInterview.getEinId(); engageInterview.setEinId(ceinId); //޸Ϣ if(engageInterview!=null){ engageInterviewBizI.update(engageInterview); } return "changeSuccess"; } //ģ @Override public EngageInterview getModel() { // TODO Auto-generated method stub return engageInterview; } public Page getPage() { return page; } public void setPage(Page page) { this.page = page; } }
true
f55038064def98eadd7455fe8bcda92c91a80e7b
Java
ralsc/Condominio
/src/java/entidades/Condominio.java
UTF-8
3,365
2.078125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entidades; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; /** * * @author Rafael */ @Entity @Table(name = "Condominio") public class Condominio implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Temporal(TemporalType.DATE) @Column private Date data; @Column private Float valor; @Column private String observacao; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "fk_morador") private Morador morador; @OneToOne(fetch = FetchType.EAGER) @Cascade({ CascadeType.ALL }) @JoinColumn(name = "fk_pagamento", nullable = false) private Pagamento pagamento; @OneToMany(orphanRemoval = true, fetch = FetchType.LAZY, mappedBy = "condominio", cascade = javax.persistence.CascadeType.ALL) @LazyCollection(LazyCollectionOption.FALSE) private List<TaxaMulta> listTaxaMulta; public Condominio(){} public Condominio(Integer id, Date data, Float valor, String observacao, Morador morador, Pagamento pagamento) { this.id = id; this.data = data; this.valor = valor; this.morador = morador; this.pagamento = pagamento; this.observacao = observacao; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Pagamento getPagamento() { return pagamento; } public void setPagamento(Pagamento pagamento) { this.pagamento = pagamento; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } public Float getValor() { return valor; } public void setValor(Float valor) { this.valor = valor; } public Morador getMorador() { return morador; } public void setMorador(Morador morador) { this.morador = morador; } public List<TaxaMulta> getListTaxaMulta() { return listTaxaMulta; } public void setListTaxaMulta(List<TaxaMulta> listTaxaMulta) { this.listTaxaMulta = listTaxaMulta; } public String getObservacao() { return observacao; } public void setObservacao(String observacao) { this.observacao = observacao; } }
true
ae5691bb5effbc9efa320090429dfd5b86945c55
Java
patientZer0/First-Android-Project--TrailMapper
/Trail Mapper/src/trail/mapper/MyOverlays.java
UTF-8
1,786
2.6875
3
[]
no_license
package trail.mapper; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; public class MyOverlays extends Overlay { private Context context; private List<OverlayItem> overlays; public MyOverlays(Context context) { this.context = context; overlays = new ArrayList<OverlayItem>(); } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow){ super.draw(canvas, mapView, shadow); if (shadow == false) { for (int i = 0; i < overlays.size(); i++) { OverlayItem item = overlays.get(i); GeoPoint gPoint = item.getPoint(); Point pxPoint = new Point(); mapView.getProjection().toPixels(gPoint, pxPoint); if (i == 0) { Paint painter = new Paint(); painter.setColor(Color.GREEN); painter.setStrokeWidth(4); canvas.drawCircle(pxPoint.x, pxPoint.y, 5, painter); } else { OverlayItem gpLast = overlays.get(i-1); GeoPoint gPointLast = gpLast.getPoint(); Point pxPointLast = new Point(); mapView.getProjection().toPixels(gPointLast, pxPointLast); Paint painter = new Paint(); painter.setColor(Color.GREEN); painter.setStrokeWidth(4); canvas.drawLine(pxPoint.x, pxPoint.y, pxPointLast.x, pxPointLast.y, painter); } } } } protected OverlayItem createItem(int i) { return overlays.get(i); } public int size() { return overlays.size(); } public void addOverlay(OverlayItem overlay) { overlays.add(overlay); } }
true
764cba06f3edb5142a03c34c168e812649b40361
Java
damanpreetsb/QuizApp
/app/src/main/java/com/singh/daman/quizapp/di/module/NetModule.java
UTF-8
2,202
2.203125
2
[]
no_license
package com.singh.daman.quizapp.di.module; import android.content.Context; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.singh.daman.quizapp.InitApp; import com.singh.daman.quizapp.data.ApiInterface; import java.io.File; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by Daman on 11/3/2017. */ @Module public class NetModule { private final Context context; private static final String BASE_URL = "https://qriusity.com/v1/"; public NetModule(final Context context) { this.context = context; } @Provides @Singleton ApiInterface provideApi(Retrofit retrofit) { return retrofit.create(ApiInterface.class); } @Provides @Singleton Retrofit provideRetrofit(OkHttpClient okHttpClient, Gson gson) { return new Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } @Provides @Singleton OkHttpClient provideOkHttpClient() { OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); httpClientBuilder.connectTimeout(10, TimeUnit.SECONDS); httpClientBuilder.readTimeout(10, TimeUnit.SECONDS); httpClientBuilder.writeTimeout(5, TimeUnit.SECONDS); httpClientBuilder.cache(new Cache(new File(InitApp .getApplication(context).getCacheDir(), "responses"), 10 * 1024 * 1024)); return httpClientBuilder.build(); } @Provides @Singleton Gson provideGson() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); } }
true
9e73bbb85d2123720f8c3c6c6dffdb44144b67b6
Java
alvin-qh/study-java
/se/ratelimit/src/test/java/alvin/study/se/ratelimit/TokenBucketRateLimiterTest.java
UTF-8
2,222
3.234375
3
[]
no_license
package alvin.study.se.ratelimit; import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicInteger; import static org.assertj.core.api.BDDAssertions.then; /** * 测试 {@link TokenBucketRateLimiter} 类型, 通过令牌桶进行限流 */ class TokenBucketRateLimiterTest extends RateLimiterTest { /** * 测试 {@link TokenBucketRateLimiter#tryAcquire(int)} 方法, 通过令牌桶进行限流 * * <p> * 本次测试参数值为 {@code 1} 的情况 * </p> */ @Test void testTryAcquire_shouldLimitOneByOne() { // 实例化令牌桶进行限流对象, 桶容量 50, 每秒创建 50 个令牌 var limiter = new TokenBucketRateLimiter(50, 50); // 记录通过限流的调用次数 var executeCount = new AtomicInteger(); // 记录被限流的调用次数 var blockedCount = new AtomicInteger(); // 按每秒执行 100 次的频率执行 2s 时间 executeByRate(100, 2, () -> { if (limiter.tryAcquire(1)) { // 记录通过限流 executeCount.incrementAndGet(); } else { // 记录被限流 blockedCount.incrementAndGet(); } }); // 确认通过限流的次数约为 100 次 then(executeCount.get()).isGreaterThan(70).isLessThanOrEqualTo(130); // 确认未通过限流的次数约为 100 次 then(blockedCount.get()).isGreaterThan(70).isLessThanOrEqualTo(130); } /** * 测试 {@link SlidingWindowRateLimiter#tryAcquire(int)} 方法, 通过令牌桶进行限流 * * <p> * 本次测试参数值大于 {@code 1} 的情况 * </p> */ @Test void testTryAcquire_shouldLimitByBatch() { // 实例化令牌桶进行限流对象, 桶容量 50, 每秒创建 50 个令牌 var limiter = new TokenBucketRateLimiter(50, 50); // 先请求 30 次调用, 在限流次数范围内, 返回允许 var r = limiter.tryAcquire(30); then(r).isTrue(); // 再请求 30 次调用, 超出限流次数, 返回不允许 r = limiter.tryAcquire(30); then(r).isFalse(); } }
true
c0fdf4f23d834f553863b683658ae348245b9569
Java
searles/meelanlang
/src/main/java/at/searles/meelan/parser/MeelanParser.java
UTF-8
14,927
2.234375
2
[]
no_license
package at.searles.meelan.parser; import at.searles.lexer.Lexer; import at.searles.lexer.SkipTokenizer; import at.searles.meelan.ops.Instruction; import at.searles.meelan.ops.arithmetics.*; import at.searles.meelan.ops.bool.*; import at.searles.meelan.ops.comparison.*; import at.searles.meelan.ops.cons.Cons; import at.searles.meelan.optree.Tree; import at.searles.meelan.optree.Vec; import at.searles.meelan.optree.compiled.*; import at.searles.meelan.optree.inlined.*; import at.searles.meelan.values.Bool; import at.searles.meelan.values.Int; import at.searles.meelan.values.Real; import at.searles.meelan.values.StringVal; import at.searles.parsing.*; import at.searles.parsing.utils.Utils; import at.searles.regex.Regex; import at.searles.regex.RegexParser; import org.jetbrains.annotations.NotNull; import java.util.List; public class MeelanParser { private static class Holder { static final MeelanParser INSTANCE = new MeelanParser(); } public static Parser<List<Tree>> stmts() { return Holder.INSTANCE.stmts; } public static Parser<Tree> stmt() { return Holder.INSTANCE.stmt; } public static Parser<Tree> expr() { return Holder.INSTANCE.expr; } public static Recognizer eof() { // XXX This should rather be part of the parser itself, // but due to backwards compatibility it is not. return Holder.INSTANCE.eof; } public static int whiteSpace() { return Holder.INSTANCE.wsId; } public static int singleLineComment() { return Holder.INSTANCE.slCommentId; } public static int multiLineComment() { return Holder.INSTANCE.mlCommentId; } private SkipTokenizer lexer; private Parser<List<Tree>> stmts; private Parser<Tree> expr; private Parser<Tree> stmt; private Recognizer eof; private int mlCommentId; private int slCommentId; private int wsId; public enum Annotation { STMT, EXPR, BLOCK, IN_BLOCK, STRING, VALUE, SEPARATOR, // separates two elements. Usually spacing after separator BREAK, KEYWORD_INFIX, KEYWORD_PREFIX, KEYWORD_DEF, } private MeelanParser() { initLexer(); initParser(); this.eof = Recognizer.eof(lexer); } private Regex r(String regex) { return RegexParser.parse(regex); } private Recognizer op(String s) { return Recognizer.fromString(s, lexer, false); } private Recognizer op(String s, Annotation labelId) { return Recognizer.fromString(s, lexer, false).annotate(labelId); } private void initLexer() { this.lexer = new SkipTokenizer(new Lexer()); wsId = lexer.add(r("[\n\r\t ]+")); slCommentId = lexer.add(r("'//'[^\n]*")); mlCommentId = lexer.add(r("('/*'.*'*/')!")); lexer.addSkipped(wsId); lexer.addSkipped(slCommentId); lexer.addSkipped(mlCommentId); } private void initParser() { Parser<String> idString = Parser.fromRegex(r("[A-Za-z_][0-9A-Za-z_]*"), lexer, true, new Mapping<CharSequence, String>() { @Override public String parse(ParserStream stream, @NotNull CharSequence left) { return left.toString(); } @Override public CharSequence left(@NotNull String result) { return result; } }); Parser<String> quoted = Parser.fromRegex(r("('\"'.*'\"')!"), lexer, true, new Mapping<CharSequence, String>() { @Override public String parse(ParserStream stream, @NotNull CharSequence left) { return left.toString().substring(1, left.length() - 1); } @Override public CharSequence left(@NotNull String result) { return "\"" + result + "\""; } }).annotate(Annotation.STRING); Parser<Tree> id = Parser.fromRegex(r("[A-Za-z_][0-9A-Za-z_]*"), lexer, true, Id.TOK); Parser<Tree> integer = Parser.fromRegex(r("'0'|[1-9][0-9]{0,8}"), lexer, false, Int.NUM); // max is 99999999 Parser<Tree> string = Parser.fromRegex(r("('\"'.*'\"')!"), lexer, false, StringVal.TOK); Parser<Tree> hexColor = Parser.fromRegex(r("'#'[0-9A-Fa-f]{1,8}"), lexer, false, Int.HEX); Parser<Tree> real = Parser.fromRegex(r("('0'|[1-9][0-9]*)('.'[0-9]*)?([eE][+\\-]?[0-9]+)?"), lexer, false, Real.TOK); Parser<Tree> bool = Parser.fromRegex(r("'true'|'false'"), lexer, false, Bool.TOK); Parser<Tree> primitives = id.or( integer.or(string).or(hexColor).or(real).or(bool) .annotate(Annotation.VALUE) ); Ref<Tree> exprRef = new Ref<>("expr"); Parser<List<Tree>> exprList = Utils.list(exprRef, op(",", Annotation.SEPARATOR)); Parser<Tree> vector = op("[") .then(exprList) .then(op("]")) .then(Vec.CREATOR); Parser<Tree> primary = primitives.or(vector) .or( op("(") .then(exprRef) .then(op(")"))); Parser<Tree> postfix = primary.then( Reducer.rep(op(".").then(idString.fold(Qualified.CREATOR)))); Ref<Tree> appRef = new Ref<>("app"); // If there is only one argument, inversion will take the second branch. Parser<List<Tree>> parameters = op("(") .then(exprList) .then(op(")")) .then(Reducer.opt( appRef.fold(App.APPLY_TUPEL) )) .or(Utils.singleton(appRef.annotate(Annotation.BREAK)), true); Parser<Tree> app = postfix.then(Reducer.opt(parameters.fold(App.CREATOR))); appRef.set(app); Ref<List<Tree>> stmtsRef = new Ref<>("stmt"); Parser<Tree> block = op("{") .then(stmtsRef.annotate(Annotation.IN_BLOCK)) .then(op("}")) .then(Block.CREATOR) .annotate(Annotation.BLOCK); Parser<Tree> term = block.or(app); Ref<Tree> unexprRef = new Ref<>("unexpr"); Parser<Tree> unexpr = op("-", Annotation.KEYWORD_PREFIX).then(unexprRef).then(Instruction.unary(Neg.get())) .or(op("/", Annotation.KEYWORD_PREFIX).then(unexprRef).then(Instruction.unary(Recip.get()))) .or(term); unexprRef.set(unexpr); Parser<Tree> ifexpr = unexpr.then( Reducer.opt( op("if", Annotation.KEYWORD_INFIX) .then(Utils.<Tree>properties("thenBranch")) .then(Utils.put("condition", exprRef)) .then(op("else", Annotation.KEYWORD_INFIX)) .then(Utils.put("elseBranch", exprRef)) .then(Utils.create(IfElse.class, "condition", "thenBranch", "elseBranch")) ) ); // a ( ':' a ( ':' )* )? Parser<Tree> consexpr = ifexpr.then( Reducer.opt( op(":", Annotation.KEYWORD_INFIX) .then(Utils.binary(ifexpr)) .then( Reducer.rep( Utils.append(op(":", Annotation.KEYWORD_INFIX).then(ifexpr), 2) ) ) .then(Instruction.app(Cons.get())) ) ); Parser<Tree> powexpr = consexpr.then(Reducer.rep( op("^", Annotation.KEYWORD_INFIX).then(consexpr.fold(Instruction.binary(Pow.get()))) )); Parser<Tree> mulexpr = powexpr.then(Reducer.rep( op("*", Annotation.KEYWORD_INFIX).then(powexpr.fold(Instruction.binary(Mul.get()))) .or(op("/", Annotation.KEYWORD_INFIX).then(powexpr.fold(Instruction.binary(Div.get())))) .or(op("%", Annotation.KEYWORD_INFIX).then(powexpr.fold(Instruction.binary(Mod.get())))) )); Parser<Tree> sumexpr = mulexpr.then(Reducer.rep( op("+", Annotation.KEYWORD_INFIX).then(mulexpr.fold(Instruction.binary(Add.get()))) .or(op("-", Annotation.KEYWORD_INFIX).then(mulexpr.fold(Instruction.binary(Sub.get())))) )); Parser<Tree> compexpr = sumexpr.then( Reducer.opt( op("<", Annotation.KEYWORD_INFIX).then(sumexpr).fold(Instruction.binary(Less.get())) .or(op("=<", Annotation.KEYWORD_INFIX).then(sumexpr).fold(Instruction.binary(LessEq.get()))) .or(op("==", Annotation.KEYWORD_INFIX).then(sumexpr).fold(Instruction.binary(Equal.get()))) .or(op("><", Annotation.KEYWORD_INFIX).then(sumexpr).fold(Instruction.binary(NonEqual.get()))) .or(op(">=", Annotation.KEYWORD_INFIX).then(sumexpr).fold(Instruction.binary(GreaterEqual.get()))) .or(op(">", Annotation.KEYWORD_INFIX).then(sumexpr).fold(Instruction.binary(Greater.get()))) ) ); Ref<Tree> literalRef = new Ref<>("literal"); Parser<Tree> literal = op("not", Annotation.KEYWORD_PREFIX).then(literalRef).then(Instruction.unary(Not.get())) .or(compexpr); literalRef.set(literal); Parser<Tree> andexpr = literal.then(Reducer.rep(op("and", Annotation.KEYWORD_INFIX).then(literal.fold(Instruction.binary(And.get()))))); Parser<Tree> orexpr = andexpr.then(Reducer.rep(op("or", Annotation.KEYWORD_INFIX).then(andexpr.fold(Instruction.binary(Or.get()))))); Parser<Tree> assignexpr = orexpr.then( Reducer.opt( op("=", Annotation.KEYWORD_INFIX).then(orexpr).fold(Assign.CREATE) ) ); expr = assignexpr.annotate(Annotation.EXPR); exprRef.set(expr); // now for statements Ref<Tree> stmtRef = new Ref<>("stmt"); Parser<Tree> whilestmt= op("while", Annotation.KEYWORD_PREFIX).then(expr).then( op("do", Annotation.KEYWORD_INFIX).then(stmtRef.fold(While.CREATE_DO)) .or(While.CREATE)); Parser<Tree> forstmt = op("for", Annotation.KEYWORD_PREFIX) .then(Utils.properties()) .then(Utils.put("varName", idString)) .then(op("in", Annotation.KEYWORD_INFIX)) .then(Utils.put("vector", expr)) .then(op("do", Annotation.KEYWORD_INFIX)) .then(Utils.put("body", stmtRef)) .then(Utils.create(ForEach.class, "varName", "vector", "body")); Parser<Tree> ifstmt = op("if", Annotation.KEYWORD_PREFIX) .then(Utils.properties()) .then(Utils.put("condition", expr)) .then(op("then", Annotation.KEYWORD_INFIX)) .then(Utils.put("thenBranch", stmtRef)) .then( Reducer.opt( op("else", Annotation.KEYWORD_INFIX) .then(Utils.put("elseBranch", stmtRef)) ) ) .then(Utils.create(IfElse.class, "condition", "thenBranch", "elseBranch")); stmt = whilestmt.or(forstmt).or(ifstmt).or(expr); stmtRef.set(stmt); // now for declarations Parser<Tree> externDef = op("extern", Annotation.KEYWORD_DEF) .then(Utils.properties()) .then(Utils.put("id", idString)) .then(Utils.put("type", idString.annotate(Annotation.BREAK))) .then(Reducer.opt(Utils.put("description", quoted.annotate(Annotation.BREAK)))) .then(op("=", Annotation.KEYWORD_INFIX)) .then(Utils.put("value", expr)) .then(Utils.create(ExternDeclaration.class, "id", "type", "description", "value")); Parser<List<String>> arguments = op("(").then( Utils.list(idString, op(",", Annotation.SEPARATOR)) .then(op(")"))); Parser<Tree> funcDef = op("func", Annotation.KEYWORD_DEF) .then(Utils.properties()) .then(Utils.put("id", idString)) .then(Utils.put("args", arguments)) .then(Utils.put("body", stmt.annotate(Annotation.BREAK))) .then(Utils.create(FuncDef.class, "id", "args", "body")); Parser<List<String>> possiblyEmptyArguments = arguments.or(Utils.empty()); Parser<Tree> templateDef = op("template", Annotation.KEYWORD_DEF) .then(Utils.properties()) .then(Utils.put("id", idString)) .then(Utils.put("args", possiblyEmptyArguments)) .then(Utils.put("body", block.annotate(Annotation.BREAK))) .then(Utils.create(TemplateDef.class, "id", "args", "body")); Parser<Tree> definition = op("def", Annotation.KEYWORD_DEF) .then(idString) .then(op("=", Annotation.KEYWORD_INFIX)) .then(expr.fold(Definition.CREATE)); Parser<Tree> defs = externDef.or(funcDef).or(templateDef).or(definition); // variable declarations may be chained // XXX Meelan2: Change chaining-rules. Parser<Tree> varDecl = Utils.properties() .then(Utils.put("id", idString)) .then(Reducer.opt(Utils.put("typeString", idString.annotate(Annotation.BREAK)))) .then(Reducer.opt(Utils.put("init", op("=", Annotation.KEYWORD_INFIX).then(assignexpr)))) .then(Utils.create(VarDeclaration.class, "id", "typeString", "init")); Reducer<List<Tree>, List<Tree>> vars = op("var", Annotation.KEYWORD_DEF) .then(op(",", Annotation.SEPARATOR).joinPlus(Utils.append(varDecl, 0))); Parser<Tree> objectDecl = // object a = A(c,b) idString.then( op("=", Annotation.KEYWORD_INFIX).then(expr) .fold(ObjectDeclaration.CREATE)); Reducer<List<Tree>, List<Tree>> objects = op("object", Annotation.KEYWORD_DEF).then( op(",", Annotation.SEPARATOR).joinPlus(Utils.append(objectDecl, 0))); Reducer<List<Tree>, List<Tree>> stmtAppender = vars .or(objects) .or(Utils.append(defs, 0)) .or(Utils.append(stmt, 0)) .then(op(";").opt(true)).annotate(Annotation.STMT); stmts = Utils.<Tree>empty() .then(Reducer.rep(stmtAppender)); stmtsRef.set(stmts); } }
true
f9dfb39f6dc5714352711a8f6929ae8d318a370c
Java
OnlyPaul/GA_nqProblem
/nq_java/src/NQClient.java
UTF-8
535
2.546875
3
[]
no_license
/** * Testing */ public class NQClient { public static void main(String[] args) { int n = 11; int popsize = 5000; int gencnt = 5000; int tmsize = 50; double mutprob = 0.2; Environment nqueen = new Environment(popsize, n); nqueen.natSelection(gencnt, tmsize, true, mutprob); Integer[] answer = nqueen.getAnswer(); if (answer != null) System.out.println(nqueen.getStrAnswer()); else System.out.println("no answer."); } }
true
93db60951c9ccabd89b82b46cab50a9495571b97
Java
romanlukichev/lessons2018
/src/Box.java
UTF-8
2,142
3.59375
4
[]
no_license
import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Objects; public class Box implements Comparable<Box>{ private double a; private double b; private double c; public Box(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public double getA() { return a; } public double getB() { return b; } public double getC() { return c; } @Override public boolean equals(Object otherObject){ if(this == otherObject){ return true; } if(!(otherObject instanceof Box)){ return false; } Box otherBox = (Box)otherObject; if(( Math.abs(this.a - otherBox.a) < 0.001 ) && ( Math.abs(this.b - otherBox.b) < 0.001 ) && ( Math.abs(this.c - otherBox.c) < 0.001 ) ) { return true; } else return false; } @Override public int hashCode(){ return Objects.hash(round(a, 2), round(b, 2), round(c, 2)); } @Override public int compareTo(Box otherBox) { if(( Math.abs(this.a - otherBox.a) < 0.001 ) && ( Math.abs(this.b - otherBox.b) < 0.001 ) && ( Math.abs(this.c - otherBox.c) < 0.001 ) ) { return 0; } else if(this.a * this.b * this.c < otherBox.a * otherBox.b * otherBox.c){ return -50; // why not otherBox.get(a) ? - a is private and its in other object. } return 50; } @Override public String toString(){ return Double.toString(a) + " " + Double.toString(b) + " " + Double.toString(c); // is concatenation of String slower? } public double getVolume(){ return a * b * c; } private static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(Double.toString(value)); // using BigDecimal(String) constructor bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } }
true
ff006df944e1c58b63ab2a4be14aa4f775fc6093
Java
yswname/SSMPOM2
/SSM08SpringMyBatis/src/main/java/cn/com/demo/ssm/spring/mybatis/service/impl/RlUrMapServiceImpl.java
UTF-8
315
1.609375
2
[]
no_license
package cn.com.demo.ssm.spring.mybatis.service.impl; import cn.com.demo.ssm.spring.mybatis.entity.RlUrMapEntity; import cn.com.demo.ssm.spring.mybatis.service.IRlUrMapService; public class RlUrMapServiceImpl implements IRlUrMapService { @Override public void saveRlUrMap(RlUrMapEntity rlUrMap) { } }
true
1caac5980f7850de28dc97ef5284f3f7b132d631
Java
freeman5860/FlurryApi
/app/src/main/java/com/freeman/flurryapp/db/DbObserver.java
UTF-8
276
1.71875
2
[]
no_license
package com.freeman.flurryapp.db; import com.freeman.flurryapp.entry.FlurryApplication; import java.util.ArrayList; /** * Created by alberthe on 2014/12/19. */ public interface DbObserver { public void onQueryAppList(ArrayList<FlurryApplication> data); }
true
7be3003de86425e6593e3550ffad88a0b3f20a58
Java
androcafe/mydoctorspanel
/app/src/main/java/androcafe/visitindia/com/mydoctorspanel/DoctorPanelUrl.java
UTF-8
612
1.65625
2
[]
no_license
package androcafe.visitindia.com.mydoctorspanel; public interface DoctorPanelUrl { String SIGN_UP_URL="https://doctor.codingcloud.com.my/doctor_signup.php"; String SIGN_IN_URL="https://doctor.codingcloud.com.my/doctor_signin1.php"; String INSERT_PROFILE_URL="https://doctor.codingcloud.com.my/doctor_info_up.php"; String CANCEL_APMT_URL=""; String CHANGE_SCHED_URL=""; String TODAYS_APMT_URL=""; String ALL_APMT_URL="https://doctor.codingcloud.com.my/appointment_booking_details.php"; String PATIENT_INFO_URL="https://doctor.codingcloud.com.my/patient_info1.php"; }
true
f1ed58adb4998954a6ad637cd9f26efba4245441
Java
OLOZLO/algo-study
/src/_210325/boj20208/Main_ms.java
UTF-8
1,850
2.96875
3
[]
no_license
package _210325.boj20208; import java.awt.*; import java.util.ArrayList; import java.util.Scanner; public class Main_ms { static int N, M, H; static int[] dx = {-1, 1, 0, 0}, dy = {0, 0, -1, 1}; static int[][] map; static Point house; static ArrayList<Point> milk; static boolean[] visit; static int answer; public static void main(String[] args) { Scanner sc = new Scanner(System.in); N = sc.nextInt(); M = sc.nextInt(); H = sc.nextInt(); map = new int[N][N]; milk = new ArrayList<>(); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int num = sc.nextInt(); if (num == 1) { house = new Point(i, j); } else if (num == 2) { milk.add(new Point(i, j)); } } } visit = new boolean[milk.size()]; for (int i = 0; i < milk.size(); i++) { Point init = milk.get(i); int dist = Math.abs(house.x - init.x) + Math.abs(house.y - init.y); if (dist <= M) { solve(init, i, M - dist + H, 1); } } System.out.println(answer); } static void solve(Point now, int idx, int hp, int cnt) { visit[idx] = true; for (int i = 0; i < milk.size(); i++) { if (!visit[i]) { Point next = milk.get(i); int dist = Math.abs(now.x - next.x) + Math.abs(now.y - next.y); if (dist <= hp) solve(next, i, hp - dist + H, cnt + 1); } } int dist = Math.abs(now.x - house.x) + Math.abs(now.y - house.y); if (dist <= hp) { answer = Math.max(answer, cnt); } visit[idx] = false; } }
true
dba412c8599d6da8f32e892d4c9393afdb27ca0e
Java
webueye/fake
/src/main/java/com/taoists/code/model/ProductModel.java
UTF-8
1,158
2.21875
2
[]
no_license
package com.taoists.code.model; import java.util.List; import com.taoists.base.entity.Product; /** * @author rubys@vip.qq.com * @since 2012-7-22 */ public class ProductModel { private Product product; private List<BatchModel> batchs; public int getSize() { if (batchs == null) { return 0; } return batchs.size(); } public static class BatchModel { private String batch; private Integer boxNum; private Integer fakeNum; public String getBatch() { return batch; } public void setBatch(String batch) { this.batch = batch; } public Integer getBoxNum() { return boxNum; } public void setBoxNum(Integer boxNum) { this.boxNum = boxNum; } public Integer getFakeNum() { return fakeNum; } public void setFakeNum(Integer fakeNum) { this.fakeNum = fakeNum; } } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public List<BatchModel> getBatchs() { return batchs; } public void setBatchs(List<BatchModel> batchs) { this.batchs = batchs; } }
true
aa3317e404831b90835a4745c2b7d8fcd9df721b
Java
XeonLyfe/Sn0w
/me/zeroeightsix/kami/gui/rgui/component/AbstractComponent.java
UTF-8
10,684
1.867188
2
[]
no_license
/* * Decompiled with CFR 0.151. */ package me.zeroeightsix.kami.gui.rgui.component; import java.util.ArrayList; import me.zeroeightsix.kami.gui.kami.DisplayGuiScreen; import me.zeroeightsix.kami.gui.rgui.GUI; import me.zeroeightsix.kami.gui.rgui.component.Component; import me.zeroeightsix.kami.gui.rgui.component.container.Container; import me.zeroeightsix.kami.gui.rgui.component.listen.KeyListener; import me.zeroeightsix.kami.gui.rgui.component.listen.MouseListener; import me.zeroeightsix.kami.gui.rgui.component.listen.RenderListener; import me.zeroeightsix.kami.gui.rgui.component.listen.TickListener; import me.zeroeightsix.kami.gui.rgui.component.listen.UpdateListener; import me.zeroeightsix.kami.gui.rgui.poof.IPoof; import me.zeroeightsix.kami.gui.rgui.poof.PoofInfo; import me.zeroeightsix.kami.gui.rgui.render.ComponentUI; import me.zeroeightsix.kami.gui.rgui.render.theme.Theme; import me.zeroeightsix.kami.setting.Setting; import me.zeroeightsix.kami.setting.Settings; public abstract class AbstractComponent implements Component { int x; int y; int width; int height; int minWidth = Integer.MIN_VALUE; int minHeight = Integer.MIN_VALUE; int maxWidth = Integer.MAX_VALUE; int maxHeight = Integer.MAX_VALUE; protected int priority = 0; private Setting<Boolean> visible = Settings.b("Visible", true); float opacity = 1.0f; private boolean focus = false; ComponentUI ui; Theme theme; Container parent; boolean hover = false; boolean press = false; boolean drag = false; boolean affectlayout = true; ArrayList<MouseListener> mouseListeners = new ArrayList(); ArrayList<RenderListener> renderListeners = new ArrayList(); ArrayList<KeyListener> keyListeners = new ArrayList(); ArrayList<UpdateListener> updateListeners = new ArrayList(); ArrayList<TickListener> tickListeners = new ArrayList(); ArrayList<IPoof> poofs = new ArrayList(); boolean workingy = false; boolean workingx = false; public AbstractComponent() { this.addMouseListener(new MouseListener(){ @Override public void onMouseDown(MouseListener.MouseButtonEvent event) { AbstractComponent.this.press = true; } @Override public void onMouseRelease(MouseListener.MouseButtonEvent event) { AbstractComponent.this.press = false; AbstractComponent.this.drag = false; } @Override public void onMouseDrag(MouseListener.MouseButtonEvent event) { AbstractComponent.this.drag = true; } @Override public void onMouseMove(MouseListener.MouseMoveEvent event) { } @Override public void onScroll(MouseListener.MouseScrollEvent event) { } }); } @Override public ComponentUI getUI() { if (this.ui == null) { this.ui = this.getTheme().getUIForComponent(this); } return this.ui; } @Override public Container getParent() { return this.parent; } @Override public void setParent(Container parent) { this.parent = parent; } @Override public Theme getTheme() { return this.theme; } @Override public void setTheme(Theme theme) { this.theme = theme; } @Override public void setFocussed(boolean focus) { this.focus = focus; } @Override public boolean isFocussed() { return this.focus; } @Override public int getX() { return this.x; } @Override public int getY() { return this.y; } @Override public int getWidth() { return this.width; } @Override public int getHeight() { return this.height; } @Override public void setY(int y) { int oldX = this.getX(); int oldY = this.getY(); this.y = y; if (!this.workingy) { this.workingy = true; this.getUpdateListeners().forEach(listener -> listener.updateLocation(this, oldX, oldY)); if (this.getParent() != null) { this.getParent().getUpdateListeners().forEach(listener -> listener.updateLocation(this, oldX, oldY)); } this.workingy = false; } } @Override public void setX(int x) { int oldX = this.getX(); int oldY = this.getY(); this.x = x; if (!this.workingx) { this.workingx = true; this.getUpdateListeners().forEach(listener -> listener.updateLocation(this, oldX, oldY)); if (this.getParent() != null) { this.getParent().getUpdateListeners().forEach(listener -> listener.updateLocation(this, oldX, oldY)); } this.workingx = false; } } @Override public void setWidth(int width) { width = Math.max(this.getMinimumWidth(), Math.min(width, this.getMaximumWidth())); int oldWidth = this.getWidth(); int oldHeight = this.getHeight(); this.width = width; this.getUpdateListeners().forEach(listener -> listener.updateSize(this, oldWidth, oldHeight)); if (this.getParent() != null) { this.getParent().getUpdateListeners().forEach(listener -> listener.updateSize(this, oldWidth, oldHeight)); } } @Override public void setHeight(int height) { height = Math.max(this.getMinimumHeight(), Math.min(height, this.getMaximumHeight())); int oldWidth = this.getWidth(); int oldHeight = this.getHeight(); this.height = height; this.getUpdateListeners().forEach(listener -> listener.updateSize(this, oldWidth, oldHeight)); if (this.getParent() != null) { this.getParent().getUpdateListeners().forEach(listener -> listener.updateSize(this, oldWidth, oldHeight)); } } @Override public boolean isVisible() { return this.visible.getValue(); } @Override public void setVisible(boolean visible) { this.visible.setValue(visible); } @Override public int getPriority() { return this.priority; } @Override public void kill() { this.setVisible(false); } private boolean isMouseOver() { int[] real = GUI.calculateRealPosition(this); int mx = DisplayGuiScreen.mouseX; int my = DisplayGuiScreen.mouseY; return real[0] <= mx && real[1] <= my && real[0] + this.getWidth() >= mx && real[1] + this.getHeight() >= my; } @Override public boolean isHovered() { return this.isMouseOver() && !this.press; } @Override public boolean isPressed() { return this.press; } @Override public ArrayList<MouseListener> getMouseListeners() { return this.mouseListeners; } @Override public void addMouseListener(MouseListener listener) { if (!this.mouseListeners.contains(listener)) { this.mouseListeners.add(listener); } } @Override public ArrayList<RenderListener> getRenderListeners() { return this.renderListeners; } @Override public void addRenderListener(RenderListener listener) { if (!this.renderListeners.contains(listener)) { this.renderListeners.add(listener); } } @Override public ArrayList<KeyListener> getKeyListeners() { return this.keyListeners; } @Override public void addKeyListener(KeyListener listener) { if (!this.keyListeners.contains(listener)) { this.keyListeners.add(listener); } } @Override public ArrayList<UpdateListener> getUpdateListeners() { return this.updateListeners; } @Override public void addUpdateListener(UpdateListener listener) { if (!this.updateListeners.contains(listener)) { this.updateListeners.add(listener); } } @Override public ArrayList<TickListener> getTickListeners() { return this.tickListeners; } @Override public void addTickListener(TickListener listener) { if (!this.tickListeners.contains(listener)) { this.tickListeners.add(listener); } } @Override public void addPoof(IPoof poof) { this.poofs.add(poof); } @Override public void callPoof(Class<? extends IPoof> target, PoofInfo info) { for (IPoof poof : this.poofs) { if (!target.isAssignableFrom(poof.getClass()) || !poof.getComponentClass().isAssignableFrom(this.getClass())) continue; poof.execute(this, info); } } @Override public boolean liesIn(Component container) { if (container.equals(this)) { return true; } if (container instanceof Container) { for (Component component : ((Container)container).getChildren()) { if (component.equals(this)) { return true; } boolean liesin = false; if (component instanceof Container) { liesin = this.liesIn((Container)component); } if (!liesin) continue; return true; } return false; } return false; } @Override public float getOpacity() { return this.opacity; } @Override public void setOpacity(float opacity) { this.opacity = opacity; } @Override public int getMaximumHeight() { return this.maxHeight; } @Override public int getMaximumWidth() { return this.maxWidth; } @Override public int getMinimumHeight() { return this.minHeight; } @Override public int getMinimumWidth() { return this.minWidth; } @Override public Component setMaximumWidth(int width) { this.maxWidth = width; return this; } @Override public Component setMaximumHeight(int height) { this.maxHeight = height; return this; } @Override public Component setMinimumWidth(int width) { this.minWidth = width; return this; } @Override public Component setMinimumHeight(int height) { this.minHeight = height; return this; } @Override public boolean doAffectLayout() { return this.affectlayout; } @Override public void setAffectLayout(boolean flag) { this.affectlayout = flag; } }
true
5f4fd8fd1f9af0f843eceb72dfa39fbbe2e50ad2
Java
BAT6188/company-database
/安慧软件资料/gitRepository/ITMS-3.0/Code/cy.its.trafficSituation/cy.its.trafficSituation.repository/src/main/java/cy/its/trafficSituation/repository/TrafficFlowRepository.java
UTF-8
1,094
2.1875
2
[]
no_license
package cy.its.trafficSituation.repository; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cy.its.com.util.DateUtil; import cy.its.platform.common.utils.SqlHelper; import cy.its.trafficSituation.domain.model.TrafficDeviceFlow; import cy.its.trafficSituation.domain.repository.ITrafficFlowRepository; import cy.its.trafficSituation.mybatis.client.TrafficFlowMapper; @Service public class TrafficFlowRepository implements ITrafficFlowRepository { @Autowired TrafficFlowMapper trafficFlowMapper; @Override public List<TrafficDeviceFlow> countDeviceFlow(String deviceSysNbr, Date from, Date to) { Map<String, Object> p = new HashMap<String, Object>(); p.put("deviceSysNbr", deviceSysNbr); p.put("from", DateUtil.formatDate(from)); p.put("to", DateUtil.formatDate(to)); System.out.println(SqlHelper.getMapperSql(trafficFlowMapper, "countDeviceFlow", p)); return trafficFlowMapper.countDeviceFlow(p); } }
true
f593df3cd79b8fa26337ff0c4bc43a595d363621
Java
ssverud/Matador-beyond
/src/FerryField.java
UTF-8
2,603
3.25
3
[]
no_license
public class FerryField extends GameField { private int rentPrice; private int pledgePrice; //private Player ownedBy = null; ScanThings scanThings = new ScanThings(); // Constructor public FerryField(int pos, String name, int price, int rentPrice, int pledgePrice) { setPos(pos); setName(name); this.setPrice(price); this.setRentPrice(rentPrice); this.setPledgePrice(pledgePrice); setGameFieldType(GameFieldType.FERRYFIELD); } public FerryField landedOn(Player player, Logic logic) { System.out.println("Dette er et Færgefelt"); if (getOwnedBy() != null) { for (int i = 1; i < player.getNumberOfFerriesOwned(); i++) { rentPrice = rentPrice * 2; } player.payRent(rentPrice, getOwnedBy()); System.out.println("De betalte " + rentPrice + " til " + getOwnedBy()); } else if (getOwnedBy() == null) { System.out.println("Denne Færge er ikke købt af nogen"); System.out.println("Vil de gerne købe den? - tast 1 eller 2 og tryk ENTER"); System.out.println("1. Ja"); System.out.println("2. Nej"); int answer = scanThings.scanNumber(); if (answer == 1) { System.out.println("Deres samlede valuta er: " + player.getMoney()); if (player.getMoney() > getPrice()) { player.buyField(this); setOwnedBy(player); System.out.println("Denne Færge er nu ejet af: " + getOwnedBy()); System.out.println("Deres samlede værdi af valute plus ejendomme er: " + player.getTotalValue()); System.out.println("Deres samlede valuta er: " + player.getMoney()); } else if (player.getMoney() < getPrice()) { System.out.println("De har ikke valuta nok til at købe denne grund."); } } else if (answer == 2) { System.out.println("Ok De ønsker ikke at købe den"); } } return this; } public int getRentPrice() { return rentPrice; } public void setRentPrice(int rentPrice) { this.rentPrice = rentPrice; } public int getPledgePrice() { return pledgePrice; } public void setPledgePrice(int pledgePrice) { this.pledgePrice = pledgePrice; } /* public Player getOwnedBy() { return ownedBy; } public void setOwnedBy(Player ownedBy) {this.ownedBy = ownedBy;} */ }
true
8ce4af9d9e2431cfb24d88b96539161b16c2604e
Java
shelsonjava/Synx
/WakfuClientSources/srcx/class_1691_apq.java
UTF-8
3,084
1.851563
2
[]
no_license
import org.apache.log4j.Logger; public class apq extends dKc { protected static final Logger K = Logger.getLogger(apq.class); private final bNK dvm; private final cGx dvn; private final long ctZ; private static final Runnable dvo = new dpY(); public apq(bNK parambNK, cGx paramcGx, long paramLong) { this.dvm = parambNK; this.dvn = paramcGx; this.ctZ = paramLong; } public short fU() { return 8; } public boolean fV() { if ((this.bSY.isDead()) || (this.bSY.adF())) { K.warn("Le joueur " + this.bSY + " est mort ou en combat et ne peut utiliser de machine de craft"); return false; } if (!this.bSY.aTn().contains(this.dvm.axX())) { K.warn("Le joueur " + this.bSY + " essaye d'utiliser la recette " + this.dvn + " du métier " + this.dvm.axX() + " sur la machine " + this.dvm + " alors qu'il ne connais pas le métier"); return false; } if (!this.dvm.x(this.dvn.getId(), this.dvn.getType())) { K.warn("Le joueur " + this.bSY + " essaye d'utiliser la recette " + this.dvn + " du métier " + this.dvm.axX() + " sur la machine " + this.dvm + " alors qu'elle n'est pas autorisée"); return false; } if (!this.dvn.aQ(this.bSY)) { K.warn("Le joueur " + this.bSY + " essaye d'utiliser la recette " + this.dvn + " du métier " + this.dvm.axX() + " sur la machine " + this.dvm + " alors qu'elle ne valide pas le critère"); return false; } aCH localaCH = clR.cni().vL(this.dvm.gC()); if (!e(localaCH)) { K.warn("Le joueur " + this.bSY + " essaye d'utiliser la recette " + this.dvn + " du métier " + this.dvm.axX() + " sur la machine " + this.dvm + " alors qu'il n'a pas l'objet requis dans le visuel"); return false; } bMD localbMD = this.bSY.bGP(); if (!this.bSY.a(this.dvn)) { return false; } return true; } public void begin() { K.error("[CRAFTOCC] Craft START"); aCH localaCH = clR.cni().vL(this.dvm.gC()); gA localgA = (gA)this.bSY.ayJ().dB((short)azO.dRO.hV); this.bSY.aeL().v(localaCH.gC(), false); duO.dax().ko(this.ctZ); dka.cSF().a(dvo, this.ctZ, 1); } public boolean fW() { K.error("[CRAFTOCC] Craft FINISHED"); ayC localayC = new ayC(); localayC.bt((byte)2); localayC.aS((short)8); byv.bFN().aJK().d(localayC); aCH localaCH = clR.cni().vL(this.dvm.gC()); gA localgA = (gA)this.bSY.ayJ().dB((short)azO.dRO.hV); this.bSY.aeL().v(localaCH.gC(), true); return true; } public boolean a(boolean paramBoolean1, boolean paramBoolean2) { K.error("[CRAFTOCC] Craft CANCELED"); dka.cSF().j(dvo); aCH localaCH = clR.cni().vL(this.dvm.gC()); gA localgA = (gA)this.bSY.ayJ().dB((short)azO.dRO.hV); this.bSY.aeL().v(localaCH.gC(), true); duO.dax().daH(); if (paramBoolean2) aBx(); return true; } public void aBx() { K.error("[CRAFTOCC] Craft CANCEL request"); ayC localayC = new ayC(); localayC.bt((byte)3); localayC.aS((short)8); byv.bFN().aJK().d(localayC); } }
true
101517424223ccce94e127e3d87a51cdfbf56ec5
Java
SolitaryEagle/elevator-air-conditioner-online-monitoring-system
/src/main/java/edu/hhu/air/conditioner/online/monitoring/repository/UserRepository.java
UTF-8
1,228
1.898438
2
[]
no_license
package edu.hhu.air.conditioner.online.monitoring.repository; import edu.hhu.air.conditioner.online.monitoring.constant.enums.RoleEnum; import edu.hhu.air.conditioner.online.monitoring.model.entity.User; import java.sql.Timestamp; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; /** * @author 覃国强 * @date 2019-01-31 */ public interface UserRepository extends JpaRepository<User, Long> { @Modifying(flushAutomatically = true, clearAutomatically = true) @Query("update User set activation = :#{#user.activation}, gmtModified = :#{#user.gmtModified} " + "where id = :#{#user.id}") int updateActivationById(User user); @Modifying(flushAutomatically = true, clearAutomatically = true) @Query("update User set password = :#{#user.password}, gmtModified = :#{#user.gmtModified} " + "where email = :#{#user.email}") int updatePasswordByEmail(User user); Optional<User> findByUsername(String username); Optional<User> findByEmail(String email); List<User> findByRole(RoleEnum role); }
true
f8cf6912cab6ac817eaaa75de7a03aa5410ceec3
Java
ViacheslavGbc/Android
/Restaurants/app/src/main/java/ca/georgebrown/comp3074/restaurants/Restaurant.java
UTF-8
1,566
2.546875
3
[]
no_license
package ca.georgebrown.comp3074.restaurants; public class Restaurant { private final String id; private final String name; private final String type ; private String address; private String phone ; private String website ; private String rate ; private String price; private String otherTags; public Restaurant(String id, String name, String type) { this.id = id; this.name = name; this.type = type; } public String getId() {return id;} public String getName() { return name; } public String getType() { return type; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public String getRate() { return rate; } public void setRate(String rate) { this.rate = rate; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getOtherTags() { return otherTags; } public void setOtherTags(String otherTags) { this.otherTags = otherTags; } @Override public String toString() { return name ; } }
true
2d51524c7c45e7960c7f20ac53084bb811d55842
Java
SpringMybatis/spring-boot-jpa
/src/main/java/com/example/controller/RoleController.java
UTF-8
551
2.109375
2
[]
no_license
package com.example.controller; import java.util.ArrayList; import java.util.List; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @EnableAutoConfiguration public class RoleController { @RequestMapping("/role") List<String> user() { List<String> list = new ArrayList<String>(); list.add("Hello World role!"); list.add("Spring boot role!"); return list; } }
true
01199457c56965523fcaf03a26bed4c757f13549
Java
Pato91/merakipos
/src/Icons/standardElements.java
UTF-8
884
2.5
2
[]
no_license
/* * 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 Icons; import javafx.scene.image.Image; import javafx.scene.image.ImageView; /** * * @author Meraki */ public class standardElements { public ImageView image(String name,Double width,Double height){ ImageView vv=new ImageView(); Image imageForward = new Image(getClass().getResourceAsStream(name)); vv.setImage(imageForward); vv.setFitHeight(height); vv.setFitWidth(width); return vv; } public Image image2(String name){ Image imageForward = new Image(getClass().getResourceAsStream(name)); return imageForward; } }
true
101bf729a912938c1c8d30568f0592f2a66d2475
Java
azvonov/Lessons
/lesson7/Lesson7_Allure/src/main/java/blocks/ButtonsBlock.java
UTF-8
279
2.15625
2
[]
no_license
package blocks; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class ButtonsBlock { @FindBy(id="calculate") private WebElement calculateButton; public void clickCalculateButton() { calculateButton.click(); } }
true
b5ee3f0f800485e51a9dd840c8da4758eb419441
Java
castor-data-binding/castor-jaxb-2.0
/src/main/java/org/castor/jaxb/reflection/processor/field/XmlElementWrapperProcessor.java
UTF-8
2,954
2.015625
2
[]
no_license
package org.castor.jaxb.reflection.processor.field; import java.lang.annotation.Annotation; import javax.xml.bind.annotation.XmlElementWrapper; import org.apache.commons.lang3.StringUtils; import org.castor.core.annotationprocessing.AnnotationProcessor; import org.castor.core.nature.BaseNature; import org.castor.jaxb.reflection.info.JaxbFieldNature; import org.castor.jaxb.reflection.processor.BaseFieldProcessor; import org.springframework.stereotype.Component; /** * Annotation processor for XMLElement. * * @author Joachim Grueneis, jgrueneis_at_gmail_dot_com * @version $Id$ */ @Component("xmlElementWrapperFieldProcessor") public class XmlElementWrapperProcessor extends BaseFieldProcessor { /** XmlElementWrapper.name default is ##default. */ public static final String ELEMENT_WRAPPER_NAME_DEFAULT = "##default"; /** XmlElementWrapper.namespace default is ##default. */ public static final String ELEMENT_WRAPPER_NAMESPACE_DEFAULT = "##default"; /** * {@inheritDoc} * * @see org.codehaus.castor.annoproc.AnnotationProcessor# * processAnnotation(org.castor.xml.introspection.BaseNature, * java.lang.annotation.Annotation) */ public final <I extends BaseNature, A extends Annotation> boolean processAnnotation( final I info, final A annotation) { if ((annotation instanceof XmlElementWrapper) && (info instanceof JaxbFieldNature)) { XmlElementWrapper xmlElementWrapper = (XmlElementWrapper) annotation; JaxbFieldNature fieldInfo = (JaxbFieldNature) info; this.annotationVisitMessage(xmlElementWrapper); fieldInfo.setXmlElementWrapper(true); if (!ELEMENT_WRAPPER_NAME_DEFAULT.equals(xmlElementWrapper .name())) { fieldInfo.setElementWrapperName(xmlElementWrapper.name()); } else { //TODO[WG]: nit sure this is the right place // default naming handling String xmlElementName = fieldInfo.getElementName(); if (StringUtils.isNotEmpty(xmlElementName)) { fieldInfo.setElementWrapperName(xmlElementName); } } fieldInfo.setElementWrapperNillable(xmlElementWrapper .nillable()); fieldInfo.setElementWrapperRequired(xmlElementWrapper .required()); if (!ELEMENT_WRAPPER_NAMESPACE_DEFAULT.equals(xmlElementWrapper .namespace())) { fieldInfo.setElementWrapperNamespace(xmlElementWrapper .namespace()); } return true; } return false; } /** * {@inheritDoc} * * @see AnnotationProcessor#forAnnotationClass() */ public Class<? extends Annotation> forAnnotationClass() { return XmlElementWrapper.class; } }
true
2388b1d8f100b38f68888c243b6cdbd560a5e4fd
Java
KalleHeuwes/coleman
/src/main/java/de/kheuwes/coleman/exceptions/BookGeneralException.java
UTF-8
358
2.453125
2
[]
no_license
package de.kheuwes.coleman.exceptions; public class BookGeneralException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public BookGeneralException() { super("Fehler BookGeneralException"); } public BookGeneralException(String message, Throwable cause) { super(message, cause); } }
true
6d8df923c2d0dbcdf43d9f0983f52dad92743384
Java
AndroidDevelopersZhao/TieJinshenghuoService
/src/data/TicketsPerson.java
UTF-8
1,131
2.6875
3
[]
no_license
package data; public class TicketsPerson { private String name =null; private String year =null; private String city =null; private String sex =null; private String cardNo =null; private String phoneNum =null; public TicketsPerson(String name, String year, String city, String sex, String cardNo, String phoneNum) { super(); this.name = name; this.year = year; this.city = city; this.sex = sex; this.cardNo = cardNo; this.phoneNum = phoneNum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public String getPhoneNum() { return phoneNum; } public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; } }
true
42115cb99e9c0eaaafb2dd6ed93ec5ff11543fc3
Java
wangyue168git/online-forum
/src/main/java/com/bolo/test/rpc/InfoUserService.java
UTF-8
365
1.789063
2
[ "Apache-2.0" ]
permissive
package com.bolo.test.rpc; import java.util.List; import java.util.Map; /** * Created by wangyue on 2019/2/26. */ public interface InfoUserService { List<InfoUser> insertInfoUser(InfoUser infoUser); InfoUser getInfoUserById(String id); void deleteInfoUserById(String id); String getNameById(String id); Map<String,InfoUser> getAllUser(); }
true
1d37d79f917c403592e1e3253ebb991271c07a2c
Java
Kennyproz/DPI-Individuele-opdracht
/src/mix/model/domain/Aggregator.java
UTF-8
1,667
2.46875
2
[]
no_license
package mix.model.domain; import mix.model.messages.TeamAskingMessage; import mix.model.messages.TeamReplyMessage; import java.util.ArrayList; import java.util.List; public class Aggregator { private int aggregationId; private String correlationId; private int expectedReplies; private List<TeamReplyMessage> allReplies; public List<TeamReplyMessage> getAllReplies() { return allReplies; } public Aggregator(int aggregationId, String correlationId, int expectedReplies) { this.aggregationId = aggregationId; this.correlationId = correlationId; this.expectedReplies = expectedReplies; this.allReplies = new ArrayList<>(); } public int getAggregationId() { return aggregationId; } public String getCorrelationId() { return correlationId; } public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } public void addTeamReplyMessage(TeamReplyMessage teamReplyMessage){ allReplies.add(teamReplyMessage); } public TeamReplyMessage getReply(){ // If both score the same continue, else send messsage back for (TeamReplyMessage tr : allReplies){ } // for(BankInterestReply bir : allReplies){ // if (bir.getInterest() < lowestInterest.getInterest()){ // lowestInterest = bir; // } // } // return lowestInterest; return null; } public boolean recievedAllMessages(){ return expectedReplies == allReplies.size(); } public boolean scoreAreEqual(){ return true; } }
true
0457771e3924377e465ef0d2f489d46c8082671a
Java
benhamilto/PolyGone
/core/src/ca/polygone/Levels/LevelTwo.java
UTF-8
203
1.976563
2
[]
no_license
package ca.polygone.Levels; /** * Created by Ben on 2017-03-29. */ public class LevelTwo extends PolyGoneLevel{ public LevelTwo(){ isFinalLevel = true; nextLevel = null; } }
true
99245cb99ba4a3a04c6874d60a764538f468e0e1
Java
bnbaek/okhttp
/http-server/src/main/java/net/openu/httpserver/HelloController.java
UTF-8
635
2.09375
2
[]
no_license
package net.openu.httpserver; import java.util.Arrays; import java.util.List; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by iopenu@gmail.com on 2020/02/17 * Github : https://github.com/bnbaek */ @RestController @RequestMapping("/api/hellos") public class HelloController { @GetMapping public List<Hello> hellos() { return Arrays.asList(new Hello("h1") , new Hello("h2") , new Hello("h3") , new Hello("h4") , new Hello("h5") ); } }
true
20b37be6b96ca37b449a74d8f374c84f5dd3caf8
Java
georve/dgboss-view
/commons-dgfarm/src/main/java/com/grupodgfarm/commons/resources/properties/ApplicationProperties.java
UTF-8
1,313
2.875
3
[]
no_license
package com.grupodgfarm.commons.resources.properties; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; /** * <p> * Clase usada para acceder a las propiedades (proyecto.properties) definidas * para una aplicaci&oacute;n. * </p> * * @author <a href="mailto:geormancalderon@grupodigifarm.com">Georman Calderon</a> * @version 1.0 */ public class ApplicationProperties extends PropertyPlaceholderConfigurer { /** * <code>Map</code> que contiene las propiedades definidas para la * aplicaci&oacute;n. */ private static Map<String, String> properties = new HashMap<String, String>(); /* * (non-Javadoc) */ @Override protected void loadProperties(final Properties props) throws IOException { super.loadProperties(props); System.out.println("<----load properties-->"); for (final Object key : props.keySet()) { properties.put((String) key, props.getProperty((String) key)); } } /** * Retorna el valor de una propiedad, dado su nombre. * * @param name * <code>String</code> nombre de la propieda * @return <code>String</code> con el valor de la propiedad. */ public static String getProperty(final String name) { return properties.get(name); } }
true
0bba6cd5b605e6618838ce1206d2ac8be9989a34
Java
hpca01/SchoolTracker
/app/src/main/java/com/example/schooltracker/ui/CourseAddMentorAdapter.java
UTF-8
2,547
2.40625
2
[]
no_license
package com.example.schooltracker.ui; import android.app.Application; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.RecyclerView; import com.example.schooltracker.R; import com.example.schooltracker.databinding.ActivityCourseAddMentorRecyclerBinding; import com.example.schooltracker.models.entities.Mentor; import com.example.schooltracker.utils.Clickable; import java.util.ArrayList; import java.util.List; public class CourseAddMentorAdapter extends RecyclerView.Adapter<CourseAddMentorAdapter.CMAddViewHolder> { private static final String TAG = "CourseAddMentorAdapter"; private List<Mentor> mentors = new ArrayList<>(); private final LayoutInflater inflater; private Clickable clickable; public CourseAddMentorAdapter(Context context, Clickable clickable) { this.inflater = LayoutInflater.from(context); this.clickable = clickable; } public void setMentors(List<Mentor> mentors){ this.mentors = mentors; notifyDataSetChanged(); } public List<Mentor> getMentors(){ return this.mentors; } @NonNull @Override public CMAddViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { ActivityCourseAddMentorRecyclerBinding binding = DataBindingUtil.inflate(this.inflater, R.layout.activity_course_add_mentor_recycler, parent, false); return new CMAddViewHolder(binding); } @Override public void onBindViewHolder(@NonNull CMAddViewHolder holder, int position) { Mentor m = this.mentors.get(position); holder.addMentorRecyclerBinding.setMentor(m); } @Override public int getItemCount() { return this.mentors.size(); } public static class CMAddViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { ActivityCourseAddMentorRecyclerBinding addMentorRecyclerBinding; public CMAddViewHolder(@NonNull ActivityCourseAddMentorRecyclerBinding itemView) { super(itemView.getRoot()); addMentorRecyclerBinding = itemView; addMentorRecyclerBinding.mentorCheckbox.setOnClickListener(this); } @Override public void onClick(View v) { int pos = getAdapterPosition(); Log.d(TAG, "onClick: mentor list "+pos); } } }
true
316f1f7840a705fd3c6956c7318a8ea48299b55a
Java
niuhaijun/chapter5
/src/test/java/com/smart/ditype/DiTypeTest.java
UTF-8
1,756
2.40625
2
[]
no_license
package com.smart.ditype; import static org.testng.Assert.assertNotNull; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class DiTypeTest { private static String[] CONFIG_FILES = {"com/smart/ditype/beans.xml"}; public ApplicationContext factory = null; @BeforeClass public void setUp() throws Exception { factory = new ClassPathXmlApplicationContext(CONFIG_FILES); } @Test public void testCar() { Car car = (Car) factory.getBean("car"); assertNotNull(car); System.out.println(car); } @Test public void testBoss() { Boss boss = factory.getBean("boss", Boss.class); assertNotNull(boss); System.out.println("boss:" + boss); } @Test public void testCar2() { Car car2 = (Car) factory.getBean("car2"); assertNotNull(car2); System.out.println(car2); } @Test public void testCar3() { Car car3 = (Car) factory.getBean("car3"); assertNotNull(car3); System.out.println("car3:" + car3); } @Test public void testCar4() { Car car4 = (Car) factory.getBean("car4"); assertNotNull(car4); System.out.println("car4:" + car4); } @Test public void testCar5() { Car car5 = (Car) factory.getBean("car5"); assertNotNull(car5); System.out.println("car5:" + car5); } @Test public void testBoss1() { Boss boos1 = (Boss) factory.getBean("boss1"); assertNotNull(boos1); System.out.println("boos1:" + boos1); } @Test public void testCar6() { Car car6 = (Car) factory.getBean("car6"); assertNotNull(car6); System.out.println("car6:" + car6); } }
true
51e5c6a1f6d3dcd085f1df39559ab74b5858572f
Java
WonderBo/MyUtil
/src/com/cqu/wb/pattern/decorator/Decorator_two.java
UTF-8
654
3.203125
3
[]
no_license
/** * @description 装饰者二 */ package com.cqu.wb.pattern.decorator; public class Decorator_two extends Decorator { public Decorator_two(Human human) { super(human); // TODO Auto-generated constructor stub } public void goClothespress() { System.out.println("穿衣:在衣柜找找~~~~"); } public void findPlaceOnMap() { System.out.println("出行:在地图找找----"); } @Override public void wearClothes() { // TODO Auto-generated method stub super.wearClothes(); goClothespress(); } @Override public void walkToWhere() { // TODO Auto-generated method stub super.walkToWhere(); findPlaceOnMap(); } }
true
760d5f6316b2b296affff31b71e430759864454c
Java
uanave/java-module
/src/academy/everyonecodes/java/week3/set2/exercise5/PowerCalculatorTest.java
UTF-8
643
2.9375
3
[]
no_license
package academy.everyonecodes.java.week3.set2.exercise5; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class PowerCalculatorTest { PowerCalculator powerCalculator = new PowerCalculator(); @ParameterizedTest @CsvSource({ "15.625, 2.5, 3", "18.49, 4.3, 2", "61.46559999999999, 2.8, 4" }) void calculate(double expected, double input1, double input2) { double result = powerCalculator.calculate(input1, input2); Assertions.assertEquals(expected, result); } }
true
fb41b9fb90b526d972b2cb0ee2c972ac82124daf
Java
sajash78/ALDO-Shoes
/src/test/java/Lesson1/PracticeSelectClass110520.java
UTF-8
1,689
2.359375
2
[]
no_license
package Lesson1; import io.github.bonigarcia.wdm.WebDriverManager; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import java.util.List; import java.util.concurrent.TimeUnit; public class PracticeSelectClass110520 { public static WebDriver driver; @Before public void setup(){ // System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver_win32//chromedriver.exe"); WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); driver.get("https://www.argos.co.uk/"); driver.manage().window().maximize(); } @Test public void practise() { WebElement searchbox = driver.findElement(By.id("searchTerm")); searchbox.sendKeys("nike"); WebElement searchbutton = driver.findElement(By.xpath("//body//header//div//div//div//div//span[2]")); searchbutton.click(); WebElement relevancebox = driver.findElement(By.id("sort-select")); relevancebox.click(); Select sel = new Select(relevancebox); sel.selectByIndex(1); //sel.selectByValue("Price: Low - High"); List<WebElement> prices = driver.findElements(By.cssSelector(".ProductCardstyles__TextContainer-l8f8q8-6.fDOdUb")); for (WebElement price:prices){ System.out.println(price.getText()); if (price.getText().equals("£9.99")){ price.click(); break; } } } }
true
de48a71b467754247892bd4eb88f2c22f1cf3a19
Java
qin-gs/LeetCode
/src/java8/chapter04/StreamTest.java
UTF-8
1,161
3.359375
3
[]
no_license
package java8.chapter04; import java.util.List; import java.util.stream.Collectors; public class StreamTest extends Dish { public StreamTest(String name, boolean vegetarian, int calories, Type type) { super(name, vegetarian, calories, type); } public static void main(String[] args) { List<String> threeHighCaloricDishNames = menu.stream() .filter(d -> d.getCalories() > 300) .map(Dish::getName) .limit(3) .collect(Collectors.toList()); // System.out.println(threeHighCaloricDishNames); List<String> names = menu.stream() .filter(d -> { System.out.println("filter: " + d.getName()); return d.getCalories() > 300; }) .map(d -> { System.out.println("map: " + d.getName()); return d.getName(); }) .limit(3) .collect(Collectors.toList()); // System.out.println(names); menu.forEach(System.out::println); } }
true
ffa1cec1b63e35ab8f3777a65b7388bcd81e13f6
Java
strongerYBA/YuanRepository
/designprinciple/src/main/java/com/yuan/design/pattern/creational/prototype/abstractprototype/A.java
UTF-8
311
2.421875
2
[]
no_license
package com.yuan.design.pattern.creational.prototype.abstractprototype; /** * @ClassName A * @Author Administrator * @Date 2020/1/19 11:44 */ public abstract class A implements Cloneable { @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
true
2059591e9849eabbccef7d4fb9bda9efddb647c3
Java
Fabio-Morais/Warehouse-Manager
/Documentation/DB/LibDataBase/db/SubCategoriaProduto.java
UTF-8
2,019
2.875
3
[]
no_license
package db; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.table.DefaultTableModel; public class SubCategoriaProduto { /*retornem true ou false, dependendo se corre tudo bem ou nao*/ /*Metam como parametro tudo o que precisarem (qual a warehouse a usar) * Meter as dependencias todas! * * */ public boolean selectAll(DataBase db) { db.connect(); // modelUser.setRowCount(0);//eliminar todos os dados contidos na tabela, fazer isto no inicio /*NOME da sub-cateogira*/ String sql = "SELECT * " + "FROM sub_categoria " + "ORDER BY sub_categoria"; Statement stmt = null; try { stmt = db.getC().createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { String sub_categoria = rs.getString("sub_categoria"); String categoria = rs.getString("categoria"); String format = "%-25s%s%n"; System.out.printf(format,"sub_categoria: "+sub_categoria,"categoria: "+categoria); // modelUser.addRow(new Object[] { "nome" }); } } catch (Exception e) { e.printStackTrace(); System.err.println(e.getClass().getName()+": "+e.getMessage()); System.exit(0); return false; } db.disconnect(); return true; } public boolean insertAll(DataBase db, String nome, String categoria) { /*adiciona o nome */ db.connect(); String sql = "INSERT INTO sub_categoria (sub_categoria, categoria)" + "VALUES ('"+nome+"','"+categoria+"')"; System.out.println(sql); try { Statement stmt = db.getC().createStatement(); stmt.executeUpdate(sql); } catch (Exception e) { db.disconnect(); e.printStackTrace(); return false; } db.disconnect(); return true; } public boolean updateUser(String nomeAntigo, String nome, String nomeDaCategoria) { /*Update do nome antigo para o novo nome que pertence CATEGORIA=nomeDaCategoria */ return true; } public boolean remove(String nome) { /*remove sub-categoria com estes parametros*/ return true; } }
true
96fb600b14d99e37271047b1d92462b5df089418
Java
smlsunxie/nodeWithJavaTest
/node-java/src/main/java/JavaHello.java
UTF-8
94
2.234375
2
[]
no_license
public class JavaHello { public void sayHi() { System.out.println("java say Hello"); } }
true
e00d00ff28e139425ce704bb202935d81780fba5
Java
mwakeelable/hns
/app/src/main/java/com/linked_sys/hns/Model/TimeTable.java
UTF-8
417
2.1875
2
[]
no_license
package com.linked_sys.hns.Model; public class TimeTable { public int lectureID; public int weekDayID; public String courseName; public String className; public TimeTable(int lectureID, int weekDayID, String courseName, String className) { this.lectureID = lectureID; this.weekDayID = weekDayID; this.courseName = courseName; this.className = className; } }
true
ac10aeb0c46634e5ae552a64b9c3e45fbe90efd8
Java
mortalliao/BasicKnowledgeOfJava
/java8/src/main/java/abc/basic/knowledge/java8/localtime/TestLocalDateTime.java
UTF-8
2,812
3.796875
4
[]
no_license
package abc.basic.knowledge.java8.localtime; import org.junit.Test; import java.time.*; /** * @author Jim */ public class TestLocalDateTime { // 1. LocalDate LocalTime LocalDateTime @Test public void test() { LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); LocalDateTime localDateTime1 = LocalDateTime.of(2100, 12, 31, 13, 22, 33); System.out.println(localDateTime1); LocalDateTime localDateTime2 = localDateTime.plusYears(2); System.out.println(localDateTime2); LocalDateTime localDateTime3 = localDateTime.minusMonths(2); System.out.println(localDateTime3); System.out.println(localDateTime.getYear()); System.out.println(localDateTime.getMonth()); System.out.println(localDateTime.getDayOfMonth()); System.out.println(localDateTime.getHour()); System.out.println(localDateTime.getMinute()); System.out.println(localDateTime.getSecond()); } // 2. Instant : 时间戳(以Unix 元年: 1970年1月1日00:00:00到某个时间之间的毫秒值) @Test public void test2() { // 默认获取UTC 时区(世界协调时间 格林威治时间, 本初子午线) Instant instant = Instant.now(); System.out.println(instant); OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8)); System.out.println(offsetDateTime); System.out.println(instant.toEpochMilli()); Instant instant1 = Instant.ofEpochSecond(60); System.out.println(instant1); } // 3. // Duration : 计算两个"时间"之间的间隔 @Test public void test3() throws InterruptedException { Instant instant1 = Instant.now(); Thread.sleep(1000); Instant instant2 = Instant.now(); Duration duration = Duration.between(instant1, instant2); System.out.println(duration.toMillis()); } @Test public void test4() { LocalTime localTime1 = LocalTime.now(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } LocalTime localTime2 = LocalTime.now(); Duration duration = Duration.between(localTime1, localTime2); System.out.println(duration.toMillis()); } // Period : 计算两个"日期"之间的间隔 @Test public void test5() { LocalDate localDate1 = LocalDate.of(2015, 1, 1); LocalDate localDate2 = LocalDate.now(); Period period = Period.between(localDate1, localDate2); System.out.println(period); System.out.println(period.getYears()); System.out.println(period.getMonths()); System.out.println(period.getDays()); } }
true
05612c2d47e93fa9903712ca46253ee07191dc49
Java
SwellRT/swellrt
/wave/src/test/java/org/waveprotocol/wave/model/supplement/GadgetStateCollectionTest.java
UTF-8
4,085
1.710938
2
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-generic-export-compliance" ]
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.waveprotocol.wave.model.supplement; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import junit.framework.TestCase; import org.waveprotocol.wave.model.document.Doc; import org.waveprotocol.wave.model.document.operation.automaton.DocumentSchema; import org.waveprotocol.wave.model.document.util.DefaultDocumentEventRouter; import org.waveprotocol.wave.model.document.util.DocProviders; import org.waveprotocol.wave.model.operation.SilentOperationSink; import org.waveprotocol.wave.model.supplement.ObservablePrimitiveSupplement.Listener; import org.waveprotocol.wave.model.wave.data.impl.ObservablePluggableMutableDocument; /** * Test case for {@link GadgetStateCollection}. * */ public class GadgetStateCollectionTest extends TestCase { private static final String GADGET1 = "1"; private static final String GADGET2 = "2"; private Listener listener; private GadgetStateCollection<Doc.E> states; public void testSetGadgetState() { setupDoc(); assertEquals(0, states.getGadgetState(GADGET1).countEntries()); assertEquals(0, states.getGadgetState(GADGET2).countEntries()); states.setGadgetState(GADGET1, "key1", "value1 in 1"); assertEquals(1, states.getGadgetState(GADGET1).countEntries()); assertEquals(0, states.getGadgetState(GADGET2).countEntries()); assertEquals("value1 in 1", states.getGadgetState(GADGET1).get("key1")); states.setGadgetState(GADGET2, "key1", "value1 in 2"); assertEquals(1, states.getGadgetState(GADGET1).countEntries()); assertEquals(1, states.getGadgetState(GADGET2).countEntries()); assertEquals("value1 in 1", states.getGadgetState(GADGET1).get("key1")); assertEquals("value1 in 2", states.getGadgetState(GADGET2).get("key1")); states.setGadgetState(GADGET1, "key1", null); states.setGadgetState(GADGET2, "key2", "value2 in 2"); assertEquals(0, states.getGadgetState(GADGET1).countEntries()); assertEquals(2, states.getGadgetState(GADGET2).countEntries()); assertEquals("value1 in 2", states.getGadgetState(GADGET2).get("key1")); assertEquals("value2 in 2", states.getGadgetState(GADGET2).get("key2")); } public void testGadgetStateEvents() { setupDoc(); never(); states.setGadgetState(GADGET1, "key1", "value1 in 1"); verify(listener).onGadgetStateChanged(GADGET1, "key1", null, "value1 in 1"); states.setGadgetState(GADGET2, "key1", "value1 in 2"); verify(listener).onGadgetStateChanged(GADGET2, "key1", null, "value1 in 2"); states.setGadgetState(GADGET1, "key1", "value2 in 1"); verify(listener).onGadgetStateChanged(GADGET1, "key1", "value1 in 1", "value2 in 1"); states.setGadgetState(GADGET2, "key1", null); verify(listener).onGadgetStateChanged(GADGET2, "key1", "value1 in 2", null); } private void setupDoc() { ObservablePluggableMutableDocument doc = new ObservablePluggableMutableDocument( DocumentSchema.NO_SCHEMA_CONSTRAINTS, DocProviders.POJO.parse("").asOperation()); doc.init(SilentOperationSink.VOID); listener = mock(Listener.class); states = GadgetStateCollection.create(DefaultDocumentEventRouter.create(doc), doc.getDocumentElement(), listener); } }
true
1049d066821fc6d15192b217a249d181814934be
Java
Veronica-sham/guess-number-maven-2020-4-7-9-6-7-285
/src/main/java/com/oocl/InputHandler.java
UTF-8
1,668
3.125
3
[]
no_license
package com.oocl; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class InputHandler { private static final String SPLIT_WORDS = ""; private static final String INPUT_WRONG_MESSAGE = "Wrong Input, Input again"; private static final String INITIAL_MESSAGE = " Input 4 numbers in the format of xxxx(e.g.1234): "; public static final int VALID_INPUT_LENGTH = 4; private String inputNumbers; public void validateInput() { List<String> inputNumber; String inputNumbers = ""; String inputRightMessage = "You entered string "; int inputLength; long distinctWordsCountInInput; Scanner consoleInput = new Scanner(System.in); do { System.out.println(INITIAL_MESSAGE); String userInputNumber = consoleInput.nextLine(); inputNumber = Arrays.asList(userInputNumber.split(SPLIT_WORDS)); inputLength = inputNumber.size(); distinctWordsCountInInput = inputNumber.stream().distinct().count(); if (inputLength == distinctWordsCountInInput && inputLength == VALID_INPUT_LENGTH) { inputRightMessage = inputRightMessage + userInputNumber; System.out.println(inputRightMessage); inputNumbers = userInputNumber; } else { System.out.println(INPUT_WRONG_MESSAGE); } } while (inputLength != distinctWordsCountInInput || inputLength != VALID_INPUT_LENGTH); this.inputNumbers = inputNumbers; } public String getUserInput() { validateInput(); return this.inputNumbers; } }
true
37c04c1354ddbd3bbf89929296976e1b7ed4dad8
Java
pzzzsakura/wxstore
/mmns/src/main/java/com/irecssa/mmns/service/AddressService.java
UTF-8
786
1.796875
2
[]
no_license
package com.irecssa.mmns.service; import com.irecssa.mmns.dto.execution.AddressExecution; import com.irecssa.mmns.entity.Address; import com.irecssa.mmns.entity.PersonInfo; /** * @author: Ma.li.ran * @datetime: 2017/11/25 14:17 * @desc: * @environment: jdk1.8.0_121/IDEA 2017.2.6/Tomcat8.0.47/mysql5.7 */ public interface AddressService { AddressExecution addAddress(Address address,PersonInfo personInfo); AddressExecution modifyAddress(Address address); AddressExecution getAddressList(String personInfoId); AddressExecution getAddress(Address address); AddressExecution getIsDefaultAddress(String personInfoId); AddressExecution modifyIsDefault(String addressId,String personInfoId); AddressExecution removeAddress(String address,String personInfoId); }
true