blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
โŒ€
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
โŒ€
gha_stargazers_count
int32
0
112k
โŒ€
gha_forks_count
int32
0
39.4k
โŒ€
gha_open_issues_count
int32
0
11k
โŒ€
gha_language
stringlengths
1
21
โŒ€
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
1c50b5b225cee0e6c6719e8270a18d5a89f924c4
29,678,224,048,783
e23c077a0acc9ec32757b46bfd5ed2b031dacd7c
/MyTravel/app/src/main/java/com/example/mytravel/ui/detailtour/DetailTourFrMvpView.java
8dfc47334020f92137e883ded011b95cddf506db
[]
no_license
KhacTung-Shjn/travel
https://github.com/KhacTung-Shjn/travel
9a7b3800f5e2319b6b6683a11b1dc526a5fbe0f9
1c59ee644b1aa00b5db7ed72cc9de8d9d190e346
refs/heads/master
2022-12-04T05:48:24.533000
2020-08-02T03:16:23
2020-08-02T03:16:23
270,491,299
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mytravel.ui.detailtour; import com.example.mytravel.base.MvpView; public interface DetailTourFrMvpView extends MvpView { }
UTF-8
Java
145
java
DetailTourFrMvpView.java
Java
[]
null
[]
package com.example.mytravel.ui.detailtour; import com.example.mytravel.base.MvpView; public interface DetailTourFrMvpView extends MvpView { }
145
0.827586
0.827586
6
23.166666
23.190636
54
false
false
0
0
0
0
0
0
0.333333
false
false
3
a316c670d155778e210490e6a4ad16590ed8b22f
13,400,297,999,724
27d45e0f93bf1156c4cc4f698a7241fcb90d217d
/src/control/GalleryUploadController.java
ddaae46e4839632e2e1031ce18af3fb52e5c9f09
[]
no_license
sophie-jhkim/AnneFanpage
https://github.com/sophie-jhkim/AnneFanpage
92e776e1748637afa207d0a2b3f4a992a761ab33
035d5bd1c90f2b91a15ebee1967a95e6517f56e7
refs/heads/master
2023-07-17T18:53:45.692000
2021-08-02T13:57:23
2021-08-02T13:57:23
374,912,589
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package control; import java.util.Enumeration; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; import dao.GalleryDao; import dto.Gallery; import dto.Mania; @Component("/AnneCustom/gallery_upload.do") public class GalleryUploadController implements Controller, DataBinding{ private GalleryDao galleryDao; public GalleryUploadController setGalleryDao(GalleryDao galleryDao) { this.galleryDao = galleryDao; return this; } @Override public Object[] getDataBinders() { return new Object[] { "photo", dto.Gallery.class, }; } @Override public String execute(Map<String, Object> model) throws Exception { int result =-1; HttpSession session = (HttpSession) model.get("session"); Mania mania = (Mania) session.getAttribute("mania"); Gallery gallery = (Gallery) model.get("photo"); String savePath = "../AnneCutom/photo"; int uploadFileSizeLimit = 5*1024*1024; String encType = "UTF-8"; // ServletContext context = request.getSession().getSetvletContext(); // String uploadFilePath = context.getRealPath(savePath); if(mania == null) { return "LoginForm.jsp"; }else if(gallery.getContent() == null){ return "PhotoUpload.jsp"; }else{ try { // MultipartRequest multi = new MultipartRequest(request, // uploadFilePath, uploadFileSizeLimit, encType, // new DefaultFileRenamePolicy()); // Enumeration file = multi.getFileNames(); result = galleryDao.insertPhoto(gallery); if(result<0) { System.out.println("์—…๋กœ๋“œ ์‹คํŒจ"); }else { return "redirect: gallery.do"; } }catch(Exception e) { e.printStackTrace(); } } return "redirect: gallery.do"; } }
UTF-8
Java
1,815
java
GalleryUploadController.java
Java
[]
null
[]
package control; import java.util.Enumeration; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; import dao.GalleryDao; import dto.Gallery; import dto.Mania; @Component("/AnneCustom/gallery_upload.do") public class GalleryUploadController implements Controller, DataBinding{ private GalleryDao galleryDao; public GalleryUploadController setGalleryDao(GalleryDao galleryDao) { this.galleryDao = galleryDao; return this; } @Override public Object[] getDataBinders() { return new Object[] { "photo", dto.Gallery.class, }; } @Override public String execute(Map<String, Object> model) throws Exception { int result =-1; HttpSession session = (HttpSession) model.get("session"); Mania mania = (Mania) session.getAttribute("mania"); Gallery gallery = (Gallery) model.get("photo"); String savePath = "../AnneCutom/photo"; int uploadFileSizeLimit = 5*1024*1024; String encType = "UTF-8"; // ServletContext context = request.getSession().getSetvletContext(); // String uploadFilePath = context.getRealPath(savePath); if(mania == null) { return "LoginForm.jsp"; }else if(gallery.getContent() == null){ return "PhotoUpload.jsp"; }else{ try { // MultipartRequest multi = new MultipartRequest(request, // uploadFilePath, uploadFileSizeLimit, encType, // new DefaultFileRenamePolicy()); // Enumeration file = multi.getFileNames(); result = galleryDao.insertPhoto(gallery); if(result<0) { System.out.println("์—…๋กœ๋“œ ์‹คํŒจ"); }else { return "redirect: gallery.do"; } }catch(Exception e) { e.printStackTrace(); } } return "redirect: gallery.do"; } }
1,815
0.716897
0.710249
69
25.15942
21.043518
72
false
false
0
0
0
0
0
0
2.173913
false
false
3
f0e24b40e1fb9994b704786d5e0a818622869d9c
21,406,117,045,291
1b72958ab7d8749594fd0dca20e3d9e793151b4e
/dep-scoring-ctrl/src/com/ctb/lexington/domain/score/controller/tbcontroller/StudentResultStatusController.java
984c98a6f8b054d29cf4d8ff9448ef6a2f1aacc4
[]
no_license
sumit-sardar/GitMigrationRepo01
https://github.com/sumit-sardar/GitMigrationRepo01
d0a89e33d3c7d873fac2dd66a7a5e59fd2b1bc3a
a474889914ea0e9805547ac7f4659c49e1a6b712
refs/heads/master
2021-01-17T00:45:16.256000
2016-05-12T18:37:01
2016-05-12T18:37:01
61,346,131
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ctb.lexington.domain.score.controller.tbcontroller; import java.sql.Connection; import java.io.IOException; import java.sql.SQLException; import com.ctb.lexington.exception.CTBSystemException; import com.ctb.lexington.exception.DataException; import com.ctb.lexington.db.data.ContextData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABECompositeFactData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABEContentAreaFactData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABEItemFactData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABEPredSubjectFactData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABEPrimObjFactData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABESecObjFactData; import com.ctb.lexington.db.mapper.tbmapper.IrsTABECompositeFactMapper; import com.ctb.lexington.db.mapper.tbmapper.IrsTABEContentAreaFactMapper; import com.ctb.lexington.db.mapper.tbmapper.IrsTABEPrimObjFactMapper; import com.ctb.lexington.db.mapper.tbmapper.IrsTABESecObjFactMapper; import com.ctb.lexington.db.mapper.tbmapper.IrsTABEItemFactMapper; import com.ctb.lexington.db.mapper.tbmapper.IrsTABEPredSubjectFactMapper; /** * @author Rama_Rao * */ public class StudentResultStatusController{ private ContextData context; private IrsTABECompositeFactMapper irsTABECompositeFactMapper; private IrsTABEContentAreaFactMapper irsTABEContentAreaFactMapper; private IrsTABEPrimObjFactMapper irsTABEPrimObjFactMapper; private IrsTABESecObjFactMapper irsTABESecObjFactMapper; private IrsTABEItemFactMapper irsTABEItemFactMapper; private IrsTABEPredSubjectFactMapper irsTABEPredSubjectFactMapper; public StudentResultStatusController(Connection conn, ContextData context){ this.context = context; irsTABEPredSubjectFactMapper = new IrsTABEPredSubjectFactMapper(conn); irsTABECompositeFactMapper = new IrsTABECompositeFactMapper(conn); irsTABEContentAreaFactMapper = new IrsTABEContentAreaFactMapper(conn); irsTABEPrimObjFactMapper = new IrsTABEPrimObjFactMapper(conn); irsTABESecObjFactMapper = new IrsTABESecObjFactMapper(conn); irsTABEItemFactMapper = new IrsTABEItemFactMapper(conn); } public void run() throws IOException, DataException, CTBSystemException, SQLException { Long priorResult = new Long(1).equals(context.getCurrentResultId())?new Long(2):new Long(1); IrsTABEPredSubjectFactData tabePredSubjectFactData = new IrsTABEPredSubjectFactData(); tabePredSubjectFactData.setStudentid(context.getStudentId()); tabePredSubjectFactData.setSessionid(context.getSessionId()); tabePredSubjectFactData.setCurrentResultid(priorResult); tabePredSubjectFactData.setAssessmentid(context.getAssessmentId()); tabePredSubjectFactData.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabePredSubjectFactData.setProgramid(context.getProgramId()); irsTABEPredSubjectFactMapper.updateCurrentResultStatus(tabePredSubjectFactData); IrsTABECompositeFactData tabeCompositeFactdata = new IrsTABECompositeFactData(); tabeCompositeFactdata.setStudentid(context.getStudentId()); tabeCompositeFactdata.setSessionid(context.getSessionId()); tabeCompositeFactdata.setCurrentResultid(priorResult); tabeCompositeFactdata.setAssessmentid(context.getAssessmentId()); tabeCompositeFactdata.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabeCompositeFactdata.setProgramid(context.getProgramId()); irsTABECompositeFactMapper.updateCurrentResultStatus(tabeCompositeFactdata); IrsTABEContentAreaFactData tabeContentAreaFactData = new IrsTABEContentAreaFactData(); tabeContentAreaFactData.setStudentid(context.getStudentId()); tabeContentAreaFactData.setSessionid(context.getSessionId()); tabeContentAreaFactData.setCurrentResultid(priorResult); tabeContentAreaFactData.setAssessmentid(context.getAssessmentId()); tabeContentAreaFactData.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabeContentAreaFactData.setProgramid(context.getProgramId()); irsTABEContentAreaFactMapper.updateCurrentResultStatus(tabeContentAreaFactData); IrsTABEPrimObjFactData tabePrimObjFactData = new IrsTABEPrimObjFactData(); tabePrimObjFactData.setStudentid(context.getStudentId()); tabePrimObjFactData.setSessionid(context.getSessionId()); tabePrimObjFactData.setCurrentResultid(priorResult); tabePrimObjFactData.setAssessmentid(context.getAssessmentId()); tabePrimObjFactData.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabePrimObjFactData.setProgramid(context.getProgramId()); irsTABEPrimObjFactMapper.updateCurrentResultStatus(tabePrimObjFactData); IrsTABESecObjFactData tabeSecObjFactData = new IrsTABESecObjFactData(); tabeSecObjFactData.setStudentid(context.getStudentId()); tabeSecObjFactData.setSessionid(context.getSessionId()); tabeSecObjFactData.setCurrentResultid(priorResult); tabeSecObjFactData.setAssessmentid(context.getAssessmentId()); tabeSecObjFactData.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabeSecObjFactData.setProgramid(context.getProgramId()); irsTABESecObjFactMapper.updateCurrentResultStatus(tabeSecObjFactData); IrsTABEItemFactData tabeItemFactData = new IrsTABEItemFactData(); tabeItemFactData.setStudentid(context.getStudentId()); tabeItemFactData.setSessionid(context.getSessionId()); tabeItemFactData.setCurrentResultid(priorResult); tabeItemFactData.setAssessmentid(context.getAssessmentId()); tabeItemFactData.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabeItemFactData.setProgramid(context.getProgramId()); irsTABEItemFactMapper.updateCurrentResultStatus(tabeItemFactData); } }
UTF-8
Java
6,191
java
StudentResultStatusController.java
Java
[ { "context": "r.IrsTABEPredSubjectFactMapper;\r\n\r\n/**\r\n * @author Rama_Rao\r\n *\r\n */\r\npublic class StudentResultStatusControl", "end": 1200, "score": 0.889373779296875, "start": 1192, "tag": "NAME", "value": "Rama_Rao" } ]
null
[]
package com.ctb.lexington.domain.score.controller.tbcontroller; import java.sql.Connection; import java.io.IOException; import java.sql.SQLException; import com.ctb.lexington.exception.CTBSystemException; import com.ctb.lexington.exception.DataException; import com.ctb.lexington.db.data.ContextData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABECompositeFactData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABEContentAreaFactData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABEItemFactData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABEPredSubjectFactData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABEPrimObjFactData; import com.ctb.lexington.db.irsdata.irstbdata.IrsTABESecObjFactData; import com.ctb.lexington.db.mapper.tbmapper.IrsTABECompositeFactMapper; import com.ctb.lexington.db.mapper.tbmapper.IrsTABEContentAreaFactMapper; import com.ctb.lexington.db.mapper.tbmapper.IrsTABEPrimObjFactMapper; import com.ctb.lexington.db.mapper.tbmapper.IrsTABESecObjFactMapper; import com.ctb.lexington.db.mapper.tbmapper.IrsTABEItemFactMapper; import com.ctb.lexington.db.mapper.tbmapper.IrsTABEPredSubjectFactMapper; /** * @author Rama_Rao * */ public class StudentResultStatusController{ private ContextData context; private IrsTABECompositeFactMapper irsTABECompositeFactMapper; private IrsTABEContentAreaFactMapper irsTABEContentAreaFactMapper; private IrsTABEPrimObjFactMapper irsTABEPrimObjFactMapper; private IrsTABESecObjFactMapper irsTABESecObjFactMapper; private IrsTABEItemFactMapper irsTABEItemFactMapper; private IrsTABEPredSubjectFactMapper irsTABEPredSubjectFactMapper; public StudentResultStatusController(Connection conn, ContextData context){ this.context = context; irsTABEPredSubjectFactMapper = new IrsTABEPredSubjectFactMapper(conn); irsTABECompositeFactMapper = new IrsTABECompositeFactMapper(conn); irsTABEContentAreaFactMapper = new IrsTABEContentAreaFactMapper(conn); irsTABEPrimObjFactMapper = new IrsTABEPrimObjFactMapper(conn); irsTABESecObjFactMapper = new IrsTABESecObjFactMapper(conn); irsTABEItemFactMapper = new IrsTABEItemFactMapper(conn); } public void run() throws IOException, DataException, CTBSystemException, SQLException { Long priorResult = new Long(1).equals(context.getCurrentResultId())?new Long(2):new Long(1); IrsTABEPredSubjectFactData tabePredSubjectFactData = new IrsTABEPredSubjectFactData(); tabePredSubjectFactData.setStudentid(context.getStudentId()); tabePredSubjectFactData.setSessionid(context.getSessionId()); tabePredSubjectFactData.setCurrentResultid(priorResult); tabePredSubjectFactData.setAssessmentid(context.getAssessmentId()); tabePredSubjectFactData.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabePredSubjectFactData.setProgramid(context.getProgramId()); irsTABEPredSubjectFactMapper.updateCurrentResultStatus(tabePredSubjectFactData); IrsTABECompositeFactData tabeCompositeFactdata = new IrsTABECompositeFactData(); tabeCompositeFactdata.setStudentid(context.getStudentId()); tabeCompositeFactdata.setSessionid(context.getSessionId()); tabeCompositeFactdata.setCurrentResultid(priorResult); tabeCompositeFactdata.setAssessmentid(context.getAssessmentId()); tabeCompositeFactdata.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabeCompositeFactdata.setProgramid(context.getProgramId()); irsTABECompositeFactMapper.updateCurrentResultStatus(tabeCompositeFactdata); IrsTABEContentAreaFactData tabeContentAreaFactData = new IrsTABEContentAreaFactData(); tabeContentAreaFactData.setStudentid(context.getStudentId()); tabeContentAreaFactData.setSessionid(context.getSessionId()); tabeContentAreaFactData.setCurrentResultid(priorResult); tabeContentAreaFactData.setAssessmentid(context.getAssessmentId()); tabeContentAreaFactData.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabeContentAreaFactData.setProgramid(context.getProgramId()); irsTABEContentAreaFactMapper.updateCurrentResultStatus(tabeContentAreaFactData); IrsTABEPrimObjFactData tabePrimObjFactData = new IrsTABEPrimObjFactData(); tabePrimObjFactData.setStudentid(context.getStudentId()); tabePrimObjFactData.setSessionid(context.getSessionId()); tabePrimObjFactData.setCurrentResultid(priorResult); tabePrimObjFactData.setAssessmentid(context.getAssessmentId()); tabePrimObjFactData.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabePrimObjFactData.setProgramid(context.getProgramId()); irsTABEPrimObjFactMapper.updateCurrentResultStatus(tabePrimObjFactData); IrsTABESecObjFactData tabeSecObjFactData = new IrsTABESecObjFactData(); tabeSecObjFactData.setStudentid(context.getStudentId()); tabeSecObjFactData.setSessionid(context.getSessionId()); tabeSecObjFactData.setCurrentResultid(priorResult); tabeSecObjFactData.setAssessmentid(context.getAssessmentId()); tabeSecObjFactData.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabeSecObjFactData.setProgramid(context.getProgramId()); irsTABESecObjFactMapper.updateCurrentResultStatus(tabeSecObjFactData); IrsTABEItemFactData tabeItemFactData = new IrsTABEItemFactData(); tabeItemFactData.setStudentid(context.getStudentId()); tabeItemFactData.setSessionid(context.getSessionId()); tabeItemFactData.setCurrentResultid(priorResult); tabeItemFactData.setAssessmentid(context.getAssessmentId()); tabeItemFactData.setTestCompletionTimestamp(context.getTestCompletionTimestamp()); tabeItemFactData.setProgramid(context.getProgramId()); irsTABEItemFactMapper.updateCurrentResultStatus(tabeItemFactData); } }
6,191
0.783557
0.783072
103
58.116505
27.833521
100
false
false
0
0
0
0
0
0
0.834951
false
false
3
3eb4768bb136ddd7dc815316974fbf6a817c7d7e
32,452,772,904,858
8de939e722bb91f85e0f8a96d986186277d0bbdb
/src/main/java/com/storm/util/StormConfig.java
f12c7be2d23c127333845e007f9c9d28d92ef764
[]
no_license
RevatureRobert/STORM_P1
https://github.com/RevatureRobert/STORM_P1
830fd540143fcc52e91e18cd97e6fc7ae50a8ca9
ed8fae78ea0aec2efe614d9e1d1cc8fe3bdb5e73
refs/heads/main
2023-03-25T21:08:48.193000
2021-03-26T17:33:40
2021-03-26T17:33:40
351,637,300
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.storm.util; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.sql.Connection; import java.util.Properties; /** * StormConfig will hold an instance of a jdbc */ public class StormConfig { private String username; private String password; private String jdbcUrl; private String schema; private static Connection conn; private int maxConnections; private Properties dataSourceProperties; private boolean sealed; public StormConfig(){ } public StormConfig(Properties properties){ dataSourceProperties = properties; setTargetFromProperties(properties); } public StormConfig(String fileName){ dataSourceProperties = loadProperties(fileName); } private void setTargetFromProperties(Properties properties){ if(properties == null) return; properties.forEach((key,value) ->{ switch(key.toString()){ case "username": this.username = value.toString(); break; case "password": this.password = value.toString(); break; case "jdbcUrl": this.jdbcUrl = value.toString(); break; } }); } private Properties loadProperties(){ try(InputStream input = new FileInputStream("h2.properties")){ Properties prop = new Properties(); prop.load(input); return prop; }catch (IOException e){ e.printStackTrace(); } return null; } private Properties loadProperties(String fileName){ try(InputStream input = new FileInputStream(fileName)){ Properties prop = new Properties(); prop.load(input); return prop; }catch (IOException e){ e.printStackTrace(); } return null; } public void copyStateTo(StormConfig other){ for (Field field : StormConfig.class.getDeclaredFields()) { if (!Modifier.isFinal(field.getModifiers())) { field.setAccessible(true); try { field.set(other, field.get(this)); } catch (Exception e) { throw new RuntimeException("Failed to copy HikariConfig state: " + e.getMessage(), e); } } } other.sealed = false; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public static Connection getConn() { return conn; } public static void setConn(Connection conn) { StormConfig.conn = conn; } public Properties getDataSourceProperties() { return dataSourceProperties; } public void setDataSourceProperties(Properties dataSourceProperties) { this.dataSourceProperties = dataSourceProperties; } public int getMaxConnections() { return maxConnections; } public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } }
UTF-8
Java
3,646
java
StormConfig.java
Java
[ { "context": " switch(key.toString()){\n case \"username\": this.username = value.toString();\n ", "end": 1005, "score": 0.9359612464904785, "start": 997, "tag": "USERNAME", "value": "username" }, { "context": ";\n case \"password\": this.password = value.toString();\n break;\n cas", "end": 1132, "score": 0.9539918899536133, "start": 1118, "tag": "PASSWORD", "value": "value.toString" }, { "context": "sername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n ", "end": 2615, "score": 0.9989176988601685, "start": 2607, "tag": "USERNAME", "value": "username" }, { "context": "assword(String password) {\n this.password = password;\n }\n\n public String getJdbcUrl() {\n ", "end": 2769, "score": 0.7786117792129517, "start": 2761, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.storm.util; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.sql.Connection; import java.util.Properties; /** * StormConfig will hold an instance of a jdbc */ public class StormConfig { private String username; private String password; private String jdbcUrl; private String schema; private static Connection conn; private int maxConnections; private Properties dataSourceProperties; private boolean sealed; public StormConfig(){ } public StormConfig(Properties properties){ dataSourceProperties = properties; setTargetFromProperties(properties); } public StormConfig(String fileName){ dataSourceProperties = loadProperties(fileName); } private void setTargetFromProperties(Properties properties){ if(properties == null) return; properties.forEach((key,value) ->{ switch(key.toString()){ case "username": this.username = value.toString(); break; case "password": this.password = <PASSWORD>(); break; case "jdbcUrl": this.jdbcUrl = value.toString(); break; } }); } private Properties loadProperties(){ try(InputStream input = new FileInputStream("h2.properties")){ Properties prop = new Properties(); prop.load(input); return prop; }catch (IOException e){ e.printStackTrace(); } return null; } private Properties loadProperties(String fileName){ try(InputStream input = new FileInputStream(fileName)){ Properties prop = new Properties(); prop.load(input); return prop; }catch (IOException e){ e.printStackTrace(); } return null; } public void copyStateTo(StormConfig other){ for (Field field : StormConfig.class.getDeclaredFields()) { if (!Modifier.isFinal(field.getModifiers())) { field.setAccessible(true); try { field.set(other, field.get(this)); } catch (Exception e) { throw new RuntimeException("Failed to copy HikariConfig state: " + e.getMessage(), e); } } } other.sealed = false; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public static Connection getConn() { return conn; } public static void setConn(Connection conn) { StormConfig.conn = conn; } public Properties getDataSourceProperties() { return dataSourceProperties; } public void setDataSourceProperties(Properties dataSourceProperties) { this.dataSourceProperties = dataSourceProperties; } public int getMaxConnections() { return maxConnections; } public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } }
3,644
0.595173
0.594899
148
23.635136
21.154562
106
false
false
0
0
0
0
0
0
0.378378
false
false
3
a9d3753474bf7f75458c1d4f4c5997b3f0e27893
15,685,220,606,983
e0aabab7bd366af3ba1886a8f071a1d7a1d22fe0
/SpringMVC/src/com/huyang/service/spring/ProductService.java
ccdd4c03fe54e932220a6799c4ef384569900e83
[]
no_license
programbird1994/JavaWebShoppingMall
https://github.com/programbird1994/JavaWebShoppingMall
e79a7d67a813ce6909c081c78745aaaf70d3f400
99e944eb9bf3fbd17be27e5652d3e3692a7f4ca3
refs/heads/master
2021-01-17T20:50:36.459000
2016-06-25T09:03:01
2016-06-25T09:03:01
61,934,915
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huyang.service.spring; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.huyang.dao.spring.HibernateProductDao; import com.huyang.model.spring.Comment; import com.huyang.model.spring.ProductDetail; @Service public class ProductService { @Autowired private HibernateProductDao hibernateProductDao; @Transactional public List<ProductDetail> getProducts(int shopID) { return hibernateProductDao.getProductList(shopID); } @Transactional public int getStoreCount(int productID) { return hibernateProductDao.getStoreCount(productID); } public String getAveRankByProductID(int productID) { return hibernateProductDao.getAveRankByProductID(productID); } @Transactional public List<ProductDetail> getProductsByKeyword(String keyword,boolean pricehigher,int index,int pageSize) { String priceorder; if(pricehigher) { priceorder=" "; } else { priceorder="order by price desc"; } return hibernateProductDao.getProductsByKeyword(keyword,priceorder,index, pageSize); } @Transactional public List<ProductDetail> getProductsByKeyword(String keyword,boolean pricehigher) { String priceorder; if(pricehigher) { priceorder=" "; } else { priceorder="order by price desc"; } return hibernateProductDao.getProductsByKeyword(keyword,priceorder); } @Transactional public List<ProductDetail> getProductsByCategoryID(int categoryID) { return hibernateProductDao.getProductListByCategoryID(categoryID); } @Transactional public int getproductsByKeywordcount(String keyword,String priceorder) { return hibernateProductDao.getProductsByKeywordCount(keyword, priceorder); } @Transactional public void updateStoreCount(String orderID) { hibernateProductDao.updateStoreCount(orderID); } @Transactional public void updateSellCount(int productID,String orderID) { hibernateProductDao.updateSellCount(productID,orderID); } @Transactional public ProductDetail getProductsByProductID(int productID) { return hibernateProductDao.getproductByproductID(productID); } @Transactional public List<ProductDetail> getTenBestSellProducts() { return hibernateProductDao.getTenBestSellProducts(); } @Transactional public List<ProductDetail> getTenLastSellProducts() { return hibernateProductDao.getTenLastSellProducts(); } @Transactional public List<Comment> getCommentsByProductID(int productID) { return hibernateProductDao.getCommentsByProductID(productID); } @Transactional public List<ProductDetail> getProductsByCategoryID(int index,int pagesize,int categoryID) { return hibernateProductDao.getProductsBycategory(index, pagesize, categoryID); } }
UTF-8
Java
2,831
java
ProductService.java
Java
[]
null
[]
package com.huyang.service.spring; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.huyang.dao.spring.HibernateProductDao; import com.huyang.model.spring.Comment; import com.huyang.model.spring.ProductDetail; @Service public class ProductService { @Autowired private HibernateProductDao hibernateProductDao; @Transactional public List<ProductDetail> getProducts(int shopID) { return hibernateProductDao.getProductList(shopID); } @Transactional public int getStoreCount(int productID) { return hibernateProductDao.getStoreCount(productID); } public String getAveRankByProductID(int productID) { return hibernateProductDao.getAveRankByProductID(productID); } @Transactional public List<ProductDetail> getProductsByKeyword(String keyword,boolean pricehigher,int index,int pageSize) { String priceorder; if(pricehigher) { priceorder=" "; } else { priceorder="order by price desc"; } return hibernateProductDao.getProductsByKeyword(keyword,priceorder,index, pageSize); } @Transactional public List<ProductDetail> getProductsByKeyword(String keyword,boolean pricehigher) { String priceorder; if(pricehigher) { priceorder=" "; } else { priceorder="order by price desc"; } return hibernateProductDao.getProductsByKeyword(keyword,priceorder); } @Transactional public List<ProductDetail> getProductsByCategoryID(int categoryID) { return hibernateProductDao.getProductListByCategoryID(categoryID); } @Transactional public int getproductsByKeywordcount(String keyword,String priceorder) { return hibernateProductDao.getProductsByKeywordCount(keyword, priceorder); } @Transactional public void updateStoreCount(String orderID) { hibernateProductDao.updateStoreCount(orderID); } @Transactional public void updateSellCount(int productID,String orderID) { hibernateProductDao.updateSellCount(productID,orderID); } @Transactional public ProductDetail getProductsByProductID(int productID) { return hibernateProductDao.getproductByproductID(productID); } @Transactional public List<ProductDetail> getTenBestSellProducts() { return hibernateProductDao.getTenBestSellProducts(); } @Transactional public List<ProductDetail> getTenLastSellProducts() { return hibernateProductDao.getTenLastSellProducts(); } @Transactional public List<Comment> getCommentsByProductID(int productID) { return hibernateProductDao.getCommentsByProductID(productID); } @Transactional public List<ProductDetail> getProductsByCategoryID(int index,int pagesize,int categoryID) { return hibernateProductDao.getProductsBycategory(index, pagesize, categoryID); } }
2,831
0.797951
0.797951
113
24.053097
27.291231
107
false
false
0
0
0
0
0
0
1.451327
false
false
3
ef3567a3cdc684dca3ac79d5a4b133fb610de124
2,173,253,494,136
6ef4869c6bc2ce2e77b422242e347819f6a5f665
/devices/google/Pixel 2/29/QPP6.190730.005/src/framework/android/os/IStoraged.java
bb66189a919b8c7a08ebdd2bbfcd7d389da0cb82
[]
no_license
hacking-android/frameworks
https://github.com/hacking-android/frameworks
40e40396bb2edacccabf8a920fa5722b021fb060
943f0b4d46f72532a419fb6171e40d1c93984c8e
refs/heads/master
2020-07-03T19:32:28.876000
2019-08-13T03:31:06
2019-08-13T03:31:06
202,017,534
2
0
null
false
2019-08-13T03:33:19
2019-08-12T22:19:30
2019-08-13T03:31:53
2019-08-13T03:33:18
63,898
0
0
0
Java
false
false
/* * Decompiled with CFR 0.145. */ package android.os; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; import android.os.RemoteException; public interface IStoraged extends IInterface { public int getRecentPerf() throws RemoteException; public void onUserStarted(int var1) throws RemoteException; public void onUserStopped(int var1) throws RemoteException; public static class Default implements IStoraged { @Override public IBinder asBinder() { return null; } @Override public int getRecentPerf() throws RemoteException { return 0; } @Override public void onUserStarted(int n) throws RemoteException { } @Override public void onUserStopped(int n) throws RemoteException { } } public static abstract class Stub extends Binder implements IStoraged { private static final String DESCRIPTOR = "android.os.IStoraged"; static final int TRANSACTION_getRecentPerf = 3; static final int TRANSACTION_onUserStarted = 1; static final int TRANSACTION_onUserStopped = 2; public Stub() { this.attachInterface(this, DESCRIPTOR); } public static IStoraged asInterface(IBinder iBinder) { if (iBinder == null) { return null; } IInterface iInterface = iBinder.queryLocalInterface(DESCRIPTOR); if (iInterface != null && iInterface instanceof IStoraged) { return (IStoraged)iInterface; } return new Proxy(iBinder); } public static IStoraged getDefaultImpl() { return Proxy.sDefaultImpl; } public static String getDefaultTransactionName(int n) { if (n != 1) { if (n != 2) { if (n != 3) { return null; } return "getRecentPerf"; } return "onUserStopped"; } return "onUserStarted"; } public static boolean setDefaultImpl(IStoraged iStoraged) { if (Proxy.sDefaultImpl == null && iStoraged != null) { Proxy.sDefaultImpl = iStoraged; return true; } return false; } @Override public IBinder asBinder() { return this; } @Override public String getTransactionName(int n) { return Stub.getDefaultTransactionName(n); } @Override public boolean onTransact(int n, Parcel parcel, Parcel parcel2, int n2) throws RemoteException { if (n != 1) { if (n != 2) { if (n != 3) { if (n != 1598968902) { return super.onTransact(n, parcel, parcel2, n2); } parcel2.writeString(DESCRIPTOR); return true; } parcel.enforceInterface(DESCRIPTOR); n = this.getRecentPerf(); parcel2.writeNoException(); parcel2.writeInt(n); return true; } parcel.enforceInterface(DESCRIPTOR); this.onUserStopped(parcel.readInt()); parcel2.writeNoException(); return true; } parcel.enforceInterface(DESCRIPTOR); this.onUserStarted(parcel.readInt()); parcel2.writeNoException(); return true; } private static class Proxy implements IStoraged { public static IStoraged sDefaultImpl; private IBinder mRemote; Proxy(IBinder iBinder) { this.mRemote = iBinder; } @Override public IBinder asBinder() { return this.mRemote; } public String getInterfaceDescriptor() { return Stub.DESCRIPTOR; } @Override public int getRecentPerf() throws RemoteException { Parcel parcel = Parcel.obtain(); Parcel parcel2 = Parcel.obtain(); try { parcel.writeInterfaceToken(Stub.DESCRIPTOR); if (!this.mRemote.transact(3, parcel, parcel2, 0) && Stub.getDefaultImpl() != null) { int n = Stub.getDefaultImpl().getRecentPerf(); return n; } parcel2.readException(); int n = parcel2.readInt(); return n; } finally { parcel2.recycle(); parcel.recycle(); } } @Override public void onUserStarted(int n) throws RemoteException { Parcel parcel = Parcel.obtain(); Parcel parcel2 = Parcel.obtain(); try { parcel.writeInterfaceToken(Stub.DESCRIPTOR); parcel.writeInt(n); if (!this.mRemote.transact(1, parcel, parcel2, 0) && Stub.getDefaultImpl() != null) { Stub.getDefaultImpl().onUserStarted(n); return; } parcel2.readException(); return; } finally { parcel2.recycle(); parcel.recycle(); } } @Override public void onUserStopped(int n) throws RemoteException { Parcel parcel = Parcel.obtain(); Parcel parcel2 = Parcel.obtain(); try { parcel.writeInterfaceToken(Stub.DESCRIPTOR); parcel.writeInt(n); if (!this.mRemote.transact(2, parcel, parcel2, 0) && Stub.getDefaultImpl() != null) { Stub.getDefaultImpl().onUserStopped(n); return; } parcel2.readException(); return; } finally { parcel2.recycle(); parcel.recycle(); } } } } }
UTF-8
Java
6,568
java
IStoraged.java
Java
[]
null
[]
/* * Decompiled with CFR 0.145. */ package android.os; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; import android.os.RemoteException; public interface IStoraged extends IInterface { public int getRecentPerf() throws RemoteException; public void onUserStarted(int var1) throws RemoteException; public void onUserStopped(int var1) throws RemoteException; public static class Default implements IStoraged { @Override public IBinder asBinder() { return null; } @Override public int getRecentPerf() throws RemoteException { return 0; } @Override public void onUserStarted(int n) throws RemoteException { } @Override public void onUserStopped(int n) throws RemoteException { } } public static abstract class Stub extends Binder implements IStoraged { private static final String DESCRIPTOR = "android.os.IStoraged"; static final int TRANSACTION_getRecentPerf = 3; static final int TRANSACTION_onUserStarted = 1; static final int TRANSACTION_onUserStopped = 2; public Stub() { this.attachInterface(this, DESCRIPTOR); } public static IStoraged asInterface(IBinder iBinder) { if (iBinder == null) { return null; } IInterface iInterface = iBinder.queryLocalInterface(DESCRIPTOR); if (iInterface != null && iInterface instanceof IStoraged) { return (IStoraged)iInterface; } return new Proxy(iBinder); } public static IStoraged getDefaultImpl() { return Proxy.sDefaultImpl; } public static String getDefaultTransactionName(int n) { if (n != 1) { if (n != 2) { if (n != 3) { return null; } return "getRecentPerf"; } return "onUserStopped"; } return "onUserStarted"; } public static boolean setDefaultImpl(IStoraged iStoraged) { if (Proxy.sDefaultImpl == null && iStoraged != null) { Proxy.sDefaultImpl = iStoraged; return true; } return false; } @Override public IBinder asBinder() { return this; } @Override public String getTransactionName(int n) { return Stub.getDefaultTransactionName(n); } @Override public boolean onTransact(int n, Parcel parcel, Parcel parcel2, int n2) throws RemoteException { if (n != 1) { if (n != 2) { if (n != 3) { if (n != 1598968902) { return super.onTransact(n, parcel, parcel2, n2); } parcel2.writeString(DESCRIPTOR); return true; } parcel.enforceInterface(DESCRIPTOR); n = this.getRecentPerf(); parcel2.writeNoException(); parcel2.writeInt(n); return true; } parcel.enforceInterface(DESCRIPTOR); this.onUserStopped(parcel.readInt()); parcel2.writeNoException(); return true; } parcel.enforceInterface(DESCRIPTOR); this.onUserStarted(parcel.readInt()); parcel2.writeNoException(); return true; } private static class Proxy implements IStoraged { public static IStoraged sDefaultImpl; private IBinder mRemote; Proxy(IBinder iBinder) { this.mRemote = iBinder; } @Override public IBinder asBinder() { return this.mRemote; } public String getInterfaceDescriptor() { return Stub.DESCRIPTOR; } @Override public int getRecentPerf() throws RemoteException { Parcel parcel = Parcel.obtain(); Parcel parcel2 = Parcel.obtain(); try { parcel.writeInterfaceToken(Stub.DESCRIPTOR); if (!this.mRemote.transact(3, parcel, parcel2, 0) && Stub.getDefaultImpl() != null) { int n = Stub.getDefaultImpl().getRecentPerf(); return n; } parcel2.readException(); int n = parcel2.readInt(); return n; } finally { parcel2.recycle(); parcel.recycle(); } } @Override public void onUserStarted(int n) throws RemoteException { Parcel parcel = Parcel.obtain(); Parcel parcel2 = Parcel.obtain(); try { parcel.writeInterfaceToken(Stub.DESCRIPTOR); parcel.writeInt(n); if (!this.mRemote.transact(1, parcel, parcel2, 0) && Stub.getDefaultImpl() != null) { Stub.getDefaultImpl().onUserStarted(n); return; } parcel2.readException(); return; } finally { parcel2.recycle(); parcel.recycle(); } } @Override public void onUserStopped(int n) throws RemoteException { Parcel parcel = Parcel.obtain(); Parcel parcel2 = Parcel.obtain(); try { parcel.writeInterfaceToken(Stub.DESCRIPTOR); parcel.writeInt(n); if (!this.mRemote.transact(2, parcel, parcel2, 0) && Stub.getDefaultImpl() != null) { Stub.getDefaultImpl().onUserStopped(n); return; } parcel2.readException(); return; } finally { parcel2.recycle(); parcel.recycle(); } } } } }
6,568
0.484622
0.476401
208
30.572115
22.589025
105
false
false
0
0
0
0
0
0
0.466346
false
false
3
70b8bb3cf28f88ec76459306768ae2d094490fad
29,609,504,570,487
884f3e247125f8606c20f25592e0c998c5a64d67
/src/main/java/com/bishal/todolist/model/Task.java
ca29bd1500e14e5a18bc940d5c000773f0079a5e
[]
no_license
Bishalj/Todo-List-BE
https://github.com/Bishalj/Todo-List-BE
ba6c624b799a360a6d94efb077fac895111f7698
0e1ee38332eb195216140cb7fbaa6c27908c299f
refs/heads/master
2020-05-31T05:54:33.555000
2020-04-05T06:41:01
2020-04-05T06:41:01
190,129,514
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bishal.todolist.model; import java.util.Date; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.mongodb.core.mapping.Document; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonInclude(value=Include.NON_EMPTY) @JsonIgnoreProperties(ignoreUnknown=true) @Document(value="Task") public class Task { @Id private String _id; private String title; private String taskDetail; private Date dueDate; private String label; private String status; @CreatedDate private Date createDate; @LastModifiedDate private Date updateDate; private Boolean isDeleted; public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getTaskDetail() { return taskDetail; } public void setTaskDetail(String taskDetail) { this.taskDetail = taskDetail; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public Boolean getIsDeleted() { return isDeleted; } public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
UTF-8
Java
1,958
java
Task.java
Java
[]
null
[]
package com.bishal.todolist.model; import java.util.Date; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.mongodb.core.mapping.Document; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonInclude(value=Include.NON_EMPTY) @JsonIgnoreProperties(ignoreUnknown=true) @Document(value="Task") public class Task { @Id private String _id; private String title; private String taskDetail; private Date dueDate; private String label; private String status; @CreatedDate private Date createDate; @LastModifiedDate private Date updateDate; private Boolean isDeleted; public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getTaskDetail() { return taskDetail; } public void setTaskDetail(String taskDetail) { this.taskDetail = taskDetail; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public Boolean getIsDeleted() { return isDeleted; } public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
1,958
0.752298
0.752298
87
21.505747
16.981987
62
false
false
0
0
0
0
0
0
1.413793
false
false
3
980647b5bc9be69bcae981dd590ba649d856fc62
472,446,429,358
9e6ad6ad462a1d587542c78fe84ce9981ed2e6e2
/src/main/java/com/kode/test/StringTest.java
1349c3b2eca0c2187b5c4f1f39009357ec2f4a11
[]
no_license
zhongchengyong/java-test
https://github.com/zhongchengyong/java-test
84285e8f664b896a805a33b5cfc4f41e12eb640c
380fe99f767dde3a07a66a11514a6f888ed9f92b
refs/heads/master
2021-09-13T00:09:59.364000
2018-04-23T00:57:45
2018-04-23T00:57:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kode.test; /** * Created by zhongcy on 2016/9/30. */ public class StringTest { public static void main(String[] args) { String s = "1".concat("2").concat("3").concat("4"); String s1 = "1" + "2" + "3" + System.lineSeparator(); System.out.println(s); System.out.println(s1); } }
UTF-8
Java
332
java
StringTest.java
Java
[ { "context": "package com.kode.test;\n\n/**\n * Created by zhongcy on 2016/9/30.\n */\npublic class StringTest {\n p", "end": 49, "score": 0.9994895458221436, "start": 42, "tag": "USERNAME", "value": "zhongcy" } ]
null
[]
package com.kode.test; /** * Created by zhongcy on 2016/9/30. */ public class StringTest { public static void main(String[] args) { String s = "1".concat("2").concat("3").concat("4"); String s1 = "1" + "2" + "3" + System.lineSeparator(); System.out.println(s); System.out.println(s1); } }
332
0.566265
0.518072
13
24.538462
20.660685
61
false
false
0
0
0
0
0
0
0.384615
false
false
3
5b116f56340c5712fadf7a941474597771dc3930
16,982,300,733,205
c6334d697f35c3538f7fac9e11e113e9bf379c9d
/src/test/java/com/compomics/util/test/general/TestCommandLineParser.java
5ba2aeb7ff479d9121f815a2b22a886c3929f550
[ "Apache-2.0" ]
permissive
compomics/compomics-utilities
https://github.com/compomics/compomics-utilities
cd2b5a24531c8a73eea077b9219e97a871b9ff00
c4431c0cc84769aee70a00e04de349a7100ef52f
refs/heads/master
2023-07-24T23:50:00.894000
2023-06-20T14:56:26
2023-06-20T14:56:26
41,178,332
33
25
null
false
2023-09-14T19:46:07
2015-08-21T21:30:27
2023-06-29T23:13:57
2023-09-14T19:46:07
112,367
25
16
4
Java
false
false
/* * Copyright (C) Lennart Martens * * Contact: lennart.martens AT UGent.be (' AT ' to be replaced with '@') */ package com.compomics.util.test.general; import com.compomics.util.general.CommandLineParser; import org.junit.Assert; import junit.framework.TestCase; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; /* * CVS information: * * $Revision: 1.3 $ * $Date: 2007/07/06 09:41:53 $ */ /** * This class is the test for the CommandLineParser class. * * @see com.compomics.util.general.CommandLineParser * @author Lennart Martens. */ public class TestCommandLineParser extends TestCase { // Class specific log4j logger for TestCommandLineParser instances. Logger logger = LogManager.getLogger(TestCommandLineParser.class); public TestCommandLineParser() { this("The test for the CommandLineParser class."); } public TestCommandLineParser(String aName) { super(aName); } /** * This method test the constructors and their abilitity to parse * without error. */ public void testInitialization() { // Test all 'not present cases'. CommandLineParser clp = new CommandLineParser(null); Assert.assertTrue("With just a 'null'", !clp.hasArguments()); clp = new CommandLineParser(new String[]{}); Assert.assertTrue("With just an empty String[]", !clp.hasArguments()); clp = new CommandLineParser(null, null); Assert.assertTrue("Args 'null', OptionArgs 'null'.", !clp.hasArguments()); clp = new CommandLineParser(new String[]{}, null); Assert.assertTrue("Args empty, OptionArgs 'null'.", !clp.hasArguments()); clp = new CommandLineParser(null, new String[]{}); Assert.assertTrue("Args 'null', OptionArgs empty.", !clp.hasArguments()); clp = new CommandLineParser(null, new String[]{"Test"}); Assert.assertTrue("Args 'null', OptionArgs filled.", !clp.hasArguments()); clp = new CommandLineParser(new String[]{}, new String[]{}); Assert.assertTrue("Args empty, OptionArgs empty.", !clp.hasArguments()); clp = new CommandLineParser(new String[]{}, new String[]{"Test"}); Assert.assertTrue("Args empty, OptionArgs filled.", !clp.hasArguments()); // Test four 'present' cases. clp = new CommandLineParser(new String[]{"Test"}); Assert.assertTrue(clp.hasArguments()); clp = new CommandLineParser(new String[]{"Test"}, null); Assert.assertTrue(clp.hasArguments()); clp = new CommandLineParser(new String[]{"Test"}, new String[]{}); Assert.assertTrue(clp.hasArguments()); clp = new CommandLineParser(new String[]{"Test"}, new String[]{"Test2"}); Assert.assertTrue(clp.hasArguments()); } /** * This method test the parsing of flags. */ public void testFlagParsing() { // The flags. String flag1 = "k"; String flag2 = "l"; String flag3 = "f"; String flag4 = "g"; String[] args = new String[]{"Parameter", "--Option1", "--Option2", "-klf", "-g"}; CommandLineParser clp = new CommandLineParser(args); // Check whether any arguments are in fact found. Assert.assertTrue(clp.hasArguments()); String[] result = clp.getFlags(); // See if it is not 'null' or empty. Assert.assertTrue(result != null); Assert.assertTrue(result.length > 0); // Check the 'hasFlag method'. Assert.assertTrue(clp.hasFlag(flag1)); Assert.assertTrue(clp.hasFlag(flag2)); Assert.assertTrue(clp.hasFlag(flag3)); Assert.assertTrue(clp.hasFlag(flag4)); Assert.assertFalse(clp.hasFlag("x")); // Four flags present, see if all are found. Assert.assertEquals("Incorrect number of flags found!", 4, result.length); // Cycle each and check. boolean allFound = true; boolean found1 = false; boolean found2 = false; boolean found3 = false; boolean found4 = false; for (int i = 0; i < result.length; i++) { // Logic here is: all must be present just ONCE, // and no extra can be present! if (!found1 && result[i].equals(flag1)) { found1 = true; } else if (!found2 && result[i].equals(flag2)) { found2 = true; } else if (!found3 && result[i].equals(flag3)) { found3 = true; } else if (!found4 && result[i].equals(flag4)) { found4 = true; } else { // Entry not found in list! // This means a flag has been devised from thin air! allFound = false; } } Assert.assertTrue(allFound && found1 && found2 && found3 && found4); // Test the empty String[] for the absence of flags. clp = new CommandLineParser(new String[]{"--Option1", "--Option2", "Param1", "Param2"}); Assert.assertTrue(clp.hasArguments()); result = clp.getFlags(); Assert.assertTrue(result != null); Assert.assertFalse(clp.hasFlag("k")); Assert.assertEquals(0, result.length); } /** * This method test the parsing of options. */ public void testOptionParsing() { String option1 = "option1"; String option2 = "option2"; String option3 = "option3"; // First without option parameters. CommandLineParser clp = new CommandLineParser(new String[]{"parameter", "-f", "-klg"}); // See if there are arguments. Assert.assertTrue(clp.hasArguments()); // See if there are options. String[] result = clp.getOptions(); // See if the result is not 'null' but empty. Assert.assertTrue(result != null); Assert.assertTrue(result.length == 0); // Now with only 'plain' options parameters. clp = new CommandLineParser(new String[]{"parameter", "-f", "--" + option3, "-klg", "--" + option1, "--" + option2}); // See if there are arguments. Assert.assertTrue(clp.hasArguments()); // See if there are options. result = clp.getOptions(); // See if the result is not 'null' or empty. Assert.assertTrue(result != null); Assert.assertTrue(result.length > 0); // See if the count of options are correct. Assert.assertEquals(3, result.length); // Cycle each and check. boolean allFound = true; boolean found1 = false; boolean found2 = false; boolean found3 = false; for (int i = 0; i < result.length; i++) { // Logic here is: all must be present just ONCE, // and no extra can be present! if (!found1 && result[i].equals(option1)) { found1 = true; } else if (!found2 && result[i].equals(option2)) { found2 = true; } else if (!found3 && result[i].equals(option3)) { found3 = true; } else { // Entry not found in list! // This means a flag has been devised from thin air! allFound = false; } } Assert.assertTrue(allFound && found1 && found2 && found3); // Now to check for options that carry parameters. String op1Param = "Option 1 parameter."; clp = new CommandLineParser(new String[]{"parameter", "-f", "--" + option3, "-klg", "--" + option1, op1Param, "--" + option2}, new String[]{option1}); // Okay, check for presence of option1 in the list. result = clp.getOptions(); boolean found = false; for (int i = 0; i < result.length; i++) { if (result[i].equals(option1)) { found = true; // No need to continue. break; } } Assert.assertTrue(found); // Now to see if the param is present. String param = clp.getOptionParameter(option1); Assert.assertEquals(op1Param, param); // Next, see if the 'null' behaviour is correct for all the others. Assert.assertTrue(clp.getOptionParameter(option2) == null); Assert.assertTrue(clp.getOptionParameter(option3) == null); } /** * This method test the parsing of parameters. */ public void testParameterParsing() { String param1 = "Param1"; String param2 = "Param1"; // Check for correct behaviour if no params. CommandLineParser clp = new CommandLineParser(new String[]{"-klf", "--option1"}); Assert.assertTrue(clp.getParameters().length == 0); // Check for correct behaviour if no params but option params. clp = new CommandLineParser(new String[]{"-klf", "--option1", "option1parameter"}, new String[]{"option1"}); Assert.assertTrue(clp.getParameters().length == 0); // Simple param passing. clp = new CommandLineParser(new String[]{param1}); // See if args are detected. Assert.assertTrue(clp.hasArguments()); // We should have non-null, non-zerolength params array. String[] result = clp.getParameters(); Assert.assertTrue(result != null); Assert.assertTrue(result.length > 0); // See how many params are found. Assert.assertTrue(result.length == 1); // Check the param. Assert.assertEquals(param1, result[0]); // Multiple params. clp = new CommandLineParser(new String[]{param1, param2}); result = clp.getParameters(); // See how many params are found. Assert.assertTrue(result.length == 2); // Check the params. Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); // With interference. clp = new CommandLineParser(new String[]{"--Option1", param1, "-klf", "-g", param2, "--Option2"}); result = clp.getParameters(); // See how many params are found. Assert.assertTrue(result.length == 2); // Check the params. Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); // With interference & option parameters. clp = new CommandLineParser(new String[]{"--Option1", "optionparam1", param1, "-klf", "-g", param2, "--Option2"}, new String[]{"Option1"}); result = clp.getParameters(); // See how many params are found. Assert.assertTrue(result.length == 2); // Check the params. Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); } /** * This method test compoound parameter parsing. */ public void testCompoundParameterParsing() { String compound = "This is a compound option parameter!"; String standard = "standardOptionParameter"; String strangeCompoundParam = "StrangeCompoundParam."; String regParam1 = "regularParameter1"; String regParam2 = "regularParameter2"; CommandLineParser clp = new CommandLineParser(new String[]{"-klf", "--strangeCompound", "\"" + strangeCompoundParam + "\"", "--compound", "\"This", "is", "a", "compound", "option", "parameter!\"", "--standard", standard, regParam1, regParam2}, new String[]{"compound", "standard", "strangeCompound"}); // The regular parameters. Assert.assertEquals("Incorrect number of parameters found with compound option parameter!", 2, clp.getParameters().length); Assert.assertEquals(regParam1, clp.getParameters()[0]); Assert.assertEquals(regParam2, clp.getParameters()[1]); // The flags. Assert.assertEquals("Incorrect number of flags found with compound option parameter!", 3, clp.getFlags().length); Assert.assertEquals("k", clp.getFlags()[0]); Assert.assertEquals("l", clp.getFlags()[1]); Assert.assertEquals("f", clp.getFlags()[2]); // And the option parameters. Assert.assertEquals("Incorrect number of option parameters found with compound option parameter!", 3, clp.getOptions().length); Assert.assertEquals("strangeCompound", clp.getOptions()[0]); Assert.assertEquals("compound", clp.getOptions()[1]); Assert.assertEquals("standard", clp.getOptions()[2]); Assert.assertEquals(strangeCompoundParam, clp.getOptionParameter("strangeCompound")); Assert.assertEquals(standard, clp.getOptionParameter("standard")); Assert.assertEquals(compound, clp.getOptionParameter("compound")); } }
UTF-8
Java
12,721
java
TestCommandLineParser.java
Java
[ { "context": "/*\n * Copyright (C) Lennart Martens\n * \n * Contact: lennart.martens AT UGent.be (' AT", "end": 35, "score": 0.9998761415481567, "start": 20, "tag": "NAME", "value": "Lennart Martens" }, { "context": "*\n * Copyright (C) Lennart Martens\n * \n * Contact: lennart.martens AT UGent.be (' AT ' to be replaced with '@')\n */\n", "end": 67, "score": 0.9047341346740723, "start": 52, "tag": "EMAIL", "value": "lennart.martens" }, { "context": "mpomics.util.general.CommandLineParser\n * @author\tLennart Martens.\n */\npublic class TestCommandLineParser extends T", "end": 585, "score": 0.9998706579208374, "start": 570, "tag": "NAME", "value": "Lennart Martens" } ]
null
[]
/* * Copyright (C) <NAME> * * Contact: <EMAIL> AT UGent.be (' AT ' to be replaced with '@') */ package com.compomics.util.test.general; import com.compomics.util.general.CommandLineParser; import org.junit.Assert; import junit.framework.TestCase; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; /* * CVS information: * * $Revision: 1.3 $ * $Date: 2007/07/06 09:41:53 $ */ /** * This class is the test for the CommandLineParser class. * * @see com.compomics.util.general.CommandLineParser * @author <NAME>. */ public class TestCommandLineParser extends TestCase { // Class specific log4j logger for TestCommandLineParser instances. Logger logger = LogManager.getLogger(TestCommandLineParser.class); public TestCommandLineParser() { this("The test for the CommandLineParser class."); } public TestCommandLineParser(String aName) { super(aName); } /** * This method test the constructors and their abilitity to parse * without error. */ public void testInitialization() { // Test all 'not present cases'. CommandLineParser clp = new CommandLineParser(null); Assert.assertTrue("With just a 'null'", !clp.hasArguments()); clp = new CommandLineParser(new String[]{}); Assert.assertTrue("With just an empty String[]", !clp.hasArguments()); clp = new CommandLineParser(null, null); Assert.assertTrue("Args 'null', OptionArgs 'null'.", !clp.hasArguments()); clp = new CommandLineParser(new String[]{}, null); Assert.assertTrue("Args empty, OptionArgs 'null'.", !clp.hasArguments()); clp = new CommandLineParser(null, new String[]{}); Assert.assertTrue("Args 'null', OptionArgs empty.", !clp.hasArguments()); clp = new CommandLineParser(null, new String[]{"Test"}); Assert.assertTrue("Args 'null', OptionArgs filled.", !clp.hasArguments()); clp = new CommandLineParser(new String[]{}, new String[]{}); Assert.assertTrue("Args empty, OptionArgs empty.", !clp.hasArguments()); clp = new CommandLineParser(new String[]{}, new String[]{"Test"}); Assert.assertTrue("Args empty, OptionArgs filled.", !clp.hasArguments()); // Test four 'present' cases. clp = new CommandLineParser(new String[]{"Test"}); Assert.assertTrue(clp.hasArguments()); clp = new CommandLineParser(new String[]{"Test"}, null); Assert.assertTrue(clp.hasArguments()); clp = new CommandLineParser(new String[]{"Test"}, new String[]{}); Assert.assertTrue(clp.hasArguments()); clp = new CommandLineParser(new String[]{"Test"}, new String[]{"Test2"}); Assert.assertTrue(clp.hasArguments()); } /** * This method test the parsing of flags. */ public void testFlagParsing() { // The flags. String flag1 = "k"; String flag2 = "l"; String flag3 = "f"; String flag4 = "g"; String[] args = new String[]{"Parameter", "--Option1", "--Option2", "-klf", "-g"}; CommandLineParser clp = new CommandLineParser(args); // Check whether any arguments are in fact found. Assert.assertTrue(clp.hasArguments()); String[] result = clp.getFlags(); // See if it is not 'null' or empty. Assert.assertTrue(result != null); Assert.assertTrue(result.length > 0); // Check the 'hasFlag method'. Assert.assertTrue(clp.hasFlag(flag1)); Assert.assertTrue(clp.hasFlag(flag2)); Assert.assertTrue(clp.hasFlag(flag3)); Assert.assertTrue(clp.hasFlag(flag4)); Assert.assertFalse(clp.hasFlag("x")); // Four flags present, see if all are found. Assert.assertEquals("Incorrect number of flags found!", 4, result.length); // Cycle each and check. boolean allFound = true; boolean found1 = false; boolean found2 = false; boolean found3 = false; boolean found4 = false; for (int i = 0; i < result.length; i++) { // Logic here is: all must be present just ONCE, // and no extra can be present! if (!found1 && result[i].equals(flag1)) { found1 = true; } else if (!found2 && result[i].equals(flag2)) { found2 = true; } else if (!found3 && result[i].equals(flag3)) { found3 = true; } else if (!found4 && result[i].equals(flag4)) { found4 = true; } else { // Entry not found in list! // This means a flag has been devised from thin air! allFound = false; } } Assert.assertTrue(allFound && found1 && found2 && found3 && found4); // Test the empty String[] for the absence of flags. clp = new CommandLineParser(new String[]{"--Option1", "--Option2", "Param1", "Param2"}); Assert.assertTrue(clp.hasArguments()); result = clp.getFlags(); Assert.assertTrue(result != null); Assert.assertFalse(clp.hasFlag("k")); Assert.assertEquals(0, result.length); } /** * This method test the parsing of options. */ public void testOptionParsing() { String option1 = "option1"; String option2 = "option2"; String option3 = "option3"; // First without option parameters. CommandLineParser clp = new CommandLineParser(new String[]{"parameter", "-f", "-klg"}); // See if there are arguments. Assert.assertTrue(clp.hasArguments()); // See if there are options. String[] result = clp.getOptions(); // See if the result is not 'null' but empty. Assert.assertTrue(result != null); Assert.assertTrue(result.length == 0); // Now with only 'plain' options parameters. clp = new CommandLineParser(new String[]{"parameter", "-f", "--" + option3, "-klg", "--" + option1, "--" + option2}); // See if there are arguments. Assert.assertTrue(clp.hasArguments()); // See if there are options. result = clp.getOptions(); // See if the result is not 'null' or empty. Assert.assertTrue(result != null); Assert.assertTrue(result.length > 0); // See if the count of options are correct. Assert.assertEquals(3, result.length); // Cycle each and check. boolean allFound = true; boolean found1 = false; boolean found2 = false; boolean found3 = false; for (int i = 0; i < result.length; i++) { // Logic here is: all must be present just ONCE, // and no extra can be present! if (!found1 && result[i].equals(option1)) { found1 = true; } else if (!found2 && result[i].equals(option2)) { found2 = true; } else if (!found3 && result[i].equals(option3)) { found3 = true; } else { // Entry not found in list! // This means a flag has been devised from thin air! allFound = false; } } Assert.assertTrue(allFound && found1 && found2 && found3); // Now to check for options that carry parameters. String op1Param = "Option 1 parameter."; clp = new CommandLineParser(new String[]{"parameter", "-f", "--" + option3, "-klg", "--" + option1, op1Param, "--" + option2}, new String[]{option1}); // Okay, check for presence of option1 in the list. result = clp.getOptions(); boolean found = false; for (int i = 0; i < result.length; i++) { if (result[i].equals(option1)) { found = true; // No need to continue. break; } } Assert.assertTrue(found); // Now to see if the param is present. String param = clp.getOptionParameter(option1); Assert.assertEquals(op1Param, param); // Next, see if the 'null' behaviour is correct for all the others. Assert.assertTrue(clp.getOptionParameter(option2) == null); Assert.assertTrue(clp.getOptionParameter(option3) == null); } /** * This method test the parsing of parameters. */ public void testParameterParsing() { String param1 = "Param1"; String param2 = "Param1"; // Check for correct behaviour if no params. CommandLineParser clp = new CommandLineParser(new String[]{"-klf", "--option1"}); Assert.assertTrue(clp.getParameters().length == 0); // Check for correct behaviour if no params but option params. clp = new CommandLineParser(new String[]{"-klf", "--option1", "option1parameter"}, new String[]{"option1"}); Assert.assertTrue(clp.getParameters().length == 0); // Simple param passing. clp = new CommandLineParser(new String[]{param1}); // See if args are detected. Assert.assertTrue(clp.hasArguments()); // We should have non-null, non-zerolength params array. String[] result = clp.getParameters(); Assert.assertTrue(result != null); Assert.assertTrue(result.length > 0); // See how many params are found. Assert.assertTrue(result.length == 1); // Check the param. Assert.assertEquals(param1, result[0]); // Multiple params. clp = new CommandLineParser(new String[]{param1, param2}); result = clp.getParameters(); // See how many params are found. Assert.assertTrue(result.length == 2); // Check the params. Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); // With interference. clp = new CommandLineParser(new String[]{"--Option1", param1, "-klf", "-g", param2, "--Option2"}); result = clp.getParameters(); // See how many params are found. Assert.assertTrue(result.length == 2); // Check the params. Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); // With interference & option parameters. clp = new CommandLineParser(new String[]{"--Option1", "optionparam1", param1, "-klf", "-g", param2, "--Option2"}, new String[]{"Option1"}); result = clp.getParameters(); // See how many params are found. Assert.assertTrue(result.length == 2); // Check the params. Assert.assertEquals(param1, result[0]); Assert.assertEquals(param2, result[1]); } /** * This method test compoound parameter parsing. */ public void testCompoundParameterParsing() { String compound = "This is a compound option parameter!"; String standard = "standardOptionParameter"; String strangeCompoundParam = "StrangeCompoundParam."; String regParam1 = "regularParameter1"; String regParam2 = "regularParameter2"; CommandLineParser clp = new CommandLineParser(new String[]{"-klf", "--strangeCompound", "\"" + strangeCompoundParam + "\"", "--compound", "\"This", "is", "a", "compound", "option", "parameter!\"", "--standard", standard, regParam1, regParam2}, new String[]{"compound", "standard", "strangeCompound"}); // The regular parameters. Assert.assertEquals("Incorrect number of parameters found with compound option parameter!", 2, clp.getParameters().length); Assert.assertEquals(regParam1, clp.getParameters()[0]); Assert.assertEquals(regParam2, clp.getParameters()[1]); // The flags. Assert.assertEquals("Incorrect number of flags found with compound option parameter!", 3, clp.getFlags().length); Assert.assertEquals("k", clp.getFlags()[0]); Assert.assertEquals("l", clp.getFlags()[1]); Assert.assertEquals("f", clp.getFlags()[2]); // And the option parameters. Assert.assertEquals("Incorrect number of option parameters found with compound option parameter!", 3, clp.getOptions().length); Assert.assertEquals("strangeCompound", clp.getOptions()[0]); Assert.assertEquals("compound", clp.getOptions()[1]); Assert.assertEquals("standard", clp.getOptions()[2]); Assert.assertEquals(strangeCompoundParam, clp.getOptionParameter("strangeCompound")); Assert.assertEquals(standard, clp.getOptionParameter("standard")); Assert.assertEquals(compound, clp.getOptionParameter("compound")); } }
12,695
0.60011
0.587454
302
41.122517
27.571489
143
false
false
0
0
0
0
0
0
0.884106
false
false
3
3de354a2abd72618082aaf204e3970229b67a8fd
14,061,722,951,992
bc60f460a9649ca1827418d2965478111f681de6
/app/src/main/java/com/panachai/vocabulary_20words/testDatabaseMain.java
28269040ad3a1189f73469aaf63dff56dbf6a6b1
[]
no_license
panachainy/Vocabulary_20Words
https://github.com/panachainy/Vocabulary_20Words
2f517dded3c8be55c9dfc8acdee406bf48e340ff
f4a309faa5060922195ca44df87e8a26c899face
refs/heads/master
2021-06-13T00:23:54.326000
2017-03-15T16:31:25
2017-03-15T16:31:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.panachai.vocabulary_20words; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; public class testDatabaseMain extends AppCompatActivity { ListView lvContact; DBHelper mydb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_database_main); mydb = new DBHelper(this); lvContact = (ListView) findViewById(R.id.listView1); ArrayList arrayList = mydb.getAllProfile(); ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,arrayList); lvContact.setAdapter(arrayAdapter); //เน€เธ›เน‡เธ™เธเธฒเธฃเน€เธ‚เธตเธขเธ™ Event OnClick เธญเธตเธเนเธšเธšเธ™เธถเธ‡ //เนƒเธชเนˆ Event เน€เธกเธทเนˆเธญเธœเธนเน‰เนƒเธŠเน‰เน€เธฅเธทเธญเธเธฃเธฒเธขเธŠเธทเนˆเธญเธœเธนเน‰เธ•เธดเธ”เธ•เนˆเธญเนƒเธ™ listview lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int i, long id) { //เธชเนˆเธ‡เธ„เนˆเธฒเธœเธนเน‰เธ•เธดเธ”เธ•เนˆเธญเธ—เธตเนˆเน€เธฅเธทเธญเธเน„เธ›เธขเธฑเธ‡เธญเธตเธ Activity เธ™เธถเธ‡ Bundle bundle = new Bundle(); bundle.putInt("id",i+1); //เน€เธžเธทเนˆเธญเนƒเธซเน‰ index เธ‚เธญเธ‡ ItemList เธ•เธฃเธ‡เธเธฑเธš listview Intent intent = new Intent(getApplicationContext(), testDatabase.class); intent.putExtras(bundle); startActivity(intent); } }); } }
UTF-8
Java
1,841
java
testDatabaseMain.java
Java
[]
null
[]
package com.panachai.vocabulary_20words; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; public class testDatabaseMain extends AppCompatActivity { ListView lvContact; DBHelper mydb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_database_main); mydb = new DBHelper(this); lvContact = (ListView) findViewById(R.id.listView1); ArrayList arrayList = mydb.getAllProfile(); ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,arrayList); lvContact.setAdapter(arrayAdapter); //เน€เธ›เน‡เธ™เธเธฒเธฃเน€เธ‚เธตเธขเธ™ Event OnClick เธญเธตเธเนเธšเธšเธ™เธถเธ‡ //เนƒเธชเนˆ Event เน€เธกเธทเนˆเธญเธœเธนเน‰เนƒเธŠเน‰เน€เธฅเธทเธญเธเธฃเธฒเธขเธŠเธทเนˆเธญเธœเธนเน‰เธ•เธดเธ”เธ•เนˆเธญเนƒเธ™ listview lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int i, long id) { //เธชเนˆเธ‡เธ„เนˆเธฒเธœเธนเน‰เธ•เธดเธ”เธ•เนˆเธญเธ—เธตเนˆเน€เธฅเธทเธญเธเน„เธ›เธขเธฑเธ‡เธญเธตเธ Activity เธ™เธถเธ‡ Bundle bundle = new Bundle(); bundle.putInt("id",i+1); //เน€เธžเธทเนˆเธญเนƒเธซเน‰ index เธ‚เธญเธ‡ ItemList เธ•เธฃเธ‡เธเธฑเธš listview Intent intent = new Intent(getApplicationContext(), testDatabase.class); intent.putExtras(bundle); startActivity(intent); } }); } }
1,841
0.656808
0.653112
46
34.282608
25.46751
88
false
false
0
0
0
0
0
0
0.673913
false
false
3
2b9ddeb69708b4081d4577eb781b265fff60f53c
24,172,076,000,095
309231b0449f3a98ba8ddfb66be513b576d439bc
/src/main/java/ui/legui/listener/WindowIconifyEventListener.java
edfd27317d7a9233b694244483909f1cbc15b300
[]
no_license
costia097/lwjglPRac
https://github.com/costia097/lwjglPRac
0924278aa977e6bd56cdb89ded9b9c2e0dece469
4365797b03af4230dc4eaad46c8e5f4cb9ba6e1c
refs/heads/master
2020-04-27T00:33:16.679000
2019-08-12T19:21:53
2019-08-12T19:21:53
173,937,493
1
0
null
false
2019-08-14T07:56:48
2019-03-05T11:54:19
2019-08-13T06:37:36
2019-08-14T07:54:30
17,000
0
0
1
Java
false
false
package ui.legui.listener; import ui.legui.event.WindowIconifyEvent; /** * Created by ShchAlexander on 04.02.2017. */ public interface WindowIconifyEventListener extends EventListener<WindowIconifyEvent> { void process(WindowIconifyEvent event); }
UTF-8
Java
257
java
WindowIconifyEventListener.java
Java
[ { "context": "legui.event.WindowIconifyEvent;\n\n/**\n * Created by ShchAlexander on 04.02.2017.\n */\npublic interface WindowIconify", "end": 102, "score": 0.844947338104248, "start": 89, "tag": "USERNAME", "value": "ShchAlexander" } ]
null
[]
package ui.legui.listener; import ui.legui.event.WindowIconifyEvent; /** * Created by ShchAlexander on 04.02.2017. */ public interface WindowIconifyEventListener extends EventListener<WindowIconifyEvent> { void process(WindowIconifyEvent event); }
257
0.789883
0.758755
11
22.363636
27.063133
87
false
false
0
0
0
0
0
0
0.272727
false
false
3
c56a64532484603781bd765539d01eab0ac227b7
27,556,510,205,976
fc66f6d24a86c9844e380678cd996e1d79b4af7c
/src/me/aelesia/runescape/tasks/base/DisposeTask.java
c6667c542caae5f9077d7ed89299e517a65b87a7
[]
no_license
aelesia/runescape-bots-master4
https://github.com/aelesia/runescape-bots-master4
8f9c4cf84b4b0bf8d1212092627a2b6549e2c1ee
4de2492b6719d0367a6ac2cd6162e0bbf48523c5
refs/heads/master
2021-09-22T11:20:39.715000
2018-09-09T10:13:41
2018-09-09T10:13:41
147,384,824
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.aelesia.runescape.tasks.base; import me.aelesia.runescape.actions.InventoryActions; import me.aelesia.runescape.exceptions.IllegalArgumentException; import me.aelesia.runescape.utils.game.InventoryUtils; import me.aelesia.runescape.utils.general.CommonUtils; public abstract class DisposeTask extends BaseTask { protected String[] itemsToDispose; public DisposeTask(String ...itemsToDispose) { if (CommonUtils.isEmpty(itemsToDispose)) { throw new IllegalArgumentException(""); } this.itemsToDispose = itemsToDispose; } @Override public void validate() {} @Override public void exit() { InventoryActions.close(); } @Override public boolean execute() { if (InventoryUtils.contains(itemsToDispose)) { InventoryActions.disposeAll(itemsToDispose); } return true; } }
UTF-8
Java
814
java
DisposeTask.java
Java
[]
null
[]
package me.aelesia.runescape.tasks.base; import me.aelesia.runescape.actions.InventoryActions; import me.aelesia.runescape.exceptions.IllegalArgumentException; import me.aelesia.runescape.utils.game.InventoryUtils; import me.aelesia.runescape.utils.general.CommonUtils; public abstract class DisposeTask extends BaseTask { protected String[] itemsToDispose; public DisposeTask(String ...itemsToDispose) { if (CommonUtils.isEmpty(itemsToDispose)) { throw new IllegalArgumentException(""); } this.itemsToDispose = itemsToDispose; } @Override public void validate() {} @Override public void exit() { InventoryActions.close(); } @Override public boolean execute() { if (InventoryUtils.contains(itemsToDispose)) { InventoryActions.disposeAll(itemsToDispose); } return true; } }
814
0.77027
0.77027
33
23.666666
21.199867
64
false
false
0
0
0
0
0
0
1.393939
false
false
3
e2d2a0ef66e7aecce97cd6bef006dc56c610b46b
22,497,038,751,345
04957c31e81b79fb14bcdee26353e95336133f65
/app/src/main/java/com/baikaleg/v3/cookingaid/ui/storage/StorageActivity.java
140d700d2c793c30013f989d67625e43219e830e
[]
no_license
VladZaytcev/Capstone
https://github.com/VladZaytcev/Capstone
f67905a1179fe7d95f9454616eeb5aaf7eb96d0d
a39af63637b612292073d3e8cadf34f3ac88c663
refs/heads/master
2020-03-21T21:02:35.243000
2018-08-07T01:04:36
2018-08-07T01:04:36
139,043,216
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.baikaleg.v3.cookingaid.ui.storage; import android.arch.lifecycle.ViewModelProviders; import android.databinding.BindingAdapter; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.LayoutInflater; import com.baikaleg.v3.cookingaid.R; import com.baikaleg.v3.cookingaid.data.database.entity.ProductEntity; import com.baikaleg.v3.cookingaid.databinding.ActivityStorageBinding; import com.baikaleg.v3.cookingaid.ui.BaseActivity; import com.baikaleg.v3.cookingaid.ui.SwipeToDeleteCallback; import com.baikaleg.v3.cookingaid.ui.addeditproduct.AddEditProductDialog; import com.baikaleg.v3.cookingaid.ui.addeditproduct.AddEditProductModel; import java.util.List; public class StorageActivity extends BaseActivity implements StorageItemNavigator { private StorageViewModel viewModel; private AddEditProductDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflater = LayoutInflater.from(this); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(getString(R.string.title_activity_storage)); } viewModel = ViewModelProviders.of(this).get(StorageViewModel.class); ActivityStorageBinding binding = DataBindingUtil .inflate(inflater, R.layout.activity_storage, frameLayout, true); binding.setLifecycleOwner(this); binding.setModel(viewModel); StorageViewAdapter adapter = new StorageViewAdapter(this, this); binding.productsContent.setAdapter(adapter); binding.productsContent.setLayoutManager(new LinearLayoutManager(this)); SwipeToDeleteCallback swipe = new SwipeToDeleteCallback(this) { @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { adapter.remove(viewHolder.getLayoutPosition()); } }; ItemTouchHelper itemTouchHelper = new ItemTouchHelper(swipe); itemTouchHelper.attachToRecyclerView(binding.productsContent); binding.fab.setOnClickListener(view -> { dialog = AddEditProductDialog.newInstance(AddEditProductModel.DIALOG_STORAGE_ID, 0); dialog.show(getSupportFragmentManager(), "dialog"); }); } @Override protected void onResume() { super.onResume(); navigationView.getMenu().getItem(2).setChecked(true); } @Override protected void onDestroy() { super.onDestroy(); viewModel.onDestroy(); } @Override public void onItemClicked(int id) { dialog = AddEditProductDialog.newInstance(AddEditProductModel.DIALOG_STORAGE_ID, id); dialog.show(getSupportFragmentManager(), "dialog"); } @Override public void onItemRemoved(ProductEntity entity) { viewModel.remove(entity); } @SuppressWarnings("unchecked") @BindingAdapter("app:storageProducts") public static void setStorageProducts(RecyclerView recyclerView, List<ProductEntity> entities) { StorageViewAdapter adapter = (StorageViewAdapter) recyclerView.getAdapter(); if (adapter != null && entities != null) { adapter.refresh(entities); } } }
UTF-8
Java
3,446
java
StorageActivity.java
Java
[]
null
[]
package com.baikaleg.v3.cookingaid.ui.storage; import android.arch.lifecycle.ViewModelProviders; import android.databinding.BindingAdapter; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.LayoutInflater; import com.baikaleg.v3.cookingaid.R; import com.baikaleg.v3.cookingaid.data.database.entity.ProductEntity; import com.baikaleg.v3.cookingaid.databinding.ActivityStorageBinding; import com.baikaleg.v3.cookingaid.ui.BaseActivity; import com.baikaleg.v3.cookingaid.ui.SwipeToDeleteCallback; import com.baikaleg.v3.cookingaid.ui.addeditproduct.AddEditProductDialog; import com.baikaleg.v3.cookingaid.ui.addeditproduct.AddEditProductModel; import java.util.List; public class StorageActivity extends BaseActivity implements StorageItemNavigator { private StorageViewModel viewModel; private AddEditProductDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflater = LayoutInflater.from(this); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(getString(R.string.title_activity_storage)); } viewModel = ViewModelProviders.of(this).get(StorageViewModel.class); ActivityStorageBinding binding = DataBindingUtil .inflate(inflater, R.layout.activity_storage, frameLayout, true); binding.setLifecycleOwner(this); binding.setModel(viewModel); StorageViewAdapter adapter = new StorageViewAdapter(this, this); binding.productsContent.setAdapter(adapter); binding.productsContent.setLayoutManager(new LinearLayoutManager(this)); SwipeToDeleteCallback swipe = new SwipeToDeleteCallback(this) { @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { adapter.remove(viewHolder.getLayoutPosition()); } }; ItemTouchHelper itemTouchHelper = new ItemTouchHelper(swipe); itemTouchHelper.attachToRecyclerView(binding.productsContent); binding.fab.setOnClickListener(view -> { dialog = AddEditProductDialog.newInstance(AddEditProductModel.DIALOG_STORAGE_ID, 0); dialog.show(getSupportFragmentManager(), "dialog"); }); } @Override protected void onResume() { super.onResume(); navigationView.getMenu().getItem(2).setChecked(true); } @Override protected void onDestroy() { super.onDestroy(); viewModel.onDestroy(); } @Override public void onItemClicked(int id) { dialog = AddEditProductDialog.newInstance(AddEditProductModel.DIALOG_STORAGE_ID, id); dialog.show(getSupportFragmentManager(), "dialog"); } @Override public void onItemRemoved(ProductEntity entity) { viewModel.remove(entity); } @SuppressWarnings("unchecked") @BindingAdapter("app:storageProducts") public static void setStorageProducts(RecyclerView recyclerView, List<ProductEntity> entities) { StorageViewAdapter adapter = (StorageViewAdapter) recyclerView.getAdapter(); if (adapter != null && entities != null) { adapter.refresh(entities); } } }
3,446
0.725189
0.721416
92
36.45652
28.943127
100
false
false
0
0
0
0
0
0
0.597826
false
false
3
cd8f603e1bdf9b1f1f06c16c21b994ad9cbdc8fc
22,874,995,865,443
de079f215b27f94edf32d9eeaf0a6e9bb8c4e226
/src/codechef/problems/sort.java
68d86db6dde0080077c37de1ce0e8803bfd204f6
[]
no_license
yashshh/codechef-problems
https://github.com/yashshh/codechef-problems
06a966b48b291fd5d792e696e3d83040baec8286
7315fd66d0270524e69685d6883cb211d4aa505a
refs/heads/master
2020-07-12T16:17:33.951000
2019-08-28T06:15:41
2019-08-28T06:15:41
204,861,509
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package codechef.problems; import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; /** * * @author JAIN */ public class sort { // Complete the miniMaxSum function below. static void miniMaxSum(int[] arr) { for(int i=0;i<4;i++) { for(int j=1+i;j<5;j++) { if(arr[i]>arr[j]) { int x=arr[i]; arr[i]=arr[j]; arr[j]=x; } } } for(int i=0;i<5;i++) { System.out.println(arr[i]); } int x2=0; int x1=0; for(int i=0;i<4;i++) { x2=x2+arr[i]; } for(int i=1;i<5;i++) { x1=x1+arr[i]; } System.out.println(x2 +" "+x1); } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int[] arr = new int[5]; for (int i = 0; i < 5; i++) { arr[i]=scanner.nextInt(); } miniMaxSum(arr); scanner.close(); } }
UTF-8
Java
1,405
java
sort.java
Java
[ { "context": "*;\r\nimport java.util.regex.*;\r\n/**\r\n *\r\n * @author JAIN\r\n */\r\npublic class sort {\r\n\r\n\r\n\r\n \r\n // Com", "end": 408, "score": 0.9079997539520264, "start": 404, "tag": "NAME", "value": "JAIN" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package codechef.problems; import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; /** * * @author JAIN */ public class sort { // Complete the miniMaxSum function below. static void miniMaxSum(int[] arr) { for(int i=0;i<4;i++) { for(int j=1+i;j<5;j++) { if(arr[i]>arr[j]) { int x=arr[i]; arr[i]=arr[j]; arr[j]=x; } } } for(int i=0;i<5;i++) { System.out.println(arr[i]); } int x2=0; int x1=0; for(int i=0;i<4;i++) { x2=x2+arr[i]; } for(int i=1;i<5;i++) { x1=x1+arr[i]; } System.out.println(x2 +" "+x1); } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int[] arr = new int[5]; for (int i = 0; i < 5; i++) { arr[i]=scanner.nextInt(); } miniMaxSum(arr); scanner.close(); } }
1,405
0.471174
0.454804
65
19.492308
16.963421
79
false
false
0
0
0
0
0
0
0.569231
false
false
3
dabeb073e3286a5ea14632898e3a0f1bb0e35585
2,946,347,610,211
004d0bc7735d37ddbd41ad8a95e4099cba180395
/src/main/java/recommendation/groups/evolution/composed/cleanuppers/MultiRecommenderEngineResultRecommendationCleanupperFactory.java
3c6519d8ace7da9a987c77bdf740417e2b3a3990
[]
no_license
xubinzheng/SOMINT
https://github.com/xubinzheng/SOMINT
be6c84618c4015b390acdd213c51b168fde58281
85a8a2843a4e265162009b9178d920de3b910849
refs/heads/master
2021-01-15T22:58:10.246000
2015-01-13T04:16:32
2015-01-13T04:16:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package recommendation.groups.evolution.composed.cleanuppers; public class MultiRecommenderEngineResultRecommendationCleanupperFactory<V> implements RecommendationCleanupperFactory<V> { @Override public RecommendationCleanupper<V> createRecommendationCleanupper() { return new MultiRecommenderEngineResultRecommendationCleanupper<V>(); } }
UTF-8
Java
350
java
MultiRecommenderEngineResultRecommendationCleanupperFactory.java
Java
[]
null
[]
package recommendation.groups.evolution.composed.cleanuppers; public class MultiRecommenderEngineResultRecommendationCleanupperFactory<V> implements RecommendationCleanupperFactory<V> { @Override public RecommendationCleanupper<V> createRecommendationCleanupper() { return new MultiRecommenderEngineResultRecommendationCleanupper<V>(); } }
350
0.854286
0.854286
11
30.818182
33.247879
86
false
false
0
0
0
0
0
0
0.818182
false
false
3
d0f07e1cd71865ac62c2c6b4251cac91f6085869
25,675,314,546,160
6d158fbbd1fe40c3b82ebca51ca9e160a0d115cb
/src/main/java/serviceImpl/UserServiceImpl.java
5a0c9b3c9191093f1390e8f6ae5785731f60e0d0
[]
no_license
dagealuba/Music_web
https://github.com/dagealuba/Music_web
50cf84270ce5e2e55d527925c147289d33888ae3
7ed8a22ed6d82c65e8c7f6abbe36de70f435aa6c
refs/heads/master
2023-03-04T13:03:20.958000
2019-06-18T15:40:28
2019-06-18T15:40:28
174,840,667
1
1
null
false
2023-02-22T05:09:06
2019-03-10T15:13:42
2019-06-18T15:41:01
2023-02-22T05:09:05
3,097
1
1
2
Java
false
false
package serviceImpl; import entity.Love; import entity.User; import factory.DaoFactory; import service.UserService; import java.util.List; import java.util.UUID; public class UserServiceImpl implements UserService { @Override public User findUserById(String userId) { return DaoFactory.getUserDaoImpl().getUserById(userId); } @Override public User findUserByEmail(String userEmail) { return DaoFactory.getUserDaoImpl().getUserByEmail(userEmail); } @Override public List<User> findUserById(List<String> userIds) { return null; } @Override public List<User> findUserByName(String userName) { return DaoFactory.getUserDaoImpl().getUsersByName(userName); } @Override public List<User> findAllUsers() { return null; } @Override public boolean insert(User user) { Love _default = new Love(); _default.setLoveId(UUID.randomUUID().toString()); _default.setUserId(user.getUserId()); _default.setLoveName("้ป˜่ฎคๆ”ถ่—ๅคน"); _default.setMusicId(null); return DaoFactory.getUserDaoImpl().addUser(user) && DaoFactory.getLoveDaoImpl().addLove(_default); } @Override public boolean insert(List<User> users) { return false; } @Override public boolean update(List<User> users) { return false; } @Override public boolean delete(List<User> users) { return false; } @Override public Boolean updateUserAvatar(String url, String userId) { User user = findUserById(userId); user.setAvatarSrc(url); return DaoFactory.getUserDaoImpl().updateUser(user); } }
UTF-8
Java
1,702
java
UserServiceImpl.java
Java
[]
null
[]
package serviceImpl; import entity.Love; import entity.User; import factory.DaoFactory; import service.UserService; import java.util.List; import java.util.UUID; public class UserServiceImpl implements UserService { @Override public User findUserById(String userId) { return DaoFactory.getUserDaoImpl().getUserById(userId); } @Override public User findUserByEmail(String userEmail) { return DaoFactory.getUserDaoImpl().getUserByEmail(userEmail); } @Override public List<User> findUserById(List<String> userIds) { return null; } @Override public List<User> findUserByName(String userName) { return DaoFactory.getUserDaoImpl().getUsersByName(userName); } @Override public List<User> findAllUsers() { return null; } @Override public boolean insert(User user) { Love _default = new Love(); _default.setLoveId(UUID.randomUUID().toString()); _default.setUserId(user.getUserId()); _default.setLoveName("้ป˜่ฎคๆ”ถ่—ๅคน"); _default.setMusicId(null); return DaoFactory.getUserDaoImpl().addUser(user) && DaoFactory.getLoveDaoImpl().addLove(_default); } @Override public boolean insert(List<User> users) { return false; } @Override public boolean update(List<User> users) { return false; } @Override public boolean delete(List<User> users) { return false; } @Override public Boolean updateUserAvatar(String url, String userId) { User user = findUserById(userId); user.setAvatarSrc(url); return DaoFactory.getUserDaoImpl().updateUser(user); } }
1,702
0.661939
0.661939
69
23.52174
22.904091
106
false
false
0
0
0
0
0
0
0.362319
false
false
3
adaa5c90077156cf4c04f88645006ffd327fd0ae
9,079,560,891,531
d3d3146ba91da060527dcb06a60daf903ce383bc
/src/main/dao/AereoDao.java
28e24ba7e9abb34e288b02d3232c7d665664fadb
[]
no_license
giacomodibiagio/compagniaaereajdbc
https://github.com/giacomodibiagio/compagniaaereajdbc
8b72650b0ff2bd234fdad2667c09d940b2bfc869
ce9c157d20646f5059ab64d978b0afcf801d61d6
refs/heads/master
2023-05-04T21:31:32.770000
2021-05-28T12:32:31
2021-05-28T12:32:31
371,694,375
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.dao; import main.model.Aereo; public interface AereoDao extends Dao<Aereo> { }
UTF-8
Java
95
java
AereoDao.java
Java
[]
null
[]
package main.dao; import main.model.Aereo; public interface AereoDao extends Dao<Aereo> { }
95
0.757895
0.757895
7
12.571428
16.369459
46
false
false
0
0
0
0
0
0
0.285714
false
false
3
15ec0e7013d886bae1be25780856b0bb23c5eebd
9,079,560,888,814
4012cf19d29a3a0743800dde99835667ca80c2cc
/concurrent/src/cn/blocking/que/ReadWriteDemoLock.java
c1308dfe0fdbba0e310e1058156963d57605a6cf
[]
no_license
LovingMoney/LovingMoney
https://github.com/LovingMoney/LovingMoney
77e78b204e7e846ee193327a89ea10c098b0269a
291caee2a96f0d4dbd45f7618a368f2e4f283bf4
refs/heads/master
2020-03-19T01:24:58.739000
2018-06-06T12:28:26
2018-06-06T12:28:26
135,543,718
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.blocking.que; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteDemoLock { public static String name = "ๅผ ไธ‰"; public static void main(String[] args) { ReadWriteLock lock = new ReentrantReadWriteLock(); new Thread(new Demo12_read(lock)).start(); new Thread(new Demo12_read(lock)).start(); new Thread(new Demo12_read(lock)).start(); new Thread(new Demo12_write(lock)).start(); new Thread(new Demo12_read(lock)).start(); new Thread(new Demo12_write(lock)).start(); } } class Demo12_read implements Runnable{ ReadWriteLock lock = null; public Demo12_read(ReadWriteLock lock) { this.lock = lock; } @Override public void run() { lock.readLock().lock(); System.out.println(Thread.currentThread()+"ๅผ€ๅง‹้ƒฝๆ•ฐๆฎ"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("่ฏปๅ–ๅˆฐๆ•ฐๆฎ"+ReadWriteDemoLock.name); lock.readLock().unlock(); } } class Demo12_write implements Runnable{ ReadWriteLock lock = null; public Demo12_write(ReadWriteLock lock) { this.lock = lock; } @Override public void run() { lock.writeLock().lock(); System.out.println(Thread.currentThread()+"ๅผ€ๅง‹ๅ†™ๆ•ฐๆฎ"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("ๅ†™ๅ…ฅๆ•ฐๆฎ"+ReadWriteDemoLock.name); lock.writeLock().unlock(); } }
GB18030
Java
1,546
java
ReadWriteDemoLock.java
Java
[ { "context": "WriteDemoLock {\r\n\t\r\n\tpublic static String name = \"ๅผ ไธ‰\";\r\n\t\r\n\tpublic static void main(String[] args) {\r\n", "end": 208, "score": 0.9993423223495483, "start": 206, "tag": "NAME", "value": "ๅผ ไธ‰" } ]
null
[]
package cn.blocking.que; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteDemoLock { public static String name = "ๅผ ไธ‰"; public static void main(String[] args) { ReadWriteLock lock = new ReentrantReadWriteLock(); new Thread(new Demo12_read(lock)).start(); new Thread(new Demo12_read(lock)).start(); new Thread(new Demo12_read(lock)).start(); new Thread(new Demo12_write(lock)).start(); new Thread(new Demo12_read(lock)).start(); new Thread(new Demo12_write(lock)).start(); } } class Demo12_read implements Runnable{ ReadWriteLock lock = null; public Demo12_read(ReadWriteLock lock) { this.lock = lock; } @Override public void run() { lock.readLock().lock(); System.out.println(Thread.currentThread()+"ๅผ€ๅง‹้ƒฝๆ•ฐๆฎ"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("่ฏปๅ–ๅˆฐๆ•ฐๆฎ"+ReadWriteDemoLock.name); lock.readLock().unlock(); } } class Demo12_write implements Runnable{ ReadWriteLock lock = null; public Demo12_write(ReadWriteLock lock) { this.lock = lock; } @Override public void run() { lock.writeLock().lock(); System.out.println(Thread.currentThread()+"ๅผ€ๅง‹ๅ†™ๆ•ฐๆฎ"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("ๅ†™ๅ…ฅๆ•ฐๆฎ"+ReadWriteDemoLock.name); lock.writeLock().unlock(); } }
1,546
0.678191
0.659574
61
22.655737
18.762436
57
false
false
0
0
0
0
0
0
1.704918
false
false
3
7acbdfe49ea2c4269adad55d8f8008dd66ce5b5c
455,266,536,448
06bbe02ea25a53dbc4fc7a5361ac1ac67841bb33
/src/main/java/com/silent/template/backstage/dao/UserDao.java
7a3d0e13d8fe3f942b88a5c62fab668ee1d94f73
[]
no_license
silenters/silent-template-backstage
https://github.com/silenters/silent-template-backstage
41a5f6dcc8bc4ccaf7204fbfd5af3707fc1d2b54
6e870a52457c35c890380f6049082fb223955bbf
refs/heads/master
2020-03-17T02:43:17.233000
2018-05-13T03:31:53
2018-05-13T03:31:53
133,202,282
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.silent.template.backstage.dao; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.silent.template.backstage.bean.po.UserPo; /** * ็”จๆˆทไฟกๆฏๅค„็†DAO * @author TanJin * @date 2018ๅนด3ๆœˆ5ๆ—ฅ */ public interface UserDao { /** * ๆ นๆฎ็”จๆˆทๅ่Žทๅ–ๆŒ‡ๅฎš็”จๆˆทไฟกๆฏ * @param username * @return */ @Select("SELECT * FROM auth_user WHERE username = #{username}") public UserPo loadUserByUsername(String username); /** * ่Žทๅ–ๆ‰€ๆœ‰็”จๆˆทไฟกๆฏ */ @Select("SELECT * FROM auth_user") public List<UserPo> loadAll(); /** * ๆ นๆฎ็”จๆˆทID่Žทๅ–ๆŒ‡ๅฎš็”จๆˆทไฟกๆฏ * @param userId * @return */ @Select("SELECT * FROM auth_user WHERE id = #{id}") public UserPo loadUserById(String userId); /** * ๆ นๆฎ็”จๆˆทIDๅˆ ้™คๆŒ‡ๅฎš็”จๆˆท * @param userId * @return */ @Delete("DELETE FROM auth_user WHERE id = #{id}") public int deleteUser(String userId); /** * ๆ–ฐๅขž็”จๆˆท * @param userPo * @return */ @Insert("INSERT INTO auth_user(id, username, password, realname, company, job, salt, status, time) VALUES " + "(#{id}, #{username}, #{password}, #{realname}, #{company}, #{job}, #{salt}, #{status}, #{time})") public int insertUser(UserPo userPo); /** * ๆ›ดๆ–ฐ็”จๆˆทไฟกๆฏ * @param userPo * @return */ @Update("UPDATE auth_user SET username=#{username}, password=#{password}, realname=#{realname}, company=#{company}, job=#{job}, salt=#{salt}, status=#{status}, time=#{time} WHERE id = #{id}") public int updateUser(UserPo userPo); }
UTF-8
Java
1,678
java
UserDao.java
Java
[ { "context": "stage.bean.po.UserPo;\n\n/**\n * ็”จๆˆทไฟกๆฏๅค„็†DAO\n * @author TanJin\n * @date 2018ๅนด3ๆœˆ5ๆ—ฅ\n */\npublic interface UserDao {", "end": 337, "score": 0.9529891610145569, "start": 331, "tag": "USERNAME", "value": "TanJin" }, { "context": "rn\n\t */\n\t@Update(\"UPDATE auth_user SET username=#{username}, password=#{password}, realname=#{realname}, com", "end": 1370, "score": 0.9207032918930054, "start": 1362, "tag": "USERNAME", "value": "username" }, { "context": "TE auth_user SET username=#{username}, password=#{password}, realname=#{realname}, company=#{company}, job=#", "end": 1392, "score": 0.9743049144744873, "start": 1384, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.silent.template.backstage.dao; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.silent.template.backstage.bean.po.UserPo; /** * ็”จๆˆทไฟกๆฏๅค„็†DAO * @author TanJin * @date 2018ๅนด3ๆœˆ5ๆ—ฅ */ public interface UserDao { /** * ๆ นๆฎ็”จๆˆทๅ่Žทๅ–ๆŒ‡ๅฎš็”จๆˆทไฟกๆฏ * @param username * @return */ @Select("SELECT * FROM auth_user WHERE username = #{username}") public UserPo loadUserByUsername(String username); /** * ่Žทๅ–ๆ‰€ๆœ‰็”จๆˆทไฟกๆฏ */ @Select("SELECT * FROM auth_user") public List<UserPo> loadAll(); /** * ๆ นๆฎ็”จๆˆทID่Žทๅ–ๆŒ‡ๅฎš็”จๆˆทไฟกๆฏ * @param userId * @return */ @Select("SELECT * FROM auth_user WHERE id = #{id}") public UserPo loadUserById(String userId); /** * ๆ นๆฎ็”จๆˆทIDๅˆ ้™คๆŒ‡ๅฎš็”จๆˆท * @param userId * @return */ @Delete("DELETE FROM auth_user WHERE id = #{id}") public int deleteUser(String userId); /** * ๆ–ฐๅขž็”จๆˆท * @param userPo * @return */ @Insert("INSERT INTO auth_user(id, username, password, realname, company, job, salt, status, time) VALUES " + "(#{id}, #{username}, #{password}, #{realname}, #{company}, #{job}, #{salt}, #{status}, #{time})") public int insertUser(UserPo userPo); /** * ๆ›ดๆ–ฐ็”จๆˆทไฟกๆฏ * @param userPo * @return */ @Update("UPDATE auth_user SET username=#{username}, password=#{<PASSWORD>}, realname=#{realname}, company=#{company}, job=#{job}, salt=#{salt}, status=#{status}, time=#{time} WHERE id = #{id}") public int updateUser(UserPo userPo); }
1,680
0.668597
0.664736
65
22.907692
31.117012
192
false
false
0
0
0
0
0
0
1.261539
false
false
3
7dd24122f71f68ef8309dc61704adef8e2a5f440
10,557,029,648,800
ed551db77c18c6e0f8acdd5b6c80c4bb93c7f602
/audit/src/main/java/org/apache/karaf/audit/util/NumberOutput.java
ca0cbaa138887a2f0d86b340bc357073a58b5ee1
[ "BSD-3-Clause", "EPL-1.0", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
sho25/karaf
https://github.com/sho25/karaf
df43b8540b374dae00715d454679f3f264b530af
95110009181760c3e7ef86e96834a763899962db
refs/heads/master
2023-08-03T18:58:47.471000
2020-03-09T17:56:12
2020-03-09T17:56:12
255,053,862
0
0
Apache-2.0
false
2023-07-23T11:42:03
2020-04-12T09:59:19
2020-04-12T10:13:18
2023-07-23T11:42:02
23,804
0
0
1
Java
false
false
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|karaf operator|. name|audit operator|. name|util package|; end_package begin_comment comment|/** * Code copied from org.codehaus.jackson.io.NumberOutput */ end_comment begin_class specifier|public specifier|final class|class name|NumberOutput block|{ specifier|private specifier|static name|int name|MILLION init|= literal|1000000 decl_stmt|; specifier|private specifier|static name|int name|BILLION init|= literal|1000000000 decl_stmt|; specifier|private specifier|static name|long name|BILLION_L init|= literal|1000000000L decl_stmt|; specifier|private specifier|static name|long name|MIN_INT_AS_LONG init|= operator|( name|long operator|) name|Integer operator|. name|MIN_VALUE decl_stmt|; specifier|private specifier|static name|long name|MAX_INT_AS_LONG init|= operator|( name|long operator|) name|Integer operator|. name|MAX_VALUE decl_stmt|; specifier|final specifier|static name|String name|SMALLEST_INT init|= name|String operator|. name|valueOf argument_list|( name|Integer operator|. name|MIN_VALUE argument_list|) decl_stmt|; specifier|final specifier|static name|String name|SMALLEST_LONG init|= name|String operator|. name|valueOf argument_list|( name|Long operator|. name|MIN_VALUE argument_list|) decl_stmt|; comment|/** * Encoded representations of 3-decimal-digit indexed values, where * 3 LSB are ascii characters * * @since 2.8.2 */ specifier|private specifier|final specifier|static name|int index|[] name|TRIPLET_TO_CHARS init|= operator|new name|int index|[ literal|1000 index|] decl_stmt|; static|static block|{ comment|/* Let's fill it with NULLs for ignorable leading digits, * and digit chars for others */ name|int name|fullIx init|= literal|0 decl_stmt|; for|for control|( name|int name|i1 init|= literal|0 init|; name|i1 operator|< literal|10 condition|; operator|++ name|i1 control|) block|{ for|for control|( name|int name|i2 init|= literal|0 init|; name|i2 operator|< literal|10 condition|; operator|++ name|i2 control|) block|{ for|for control|( name|int name|i3 init|= literal|0 init|; name|i3 operator|< literal|10 condition|; operator|++ name|i3 control|) block|{ name|int name|enc init|= operator|( operator|( name|i1 operator|+ literal|'0' operator|) operator|<< literal|16 operator|) operator|| operator|( operator|( name|i2 operator|+ literal|'0' operator|) operator|<< literal|8 operator|) operator|| operator|( name|i3 operator|+ literal|'0' operator|) decl_stmt|; name|TRIPLET_TO_CHARS index|[ name|fullIx operator|++ index|] operator|= name|enc expr_stmt|; block|} block|} block|} block|} specifier|private specifier|final specifier|static name|String index|[] name|sSmallIntStrs init|= operator|new name|String index|[] block|{ literal|"0" block|, literal|"1" block|, literal|"2" block|, literal|"3" block|, literal|"4" block|, literal|"5" block|, literal|"6" block|, literal|"7" block|, literal|"8" block|, literal|"9" block|, literal|"10" block|} decl_stmt|; specifier|private specifier|final specifier|static name|String index|[] name|sSmallIntStrs2 init|= operator|new name|String index|[] block|{ literal|"-1" block|, literal|"-2" block|, literal|"-3" block|, literal|"-4" block|, literal|"-5" block|, literal|"-6" block|, literal|"-7" block|, literal|"-8" block|, literal|"-9" block|, literal|"-10" block|} decl_stmt|; comment|/* /********************************************************** /* Efficient serialization methods using raw buffers /********************************************************** */ comment|/** * @return Offset within buffer after outputting int */ specifier|public specifier|static name|int name|outputInt parameter_list|( name|int name|v parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ if|if condition|( name|v operator|< literal|0 condition|) block|{ if|if condition|( name|v operator|== name|Integer operator|. name|MIN_VALUE condition|) block|{ comment|// Special case: no matching positive value within range; comment|// let's then "upgrade" to long and output as such. return|return name|_outputSmallestI argument_list|( name|b argument_list|, name|off argument_list|) return|; block|} name|b index|[ name|off operator|++ index|] operator|= literal|'-' expr_stmt|; name|v operator|= operator|- name|v expr_stmt|; block|} if|if condition|( name|v operator|< name|MILLION condition|) block|{ comment|// at most 2 triplets... if|if condition|( name|v operator|< literal|1000 condition|) block|{ if|if condition|( name|v operator|< literal|10 condition|) block|{ name|b index|[ name|off index|] operator|= call|( name|char call|) argument_list|( literal|'0' operator|+ name|v argument_list|) expr_stmt|; return|return name|off operator|+ literal|1 return|; block|} return|return name|_leading3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|v operator|-= operator|( name|thousands operator|* literal|1000 operator|) expr_stmt|; comment|// == value % 1000 name|off operator|= name|_leading3 argument_list|( name|thousands argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_full3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; return|return name|off return|; block|} comment|// ok, all 3 triplets included comment|/* Let's first hand possible billions separately before * handling 3 triplets. This is possible since we know we * can have at most '2' as billion count. */ if|if condition|( name|v operator|>= name|BILLION condition|) block|{ name|v operator|-= name|BILLION expr_stmt|; if|if condition|( name|v operator|>= name|BILLION condition|) block|{ name|v operator|-= name|BILLION expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= literal|'2' expr_stmt|; block|} else|else block|{ name|b index|[ name|off operator|++ index|] operator|= literal|'1' expr_stmt|; block|} return|return name|_outputFullBillion argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} name|int name|newValue init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|newValue operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|v operator|= name|newValue expr_stmt|; name|newValue operator|/= literal|1000 expr_stmt|; name|int name|thousands init|= operator|( name|v operator|- operator|( name|newValue operator|* literal|1000 operator|) operator|) decl_stmt|; name|off operator|= name|_leading3 argument_list|( name|newValue argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_full3 argument_list|( name|thousands argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; return|return name|_full3 argument_list|( name|ones argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} specifier|public specifier|static name|int name|outputInt parameter_list|( name|int name|v parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ if|if condition|( name|v operator|< literal|0 condition|) block|{ if|if condition|( name|v operator|== name|Integer operator|. name|MIN_VALUE condition|) block|{ return|return name|_outputSmallestI argument_list|( name|b argument_list|, name|off argument_list|) return|; block|} name|b index|[ name|off operator|++ index|] operator|= literal|'-' expr_stmt|; name|v operator|= operator|- name|v expr_stmt|; block|} if|if condition|( name|v operator|< name|MILLION condition|) block|{ comment|// at most 2 triplets... if|if condition|( name|v operator|< literal|1000 condition|) block|{ if|if condition|( name|v operator|< literal|10 condition|) block|{ name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( literal|'0' operator|+ name|v argument_list|) expr_stmt|; block|} else|else block|{ name|off operator|= name|_leading3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} block|} else|else block|{ name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|v operator|-= operator|( name|thousands operator|* literal|1000 operator|) expr_stmt|; comment|// == value % 1000 name|off operator|= name|_leading3 argument_list|( name|thousands argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_full3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} return|return name|off return|; block|} if|if condition|( name|v operator|>= name|BILLION condition|) block|{ name|v operator|-= name|BILLION expr_stmt|; if|if condition|( name|v operator|>= name|BILLION condition|) block|{ name|v operator|-= name|BILLION expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= literal|'2' expr_stmt|; block|} else|else block|{ name|b index|[ name|off operator|++ index|] operator|= literal|'1' expr_stmt|; block|} return|return name|_outputFullBillion argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} name|int name|newValue init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|newValue operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|v operator|= name|newValue expr_stmt|; name|newValue operator|/= literal|1000 expr_stmt|; name|int name|thousands init|= operator|( name|v operator|- operator|( name|newValue operator|* literal|1000 operator|) operator|) decl_stmt|; name|off operator|= name|_leading3 argument_list|( name|newValue argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_full3 argument_list|( name|thousands argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; return|return name|_full3 argument_list|( name|ones argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} comment|/** * @return Offset within buffer after outputting int */ specifier|public specifier|static name|int name|outputLong parameter_list|( name|long name|v parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ comment|// First: does it actually fit in an int? if|if condition|( name|v operator|< literal|0L condition|) block|{ if|if condition|( name|v operator|> name|MIN_INT_AS_LONG condition|) block|{ return|return name|outputInt argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} if|if condition|( name|v operator|== name|Long operator|. name|MIN_VALUE condition|) block|{ return|return name|_outputSmallestL argument_list|( name|b argument_list|, name|off argument_list|) return|; block|} name|b index|[ name|off operator|++ index|] operator|= literal|'-' expr_stmt|; name|v operator|= operator|- name|v expr_stmt|; block|} else|else block|{ if|if condition|( name|v operator|<= name|MAX_INT_AS_LONG condition|) block|{ return|return name|outputInt argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} block|} comment|// Ok, let's separate last 9 digits (3 x full sets of 3) name|long name|upper init|= name|v operator|/ name|BILLION_L decl_stmt|; name|v operator|-= operator|( name|upper operator|* name|BILLION_L operator|) expr_stmt|; comment|// two integers? if|if condition|( name|upper operator|< name|BILLION_L condition|) block|{ name|off operator|= name|_outputUptoBillion argument_list|( operator|( name|int operator|) name|upper argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} else|else block|{ comment|// no, two ints and bits; hi may be about 16 or so name|long name|hi init|= name|upper operator|/ name|BILLION_L decl_stmt|; name|upper operator|-= operator|( name|hi operator|* name|BILLION_L operator|) expr_stmt|; name|off operator|= name|_leading3 argument_list|( operator|( name|int operator|) name|hi argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_outputFullBillion argument_list|( operator|( name|int operator|) name|upper argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} return|return name|_outputFullBillion argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} specifier|public specifier|static name|int name|outputLong parameter_list|( name|long name|v parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ if|if condition|( name|v operator|< literal|0L condition|) block|{ if|if condition|( name|v operator|> name|MIN_INT_AS_LONG condition|) block|{ return|return name|outputInt argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} if|if condition|( name|v operator|== name|Long operator|. name|MIN_VALUE condition|) block|{ return|return name|_outputSmallestL argument_list|( name|b argument_list|, name|off argument_list|) return|; block|} name|b index|[ name|off operator|++ index|] operator|= literal|'-' expr_stmt|; name|v operator|= operator|- name|v expr_stmt|; block|} else|else block|{ if|if condition|( name|v operator|<= name|MAX_INT_AS_LONG condition|) block|{ return|return name|outputInt argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} block|} comment|// Ok, let's separate last 9 digits (3 x full sets of 3) name|long name|upper init|= name|v operator|/ name|BILLION_L decl_stmt|; name|v operator|-= operator|( name|upper operator|* name|BILLION_L operator|) expr_stmt|; comment|// two integers? if|if condition|( name|upper operator|< name|BILLION_L condition|) block|{ name|off operator|= name|_outputUptoBillion argument_list|( operator|( name|int operator|) name|upper argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} else|else block|{ comment|// no, two ints and bits; hi may be about 16 or so name|long name|hi init|= name|upper operator|/ name|BILLION_L decl_stmt|; name|upper operator|-= operator|( name|hi operator|* name|BILLION_L operator|) expr_stmt|; name|off operator|= name|_leading3 argument_list|( operator|( name|int operator|) name|hi argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_outputFullBillion argument_list|( operator|( name|int operator|) name|upper argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} return|return name|_outputFullBillion argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} comment|/* /********************************************************** /* Convenience serialization methods /********************************************************** */ comment|/* !!! 05-Aug-2008, tatus: Any ways to further optimize * these? (or need: only called by diagnostics methods?) */ specifier|public specifier|static name|String name|toString parameter_list|( name|int name|v parameter_list|) block|{ comment|// Lookup table for small values if|if condition|( name|v operator|< name|sSmallIntStrs operator|. name|length condition|) block|{ if|if condition|( name|v operator|>= literal|0 condition|) block|{ return|return name|sSmallIntStrs index|[ name|v index|] return|; block|} name|int name|v2 init|= operator|- name|v operator|- literal|1 decl_stmt|; if|if condition|( name|v2 operator|< name|sSmallIntStrs2 operator|. name|length condition|) block|{ return|return name|sSmallIntStrs2 index|[ name|v2 index|] return|; block|} block|} return|return name|Integer operator|. name|toString argument_list|( name|v argument_list|) return|; block|} specifier|public specifier|static name|String name|toString parameter_list|( name|long name|v parameter_list|) block|{ if|if condition|( name|v operator|<= name|Integer operator|. name|MAX_VALUE operator|&& name|v operator|>= name|Integer operator|. name|MIN_VALUE condition|) block|{ return|return name|toString argument_list|( operator|( name|int operator|) name|v argument_list|) return|; block|} return|return name|Long operator|. name|toString argument_list|( name|v argument_list|) return|; block|} specifier|public specifier|static name|String name|toString parameter_list|( name|double name|v parameter_list|) block|{ return|return name|Double operator|. name|toString argument_list|( name|v argument_list|) return|; block|} comment|/** * @since 2.6.0 */ specifier|public specifier|static name|String name|toString parameter_list|( name|float name|v parameter_list|) block|{ return|return name|Float operator|. name|toString argument_list|( name|v argument_list|) return|; block|} comment|/* /********************************************************** /* Internal helper methods /********************************************************** */ specifier|private specifier|static name|int name|_outputUptoBillion parameter_list|( name|int name|v parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ if|if condition|( name|v operator|< name|MILLION condition|) block|{ comment|// at most 2 triplets... if|if condition|( name|v operator|< literal|1000 condition|) block|{ return|return name|_leading3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) decl_stmt|; comment|// == value % 1000 return|return name|_outputUptoMillion argument_list|( name|b argument_list|, name|off argument_list|, name|thousands argument_list|, name|ones argument_list|) return|; block|} name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|int name|millions init|= name|thousands operator|/ literal|1000 decl_stmt|; name|thousands operator|-= operator|( name|millions operator|* literal|1000 operator|) expr_stmt|; name|off operator|= name|_leading3 argument_list|( name|millions argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputFullBillion parameter_list|( name|int name|v parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|int name|millions init|= name|thousands operator|/ literal|1000 decl_stmt|; name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|millions index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; name|thousands operator|-= operator|( name|millions operator|* literal|1000 operator|) expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputUptoBillion parameter_list|( name|int name|v parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ if|if condition|( name|v operator|< name|MILLION condition|) block|{ comment|// at most 2 triplets... if|if condition|( name|v operator|< literal|1000 condition|) block|{ return|return name|_leading3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) decl_stmt|; comment|// == value % 1000 return|return name|_outputUptoMillion argument_list|( name|b argument_list|, name|off argument_list|, name|thousands argument_list|, name|ones argument_list|) return|; block|} name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|int name|millions init|= name|thousands operator|/ literal|1000 decl_stmt|; name|thousands operator|-= operator|( name|millions operator|* literal|1000 operator|) expr_stmt|; name|off operator|= name|_leading3 argument_list|( name|millions argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputFullBillion parameter_list|( name|int name|v parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|int name|millions init|= name|thousands operator|/ literal|1000 decl_stmt|; name|thousands operator|-= operator|( name|millions operator|* literal|1000 operator|) expr_stmt|; name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|millions index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputUptoMillion parameter_list|( name|char index|[] name|b parameter_list|, name|int name|off parameter_list|, name|int name|thousands parameter_list|, name|int name|ones parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] decl_stmt|; if|if condition|( name|thousands operator|> literal|9 condition|) block|{ if|if condition|( name|thousands operator|> literal|99 condition|) block|{ name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; comment|// and then full name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputUptoMillion parameter_list|( name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|, name|int name|thousands parameter_list|, name|int name|ones parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] decl_stmt|; if|if condition|( name|thousands operator|> literal|9 condition|) block|{ if|if condition|( name|thousands operator|> literal|99 condition|) block|{ name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; comment|// and then full name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_leading3 parameter_list|( name|int name|t parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|t index|] decl_stmt|; if|if condition|( name|t operator|> literal|9 condition|) block|{ if|if condition|( name|t operator|> literal|99 condition|) block|{ name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_leading3 parameter_list|( name|int name|t parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|t index|] decl_stmt|; if|if condition|( name|t operator|> literal|9 condition|) block|{ if|if condition|( name|t operator|> literal|99 condition|) block|{ name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_full3 parameter_list|( name|int name|t parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|t index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_full3 parameter_list|( name|int name|t parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|t index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; return|return name|off return|; block|} comment|// // // Special cases for where we can not flip the sign bit specifier|private specifier|static name|int name|_outputSmallestL parameter_list|( name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|len init|= name|SMALLEST_LONG operator|. name|length argument_list|() decl_stmt|; name|SMALLEST_LONG operator|. name|getChars argument_list|( literal|0 argument_list|, name|len argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; return|return operator|( name|off operator|+ name|len operator|) return|; block|} specifier|private specifier|static name|int name|_outputSmallestL parameter_list|( name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|len init|= name|SMALLEST_LONG operator|. name|length argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|len condition|; operator|++ name|i control|) block|{ name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|SMALLEST_LONG operator|. name|charAt argument_list|( name|i argument_list|) expr_stmt|; block|} return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputSmallestI parameter_list|( name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|len init|= name|SMALLEST_INT operator|. name|length argument_list|() decl_stmt|; name|SMALLEST_INT operator|. name|getChars argument_list|( literal|0 argument_list|, name|len argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; return|return operator|( name|off operator|+ name|len operator|) return|; block|} specifier|private specifier|static name|int name|_outputSmallestI parameter_list|( name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|len init|= name|SMALLEST_INT operator|. name|length argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|len condition|; operator|++ name|i control|) block|{ name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|SMALLEST_INT operator|. name|charAt argument_list|( name|i argument_list|) expr_stmt|; block|} return|return name|off return|; block|} block|} end_class end_unit
UTF-8
Java
37,190
java
NumberOutput.java
Java
[]
null
[]
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|karaf operator|. name|audit operator|. name|util package|; end_package begin_comment comment|/** * Code copied from org.codehaus.jackson.io.NumberOutput */ end_comment begin_class specifier|public specifier|final class|class name|NumberOutput block|{ specifier|private specifier|static name|int name|MILLION init|= literal|1000000 decl_stmt|; specifier|private specifier|static name|int name|BILLION init|= literal|1000000000 decl_stmt|; specifier|private specifier|static name|long name|BILLION_L init|= literal|1000000000L decl_stmt|; specifier|private specifier|static name|long name|MIN_INT_AS_LONG init|= operator|( name|long operator|) name|Integer operator|. name|MIN_VALUE decl_stmt|; specifier|private specifier|static name|long name|MAX_INT_AS_LONG init|= operator|( name|long operator|) name|Integer operator|. name|MAX_VALUE decl_stmt|; specifier|final specifier|static name|String name|SMALLEST_INT init|= name|String operator|. name|valueOf argument_list|( name|Integer operator|. name|MIN_VALUE argument_list|) decl_stmt|; specifier|final specifier|static name|String name|SMALLEST_LONG init|= name|String operator|. name|valueOf argument_list|( name|Long operator|. name|MIN_VALUE argument_list|) decl_stmt|; comment|/** * Encoded representations of 3-decimal-digit indexed values, where * 3 LSB are ascii characters * * @since 2.8.2 */ specifier|private specifier|final specifier|static name|int index|[] name|TRIPLET_TO_CHARS init|= operator|new name|int index|[ literal|1000 index|] decl_stmt|; static|static block|{ comment|/* Let's fill it with NULLs for ignorable leading digits, * and digit chars for others */ name|int name|fullIx init|= literal|0 decl_stmt|; for|for control|( name|int name|i1 init|= literal|0 init|; name|i1 operator|< literal|10 condition|; operator|++ name|i1 control|) block|{ for|for control|( name|int name|i2 init|= literal|0 init|; name|i2 operator|< literal|10 condition|; operator|++ name|i2 control|) block|{ for|for control|( name|int name|i3 init|= literal|0 init|; name|i3 operator|< literal|10 condition|; operator|++ name|i3 control|) block|{ name|int name|enc init|= operator|( operator|( name|i1 operator|+ literal|'0' operator|) operator|<< literal|16 operator|) operator|| operator|( operator|( name|i2 operator|+ literal|'0' operator|) operator|<< literal|8 operator|) operator|| operator|( name|i3 operator|+ literal|'0' operator|) decl_stmt|; name|TRIPLET_TO_CHARS index|[ name|fullIx operator|++ index|] operator|= name|enc expr_stmt|; block|} block|} block|} block|} specifier|private specifier|final specifier|static name|String index|[] name|sSmallIntStrs init|= operator|new name|String index|[] block|{ literal|"0" block|, literal|"1" block|, literal|"2" block|, literal|"3" block|, literal|"4" block|, literal|"5" block|, literal|"6" block|, literal|"7" block|, literal|"8" block|, literal|"9" block|, literal|"10" block|} decl_stmt|; specifier|private specifier|final specifier|static name|String index|[] name|sSmallIntStrs2 init|= operator|new name|String index|[] block|{ literal|"-1" block|, literal|"-2" block|, literal|"-3" block|, literal|"-4" block|, literal|"-5" block|, literal|"-6" block|, literal|"-7" block|, literal|"-8" block|, literal|"-9" block|, literal|"-10" block|} decl_stmt|; comment|/* /********************************************************** /* Efficient serialization methods using raw buffers /********************************************************** */ comment|/** * @return Offset within buffer after outputting int */ specifier|public specifier|static name|int name|outputInt parameter_list|( name|int name|v parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ if|if condition|( name|v operator|< literal|0 condition|) block|{ if|if condition|( name|v operator|== name|Integer operator|. name|MIN_VALUE condition|) block|{ comment|// Special case: no matching positive value within range; comment|// let's then "upgrade" to long and output as such. return|return name|_outputSmallestI argument_list|( name|b argument_list|, name|off argument_list|) return|; block|} name|b index|[ name|off operator|++ index|] operator|= literal|'-' expr_stmt|; name|v operator|= operator|- name|v expr_stmt|; block|} if|if condition|( name|v operator|< name|MILLION condition|) block|{ comment|// at most 2 triplets... if|if condition|( name|v operator|< literal|1000 condition|) block|{ if|if condition|( name|v operator|< literal|10 condition|) block|{ name|b index|[ name|off index|] operator|= call|( name|char call|) argument_list|( literal|'0' operator|+ name|v argument_list|) expr_stmt|; return|return name|off operator|+ literal|1 return|; block|} return|return name|_leading3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|v operator|-= operator|( name|thousands operator|* literal|1000 operator|) expr_stmt|; comment|// == value % 1000 name|off operator|= name|_leading3 argument_list|( name|thousands argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_full3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; return|return name|off return|; block|} comment|// ok, all 3 triplets included comment|/* Let's first hand possible billions separately before * handling 3 triplets. This is possible since we know we * can have at most '2' as billion count. */ if|if condition|( name|v operator|>= name|BILLION condition|) block|{ name|v operator|-= name|BILLION expr_stmt|; if|if condition|( name|v operator|>= name|BILLION condition|) block|{ name|v operator|-= name|BILLION expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= literal|'2' expr_stmt|; block|} else|else block|{ name|b index|[ name|off operator|++ index|] operator|= literal|'1' expr_stmt|; block|} return|return name|_outputFullBillion argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} name|int name|newValue init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|newValue operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|v operator|= name|newValue expr_stmt|; name|newValue operator|/= literal|1000 expr_stmt|; name|int name|thousands init|= operator|( name|v operator|- operator|( name|newValue operator|* literal|1000 operator|) operator|) decl_stmt|; name|off operator|= name|_leading3 argument_list|( name|newValue argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_full3 argument_list|( name|thousands argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; return|return name|_full3 argument_list|( name|ones argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} specifier|public specifier|static name|int name|outputInt parameter_list|( name|int name|v parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ if|if condition|( name|v operator|< literal|0 condition|) block|{ if|if condition|( name|v operator|== name|Integer operator|. name|MIN_VALUE condition|) block|{ return|return name|_outputSmallestI argument_list|( name|b argument_list|, name|off argument_list|) return|; block|} name|b index|[ name|off operator|++ index|] operator|= literal|'-' expr_stmt|; name|v operator|= operator|- name|v expr_stmt|; block|} if|if condition|( name|v operator|< name|MILLION condition|) block|{ comment|// at most 2 triplets... if|if condition|( name|v operator|< literal|1000 condition|) block|{ if|if condition|( name|v operator|< literal|10 condition|) block|{ name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( literal|'0' operator|+ name|v argument_list|) expr_stmt|; block|} else|else block|{ name|off operator|= name|_leading3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} block|} else|else block|{ name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|v operator|-= operator|( name|thousands operator|* literal|1000 operator|) expr_stmt|; comment|// == value % 1000 name|off operator|= name|_leading3 argument_list|( name|thousands argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_full3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} return|return name|off return|; block|} if|if condition|( name|v operator|>= name|BILLION condition|) block|{ name|v operator|-= name|BILLION expr_stmt|; if|if condition|( name|v operator|>= name|BILLION condition|) block|{ name|v operator|-= name|BILLION expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= literal|'2' expr_stmt|; block|} else|else block|{ name|b index|[ name|off operator|++ index|] operator|= literal|'1' expr_stmt|; block|} return|return name|_outputFullBillion argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} name|int name|newValue init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|newValue operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|v operator|= name|newValue expr_stmt|; name|newValue operator|/= literal|1000 expr_stmt|; name|int name|thousands init|= operator|( name|v operator|- operator|( name|newValue operator|* literal|1000 operator|) operator|) decl_stmt|; name|off operator|= name|_leading3 argument_list|( name|newValue argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_full3 argument_list|( name|thousands argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; return|return name|_full3 argument_list|( name|ones argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} comment|/** * @return Offset within buffer after outputting int */ specifier|public specifier|static name|int name|outputLong parameter_list|( name|long name|v parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ comment|// First: does it actually fit in an int? if|if condition|( name|v operator|< literal|0L condition|) block|{ if|if condition|( name|v operator|> name|MIN_INT_AS_LONG condition|) block|{ return|return name|outputInt argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} if|if condition|( name|v operator|== name|Long operator|. name|MIN_VALUE condition|) block|{ return|return name|_outputSmallestL argument_list|( name|b argument_list|, name|off argument_list|) return|; block|} name|b index|[ name|off operator|++ index|] operator|= literal|'-' expr_stmt|; name|v operator|= operator|- name|v expr_stmt|; block|} else|else block|{ if|if condition|( name|v operator|<= name|MAX_INT_AS_LONG condition|) block|{ return|return name|outputInt argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} block|} comment|// Ok, let's separate last 9 digits (3 x full sets of 3) name|long name|upper init|= name|v operator|/ name|BILLION_L decl_stmt|; name|v operator|-= operator|( name|upper operator|* name|BILLION_L operator|) expr_stmt|; comment|// two integers? if|if condition|( name|upper operator|< name|BILLION_L condition|) block|{ name|off operator|= name|_outputUptoBillion argument_list|( operator|( name|int operator|) name|upper argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} else|else block|{ comment|// no, two ints and bits; hi may be about 16 or so name|long name|hi init|= name|upper operator|/ name|BILLION_L decl_stmt|; name|upper operator|-= operator|( name|hi operator|* name|BILLION_L operator|) expr_stmt|; name|off operator|= name|_leading3 argument_list|( operator|( name|int operator|) name|hi argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_outputFullBillion argument_list|( operator|( name|int operator|) name|upper argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} return|return name|_outputFullBillion argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} specifier|public specifier|static name|int name|outputLong parameter_list|( name|long name|v parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ if|if condition|( name|v operator|< literal|0L condition|) block|{ if|if condition|( name|v operator|> name|MIN_INT_AS_LONG condition|) block|{ return|return name|outputInt argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} if|if condition|( name|v operator|== name|Long operator|. name|MIN_VALUE condition|) block|{ return|return name|_outputSmallestL argument_list|( name|b argument_list|, name|off argument_list|) return|; block|} name|b index|[ name|off operator|++ index|] operator|= literal|'-' expr_stmt|; name|v operator|= operator|- name|v expr_stmt|; block|} else|else block|{ if|if condition|( name|v operator|<= name|MAX_INT_AS_LONG condition|) block|{ return|return name|outputInt argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} block|} comment|// Ok, let's separate last 9 digits (3 x full sets of 3) name|long name|upper init|= name|v operator|/ name|BILLION_L decl_stmt|; name|v operator|-= operator|( name|upper operator|* name|BILLION_L operator|) expr_stmt|; comment|// two integers? if|if condition|( name|upper operator|< name|BILLION_L condition|) block|{ name|off operator|= name|_outputUptoBillion argument_list|( operator|( name|int operator|) name|upper argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} else|else block|{ comment|// no, two ints and bits; hi may be about 16 or so name|long name|hi init|= name|upper operator|/ name|BILLION_L decl_stmt|; name|upper operator|-= operator|( name|hi operator|* name|BILLION_L operator|) expr_stmt|; name|off operator|= name|_leading3 argument_list|( operator|( name|int operator|) name|hi argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|off operator|= name|_outputFullBillion argument_list|( operator|( name|int operator|) name|upper argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; block|} return|return name|_outputFullBillion argument_list|( operator|( name|int operator|) name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} comment|/* /********************************************************** /* Convenience serialization methods /********************************************************** */ comment|/* !!! 05-Aug-2008, tatus: Any ways to further optimize * these? (or need: only called by diagnostics methods?) */ specifier|public specifier|static name|String name|toString parameter_list|( name|int name|v parameter_list|) block|{ comment|// Lookup table for small values if|if condition|( name|v operator|< name|sSmallIntStrs operator|. name|length condition|) block|{ if|if condition|( name|v operator|>= literal|0 condition|) block|{ return|return name|sSmallIntStrs index|[ name|v index|] return|; block|} name|int name|v2 init|= operator|- name|v operator|- literal|1 decl_stmt|; if|if condition|( name|v2 operator|< name|sSmallIntStrs2 operator|. name|length condition|) block|{ return|return name|sSmallIntStrs2 index|[ name|v2 index|] return|; block|} block|} return|return name|Integer operator|. name|toString argument_list|( name|v argument_list|) return|; block|} specifier|public specifier|static name|String name|toString parameter_list|( name|long name|v parameter_list|) block|{ if|if condition|( name|v operator|<= name|Integer operator|. name|MAX_VALUE operator|&& name|v operator|>= name|Integer operator|. name|MIN_VALUE condition|) block|{ return|return name|toString argument_list|( operator|( name|int operator|) name|v argument_list|) return|; block|} return|return name|Long operator|. name|toString argument_list|( name|v argument_list|) return|; block|} specifier|public specifier|static name|String name|toString parameter_list|( name|double name|v parameter_list|) block|{ return|return name|Double operator|. name|toString argument_list|( name|v argument_list|) return|; block|} comment|/** * @since 2.6.0 */ specifier|public specifier|static name|String name|toString parameter_list|( name|float name|v parameter_list|) block|{ return|return name|Float operator|. name|toString argument_list|( name|v argument_list|) return|; block|} comment|/* /********************************************************** /* Internal helper methods /********************************************************** */ specifier|private specifier|static name|int name|_outputUptoBillion parameter_list|( name|int name|v parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ if|if condition|( name|v operator|< name|MILLION condition|) block|{ comment|// at most 2 triplets... if|if condition|( name|v operator|< literal|1000 condition|) block|{ return|return name|_leading3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) decl_stmt|; comment|// == value % 1000 return|return name|_outputUptoMillion argument_list|( name|b argument_list|, name|off argument_list|, name|thousands argument_list|, name|ones argument_list|) return|; block|} name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|int name|millions init|= name|thousands operator|/ literal|1000 decl_stmt|; name|thousands operator|-= operator|( name|millions operator|* literal|1000 operator|) expr_stmt|; name|off operator|= name|_leading3 argument_list|( name|millions argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputFullBillion parameter_list|( name|int name|v parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|int name|millions init|= name|thousands operator|/ literal|1000 decl_stmt|; name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|millions index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; name|thousands operator|-= operator|( name|millions operator|* literal|1000 operator|) expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputUptoBillion parameter_list|( name|int name|v parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ if|if condition|( name|v operator|< name|MILLION condition|) block|{ comment|// at most 2 triplets... if|if condition|( name|v operator|< literal|1000 condition|) block|{ return|return name|_leading3 argument_list|( name|v argument_list|, name|b argument_list|, name|off argument_list|) return|; block|} name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) decl_stmt|; comment|// == value % 1000 return|return name|_outputUptoMillion argument_list|( name|b argument_list|, name|off argument_list|, name|thousands argument_list|, name|ones argument_list|) return|; block|} name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|int name|millions init|= name|thousands operator|/ literal|1000 decl_stmt|; name|thousands operator|-= operator|( name|millions operator|* literal|1000 operator|) expr_stmt|; name|off operator|= name|_leading3 argument_list|( name|millions argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputFullBillion parameter_list|( name|int name|v parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|thousands init|= name|v operator|/ literal|1000 decl_stmt|; name|int name|ones init|= operator|( name|v operator|- operator|( name|thousands operator|* literal|1000 operator|) operator|) decl_stmt|; comment|// == value % 1000 name|int name|millions init|= name|thousands operator|/ literal|1000 decl_stmt|; name|thousands operator|-= operator|( name|millions operator|* literal|1000 operator|) expr_stmt|; name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|millions index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputUptoMillion parameter_list|( name|char index|[] name|b parameter_list|, name|int name|off parameter_list|, name|int name|thousands parameter_list|, name|int name|ones parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] decl_stmt|; if|if condition|( name|thousands operator|> literal|9 condition|) block|{ if|if condition|( name|thousands operator|> literal|99 condition|) block|{ name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; comment|// and then full name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputUptoMillion parameter_list|( name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|, name|int name|thousands parameter_list|, name|int name|ones parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|thousands index|] decl_stmt|; if|if condition|( name|thousands operator|> literal|9 condition|) block|{ if|if condition|( name|thousands operator|> literal|99 condition|) block|{ name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; comment|// and then full name|enc operator|= name|TRIPLET_TO_CHARS index|[ name|ones index|] expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_leading3 parameter_list|( name|int name|t parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|t index|] decl_stmt|; if|if condition|( name|t operator|> literal|9 condition|) block|{ if|if condition|( name|t operator|> literal|99 condition|) block|{ name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_leading3 parameter_list|( name|int name|t parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|t index|] decl_stmt|; if|if condition|( name|t operator|> literal|9 condition|) block|{ if|if condition|( name|t operator|> literal|99 condition|) block|{ name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; block|} name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_full3 parameter_list|( name|int name|t parameter_list|, name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|t index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( operator|( name|enc operator|>> literal|8 operator|) operator|& literal|0x7F argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|char call|) argument_list|( name|enc operator|& literal|0x7F argument_list|) expr_stmt|; return|return name|off return|; block|} specifier|private specifier|static name|int name|_full3 parameter_list|( name|int name|t parameter_list|, name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|enc init|= name|TRIPLET_TO_CHARS index|[ name|t index|] decl_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|16 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= call|( name|byte call|) argument_list|( name|enc operator|>> literal|8 argument_list|) expr_stmt|; name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|enc expr_stmt|; return|return name|off return|; block|} comment|// // // Special cases for where we can not flip the sign bit specifier|private specifier|static name|int name|_outputSmallestL parameter_list|( name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|len init|= name|SMALLEST_LONG operator|. name|length argument_list|() decl_stmt|; name|SMALLEST_LONG operator|. name|getChars argument_list|( literal|0 argument_list|, name|len argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; return|return operator|( name|off operator|+ name|len operator|) return|; block|} specifier|private specifier|static name|int name|_outputSmallestL parameter_list|( name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|len init|= name|SMALLEST_LONG operator|. name|length argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|len condition|; operator|++ name|i control|) block|{ name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|SMALLEST_LONG operator|. name|charAt argument_list|( name|i argument_list|) expr_stmt|; block|} return|return name|off return|; block|} specifier|private specifier|static name|int name|_outputSmallestI parameter_list|( name|char index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|len init|= name|SMALLEST_INT operator|. name|length argument_list|() decl_stmt|; name|SMALLEST_INT operator|. name|getChars argument_list|( literal|0 argument_list|, name|len argument_list|, name|b argument_list|, name|off argument_list|) expr_stmt|; return|return operator|( name|off operator|+ name|len operator|) return|; block|} specifier|private specifier|static name|int name|_outputSmallestI parameter_list|( name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|) block|{ name|int name|len init|= name|SMALLEST_INT operator|. name|length argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|len condition|; operator|++ name|i control|) block|{ name|b index|[ name|off operator|++ index|] operator|= operator|( name|byte operator|) name|SMALLEST_INT operator|. name|charAt argument_list|( name|i argument_list|) expr_stmt|; block|} return|return name|off return|; block|} block|} end_class end_unit
37,190
0.72982
0.717505
3,096
11.01195
16.980463
810
false
false
0
0
0
0
0
0
1.116602
false
false
3
0a387996188552d28edddeeb066da88bc79eaa3e
30,056,181,200,886
e57cd45896daf6a79700db415359adf6bf957e3c
/src/Solving_Step_by_Step/Chap09/BOJ_11653/Main.java
fcb0dd379275172a5c987ac3aa3ac477ba6955e8
[]
no_license
Charmull/Algorithm-BOJ_PS_Java
https://github.com/Charmull/Algorithm-BOJ_PS_Java
ed6d7dfb17be711a341ed3589e160bc64c31e8b6
278b97145e23809c3ee50a0fa30d998d6852bb62
refs/heads/master
2023-08-16T22:05:41.189000
2021-10-03T12:20:37
2021-10-03T12:20:37
347,173,726
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Solving_Step_by_Step.Chap09.BOJ_11653; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; // ๋ฉ”๋ชจ๋ฆฌ : 14692KB, ์‹œ๊ฐ„ : 168ms public class Main { public static void returnPrime(int num, StringBuilder sb) { int i = 2; while(num != 1) { if(num % i == 0) { sb.append(i).append('\n'); num /= i; } else { i++; } } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int N = Integer.parseInt(br.readLine()); returnPrime(N, sb); System.out.println(sb); br.close(); } }
UTF-8
Java
828
java
Main.java
Java
[]
null
[]
package Solving_Step_by_Step.Chap09.BOJ_11653; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; // ๋ฉ”๋ชจ๋ฆฌ : 14692KB, ์‹œ๊ฐ„ : 168ms public class Main { public static void returnPrime(int num, StringBuilder sb) { int i = 2; while(num != 1) { if(num % i == 0) { sb.append(i).append('\n'); num /= i; } else { i++; } } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int N = Integer.parseInt(br.readLine()); returnPrime(N, sb); System.out.println(sb); br.close(); } }
828
0.5489
0.526895
32
24.5625
20.285366
81
false
false
0
0
0
0
0
0
0.53125
false
false
3
feefd8bde8dfcf3b8f36b60ef685aca0d4c5f2ff
36,361,193,160,940
5d57e65264616c5baaecebaf79c4694b7ddd38ef
/src/main/java/com/amazonaws/lambda/pool/DAO.java
f0a2a238d44c5419ae0a5cadbdea1c1687e3cae4
[]
no_license
danielamas/aws_lambda
https://github.com/danielamas/aws_lambda
53cba67c7235eeaed6e5986ed7089606dd55247d
cce131b1d2972dc98f4e73a62deb1cae03687ac4
refs/heads/master
2021-04-29T17:40:34.018000
2018-02-16T18:29:46
2018-02-16T18:29:46
121,676,217
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amazonaws.lambda.pool; import javax.sql.DataSource; import org.apache.commons.dbcp.ConnectionFactory; import org.apache.commons.dbcp.DriverManagerConnectionFactory; import org.apache.commons.dbcp.PoolableConnectionFactory; import org.apache.commons.dbcp.PoolingDataSource; import org.apache.commons.pool.impl.GenericObjectPool; import com.amazonaws.services.lambda.runtime.Context; public class DAO { // public static Connection connection = null; // private static final String ENDPOINT = "mysql.cnqdm4ugj5z5.us-east-1.rds.amazonaws.com"; // // public static Connection getConnection() { // try { // Class.forName("com.mysql.jdbc.Driver"); // if(connection == null) { // connection = DriverManager.getConnection("jdbc:mysql://"+ENDPOINT+":3306/lambda","", ""); // } // } catch (Exception e) { // e.printStackTrace(); // } // return connection; // } static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String JDBC_DB_URL = "jdbc:mysql://"+ENDPOINT+":3306/lambda"; static final String JDBC_USER = ""; static final String JDBC_PASS = ""; private static GenericObjectPool gPool = null; private static DataSource dataSource = null; private static void configPool() { if(gPool == null) { // Creates an Instance of GenericObjectPool That Holds Our Pool of Connections Object! gPool = new GenericObjectPool(); gPool.setMaxActive(2); gPool.setMaxIdle(1); } } public static DataSource getDataSource() { try { if(dataSource == null) { Class.forName(JDBC_DRIVER); configPool(); // Creates a ConnectionFactory Object Which Will Be Use by the Pool to Create the Connection Object! ConnectionFactory cf = new DriverManagerConnectionFactory(JDBC_DB_URL, JDBC_USER, JDBC_PASS); // Creates a PoolableConnectionFactory That Will Wraps the Connection Object Created by the ConnectionFactory to Add Object Pooling Functionality! // PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, gPool, null, null, false, true); new PoolableConnectionFactory(cf, gPool, null, null, false, true); dataSource = new PoolingDataSource(gPool); } } catch (Exception e) { e.printStackTrace(); } return dataSource; } private static GenericObjectPool getConfigPool() { try { getDataSource(); } catch (Exception e) { e.printStackTrace(); } return gPool; } // This Method Is Used To Print The Connection Pool Status public static void printDbStatus(StringBuilder resp) { resp.append("\n Max Connection Active " + getConfigPool().getMaxActive() + " -" + "Connection Active: " + getConfigPool().getNumActive() + " - " + "Connection Idle: " + getConfigPool().getNumIdle()); } }
UTF-8
Java
2,736
java
DAO.java
Java
[]
null
[]
package com.amazonaws.lambda.pool; import javax.sql.DataSource; import org.apache.commons.dbcp.ConnectionFactory; import org.apache.commons.dbcp.DriverManagerConnectionFactory; import org.apache.commons.dbcp.PoolableConnectionFactory; import org.apache.commons.dbcp.PoolingDataSource; import org.apache.commons.pool.impl.GenericObjectPool; import com.amazonaws.services.lambda.runtime.Context; public class DAO { // public static Connection connection = null; // private static final String ENDPOINT = "mysql.cnqdm4ugj5z5.us-east-1.rds.amazonaws.com"; // // public static Connection getConnection() { // try { // Class.forName("com.mysql.jdbc.Driver"); // if(connection == null) { // connection = DriverManager.getConnection("jdbc:mysql://"+ENDPOINT+":3306/lambda","", ""); // } // } catch (Exception e) { // e.printStackTrace(); // } // return connection; // } static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String JDBC_DB_URL = "jdbc:mysql://"+ENDPOINT+":3306/lambda"; static final String JDBC_USER = ""; static final String JDBC_PASS = ""; private static GenericObjectPool gPool = null; private static DataSource dataSource = null; private static void configPool() { if(gPool == null) { // Creates an Instance of GenericObjectPool That Holds Our Pool of Connections Object! gPool = new GenericObjectPool(); gPool.setMaxActive(2); gPool.setMaxIdle(1); } } public static DataSource getDataSource() { try { if(dataSource == null) { Class.forName(JDBC_DRIVER); configPool(); // Creates a ConnectionFactory Object Which Will Be Use by the Pool to Create the Connection Object! ConnectionFactory cf = new DriverManagerConnectionFactory(JDBC_DB_URL, JDBC_USER, JDBC_PASS); // Creates a PoolableConnectionFactory That Will Wraps the Connection Object Created by the ConnectionFactory to Add Object Pooling Functionality! // PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, gPool, null, null, false, true); new PoolableConnectionFactory(cf, gPool, null, null, false, true); dataSource = new PoolingDataSource(gPool); } } catch (Exception e) { e.printStackTrace(); } return dataSource; } private static GenericObjectPool getConfigPool() { try { getDataSource(); } catch (Exception e) { e.printStackTrace(); } return gPool; } // This Method Is Used To Print The Connection Pool Status public static void printDbStatus(StringBuilder resp) { resp.append("\n Max Connection Active " + getConfigPool().getMaxActive() + " -" + "Connection Active: " + getConfigPool().getNumActive() + " - " + "Connection Idle: " + getConfigPool().getNumIdle()); } }
2,736
0.714547
0.70943
86
30.813953
31.533855
150
false
false
0
0
0
0
0
0
2.348837
false
false
3
b7051f24b3490f749367809fa69db0f43dfa96e0
39,024,072,887,076
6482753b5eb6357e7fe70e3057195e91682db323
/io/netty/channel/EventLoop.java
95b5cd8a830cf49448db1971bcf09f77b6897baa
[]
no_license
TheShermanTanker/Server-1.16.3
https://github.com/TheShermanTanker/Server-1.16.3
45cf9996afa4cd4d8963f8fd0588ae4ee9dca93c
48cc08cb94c3094ebddb6ccfb4ea25538492bebf
refs/heads/master
2022-12-19T02:20:01.786000
2020-09-18T21:29:40
2020-09-18T21:29:40
296,730,962
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.netty.channel; import io.netty.util.concurrent.OrderedEventExecutor; public interface EventLoop extends OrderedEventExecutor, EventLoopGroup { EventLoopGroup parent(); }
UTF-8
Java
187
java
EventLoop.java
Java
[]
null
[]
package io.netty.channel; import io.netty.util.concurrent.OrderedEventExecutor; public interface EventLoop extends OrderedEventExecutor, EventLoopGroup { EventLoopGroup parent(); }
187
0.818182
0.818182
7
25.714285
26.509912
73
false
false
0
0
0
0
0
0
0.571429
false
false
3
8f311c7bfa981c7f444009b15af8bc2d3bfbcc68
39,058,432,617,621
98cc0bf108fbf949aa55da5d3c831708fdc01ed6
/hcConference/src/main/java/hc/test/web/entity/demo/TConference.java
6110f4275725129f593fc0af600406cd3ef81fdb
[]
no_license
newGuyXin/aXinRepo1
https://github.com/newGuyXin/aXinRepo1
b31af1b7bc2cad21dc9e86438e75e7c16c20d0f6
95f91767fd49cca76fda46d33b882c19730ef5db
refs/heads/master
2022-11-14T00:52:36.054000
2020-07-02T09:32:58
2020-07-02T09:32:58
250,248,448
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hc.test.web.entity.demo; import hc.test.web.entity.base.BaseEntity; import lombok.Getter; import lombok.Setter; /** * ไผš่ฎฎๅฎคๅฎžไฝ“็ฑป */ @Getter @Setter public class TConference extends BaseEntity { //ไผš่ฎฎๅฎคๅ็งฐ private String name; //ไผš่ฎฎๅฎค็ผ–ๅท private Integer code; //ๅค‡ๆณจไฟกๆฏ private String remark; }
UTF-8
Java
361
java
TConference.java
Java
[]
null
[]
package hc.test.web.entity.demo; import hc.test.web.entity.base.BaseEntity; import lombok.Getter; import lombok.Setter; /** * ไผš่ฎฎๅฎคๅฎžไฝ“็ฑป */ @Getter @Setter public class TConference extends BaseEntity { //ไผš่ฎฎๅฎคๅ็งฐ private String name; //ไผš่ฎฎๅฎค็ผ–ๅท private Integer code; //ๅค‡ๆณจไฟกๆฏ private String remark; }
361
0.691589
0.691589
23
12.956522
13.595006
45
false
false
0
0
0
0
0
0
0.304348
false
false
3
8dd90f9f1e45033a4b777d53bc3effced623bd0f
36,636,071,066,603
31b6c73a0730650831475e930a1c60cae9526559
/ThanksgivingMaps/ThanksgivingMaps.java
9905152882c37d3a0b1c58237a72935fd377f3d6
[]
no_license
johnanselmo-s3i/DataStructures1819
https://github.com/johnanselmo-s3i/DataStructures1819
f116d678bb453c637ca30a506b1cf33125d759f5
e782f2ec7a6998318656a84481183e056ded0fe5
refs/heads/master
2020-03-27T13:40:03.119000
2019-05-28T14:32:50
2019-05-28T14:32:50
146,621,917
2
3
null
false
2019-05-23T14:40:37
2018-08-29T15:36:55
2019-05-23T14:39:04
2019-05-23T14:40:36
308
1
2
1
Java
false
false
import java.util.ArrayList; import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; import java.util.Map; import java.util.TreeMap; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; public class ThanksgivingMaps { public static void main( String[] args ) { ArrayList<String> foods = new ArrayList<>(); Map<String, Integer> foodMap = map1(); Object[] foodArray = foodMap.keySet().toArray(); System.out.println("Map 1:"); for ( int i = 0; i < foodMap.keySet().size(); i++ ) { System.out.println( foodArray[i] + ": " + foodMap.get( foodArray[i] ) ); } System.out.println("\n\n\nMap 2:"); Map<Integer, TreeSet<String>> foodMap2 = map2(); Object[] foodArray2 = foodMap2.keySet().toArray(); for ( int i = 0; i < foodMap2.keySet().size(); i++ ) { System.out.println( foodArray2[i] + ": " + foodMap2.get( foodArray2[i] ) ); } } public static Map<String, Integer> map1() { ArrayList<String> foods = getFoods(); Map<String, Integer> foodMap = new TreeMap<>(); for ( int i = 0; i < foods.size(); i++ ) { if ( foodMap.get( foods.get( i ) ) != null ) { foodMap.put( foods.get( i ), foodMap.get( foods.get( i ) ) + 1 ); } foodMap.putIfAbsent( foods.get( i ), 1 ); } return foodMap; } public static Map<Integer, TreeSet<String>> map2() { Map<String, Integer> foodMap = map1(); Map<Integer, TreeSet<String>> newFoodMap = new TreeMap<>(); ArrayList<String> foods = getFoods(); Set<String> nonRepetFoods = new LinkedHashSet<>( foods ); foods = new ArrayList<>( nonRepetFoods ); for ( int i = 0; i < foodMap.keySet().size(); i++ ) { if ( newFoodMap.get( foodMap.get( foods.get( i ) ) ) != null ) { newFoodMap.get( foodMap.get( foods.get( i ) ) ).add( foods.get( i ) ); newFoodMap.put( foodMap.get( foods.get( i ) ), newFoodMap.get( foodMap.get( foods.get( i ) ) ) ); } TreeSet<String> foodsForScore = new TreeSet<>(); foodsForScore.add( foods.get( i ) ); newFoodMap.putIfAbsent( foodMap.get( foods.get( i ) ), foodsForScore ); } return newFoodMap; } public static ArrayList<String> getFoods() { ArrayList<String> foods = new ArrayList<>(); File f = new File( "Foods.txt" ); try { Scanner sc = new Scanner( f ); while ( sc.hasNext() ) { foods.add( sc.nextLine() ); } return foods; } catch ( FileNotFoundException e ) { System.out.println( "No file bro" ); } return null; } }
UTF-8
Java
2,912
java
ThanksgivingMaps.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; import java.util.Map; import java.util.TreeMap; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; public class ThanksgivingMaps { public static void main( String[] args ) { ArrayList<String> foods = new ArrayList<>(); Map<String, Integer> foodMap = map1(); Object[] foodArray = foodMap.keySet().toArray(); System.out.println("Map 1:"); for ( int i = 0; i < foodMap.keySet().size(); i++ ) { System.out.println( foodArray[i] + ": " + foodMap.get( foodArray[i] ) ); } System.out.println("\n\n\nMap 2:"); Map<Integer, TreeSet<String>> foodMap2 = map2(); Object[] foodArray2 = foodMap2.keySet().toArray(); for ( int i = 0; i < foodMap2.keySet().size(); i++ ) { System.out.println( foodArray2[i] + ": " + foodMap2.get( foodArray2[i] ) ); } } public static Map<String, Integer> map1() { ArrayList<String> foods = getFoods(); Map<String, Integer> foodMap = new TreeMap<>(); for ( int i = 0; i < foods.size(); i++ ) { if ( foodMap.get( foods.get( i ) ) != null ) { foodMap.put( foods.get( i ), foodMap.get( foods.get( i ) ) + 1 ); } foodMap.putIfAbsent( foods.get( i ), 1 ); } return foodMap; } public static Map<Integer, TreeSet<String>> map2() { Map<String, Integer> foodMap = map1(); Map<Integer, TreeSet<String>> newFoodMap = new TreeMap<>(); ArrayList<String> foods = getFoods(); Set<String> nonRepetFoods = new LinkedHashSet<>( foods ); foods = new ArrayList<>( nonRepetFoods ); for ( int i = 0; i < foodMap.keySet().size(); i++ ) { if ( newFoodMap.get( foodMap.get( foods.get( i ) ) ) != null ) { newFoodMap.get( foodMap.get( foods.get( i ) ) ).add( foods.get( i ) ); newFoodMap.put( foodMap.get( foods.get( i ) ), newFoodMap.get( foodMap.get( foods.get( i ) ) ) ); } TreeSet<String> foodsForScore = new TreeSet<>(); foodsForScore.add( foods.get( i ) ); newFoodMap.putIfAbsent( foodMap.get( foods.get( i ) ), foodsForScore ); } return newFoodMap; } public static ArrayList<String> getFoods() { ArrayList<String> foods = new ArrayList<>(); File f = new File( "Foods.txt" ); try { Scanner sc = new Scanner( f ); while ( sc.hasNext() ) { foods.add( sc.nextLine() ); } return foods; } catch ( FileNotFoundException e ) { System.out.println( "No file bro" ); } return null; } }
2,912
0.549451
0.542582
82
34.524391
26.127373
114
false
false
0
0
0
0
0
0
0.756098
false
false
3
c56613dcb40ca9650e7a71780d5a43b0049c464a
39,453,569,582,561
5cb666b24f3abf90f95ff7f77125065de1052f6f
/app/src/main/java/ru/pks/beatystyle/ItemViewActivity.java
e9879a2c59d3bf72ab5433154c0d1ecccbaec4ba
[]
no_license
KirillNN/BeatyStyle
https://github.com/KirillNN/BeatyStyle
a657be8322fb08ad8f9814f2d4f319ba23705d66
de3f76c2724e9a73d03aa66d830e7671d27b04cd
refs/heads/master
2018-11-05T07:23:49.098000
2018-09-25T17:17:43
2018-09-25T17:17:43
117,264,229
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.pks.beatystyle; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class ItemViewActivity extends AppCompatActivity implements ItemViewFragment.NomenclatureListListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_view); } @Override public void itemClicked(long id) { TopActivity.itemType = (int) id; Intent intent = new Intent(this, ItemDetailActivity.class); startActivity(intent); } }
UTF-8
Java
597
java
ItemViewActivity.java
Java
[]
null
[]
package ru.pks.beatystyle; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class ItemViewActivity extends AppCompatActivity implements ItemViewFragment.NomenclatureListListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_view); } @Override public void itemClicked(long id) { TopActivity.itemType = (int) id; Intent intent = new Intent(this, ItemDetailActivity.class); startActivity(intent); } }
597
0.768844
0.767169
24
23.875
22.011951
66
false
false
0
0
0
0
0
0
0.416667
false
false
3
e67d5872ee0c5ba625a1b1017939cd577ba759d3
5,403,068,925,205
e3ee65e4f0fa745ed58630943869238e1d6e0eff
/app/src/main/java/org/desperu/go4lunch/viewmodel/MessageViewModel.java
96e95b9585dd682b2f09a0dd81987f5521bc8e02
[]
no_license
desperu/Go4Lunch
https://github.com/desperu/Go4Lunch
fed06fe9f1f0d8ae2620f3a15c53999261cb5924
19085bd3158629c4a3a2c4f4daa7f30bcaf44445
refs/heads/master
2020-09-13T05:53:01.848000
2020-01-23T13:54:13
2020-01-23T13:54:13
222,671,798
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.desperu.go4lunch.viewmodel; import android.app.Application; import android.content.Context; import android.net.Uri; import android.util.TypedValue; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import androidx.cardview.widget.CardView; import androidx.databinding.BindingAdapter; import androidx.databinding.ObservableBoolean; import androidx.databinding.ObservableField; import androidx.databinding.ObservableInt; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.Query; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import org.desperu.go4lunch.R; import org.desperu.go4lunch.api.firestore.MessageHelper; import org.desperu.go4lunch.models.Message; import org.desperu.go4lunch.models.User; import org.desperu.go4lunch.utils.Go4LunchUtils; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.util.Date; import java.util.List; import java.util.UUID; public class MessageViewModel extends AndroidViewModel { // FOR DATA private MutableLiveData<List<Message>> allMessageList = new MutableLiveData<>(); private ObservableBoolean isCurrentUser = new ObservableBoolean(); private ObservableField<String> textMessage = new ObservableField<>(); private ObservableInt textAlignment = new ObservableInt(); private ObservableInt messageTextState = new ObservableInt(); private ObservableField<String> dateMessage = new ObservableField<>(); private ObservableField<String> userSenderName = new ObservableField<>(); private ObservableField<String> senderUrlPicture = new ObservableField<>(); private ObservableField<String> messageUrlPicture = new ObservableField<>(); private ObservableInt messageImageState = new ObservableInt(); // CONSTRUCTORS public MessageViewModel(Application application) { super(application); } public MessageViewModel(Application application, Message message, String currentUserId) { super(application); this.setMessageData(message, currentUserId); this.setProfileUserSender(message); this.setMessageImageUrl(message); } // -------------- // REQUEST // -------------- /** * Create message for chat. * @param message Text message. * @param userSender User sender. */ public void createMessage(String message, User userSender) { MessageHelper.createMessageForChat(message, userSender) .addOnFailureListener(this.onFailureListener()); } /** * Upload a picture in Firebase and send a message. * @param uriImageSelected Uri of selected image from phone storage. * @param message Text message. * @param currentUser User object of current user. */ public void uploadPhotoInFirebaseAndSendMessage(Uri uriImageSelected, String message, User currentUser) { String uuid = UUID.randomUUID().toString(); // GENERATE UNIQUE STRING // UPLOAD TO GCS StorageReference mImageRef = FirebaseStorage.getInstance().getReference(uuid); mImageRef.putFile(uriImageSelected) .addOnSuccessListener(taskSnapshot -> { Task<Uri> firebaseUri = taskSnapshot.getStorage().getDownloadUrl(); firebaseUri.addOnSuccessListener(uri -> { // SAVE MESSAGE IN FIRESTORE MessageHelper.createMessageWithImageForChat( uri.toString(), message, currentUser) .addOnFailureListener(onFailureListener()); }); }) .addOnFailureListener(this.onFailureListener()); } /** * Get all message for chat. * @return All messages. */ public Query getAllMessage() { return MessageHelper.getAllMessageForChat(); } /** * Get all message list for chat. */ public void getAllMessageList() { MessageHelper.getAllMessageForChat().get().addOnSuccessListener(queryDocumentSnapshots -> allMessageList.postValue(queryDocumentSnapshots.toObjects(Message.class))); } // -------------------- // ERROR HANDLER // -------------------- @NotNull @Contract(pure = true) private OnFailureListener onFailureListener(){ return e -> Toast.makeText(getApplication(), getApplication().getString(R.string.error_unknown_error), Toast.LENGTH_LONG).show(); } // -------------------- // UTILS // -------------------- /** * Get default margin, dp to pixel. * @param context Context from this method is called. * @return Pixel value. */ private static int getDefaultMargin(@NotNull Context context) { return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, context.getResources().getDimension(R.dimen.default_margin), context.getResources().getDisplayMetrics()) / 2.5); } /** * Get margin bottom message container, dp to pixel. * @param context Context from this method is called. * @return Pixel value. */ private static int getMarginBottom(@NotNull Context context) { return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, context.getResources().getDimension(R.dimen.fragment_chat_message_item_container_text_and_image_message_container_margin_bottom), context.getResources().getDisplayMetrics()) / 2.5); } // --- SETTERS --- /** * Set message data. * @param message Message object. * @param currentUserId Current user Id. */ private void setMessageData(@NotNull Message message, String currentUserId) { // Check if current user is the sender this.isCurrentUser.set(message.getUserSender().getUid().equals(currentUserId)); // Set text and alignment message this.textMessage.set(message.getMessage()); this.textAlignment.set(isCurrentUser.get() ? View.TEXT_ALIGNMENT_TEXT_END : View.TEXT_ALIGNMENT_TEXT_START); // Set message visibility this.messageTextState.set(message.getMessage() == null ? View.GONE : View.VISIBLE); // Set date message if (message.getDateCreated() != null) this.dateMessage.set(Go4LunchUtils.convertDateToString(message.getDateCreated(), new Date())); } /** * Set profile user sender data. * @param message Message object. */ private void setProfileUserSender(@NotNull Message message) { // Set profile sender urlPicture this.senderUrlPicture.set(message.getUserSender().getUrlPicture()); // Set user sender name this.userSenderName.set(message.getUserSender().getUserName()); } /** * Set message image data. * @param message Message object. */ private void setMessageImageUrl(@NotNull Message message) { // Set message image sent url this.messageUrlPicture.set(message.getUrlImage()); this.messageImageState.set(message.getUrlImage() != null ? View.VISIBLE : View.GONE); } // For live data test only void setAllMessageListLiveData(List<Message> allMessageList) { this.allMessageList.postValue(allMessageList); } // --- GETTERS --- public LiveData<List<Message>> getAllMessageListLiveData() { return this.allMessageList; } public ObservableBoolean getIsCurrentUser() { return isCurrentUser; } public ObservableField<String> getTextMessage() { return this.textMessage; } public ObservableInt getTextAlignment() { return this.textAlignment; } public ObservableInt getMessageTextState() { return this.messageTextState; } public ObservableField<String> getDateMessage() { return this.dateMessage; } public ObservableField<String> getUserSenderName() { return this.userSenderName; } public ObservableField<String> getSenderUrlPicture() { return this.senderUrlPicture; } public ObservableField<String> getMessageUrlPicture() { return this.messageUrlPicture; } public ObservableInt getMessageImageState() { return this.messageImageState; } @BindingAdapter("messageBackground") public static void setMessageContainerBackground(@NotNull LinearLayout linear, boolean isCurrentUser) { linear.setBackground(isCurrentUser ? linear.getContext().getResources().getDrawable(R.drawable.ic_chat_message_not_sender_background) : linear.getContext().getResources().getDrawable(R.drawable.ic_chat_message_sender_background)); } @BindingAdapter("senderPicture") public static void setProfileImage(@NotNull ImageView imageView, String url) { Glide.with(imageView.getContext()).load(url != null && !url.isEmpty() ? url : R.drawable.ic_anon_user_48dp).circleCrop().into(imageView); } @BindingAdapter("messagePicture") public static void setMessageImage(@NotNull ImageView imageView, String url) { Glide.with(imageView.getContext()).load(url).into(imageView); } @BindingAdapter("linearAlignParent") public static void setProfileContainerAlignment(@NotNull LinearLayout linearLayout, boolean isCurrentUser) { RelativeLayout.LayoutParams paramsLayoutHeader = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); paramsLayoutHeader.addRule(isCurrentUser ? RelativeLayout.ALIGN_PARENT_END : RelativeLayout.ALIGN_PARENT_START); linearLayout.setLayoutParams(paramsLayoutHeader); } @BindingAdapter("relativeAlignOf") public static void setMessageContainerAlignment(@NotNull RelativeLayout relativeLayout, boolean isCurrentUser) { RelativeLayout.LayoutParams paramsLayoutContent = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); paramsLayoutContent.addRule(isCurrentUser ? RelativeLayout.START_OF : RelativeLayout.END_OF, R.id.fragment_chat_message_item_profile_container); paramsLayoutContent.addRule(RelativeLayout.ALIGN_PARENT_TOP, R.id.fragment_chat_message_item_root_view); relativeLayout.setLayoutParams(paramsLayoutContent); } @BindingAdapter("linearAlignment") public static void setTextMessageContainerAlignment(@NotNull LinearLayout linearLayout, boolean isCurrentUser) { RelativeLayout.LayoutParams paramsLayoutMessage = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); paramsLayoutMessage.addRule(isCurrentUser ? RelativeLayout.ALIGN_PARENT_END : RelativeLayout.ALIGN_PARENT_START, R.id.fragment_chat_message_item_message_container); paramsLayoutMessage.addRule(RelativeLayout.BELOW, R.id.fragment_chat_message_item_container_image_sent_cardview); paramsLayoutMessage.setMargins(getDefaultMargin(linearLayout.getContext()), 0, getDefaultMargin(linearLayout.getContext()), getMarginBottom(linearLayout.getContext())); linearLayout.setLayoutParams(paramsLayoutMessage); } @BindingAdapter("cardViewAlignTo") public static void setImageContainerAlignment(@NotNull CardView cardView, boolean isCurrentUser) { RelativeLayout.LayoutParams paramsImageView = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); paramsImageView.addRule(isCurrentUser ? RelativeLayout.ALIGN_PARENT_END : RelativeLayout.ALIGN_PARENT_START, R.id.fragment_chat_message_item_message_container); paramsImageView.setMargins(getDefaultMargin(cardView.getContext()), 0, getDefaultMargin(cardView.getContext()), getMarginBottom(cardView.getContext())); cardView.setLayoutParams(paramsImageView); } @BindingAdapter("textAlignment") public static void setDateMessageTextAlignment(@NotNull TextView textView, boolean isCurrentUser) { textView.setTextAlignment(isCurrentUser ? View.TEXT_ALIGNMENT_TEXT_END : View.TEXT_ALIGNMENT_TEXT_START); } }
UTF-8
Java
12,638
java
MessageViewModel.java
Java
[]
null
[]
package org.desperu.go4lunch.viewmodel; import android.app.Application; import android.content.Context; import android.net.Uri; import android.util.TypedValue; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import androidx.cardview.widget.CardView; import androidx.databinding.BindingAdapter; import androidx.databinding.ObservableBoolean; import androidx.databinding.ObservableField; import androidx.databinding.ObservableInt; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.Query; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import org.desperu.go4lunch.R; import org.desperu.go4lunch.api.firestore.MessageHelper; import org.desperu.go4lunch.models.Message; import org.desperu.go4lunch.models.User; import org.desperu.go4lunch.utils.Go4LunchUtils; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.util.Date; import java.util.List; import java.util.UUID; public class MessageViewModel extends AndroidViewModel { // FOR DATA private MutableLiveData<List<Message>> allMessageList = new MutableLiveData<>(); private ObservableBoolean isCurrentUser = new ObservableBoolean(); private ObservableField<String> textMessage = new ObservableField<>(); private ObservableInt textAlignment = new ObservableInt(); private ObservableInt messageTextState = new ObservableInt(); private ObservableField<String> dateMessage = new ObservableField<>(); private ObservableField<String> userSenderName = new ObservableField<>(); private ObservableField<String> senderUrlPicture = new ObservableField<>(); private ObservableField<String> messageUrlPicture = new ObservableField<>(); private ObservableInt messageImageState = new ObservableInt(); // CONSTRUCTORS public MessageViewModel(Application application) { super(application); } public MessageViewModel(Application application, Message message, String currentUserId) { super(application); this.setMessageData(message, currentUserId); this.setProfileUserSender(message); this.setMessageImageUrl(message); } // -------------- // REQUEST // -------------- /** * Create message for chat. * @param message Text message. * @param userSender User sender. */ public void createMessage(String message, User userSender) { MessageHelper.createMessageForChat(message, userSender) .addOnFailureListener(this.onFailureListener()); } /** * Upload a picture in Firebase and send a message. * @param uriImageSelected Uri of selected image from phone storage. * @param message Text message. * @param currentUser User object of current user. */ public void uploadPhotoInFirebaseAndSendMessage(Uri uriImageSelected, String message, User currentUser) { String uuid = UUID.randomUUID().toString(); // GENERATE UNIQUE STRING // UPLOAD TO GCS StorageReference mImageRef = FirebaseStorage.getInstance().getReference(uuid); mImageRef.putFile(uriImageSelected) .addOnSuccessListener(taskSnapshot -> { Task<Uri> firebaseUri = taskSnapshot.getStorage().getDownloadUrl(); firebaseUri.addOnSuccessListener(uri -> { // SAVE MESSAGE IN FIRESTORE MessageHelper.createMessageWithImageForChat( uri.toString(), message, currentUser) .addOnFailureListener(onFailureListener()); }); }) .addOnFailureListener(this.onFailureListener()); } /** * Get all message for chat. * @return All messages. */ public Query getAllMessage() { return MessageHelper.getAllMessageForChat(); } /** * Get all message list for chat. */ public void getAllMessageList() { MessageHelper.getAllMessageForChat().get().addOnSuccessListener(queryDocumentSnapshots -> allMessageList.postValue(queryDocumentSnapshots.toObjects(Message.class))); } // -------------------- // ERROR HANDLER // -------------------- @NotNull @Contract(pure = true) private OnFailureListener onFailureListener(){ return e -> Toast.makeText(getApplication(), getApplication().getString(R.string.error_unknown_error), Toast.LENGTH_LONG).show(); } // -------------------- // UTILS // -------------------- /** * Get default margin, dp to pixel. * @param context Context from this method is called. * @return Pixel value. */ private static int getDefaultMargin(@NotNull Context context) { return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, context.getResources().getDimension(R.dimen.default_margin), context.getResources().getDisplayMetrics()) / 2.5); } /** * Get margin bottom message container, dp to pixel. * @param context Context from this method is called. * @return Pixel value. */ private static int getMarginBottom(@NotNull Context context) { return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, context.getResources().getDimension(R.dimen.fragment_chat_message_item_container_text_and_image_message_container_margin_bottom), context.getResources().getDisplayMetrics()) / 2.5); } // --- SETTERS --- /** * Set message data. * @param message Message object. * @param currentUserId Current user Id. */ private void setMessageData(@NotNull Message message, String currentUserId) { // Check if current user is the sender this.isCurrentUser.set(message.getUserSender().getUid().equals(currentUserId)); // Set text and alignment message this.textMessage.set(message.getMessage()); this.textAlignment.set(isCurrentUser.get() ? View.TEXT_ALIGNMENT_TEXT_END : View.TEXT_ALIGNMENT_TEXT_START); // Set message visibility this.messageTextState.set(message.getMessage() == null ? View.GONE : View.VISIBLE); // Set date message if (message.getDateCreated() != null) this.dateMessage.set(Go4LunchUtils.convertDateToString(message.getDateCreated(), new Date())); } /** * Set profile user sender data. * @param message Message object. */ private void setProfileUserSender(@NotNull Message message) { // Set profile sender urlPicture this.senderUrlPicture.set(message.getUserSender().getUrlPicture()); // Set user sender name this.userSenderName.set(message.getUserSender().getUserName()); } /** * Set message image data. * @param message Message object. */ private void setMessageImageUrl(@NotNull Message message) { // Set message image sent url this.messageUrlPicture.set(message.getUrlImage()); this.messageImageState.set(message.getUrlImage() != null ? View.VISIBLE : View.GONE); } // For live data test only void setAllMessageListLiveData(List<Message> allMessageList) { this.allMessageList.postValue(allMessageList); } // --- GETTERS --- public LiveData<List<Message>> getAllMessageListLiveData() { return this.allMessageList; } public ObservableBoolean getIsCurrentUser() { return isCurrentUser; } public ObservableField<String> getTextMessage() { return this.textMessage; } public ObservableInt getTextAlignment() { return this.textAlignment; } public ObservableInt getMessageTextState() { return this.messageTextState; } public ObservableField<String> getDateMessage() { return this.dateMessage; } public ObservableField<String> getUserSenderName() { return this.userSenderName; } public ObservableField<String> getSenderUrlPicture() { return this.senderUrlPicture; } public ObservableField<String> getMessageUrlPicture() { return this.messageUrlPicture; } public ObservableInt getMessageImageState() { return this.messageImageState; } @BindingAdapter("messageBackground") public static void setMessageContainerBackground(@NotNull LinearLayout linear, boolean isCurrentUser) { linear.setBackground(isCurrentUser ? linear.getContext().getResources().getDrawable(R.drawable.ic_chat_message_not_sender_background) : linear.getContext().getResources().getDrawable(R.drawable.ic_chat_message_sender_background)); } @BindingAdapter("senderPicture") public static void setProfileImage(@NotNull ImageView imageView, String url) { Glide.with(imageView.getContext()).load(url != null && !url.isEmpty() ? url : R.drawable.ic_anon_user_48dp).circleCrop().into(imageView); } @BindingAdapter("messagePicture") public static void setMessageImage(@NotNull ImageView imageView, String url) { Glide.with(imageView.getContext()).load(url).into(imageView); } @BindingAdapter("linearAlignParent") public static void setProfileContainerAlignment(@NotNull LinearLayout linearLayout, boolean isCurrentUser) { RelativeLayout.LayoutParams paramsLayoutHeader = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); paramsLayoutHeader.addRule(isCurrentUser ? RelativeLayout.ALIGN_PARENT_END : RelativeLayout.ALIGN_PARENT_START); linearLayout.setLayoutParams(paramsLayoutHeader); } @BindingAdapter("relativeAlignOf") public static void setMessageContainerAlignment(@NotNull RelativeLayout relativeLayout, boolean isCurrentUser) { RelativeLayout.LayoutParams paramsLayoutContent = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); paramsLayoutContent.addRule(isCurrentUser ? RelativeLayout.START_OF : RelativeLayout.END_OF, R.id.fragment_chat_message_item_profile_container); paramsLayoutContent.addRule(RelativeLayout.ALIGN_PARENT_TOP, R.id.fragment_chat_message_item_root_view); relativeLayout.setLayoutParams(paramsLayoutContent); } @BindingAdapter("linearAlignment") public static void setTextMessageContainerAlignment(@NotNull LinearLayout linearLayout, boolean isCurrentUser) { RelativeLayout.LayoutParams paramsLayoutMessage = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); paramsLayoutMessage.addRule(isCurrentUser ? RelativeLayout.ALIGN_PARENT_END : RelativeLayout.ALIGN_PARENT_START, R.id.fragment_chat_message_item_message_container); paramsLayoutMessage.addRule(RelativeLayout.BELOW, R.id.fragment_chat_message_item_container_image_sent_cardview); paramsLayoutMessage.setMargins(getDefaultMargin(linearLayout.getContext()), 0, getDefaultMargin(linearLayout.getContext()), getMarginBottom(linearLayout.getContext())); linearLayout.setLayoutParams(paramsLayoutMessage); } @BindingAdapter("cardViewAlignTo") public static void setImageContainerAlignment(@NotNull CardView cardView, boolean isCurrentUser) { RelativeLayout.LayoutParams paramsImageView = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); paramsImageView.addRule(isCurrentUser ? RelativeLayout.ALIGN_PARENT_END : RelativeLayout.ALIGN_PARENT_START, R.id.fragment_chat_message_item_message_container); paramsImageView.setMargins(getDefaultMargin(cardView.getContext()), 0, getDefaultMargin(cardView.getContext()), getMarginBottom(cardView.getContext())); cardView.setLayoutParams(paramsImageView); } @BindingAdapter("textAlignment") public static void setDateMessageTextAlignment(@NotNull TextView textView, boolean isCurrentUser) { textView.setTextAlignment(isCurrentUser ? View.TEXT_ALIGNMENT_TEXT_END : View.TEXT_ALIGNMENT_TEXT_START); } }
12,638
0.708815
0.707549
286
43.192307
35.814228
145
false
false
0
0
0
0
0
0
0.503497
false
false
3
e236f9be72c06e97a9749777c7d3776c0e12a50c
7,730,941,189,598
e23ac3b0fda116779401f100d7a5a1e61f321bcd
/08-spring-boot-springmvc-mybatis/src/main/java/com/serendipity/service/impl/UsersServiceImpl.java
c568cac1afda11c1df0d48b5374bc17c579fc767
[]
no_license
SerendipityH/SpringBoot
https://github.com/SerendipityH/SpringBoot
385bf6cf36e344db26dd686b7c20ce12c96323e5
d2cf5803ef770c7e1dd84d9817f0c35039f72096
refs/heads/main
2021-07-14T08:45:52.412000
2021-06-02T14:03:06
2021-06-02T14:03:06
177,093,933
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.serendipity.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.serendipity.mapper.UsersMapper; import com.serendipity.pojo.Users; import com.serendipity.service.UsersService; @Service @Transactional public class UsersServiceImpl implements UsersService { @Autowired private UsersMapper usersMapper; @Override public void addUser(Users users) { // TODO Auto-generated method stub usersMapper.insertUser(users); } @Override public List<Users> findAllUsers() { return usersMapper.selectAllUsers(); } @Override public Users findUserById(Integer id) { // TODO Auto-generated method stub return usersMapper.selectUserById(id); } @Override public void updateUser(Users user) { // TODO Auto-generated method stub usersMapper.updateUser(user); } @Override public void deleteUserById(Integer id) { // TODO Auto-generated method stub usersMapper.deleteUserById(id); } }
UTF-8
Java
1,252
java
UsersServiceImpl.java
Java
[]
null
[]
package com.serendipity.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.serendipity.mapper.UsersMapper; import com.serendipity.pojo.Users; import com.serendipity.service.UsersService; @Service @Transactional public class UsersServiceImpl implements UsersService { @Autowired private UsersMapper usersMapper; @Override public void addUser(Users users) { // TODO Auto-generated method stub usersMapper.insertUser(users); } @Override public List<Users> findAllUsers() { return usersMapper.selectAllUsers(); } @Override public Users findUserById(Integer id) { // TODO Auto-generated method stub return usersMapper.selectUserById(id); } @Override public void updateUser(Users user) { // TODO Auto-generated method stub usersMapper.updateUser(user); } @Override public void deleteUserById(Integer id) { // TODO Auto-generated method stub usersMapper.deleteUserById(id); } }
1,252
0.682109
0.682109
50
23.040001
19.861481
64
false
false
0
0
0
0
0
0
0.28
false
false
3
f77669356efe07a43000da20253c0a60d7b12421
4,054,449,137,214
cc5798c4e32a26422c719747ae6b4ef3a425aeac
/app/src/main/java/Adapters/UserViewAdapter.java
d9e36e00eef999e16f6feeb1df5d6aae1c517d59
[]
no_license
dushyanthkandiah/QuikDelAdmin
https://github.com/dushyanthkandiah/QuikDelAdmin
5f212ce2ddec1fe5f94a7a5df643996d3ec0087c
4938de336ffc25e6d04cb8bcd25c983df9fae11c
refs/heads/master
2020-04-13T00:08:18.403000
2018-12-24T10:42:54
2018-12-24T10:42:54
162,838,571
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Adapters; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.view.GravityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.dushyanth.quikdeladmin.HomeActivity; import com.example.dushyanth.quikdeladmin.ProfileActivity; import com.example.dushyanth.quikdeladmin.R; import com.example.dushyanth.quikdeladmin.UserActivity; import java.util.ArrayList; import Fragments.FragmentUsers; import Models.ClassUsers; import OtherClasses.SessionData; import OtherClasses.ShowDialog; import OtherClasses.Utils; @RequiresApi(api = Build.VERSION_CODES.N) @SuppressLint("NewApi") public class UserViewAdapter extends RecyclerView.Adapter<UserViewAdapter.VHolder> { private ArrayList<ClassUsers> data; private FragmentUsers fragmentUsers; public UserViewAdapter(ArrayList<ClassUsers> data, FragmentUsers fragmentUsers) { this.data = data; this.fragmentUsers = fragmentUsers; } @NonNull @Override public VHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(fragmentUsers.getActivity()); View view = inflater.inflate(R.layout.rcyvw_users, parent, false); return new VHolder(view); } @Override public void onBindViewHolder(@NonNull final VHolder holder, final int position) { holder.lblName.setText(data.get(position).getName()); holder.lblEmail.setText(data.get(position).getEmail() + ""); holder.lblPhone.setText(data.get(position).getPhone() + ""); holder.imgProfilePicture.setImageBitmap(Utils.getImage(data.get(position).getPicture())); if (data.get(position).getStatus().equals("deactive")) { holder.imgEnableDisable.setImageDrawable(fragmentUsers.getResources().getDrawable(R.drawable.eye_disable)); } else holder.imgEnableDisable.setImageDrawable(fragmentUsers.getResources().getDrawable(R.drawable.eye_enable)); holder.imgEnableDisable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragmentUsers.serverUsers.enableDisableCustomer(fragmentUsers, data.get(position).getId(), holder.imgEnableDisable); } }); holder.imgDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(fragmentUsers.getActivity()).setTitle("Account Deletion Confirmation") .setMessage("Are you sure you wan't to delete "+ data.get(position).getName() +"'s account?") .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { fragmentUsers.serverUsers.deleteUser(fragmentUsers, data.get(position).getId(), data.get(position).getName()); dialog.dismiss(); } }).setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); } }); holder.cardClick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SessionData.selectedUserId = data.get(position).getId(); Intent intent = new Intent(fragmentUsers.homeActivity, UserActivity.class); intent.putExtra("clickedType", "update"); fragmentUsers.homeActivity.startActivityForResult(intent, 106); fragmentUsers.homeActivity.overridePendingTransition(R.anim.animation_enter, R.anim.animation_leave); } }); if (!"adm".equals(SessionData.designation)){ holder.imgDelete.setVisibility(View.INVISIBLE); holder.imgEnableDisable.setVisibility(View.INVISIBLE); } } @Override public int getItemCount() { return data.size(); } public class VHolder extends RecyclerView.ViewHolder { TextView lblName, lblEmail, lblGender, lblPhone; CardView cardClick; ImageView imgProfilePicture, imgEnableDisable, imgDelete; public VHolder(View itemView) { super(itemView); lblName = itemView.findViewById(R.id.lblName); lblEmail = itemView.findViewById(R.id.lblEmail); lblGender = itemView.findViewById(R.id.lblGender); lblPhone = itemView.findViewById(R.id.lblPhone); imgProfilePicture = itemView.findViewById(R.id.imgProfilePicture); imgEnableDisable = itemView.findViewById(R.id.imgEnableDisable); cardClick = itemView.findViewById(R.id.cardClick); imgDelete = itemView.findViewById(R.id.imgDelete); } } }
UTF-8
Java
5,602
java
UserViewAdapter.java
Java
[]
null
[]
package Adapters; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.view.GravityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.dushyanth.quikdeladmin.HomeActivity; import com.example.dushyanth.quikdeladmin.ProfileActivity; import com.example.dushyanth.quikdeladmin.R; import com.example.dushyanth.quikdeladmin.UserActivity; import java.util.ArrayList; import Fragments.FragmentUsers; import Models.ClassUsers; import OtherClasses.SessionData; import OtherClasses.ShowDialog; import OtherClasses.Utils; @RequiresApi(api = Build.VERSION_CODES.N) @SuppressLint("NewApi") public class UserViewAdapter extends RecyclerView.Adapter<UserViewAdapter.VHolder> { private ArrayList<ClassUsers> data; private FragmentUsers fragmentUsers; public UserViewAdapter(ArrayList<ClassUsers> data, FragmentUsers fragmentUsers) { this.data = data; this.fragmentUsers = fragmentUsers; } @NonNull @Override public VHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(fragmentUsers.getActivity()); View view = inflater.inflate(R.layout.rcyvw_users, parent, false); return new VHolder(view); } @Override public void onBindViewHolder(@NonNull final VHolder holder, final int position) { holder.lblName.setText(data.get(position).getName()); holder.lblEmail.setText(data.get(position).getEmail() + ""); holder.lblPhone.setText(data.get(position).getPhone() + ""); holder.imgProfilePicture.setImageBitmap(Utils.getImage(data.get(position).getPicture())); if (data.get(position).getStatus().equals("deactive")) { holder.imgEnableDisable.setImageDrawable(fragmentUsers.getResources().getDrawable(R.drawable.eye_disable)); } else holder.imgEnableDisable.setImageDrawable(fragmentUsers.getResources().getDrawable(R.drawable.eye_enable)); holder.imgEnableDisable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragmentUsers.serverUsers.enableDisableCustomer(fragmentUsers, data.get(position).getId(), holder.imgEnableDisable); } }); holder.imgDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(fragmentUsers.getActivity()).setTitle("Account Deletion Confirmation") .setMessage("Are you sure you wan't to delete "+ data.get(position).getName() +"'s account?") .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { fragmentUsers.serverUsers.deleteUser(fragmentUsers, data.get(position).getId(), data.get(position).getName()); dialog.dismiss(); } }).setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); } }); holder.cardClick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SessionData.selectedUserId = data.get(position).getId(); Intent intent = new Intent(fragmentUsers.homeActivity, UserActivity.class); intent.putExtra("clickedType", "update"); fragmentUsers.homeActivity.startActivityForResult(intent, 106); fragmentUsers.homeActivity.overridePendingTransition(R.anim.animation_enter, R.anim.animation_leave); } }); if (!"adm".equals(SessionData.designation)){ holder.imgDelete.setVisibility(View.INVISIBLE); holder.imgEnableDisable.setVisibility(View.INVISIBLE); } } @Override public int getItemCount() { return data.size(); } public class VHolder extends RecyclerView.ViewHolder { TextView lblName, lblEmail, lblGender, lblPhone; CardView cardClick; ImageView imgProfilePicture, imgEnableDisable, imgDelete; public VHolder(View itemView) { super(itemView); lblName = itemView.findViewById(R.id.lblName); lblEmail = itemView.findViewById(R.id.lblEmail); lblGender = itemView.findViewById(R.id.lblGender); lblPhone = itemView.findViewById(R.id.lblPhone); imgProfilePicture = itemView.findViewById(R.id.imgProfilePicture); imgEnableDisable = itemView.findViewById(R.id.imgEnableDisable); cardClick = itemView.findViewById(R.id.cardClick); imgDelete = itemView.findViewById(R.id.imgDelete); } } }
5,602
0.661906
0.660657
140
39.014286
33.512894
150
false
false
0
0
0
0
0
0
0.642857
false
false
3
0a7b0f71b89f13183fef9a4847eb6421525132e9
29,042,568,921,260
30e3c91f23aaa6127ee3e520becc443701e18faa
/sources/com/p683ss/android/ugc/aweme/p1807im/sdk/utils/C35209av.java
7e31604a43f3c03848cf323cf08053e1f8880ec9
[]
no_license
jakesyl/tishtosh_source
https://github.com/jakesyl/tishtosh_source
521d4ab2bc28325519cf84422cce9c5709339b1f
c88d8f6fc6147fc08dfda6bd6d8540156278fa5d
refs/heads/master
2022-09-10T17:19:16.637000
2020-05-25T06:06:31
2020-05-25T06:06:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.p683ss.android.ugc.aweme.p1807im.sdk.utils; import com.bytedance.p702im.core.p706c.C11180b; import p2628d.p2639f.p2641b.C52711k; /* renamed from: com.ss.android.ugc.aweme.im.sdk.utils.av */ public final class C35209av { /* renamed from: a */ public static final int m79593a(C11180b bVar) { C52711k.m112240b(bVar, "$this$priorityPlus"); if (bVar.isStickTop()) { return 50; } return 0; } }
UTF-8
Java
458
java
C35209av.java
Java
[]
null
[]
package com.p683ss.android.ugc.aweme.p1807im.sdk.utils; import com.bytedance.p702im.core.p706c.C11180b; import p2628d.p2639f.p2641b.C52711k; /* renamed from: com.ss.android.ugc.aweme.im.sdk.utils.av */ public final class C35209av { /* renamed from: a */ public static final int m79593a(C11180b bVar) { C52711k.m112240b(bVar, "$this$priorityPlus"); if (bVar.isStickTop()) { return 50; } return 0; } }
458
0.655022
0.515284
16
27.625
20.462999
60
false
false
0
0
0
0
0
0
0.4375
false
false
3
61a688a27156a55bab2fadd0e98c6ff855e3c4e4
20,787,641,775,667
18db825349567321164921a1f50a56029765faa5
/src/edu/mit/compilers/codegen/Operand.java
5b46919383a20796eb928907b4f42e40dd29ea0f
[]
no_license
huangjd/6.035-sp16
https://github.com/huangjd/6.035-sp16
48a9eb02245d775b451095ff7faf953d60347b08
d696a2df8f1b854c2d4758b738b05be524c25e53
refs/heads/master
2021-01-18T17:34:12.003000
2017-02-07T22:39:49
2017-02-07T22:39:49
67,671,266
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.mit.compilers.codegen; import edu.mit.compilers.common.Util; public abstract class Operand { public enum Type { r8, r64, xmm, ymm; @Override public String toString() { switch (this) { case r8: return "[r8]"; case r64: return "[r64]"; case xmm: return "[xmm]"; case ymm: return "[ymm]"; } return ""; } } abstract public Type getType(); abstract public boolean isPointer(); @Override abstract public String toString(); boolean isReg() { return this instanceof Register; } boolean isMem() { return this instanceof Memory || this instanceof BSSObject || this instanceof StringObject; } boolean isImm() { return this instanceof Imm8 || this instanceof Imm64; } boolean isImm32() { return this instanceof Imm8 || this instanceof Imm64 && Util.isImm32(((Imm64) this).val); } boolean isImm64N32() { return this instanceof Imm64 && !Util.isImm32(((Imm64) this).val); } Register[] getInvolvedRegs() { return new Register[]{}; } @Override public abstract boolean equals(Object arg0); public String toString(Type type) { return toString(); } public Long toLong() { return null; } } class JumpTarget extends Operand { BasicBlock target; public JumpTarget(BasicBlock target) { this.target = target; } @Override public Type getType() { return Type.r64; } @Override public boolean isPointer() { return false; } @Override public String toString() { return target.label; } @Override public boolean equals(Object arg0) { return arg0 instanceof JumpTarget && ((JumpTarget) arg0).target == target; } } class Imm64 extends Operand { public final long val; public Imm64(long val) { this.val = val; } @Override public String toString() { return "$" + String.valueOf(val); } @Override public Type getType() { return Type.r64; } @Override public boolean isPointer() { return false; } @Override public boolean equals(Object arg0) { return arg0 instanceof Imm64 && ((Imm64) arg0).val == val; } @Override public Long toLong() { return val; } } class Imm8 extends Operand { public final byte val; public Imm8(byte val) { this.val = val; } public Imm8(boolean val) { this.val = val ? (byte) 1 : (byte) 0; } @Override public String toString() { return "$" + String.valueOf(val); } @Override public Type getType() { return Type.r8; } @Override public boolean isPointer() { return false; } @Override public boolean equals(Object arg0) { return arg0 instanceof Imm8 && ((Imm8) arg0).val == val; } @Override public Long toLong() { return (long) val; } } class Symbol extends Operand { String symbol; public Symbol(String s) { symbol = s; } @Override public Type getType() { return Type.r64; } @Override public String toString() { return symbol; } @Override public boolean isPointer() { return false; } @Override public boolean equals(Object arg0) { return arg0 instanceof Symbol && ((Symbol) arg0).symbol.equals(symbol); } } class Array extends Operand { Type type; long size; int id; static int counter; public Array(Type type, long size) { this.type = type; this.size = size; this.id = counter; counter++; } @Override public Type getType() { return type; } @Override public String toString() { return "A" + String.valueOf(id); } @Override public boolean isPointer() { return true; } @Override public boolean equals(Object arg0) { if (!(arg0 instanceof Array)) { return false; } Array a0 = (Array) arg0; return a0.type.equals(type) && a0.size == size && a0.id == id; } } class BSSObject extends Operand { String symbol; Type type; boolean isArray; long length; public BSSObject(String symbol, Type type) { if (type != Type.r8 && type != Type.r64) { throw new RuntimeException(); } this.symbol = symbol; this.type = type; this.isArray = false; this.length = 1; } public BSSObject(String symbol, Type type, long length) { if (type != Type.r8 && type != Type.r64) { throw new RuntimeException(); } this.symbol = symbol; this.type = type; this.isArray = true; this.length = length; } @Override public Type getType() { return type; } @Override public String toString() { return symbol; } @Override public boolean isPointer() { return isArray; } @Override public boolean equals(Object arg0) { return arg0 instanceof BSSObject && ((BSSObject) arg0).symbol.equals(symbol); } } class StringObject extends Operand { String symbol; String content; static int counter; public StringObject(String s) { // for strings symbol = ".LC" + String.valueOf(counter); content = s; counter++; } @Override public Type getType() { return Type.r64; } @Override public boolean isPointer() { return true; } @Override public String toString() { return "$" + symbol; } @Override public boolean equals(Object arg0) { return arg0 instanceof StringObject && ((StringObject) arg0).symbol.equals(symbol); } } class Memory extends Operand { Register base; Register index; int offset; BSSObject bssoffset; Type multiplier; public Memory(Register base, Register index, int offset, Type multiplier) { this.base = base; this.index = index; this.offset = offset; this.bssoffset = null; this.multiplier = multiplier; assert (multiplier == Type.r8 || multiplier == Type.r64); assert (base != null); } public Memory(Register base, int offset, Type multiplier) { this.base = base; this.index = null; this.offset = offset; this.bssoffset = null; this.multiplier = multiplier; assert (multiplier == Type.r8 || multiplier == Type.r64); assert (base != null); } public Memory(BSSObject base, Register index, Type multiplier) { this.base = null; this.index = index; this.offset = 0; this.bssoffset = base; this.multiplier = multiplier; assert (multiplier == Type.r8 || multiplier == Type.r64); } public Memory(BSSObject base, int offset, Type multiplier) { this.base = null; this.index = null; this.offset = offset; this.bssoffset = base; this.multiplier = multiplier; assert (multiplier == Type.r8 || multiplier == Type.r64); } @Override public Type getType() { return multiplier; } @Override public String toString() { String mult; switch (multiplier) { case r8: mult = "1"; break; case r64: mult = "8"; break; default: throw new RuntimeException(); } if (bssoffset!= null) { if (index != null) { return bssoffset.toString() + "(," + index.toString() + "," + mult + ")"; } else { return bssoffset.toString() + "+" + String.valueOf(offset); } } else { return (offset != 0 ? String.valueOf(offset) : "") + "(" + base.toString() + (index != null ? "," + index.toString() + "," + mult : "") + ")"; } } @Override public boolean isPointer() { return true; } @Override Register[] getInvolvedRegs() { if (base != null) { if (index != null) { return new Register[]{base, index}; } else { return new Register[]{base}; } } else { if (index != null) { return new Register[]{index}; } else { return new Register[]{}; } } } @Override public boolean equals(Object arg0) { if (!(arg0 instanceof Memory)) { return false; } Memory a0 = (Memory) arg0; return a0.base.equals(base) && (a0.index == null && index == null || a0.index.equals(index)) && a0.offset == offset && a0.multiplier.equals(multiplier); } }
UTF-8
Java
8,045
java
Operand.java
Java
[]
null
[]
package edu.mit.compilers.codegen; import edu.mit.compilers.common.Util; public abstract class Operand { public enum Type { r8, r64, xmm, ymm; @Override public String toString() { switch (this) { case r8: return "[r8]"; case r64: return "[r64]"; case xmm: return "[xmm]"; case ymm: return "[ymm]"; } return ""; } } abstract public Type getType(); abstract public boolean isPointer(); @Override abstract public String toString(); boolean isReg() { return this instanceof Register; } boolean isMem() { return this instanceof Memory || this instanceof BSSObject || this instanceof StringObject; } boolean isImm() { return this instanceof Imm8 || this instanceof Imm64; } boolean isImm32() { return this instanceof Imm8 || this instanceof Imm64 && Util.isImm32(((Imm64) this).val); } boolean isImm64N32() { return this instanceof Imm64 && !Util.isImm32(((Imm64) this).val); } Register[] getInvolvedRegs() { return new Register[]{}; } @Override public abstract boolean equals(Object arg0); public String toString(Type type) { return toString(); } public Long toLong() { return null; } } class JumpTarget extends Operand { BasicBlock target; public JumpTarget(BasicBlock target) { this.target = target; } @Override public Type getType() { return Type.r64; } @Override public boolean isPointer() { return false; } @Override public String toString() { return target.label; } @Override public boolean equals(Object arg0) { return arg0 instanceof JumpTarget && ((JumpTarget) arg0).target == target; } } class Imm64 extends Operand { public final long val; public Imm64(long val) { this.val = val; } @Override public String toString() { return "$" + String.valueOf(val); } @Override public Type getType() { return Type.r64; } @Override public boolean isPointer() { return false; } @Override public boolean equals(Object arg0) { return arg0 instanceof Imm64 && ((Imm64) arg0).val == val; } @Override public Long toLong() { return val; } } class Imm8 extends Operand { public final byte val; public Imm8(byte val) { this.val = val; } public Imm8(boolean val) { this.val = val ? (byte) 1 : (byte) 0; } @Override public String toString() { return "$" + String.valueOf(val); } @Override public Type getType() { return Type.r8; } @Override public boolean isPointer() { return false; } @Override public boolean equals(Object arg0) { return arg0 instanceof Imm8 && ((Imm8) arg0).val == val; } @Override public Long toLong() { return (long) val; } } class Symbol extends Operand { String symbol; public Symbol(String s) { symbol = s; } @Override public Type getType() { return Type.r64; } @Override public String toString() { return symbol; } @Override public boolean isPointer() { return false; } @Override public boolean equals(Object arg0) { return arg0 instanceof Symbol && ((Symbol) arg0).symbol.equals(symbol); } } class Array extends Operand { Type type; long size; int id; static int counter; public Array(Type type, long size) { this.type = type; this.size = size; this.id = counter; counter++; } @Override public Type getType() { return type; } @Override public String toString() { return "A" + String.valueOf(id); } @Override public boolean isPointer() { return true; } @Override public boolean equals(Object arg0) { if (!(arg0 instanceof Array)) { return false; } Array a0 = (Array) arg0; return a0.type.equals(type) && a0.size == size && a0.id == id; } } class BSSObject extends Operand { String symbol; Type type; boolean isArray; long length; public BSSObject(String symbol, Type type) { if (type != Type.r8 && type != Type.r64) { throw new RuntimeException(); } this.symbol = symbol; this.type = type; this.isArray = false; this.length = 1; } public BSSObject(String symbol, Type type, long length) { if (type != Type.r8 && type != Type.r64) { throw new RuntimeException(); } this.symbol = symbol; this.type = type; this.isArray = true; this.length = length; } @Override public Type getType() { return type; } @Override public String toString() { return symbol; } @Override public boolean isPointer() { return isArray; } @Override public boolean equals(Object arg0) { return arg0 instanceof BSSObject && ((BSSObject) arg0).symbol.equals(symbol); } } class StringObject extends Operand { String symbol; String content; static int counter; public StringObject(String s) { // for strings symbol = ".LC" + String.valueOf(counter); content = s; counter++; } @Override public Type getType() { return Type.r64; } @Override public boolean isPointer() { return true; } @Override public String toString() { return "$" + symbol; } @Override public boolean equals(Object arg0) { return arg0 instanceof StringObject && ((StringObject) arg0).symbol.equals(symbol); } } class Memory extends Operand { Register base; Register index; int offset; BSSObject bssoffset; Type multiplier; public Memory(Register base, Register index, int offset, Type multiplier) { this.base = base; this.index = index; this.offset = offset; this.bssoffset = null; this.multiplier = multiplier; assert (multiplier == Type.r8 || multiplier == Type.r64); assert (base != null); } public Memory(Register base, int offset, Type multiplier) { this.base = base; this.index = null; this.offset = offset; this.bssoffset = null; this.multiplier = multiplier; assert (multiplier == Type.r8 || multiplier == Type.r64); assert (base != null); } public Memory(BSSObject base, Register index, Type multiplier) { this.base = null; this.index = index; this.offset = 0; this.bssoffset = base; this.multiplier = multiplier; assert (multiplier == Type.r8 || multiplier == Type.r64); } public Memory(BSSObject base, int offset, Type multiplier) { this.base = null; this.index = null; this.offset = offset; this.bssoffset = base; this.multiplier = multiplier; assert (multiplier == Type.r8 || multiplier == Type.r64); } @Override public Type getType() { return multiplier; } @Override public String toString() { String mult; switch (multiplier) { case r8: mult = "1"; break; case r64: mult = "8"; break; default: throw new RuntimeException(); } if (bssoffset!= null) { if (index != null) { return bssoffset.toString() + "(," + index.toString() + "," + mult + ")"; } else { return bssoffset.toString() + "+" + String.valueOf(offset); } } else { return (offset != 0 ? String.valueOf(offset) : "") + "(" + base.toString() + (index != null ? "," + index.toString() + "," + mult : "") + ")"; } } @Override public boolean isPointer() { return true; } @Override Register[] getInvolvedRegs() { if (base != null) { if (index != null) { return new Register[]{base, index}; } else { return new Register[]{base}; } } else { if (index != null) { return new Register[]{index}; } else { return new Register[]{}; } } } @Override public boolean equals(Object arg0) { if (!(arg0 instanceof Memory)) { return false; } Memory a0 = (Memory) arg0; return a0.base.equals(base) && (a0.index == null && index == null || a0.index.equals(index)) && a0.offset == offset && a0.multiplier.equals(multiplier); } }
8,045
0.608701
0.594282
420
18.154762
18.581797
96
false
false
0
0
0
0
0
0
0.421429
false
false
3
0b94b1e50169d97595cc3e7268c732e4451beed4
20,787,641,774,093
96f8d42c474f8dd42ecc6811b6e555363f168d3e
/baike/sources/qsbk/app/widget/qiuyoucircle/n.java
4eee864e77e0c2a67f926a62099ac875cb9e6824
[]
no_license
aheadlcx/analyzeApk
https://github.com/aheadlcx/analyzeApk
050b261595cecc85790558a02d79739a789ae3a3
25cecc394dde4ed7d4971baf0e9504dcb7fabaca
refs/heads/master
2020-03-10T10:24:49.773000
2018-04-13T09:44:45
2018-04-13T09:44:45
129,332,351
6
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package qsbk.app.widget.qiuyoucircle; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.text.SpannableStringBuilder; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.DataSource; import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber; import com.facebook.imagepipeline.image.CloseableImage; import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; import qsbk.app.QsbkApp; import qsbk.app.adapter.ParticipateAdapter.SubscribeIcon; import qsbk.app.utils.UIHelper; import qsbk.app.widget.VerticalImageSpan; class n extends BaseBitmapDataSubscriber { final /* synthetic */ SubscribeIcon a; final /* synthetic */ BaseUserCell b; n(BaseUserCell baseUserCell, SubscribeIcon subscribeIcon) { this.b = baseUserCell; this.a = subscribeIcon; } protected void onNewResultImpl(Bitmap bitmap) { int dip2px = UIHelper.dip2px(QsbkApp.mContext, 22.0f); Drawable bitmapDrawable = new BitmapDrawable(QsbkApp.mContext.getResources(), Bitmap.createScaledBitmap(bitmap, dip2px, dip2px, false)); CharSequence spannableStringBuilder = new SpannableStringBuilder(MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + this.a.getText()); VerticalImageSpan verticalImageSpan = new VerticalImageSpan(bitmapDrawable, UIHelper.dip2px(this.b.getContext(), 9.0f), UIHelper.dip2px(this.b.getContext(), 9.0f)); verticalImageSpan.setMargin(UIHelper.dip2px(this.b.getContext(), 2.0f), UIHelper.dip2px(this.b.getContext(), 2.0f)); spannableStringBuilder.setSpan(verticalImageSpan, 0, 1, 33); this.b.auditStatusView.setText(spannableStringBuilder); } protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { } }
UTF-8
Java
1,861
java
n.java
Java
[]
null
[]
package qsbk.app.widget.qiuyoucircle; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.text.SpannableStringBuilder; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.DataSource; import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber; import com.facebook.imagepipeline.image.CloseableImage; import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; import qsbk.app.QsbkApp; import qsbk.app.adapter.ParticipateAdapter.SubscribeIcon; import qsbk.app.utils.UIHelper; import qsbk.app.widget.VerticalImageSpan; class n extends BaseBitmapDataSubscriber { final /* synthetic */ SubscribeIcon a; final /* synthetic */ BaseUserCell b; n(BaseUserCell baseUserCell, SubscribeIcon subscribeIcon) { this.b = baseUserCell; this.a = subscribeIcon; } protected void onNewResultImpl(Bitmap bitmap) { int dip2px = UIHelper.dip2px(QsbkApp.mContext, 22.0f); Drawable bitmapDrawable = new BitmapDrawable(QsbkApp.mContext.getResources(), Bitmap.createScaledBitmap(bitmap, dip2px, dip2px, false)); CharSequence spannableStringBuilder = new SpannableStringBuilder(MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + this.a.getText()); VerticalImageSpan verticalImageSpan = new VerticalImageSpan(bitmapDrawable, UIHelper.dip2px(this.b.getContext(), 9.0f), UIHelper.dip2px(this.b.getContext(), 9.0f)); verticalImageSpan.setMargin(UIHelper.dip2px(this.b.getContext(), 2.0f), UIHelper.dip2px(this.b.getContext(), 2.0f)); spannableStringBuilder.setSpan(verticalImageSpan, 0, 1, 33); this.b.auditStatusView.setText(spannableStringBuilder); } protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { } }
1,861
0.780763
0.768404
38
47.973682
41.276657
172
false
false
0
0
0
0
0
0
1.078947
false
false
3
7c4da0f86ba96251fa44a5109f70188cceaa3ffe
25,177,098,305,199
13a2778e504bebfcd78e980efbedf90f888fe8fc
/freerapid-plugins/branches/tong2shot/src/projectfreeupload/cz/vity/freerapid/plugins/services/projectfreeupload/ProjectFreeUploadServiceImpl.java
41cffbaf012949a9c1dc92f89a6a088b498454c9
[]
no_license
zc0nf/freerapid
https://github.com/zc0nf/freerapid
4c57cb8670c96799d7606076a34841214220119d
4004e804fe456ae2b4551cd831a3fa8214a456cd
refs/heads/master
2020-09-02T13:23:40.791000
2019-10-09T22:17:29
2019-10-09T22:17:29
219,230,060
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.vity.freerapid.plugins.services.projectfreeupload; import cz.vity.freerapid.plugins.services.xfilesharing.XFileSharingServiceImpl; import cz.vity.freerapid.plugins.webclient.interfaces.PluginRunner; /** * Class that provides basic info about plugin * * @author birchie */ public class ProjectFreeUploadServiceImpl extends XFileSharingServiceImpl { @Override public String getServiceTitle() { return "Project-Free-Upload"; } @Override public String getName() { return "project-free-upload.com"; } @Override protected PluginRunner getPluginRunnerInstance() { return new ProjectFreeUploadFileRunner(); } }
UTF-8
Java
710
java
ProjectFreeUploadServiceImpl.java
Java
[ { "context": "t provides basic info about plugin\r\n *\r\n * @author birchie\r\n */\r\npublic class ProjectFreeUploadServiceImpl e", "end": 292, "score": 0.9993464350700378, "start": 285, "tag": "USERNAME", "value": "birchie" } ]
null
[]
package cz.vity.freerapid.plugins.services.projectfreeupload; import cz.vity.freerapid.plugins.services.xfilesharing.XFileSharingServiceImpl; import cz.vity.freerapid.plugins.webclient.interfaces.PluginRunner; /** * Class that provides basic info about plugin * * @author birchie */ public class ProjectFreeUploadServiceImpl extends XFileSharingServiceImpl { @Override public String getServiceTitle() { return "Project-Free-Upload"; } @Override public String getName() { return "project-free-upload.com"; } @Override protected PluginRunner getPluginRunnerInstance() { return new ProjectFreeUploadFileRunner(); } }
710
0.707042
0.707042
28
23.428572
25.585192
79
false
false
0
0
0
0
0
0
0.214286
false
false
3
c546bc13879e35f36afa1d77f593cf423159c049
13,443,247,645,350
6235d3b43a49a6d7fea4344300874e8e6853f020
/src/main/java/com/bytedance/android/livesdk/live/provider/b.java
a2b0ece66ad052874fa6f42344e031cec1462927
[]
no_license
junges521/src_awe
https://github.com/junges521/src_awe
a12bcfeb6c62bd55afba7147b83f4e3df8797019
cff4a5e230f3346f493df79744e6f2a6f20a47e2
refs/heads/master
2020-07-13T19:37:36.253000
2019-08-29T10:47:51
2019-08-29T10:47:51
205,140,726
0
0
null
true
2019-08-29T10:41:58
2019-08-29T10:41:58
2019-08-29T08:24:29
2019-08-23T11:31:27
177,015
0
0
0
null
false
false
package com.bytedance.android.livesdk.live.provider; import com.bytedance.android.livesdk.TTLiveSDKContext; import com.bytedance.android.livesdk.live.g; import com.bytedance.android.livesdk.network.ResponseInterceptor; import com.bytedance.android.livesdk.v.h; import com.bytedance.android.livesdk.v.j; import com.bytedance.frameworks.baselib.network.http.retrofit.a; import com.bytedance.frameworks.baselib.network.http.retrofit.converter.gson.GsonConverterFactory; import com.bytedance.retrofit2.CallAdapter; import com.bytedance.retrofit2.Converter; import com.bytedance.retrofit2.Retrofit; import com.bytedance.retrofit2.client.Client; import com.bytedance.retrofit2.intercept.Interceptor; import com.bytedance.retrofit2.rxjava2.adapter.RxJava2CallAdapterFactory; import com.meituan.robust.ChangeQuickRedirect; import com.meituan.robust.PatchProxy; import java.util.concurrent.Executor; import org.jetbrains.annotations.NotNull; public final class b implements h.b<Retrofit> { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f15876a; /* renamed from: b reason: collision with root package name */ com.bytedance.android.livesdkapi.host.h f15877b; @NotNull public final h.b.a<Retrofit> a(h.b.a<Retrofit> aVar) { g gVar; ResponseInterceptor responseInterceptor; h.b.a<Retrofit> aVar2 = aVar; if (PatchProxy.isSupport(new Object[]{aVar2}, this, f15876a, false, 10365, new Class[]{h.b.a.class}, h.b.a.class)) { return (h.b.a) PatchProxy.accessDispatch(new Object[]{aVar2}, this, f15876a, false, 10365, new Class[]{h.b.a.class}, h.b.a.class); } c cVar = new c(this); Retrofit.a aVar3 = new Retrofit.a(); Retrofit.a a2 = aVar3.a("https://" + TTLiveSDKContext.getLiveHostDomain()).a((Client.Provider) new d(cVar)).a((CallAdapter.Factory) RxJava2CallAdapterFactory.createAsync()); if (PatchProxy.isSupport(new Object[0], null, g.f15853a, true, 10285, new Class[0], g.class)) { gVar = (g) PatchProxy.accessDispatch(new Object[0], null, g.f15853a, true, 10285, new Class[0], g.class); } else { gVar = new g(); } Retrofit.a a3 = a2.a((Converter.Factory) gVar).a((Converter.Factory) GsonConverterFactory.create(j.q().c())); if (PatchProxy.isSupport(new Object[0], null, ResponseInterceptor.f16731a, true, 12545, new Class[0], ResponseInterceptor.class)) { responseInterceptor = (ResponseInterceptor) PatchProxy.accessDispatch(new Object[0], null, ResponseInterceptor.f16731a, true, 12545, new Class[0], ResponseInterceptor.class); } else { responseInterceptor = new ResponseInterceptor(TTLiveSDKContext.getHostService().a().a()); } return aVar2.a(a3.a((Interceptor) responseInterceptor).a((Executor) new a()).a()).a(); } }
UTF-8
Java
2,886
java
b.java
Java
[]
null
[]
package com.bytedance.android.livesdk.live.provider; import com.bytedance.android.livesdk.TTLiveSDKContext; import com.bytedance.android.livesdk.live.g; import com.bytedance.android.livesdk.network.ResponseInterceptor; import com.bytedance.android.livesdk.v.h; import com.bytedance.android.livesdk.v.j; import com.bytedance.frameworks.baselib.network.http.retrofit.a; import com.bytedance.frameworks.baselib.network.http.retrofit.converter.gson.GsonConverterFactory; import com.bytedance.retrofit2.CallAdapter; import com.bytedance.retrofit2.Converter; import com.bytedance.retrofit2.Retrofit; import com.bytedance.retrofit2.client.Client; import com.bytedance.retrofit2.intercept.Interceptor; import com.bytedance.retrofit2.rxjava2.adapter.RxJava2CallAdapterFactory; import com.meituan.robust.ChangeQuickRedirect; import com.meituan.robust.PatchProxy; import java.util.concurrent.Executor; import org.jetbrains.annotations.NotNull; public final class b implements h.b<Retrofit> { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f15876a; /* renamed from: b reason: collision with root package name */ com.bytedance.android.livesdkapi.host.h f15877b; @NotNull public final h.b.a<Retrofit> a(h.b.a<Retrofit> aVar) { g gVar; ResponseInterceptor responseInterceptor; h.b.a<Retrofit> aVar2 = aVar; if (PatchProxy.isSupport(new Object[]{aVar2}, this, f15876a, false, 10365, new Class[]{h.b.a.class}, h.b.a.class)) { return (h.b.a) PatchProxy.accessDispatch(new Object[]{aVar2}, this, f15876a, false, 10365, new Class[]{h.b.a.class}, h.b.a.class); } c cVar = new c(this); Retrofit.a aVar3 = new Retrofit.a(); Retrofit.a a2 = aVar3.a("https://" + TTLiveSDKContext.getLiveHostDomain()).a((Client.Provider) new d(cVar)).a((CallAdapter.Factory) RxJava2CallAdapterFactory.createAsync()); if (PatchProxy.isSupport(new Object[0], null, g.f15853a, true, 10285, new Class[0], g.class)) { gVar = (g) PatchProxy.accessDispatch(new Object[0], null, g.f15853a, true, 10285, new Class[0], g.class); } else { gVar = new g(); } Retrofit.a a3 = a2.a((Converter.Factory) gVar).a((Converter.Factory) GsonConverterFactory.create(j.q().c())); if (PatchProxy.isSupport(new Object[0], null, ResponseInterceptor.f16731a, true, 12545, new Class[0], ResponseInterceptor.class)) { responseInterceptor = (ResponseInterceptor) PatchProxy.accessDispatch(new Object[0], null, ResponseInterceptor.f16731a, true, 12545, new Class[0], ResponseInterceptor.class); } else { responseInterceptor = new ResponseInterceptor(TTLiveSDKContext.getHostService().a().a()); } return aVar2.a(a3.a((Interceptor) responseInterceptor).a((Executor) new a()).a()).a(); } }
2,886
0.720028
0.686417
53
53.452831
44.759552
186
false
false
0
0
0
0
0
0
1.301887
false
false
3
d9724020c9790bca4ea02cd32135acaab8e1a210
13,202,729,481,758
effcf55f48d57ca3055f2312cae55bf364502b16
/Lab3/LHIP.java
232ccb8858117985da85311bd0d90fd2a3791378
[]
no_license
atlas25git/NetworkingLabSem5
https://github.com/atlas25git/NetworkingLabSem5
ef8217af51d88d6a769f066db0110139ea110430
8a42644f46f939be7d6e9dfa1a2892db52b61b8e
refs/heads/main
2023-05-20T04:07:42.546000
2021-06-13T10:40:58
2021-06-13T10:40:58
366,012,415
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.net.*; public class LHIP { public static void main(String [] args) { try { InetAddress addr = InetAddress.getLocalHost(); System.out.println("Local Host\n"+addr.getHostName()+"\n"+addr.getHostAddress()); } catch (Exception ex) { System.err.println(ex); } } }
UTF-8
Java
344
java
LHIP.java
Java
[]
null
[]
import java.net.*; public class LHIP { public static void main(String [] args) { try { InetAddress addr = InetAddress.getLocalHost(); System.out.println("Local Host\n"+addr.getHostName()+"\n"+addr.getHostAddress()); } catch (Exception ex) { System.err.println(ex); } } }
344
0.561047
0.561047
13
25.461538
25.942585
93
false
false
0
0
0
0
0
0
0.384615
false
false
3
0bdedb44b7d7644895f8400e50656986edb7a0a1
8,521,215,129,479
701d414a41a4a9095fb2911ce0059793012d205b
/src/main/java/org/metadatacenter/artifacts/model/core/FieldUI.java
f7975d2da2eb4168a68f97f817c06f862f3eb984
[ "BSD-2-Clause" ]
permissive
metadatacenter/cedar-artifact-tools
https://github.com/metadatacenter/cedar-artifact-tools
b7c93b98c360fabdfb92c80db74d9a9a0dced613
63607a24feb622c2c5d6a628d871daf0ce666bff
refs/heads/main
2023-04-02T08:43:23.882000
2023-03-30T20:16:46
2023-03-30T20:16:46
190,095,070
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.metadatacenter.artifacts.model.core; import java.util.Optional; public class FieldUI { private final FieldInputType inputType; private final boolean valueRecommendationEnabled; private final boolean hidden; private final Optional<Boolean> timeZoneEnabled; private final Optional<TemporalGranularity> temporalGranularity; private final Optional<InputTimeFormat> inputTimeFormat; public FieldUI(FieldInputType inputType, boolean valueRecommendationEnabled, boolean hidden, Optional<Boolean> timeZoneEnabled, Optional<TemporalGranularity> temporalGranularity, Optional<InputTimeFormat> inputTimeFormat) { this.inputType = inputType; this.valueRecommendationEnabled = valueRecommendationEnabled; this.hidden = hidden; this.timeZoneEnabled = timeZoneEnabled; this.temporalGranularity = temporalGranularity; this.inputTimeFormat = inputTimeFormat; } public FieldInputType getInputType() { return inputType; } public boolean isTextField() { return inputType == FieldInputType.TEXTFIELD; } public boolean isTextarea() { return inputType == FieldInputType.TEXTAREA; } public boolean isRadio() { return inputType == FieldInputType.RADIO; } public boolean isCheckbox() { return inputType == FieldInputType.CHECKBOX; } public boolean isTemporal() { return inputType == FieldInputType.TEMPORAL; } public boolean isEmail() { return inputType == FieldInputType.EMAIL; } public boolean isList() { return inputType == FieldInputType.LIST; } public boolean isNumeric() { return inputType == FieldInputType.NUMERIC; } public boolean isPhoneNumber() { return inputType == FieldInputType.PHONE_NUMBER; } public boolean isSectionBreak() { return inputType == FieldInputType.SECTION_BREAK; } public boolean isRichText() { return inputType == FieldInputType.RICHTEXT; } public boolean isImage() { return inputType == FieldInputType.IMAGE; } public boolean isLink() { return inputType == FieldInputType.LINK; } public boolean isYouTube() { return inputType == FieldInputType.YOUTUBE; } public boolean isValueRecommendationEnabled() { return valueRecommendationEnabled; } public boolean isHidden() { return hidden; } public Optional<Boolean> getTimeZoneEnabled() { return timeZoneEnabled; } public Optional<TemporalGranularity> getTemporalGranularity() { return temporalGranularity; } public Optional<InputTimeFormat> getInputTimeFormat() { return inputTimeFormat; } @Override public String toString() { return "FieldUI{" + "inputType=" + inputType + ", valueRecommendationEnabled=" + valueRecommendationEnabled + ", hidden=" + hidden + ", timeZoneEnabled=" + timeZoneEnabled + ", temporalGranularity=" + temporalGranularity + ", inputTimeFormat=" + inputTimeFormat + '}'; } }
UTF-8
Java
2,836
java
FieldUI.java
Java
[]
null
[]
package org.metadatacenter.artifacts.model.core; import java.util.Optional; public class FieldUI { private final FieldInputType inputType; private final boolean valueRecommendationEnabled; private final boolean hidden; private final Optional<Boolean> timeZoneEnabled; private final Optional<TemporalGranularity> temporalGranularity; private final Optional<InputTimeFormat> inputTimeFormat; public FieldUI(FieldInputType inputType, boolean valueRecommendationEnabled, boolean hidden, Optional<Boolean> timeZoneEnabled, Optional<TemporalGranularity> temporalGranularity, Optional<InputTimeFormat> inputTimeFormat) { this.inputType = inputType; this.valueRecommendationEnabled = valueRecommendationEnabled; this.hidden = hidden; this.timeZoneEnabled = timeZoneEnabled; this.temporalGranularity = temporalGranularity; this.inputTimeFormat = inputTimeFormat; } public FieldInputType getInputType() { return inputType; } public boolean isTextField() { return inputType == FieldInputType.TEXTFIELD; } public boolean isTextarea() { return inputType == FieldInputType.TEXTAREA; } public boolean isRadio() { return inputType == FieldInputType.RADIO; } public boolean isCheckbox() { return inputType == FieldInputType.CHECKBOX; } public boolean isTemporal() { return inputType == FieldInputType.TEMPORAL; } public boolean isEmail() { return inputType == FieldInputType.EMAIL; } public boolean isList() { return inputType == FieldInputType.LIST; } public boolean isNumeric() { return inputType == FieldInputType.NUMERIC; } public boolean isPhoneNumber() { return inputType == FieldInputType.PHONE_NUMBER; } public boolean isSectionBreak() { return inputType == FieldInputType.SECTION_BREAK; } public boolean isRichText() { return inputType == FieldInputType.RICHTEXT; } public boolean isImage() { return inputType == FieldInputType.IMAGE; } public boolean isLink() { return inputType == FieldInputType.LINK; } public boolean isYouTube() { return inputType == FieldInputType.YOUTUBE; } public boolean isValueRecommendationEnabled() { return valueRecommendationEnabled; } public boolean isHidden() { return hidden; } public Optional<Boolean> getTimeZoneEnabled() { return timeZoneEnabled; } public Optional<TemporalGranularity> getTemporalGranularity() { return temporalGranularity; } public Optional<InputTimeFormat> getInputTimeFormat() { return inputTimeFormat; } @Override public String toString() { return "FieldUI{" + "inputType=" + inputType + ", valueRecommendationEnabled=" + valueRecommendationEnabled + ", hidden=" + hidden + ", timeZoneEnabled=" + timeZoneEnabled + ", temporalGranularity=" + temporalGranularity + ", inputTimeFormat=" + inputTimeFormat + '}'; } }
2,836
0.753526
0.753526
77
35.805195
32.683861
118
false
false
0
0
0
0
0
0
0.584416
false
false
3
976b6c8270de8dfa8fa06018bebe7f48bace194d
6,605,659,747,271
f3d9b8d46911c2c737412105d4c1c02f9d06fa4f
/Spring-boot/BookLibrary/src/main/java/com/example/spring_02/respository/BookDao.java
d30adaeebc2f77a16ca83dc37d7e93ac198a17be
[]
no_license
gunht/gunht.github.io
https://github.com/gunht/gunht.github.io
e18bacfa10b5345b3bf1148c54ca94996d244cfe
5f50590fece365bcafb86bfb342cb602cb4e7c4d
refs/heads/master
2021-03-26T01:50:08.673000
2021-03-15T06:44:39
2021-03-15T06:44:39
248,223,039
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.spring_02.respository; import com.example.spring_02.model.Book; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import lombok.SneakyThrows; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.FileReader; import java.io.Reader; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class BookDao extends DAO<Book>{ public BookDao(String csvFile) { this.readCSV(csvFile); } @Override public List<Book> getAll() { return collections; } @Override public Optional<Book> get(int id) { return collections.stream().filter(u -> u.getId() == id).findFirst(); } @SneakyThrows @Override public void readCSV(String csvFile) { try { File file = ResourceUtils.getFile("classpath:static/" + csvFile); CsvMapper mapper = new CsvMapper(); CsvSchema schema = CsvSchema.emptySchema().withHeader().withColumnSeparator('|');//nรชu ngฤƒn bแบฑng "," thรฌ bแป ฤ‘oแบกn .withColumnSeparator('|') ObjectReader objectReader = mapper.readerFor(Book.class).with(schema); Reader reader = new FileReader(file); MappingIterator<Book> store = objectReader.readValues(reader); while (store.hasNext()) { Book book = store.next(); this.add(book); } } catch (Exception e) { System.out.println(e); } } @Override public void add(Book book) { int id; if (collections.isEmpty()) { id = 1; } else { Book lastBook = collections.get(collections.size() - 1); id = lastBook.getId() + 1; } book.setId(id); collections.add(book); } @Override public void update(Book book) { get(book.getId()).ifPresent(existBook -> { existBook.setName(book.getName()); existBook.setAuthor(book.getAuthor()); existBook.setDescription(book.getDescription()); existBook.setImg(book.getImg()); }); } @Override public void delete(Book book) { deleteByID(book.getId()); } @Override public void deleteByID(int id) { get(id).ifPresent(existBook -> collections.remove(existBook)); } @Override public List<Book> searchByKeywork(String keywork) { return collections.stream().filter(book -> book.matchWithKeywork(keywork)).collect(Collectors.toList()); } }
UTF-8
Java
2,721
java
BookDao.java
Java
[]
null
[]
package com.example.spring_02.respository; import com.example.spring_02.model.Book; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import lombok.SneakyThrows; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.FileReader; import java.io.Reader; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class BookDao extends DAO<Book>{ public BookDao(String csvFile) { this.readCSV(csvFile); } @Override public List<Book> getAll() { return collections; } @Override public Optional<Book> get(int id) { return collections.stream().filter(u -> u.getId() == id).findFirst(); } @SneakyThrows @Override public void readCSV(String csvFile) { try { File file = ResourceUtils.getFile("classpath:static/" + csvFile); CsvMapper mapper = new CsvMapper(); CsvSchema schema = CsvSchema.emptySchema().withHeader().withColumnSeparator('|');//nรชu ngฤƒn bแบฑng "," thรฌ bแป ฤ‘oแบกn .withColumnSeparator('|') ObjectReader objectReader = mapper.readerFor(Book.class).with(schema); Reader reader = new FileReader(file); MappingIterator<Book> store = objectReader.readValues(reader); while (store.hasNext()) { Book book = store.next(); this.add(book); } } catch (Exception e) { System.out.println(e); } } @Override public void add(Book book) { int id; if (collections.isEmpty()) { id = 1; } else { Book lastBook = collections.get(collections.size() - 1); id = lastBook.getId() + 1; } book.setId(id); collections.add(book); } @Override public void update(Book book) { get(book.getId()).ifPresent(existBook -> { existBook.setName(book.getName()); existBook.setAuthor(book.getAuthor()); existBook.setDescription(book.getDescription()); existBook.setImg(book.getImg()); }); } @Override public void delete(Book book) { deleteByID(book.getId()); } @Override public void deleteByID(int id) { get(id).ifPresent(existBook -> collections.remove(existBook)); } @Override public List<Book> searchByKeywork(String keywork) { return collections.stream().filter(book -> book.matchWithKeywork(keywork)).collect(Collectors.toList()); } }
2,721
0.626337
0.623755
93
28.150537
26.411934
150
false
false
0
0
0
0
0
0
0.462366
false
false
3
189398c356dd0bce7ae470de57b13e91ec2fa1b7
11,965,778,905,974
0af8b92686a58eb0b64e319b22411432aca7a8f3
/large-multiproject/project42/src/main/java/org/gradle/test/performance42_2/Production42_136.java
6dee2c092d8d9346aa191bbc378ca6f22c1aee1a
[]
no_license
gradle/performance-comparisons
https://github.com/gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164000
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
false
2022-09-30T08:04:35
2017-01-26T14:25:33
2022-09-09T14:38:38
2022-09-30T08:04:34
19,731
14
13
103
null
false
false
package org.gradle.test.performance42_2; public class Production42_136 extends org.gradle.test.performance14_2.Production14_136 { private final String property; public Production42_136() { this.property = "foo"; } public String getProperty() { return property; } }
UTF-8
Java
305
java
Production42_136.java
Java
[]
null
[]
package org.gradle.test.performance42_2; public class Production42_136 extends org.gradle.test.performance14_2.Production14_136 { private final String property; public Production42_136() { this.property = "foo"; } public String getProperty() { return property; } }
305
0.681967
0.613115
14
20.785715
23.946901
88
false
false
0
0
0
0
0
0
0.285714
false
false
3
73722d4f6f3bac0b14a322866ede6f28996c5436
11,965,778,907,664
b4f647b57092a41d592b1cd5a35b63c411cae248
/src/testpackage/day4.java
ae769d409561f9ed4654875e313164c1a04290f8
[]
no_license
Himanshu8316/GITDemo
https://github.com/Himanshu8316/GITDemo
6eeac7c799cd5b8fbf85f8792717ed249b7f5559
245eba9bfa3a852040015247a7c4c6eebc81dfde
refs/heads/master
2022-09-24T12:18:19.524000
2020-06-07T12:43:49
2020-06-07T12:43:49
269,998,675
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package testpackage; import org.testng.annotations.Test; public class day4 { @Test(groups={"smoke"}) public void HomeLoanInterestcalculator() { System.out.println("HomeLoanInterestcalculator"); System.out.println("HomeLoanInterestcalculator01"); } }
UTF-8
Java
261
java
day4.java
Java
[]
null
[]
package testpackage; import org.testng.annotations.Test; public class day4 { @Test(groups={"smoke"}) public void HomeLoanInterestcalculator() { System.out.println("HomeLoanInterestcalculator"); System.out.println("HomeLoanInterestcalculator01"); } }
261
0.766284
0.754789
13
19.076923
19.475672
53
false
false
0
0
0
0
0
0
0.923077
false
false
3
93c8e9c974bdb4ece963d5a28fa54530015e64d1
3,856,880,658,781
80e10ba1fbc9114ddbb1eb9562e51fa209b12a56
/proyectoTecnicas/src/Clase/conexion_consulta.java
88005cb2c2f187ed4d35331da042676440dffee0
[]
no_license
Jorge710/ProyectoTecnicas-2018A
https://github.com/Jorge710/ProyectoTecnicas-2018A
a9df645a45d7e52b0695f7f5e113a05e573569b3
13df6402ece96706a59360c6d0aff93d73a80260
refs/heads/master
2020-03-21T16:56:40.172000
2018-08-09T11:39:20
2018-08-09T11:39:20
138,803,797
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Clase; import java.sql.*; import java.util.ArrayList; /** * * @author Jorge */ public class conexion_consulta { static Connection conexion = null; static Statement sentencia; static ResultSet resultado; static ResultSetMetaData resultadometa; public static void conectar() { String ruta = "jdbc:mysql://localhost/tallerMecanico"; String user = "root"; String pass = ""; try { Class.forName("com.mysql.jdbc.Driver"); conexion = DriverManager.getConnection(ruta, user, pass); sentencia = conexion.createStatement(); System.out.println("Conectado"); } catch (Exception e) { System.out.println("No conectado"); } } public static ArrayList<Object[]> buscar_caracter_tabla(String Nombre) { ArrayList<Object[]> datos = new ArrayList<Object[]>(); String q = "SELECT * FROM proveedor WHERE NomProv LIKE '" + Nombre + "%'"; try { resultado = sentencia.executeQuery(q); resultadometa = resultado.getMetaData(); //System.out.println("Correcto"); } catch (Exception e) { //System.out.println("No Correcto"); e.printStackTrace(); } try { while (resultado.next()) { Object[] filas = new Object[resultadometa.getColumnCount()]; for (int i = 0; i < resultadometa.getColumnCount(); i++) { filas[i] = resultado.getObject(i + 1); } datos.add(filas); } } catch (Exception e) { } return datos; } public static ArrayList<Object[]> buscar_empresa_tabla(String Nombre) { ArrayList<Object[]> datos = new ArrayList<Object[]>(); String q = "SELECT * FROM empresa WHERE NomEmpre LIKE '" + Nombre + "%'"; try { resultado = sentencia.executeQuery(q); resultadometa = resultado.getMetaData(); //System.out.println("Correcto"); } catch (Exception e) { //System.out.println("No Correcto"); e.printStackTrace(); } try { while (resultado.next()) { Object[] filas = new Object[resultadometa.getColumnCount()]; for (int i = 0; i < resultadometa.getColumnCount(); i++) { filas[i] = resultado.getObject(i + 1); } datos.add(filas); } } catch (Exception e) { } return datos; } public static ArrayList<Object[]> buscar_cliente_tabla(String Nombre) { ArrayList<Object[]> datos = new ArrayList<Object[]>(); String q = "SELECT * FROM cliente WHERE NomCli LIKE '" + Nombre + "%'"; try { resultado = sentencia.executeQuery(q); resultadometa = resultado.getMetaData(); //System.out.println("Correcto"); } catch (Exception e) { //System.out.println("No Correcto"); e.printStackTrace(); } try { while (resultado.next()) { Object[] filas = new Object[resultadometa.getColumnCount()]; for (int i = 0; i < resultadometa.getColumnCount(); i++) { filas[i] = resultado.getObject(i + 1); } datos.add(filas); } } catch (Exception e) { } return datos; } }
UTF-8
Java
3,679
java
conexion_consulta.java
Java
[ { "context": ".*;\nimport java.util.ArrayList;\n\n/**\n *\n * @author Jorge\n */\npublic class conexion_consulta {\n\n static ", "end": 272, "score": 0.9989251494407654, "start": 267, "tag": "NAME", "value": "Jorge" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Clase; import java.sql.*; import java.util.ArrayList; /** * * @author Jorge */ public class conexion_consulta { static Connection conexion = null; static Statement sentencia; static ResultSet resultado; static ResultSetMetaData resultadometa; public static void conectar() { String ruta = "jdbc:mysql://localhost/tallerMecanico"; String user = "root"; String pass = ""; try { Class.forName("com.mysql.jdbc.Driver"); conexion = DriverManager.getConnection(ruta, user, pass); sentencia = conexion.createStatement(); System.out.println("Conectado"); } catch (Exception e) { System.out.println("No conectado"); } } public static ArrayList<Object[]> buscar_caracter_tabla(String Nombre) { ArrayList<Object[]> datos = new ArrayList<Object[]>(); String q = "SELECT * FROM proveedor WHERE NomProv LIKE '" + Nombre + "%'"; try { resultado = sentencia.executeQuery(q); resultadometa = resultado.getMetaData(); //System.out.println("Correcto"); } catch (Exception e) { //System.out.println("No Correcto"); e.printStackTrace(); } try { while (resultado.next()) { Object[] filas = new Object[resultadometa.getColumnCount()]; for (int i = 0; i < resultadometa.getColumnCount(); i++) { filas[i] = resultado.getObject(i + 1); } datos.add(filas); } } catch (Exception e) { } return datos; } public static ArrayList<Object[]> buscar_empresa_tabla(String Nombre) { ArrayList<Object[]> datos = new ArrayList<Object[]>(); String q = "SELECT * FROM empresa WHERE NomEmpre LIKE '" + Nombre + "%'"; try { resultado = sentencia.executeQuery(q); resultadometa = resultado.getMetaData(); //System.out.println("Correcto"); } catch (Exception e) { //System.out.println("No Correcto"); e.printStackTrace(); } try { while (resultado.next()) { Object[] filas = new Object[resultadometa.getColumnCount()]; for (int i = 0; i < resultadometa.getColumnCount(); i++) { filas[i] = resultado.getObject(i + 1); } datos.add(filas); } } catch (Exception e) { } return datos; } public static ArrayList<Object[]> buscar_cliente_tabla(String Nombre) { ArrayList<Object[]> datos = new ArrayList<Object[]>(); String q = "SELECT * FROM cliente WHERE NomCli LIKE '" + Nombre + "%'"; try { resultado = sentencia.executeQuery(q); resultadometa = resultado.getMetaData(); //System.out.println("Correcto"); } catch (Exception e) { //System.out.println("No Correcto"); e.printStackTrace(); } try { while (resultado.next()) { Object[] filas = new Object[resultadometa.getColumnCount()]; for (int i = 0; i < resultadometa.getColumnCount(); i++) { filas[i] = resultado.getObject(i + 1); } datos.add(filas); } } catch (Exception e) { } return datos; } }
3,679
0.539005
0.537374
111
32.144146
24.608593
82
false
false
0
0
0
0
0
0
0.531532
false
false
3
405b176058ac78b2d638d39c67b0b9b332c240be
3,856,880,657,251
19cc45f9dd2da9542821df32d41712fcdf715e6a
/src/main/java/com/itheima/controller/QuickController.java
4714c428d6ef4e3315c6d7c68f2b9701a3ffddfd
[]
no_license
riffmj/springboot
https://github.com/riffmj/springboot
b46c279eddc65cb982c3ef7903a6e1f4805da119
234b7f6ce39549f52007495cb439990fa918bcff
refs/heads/master
2023-05-31T06:17:41.030000
2021-06-27T04:54:45
2021-06-27T04:54:45
380,653,039
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.itheima.controller; import com.itheima.domain.StudentInfoDO; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; @RestController public class QuickController { @RequestMapping("/hello") public ModelAndView quick(){ return new ModelAndView ("index"); } public final static String IMG_PATH_PREFIX = "static/assets/images"; public static File getImgDirFile(String imgPath){ // ๆž„ๅปบไธŠไผ ๆ–‡ไปถ็š„ๅญ˜ๆ”พ "ๆ–‡ไปถๅคน" ่ทฏๅพ„s String fileDirPath = new String("src/main/resources/" + imgPath); File fileDir = new File(fileDirPath); if(!fileDir.exists()){ // ้€’ๅฝ’็”Ÿๆˆๆ–‡ไปถๅคน fileDir.mkdirs(); } return fileDir; } //@RequestMapping("/hello2") @RequestMapping(value = "/hello2",method = RequestMethod.POST) @ResponseBody public String quick2(MultipartFile file,StudentInfoDO user) throws IOException { System.err.println("่ฎฟ้—ฎไบ†11" + user); String filePath = "D://0331//"; Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HHmmssSSS"); String dateString=sdf.format(date); if (file!=null) { String contentType = file.getContentType(); //่Žทๅ–ๆ–‡ไปถๅ String filename = file.getOriginalFilename(); String prefix = filename.substring(filename.lastIndexOf("."));//ๆ–‡ไปถๅŽ็ผ€ // ๅญ˜ๆ”พไธŠไผ ๅ›พ็‰‡็š„ๆ–‡ไปถๅคน File fileDir = getImgDirFile(IMG_PATH_PREFIX); // ่พ“ๅ‡บๆ–‡ไปถๅคน็ปๅฏน่ทฏๅพ„ -- ่ฟ™้‡Œ็š„็ปๅฏน่ทฏๅพ„ๆ˜ฏ็›ธๅฝ“ไบŽๅฝ“ๅ‰้กน็›ฎ็š„่ทฏๅพ„่€Œไธๆ˜ฏโ€œๅฎนๅ™จโ€่ทฏๅพ„ String absolutePath = fileDir.getAbsolutePath(); String seq=File.separator; //ๆ–ฐๆ–‡ไปถๅ String s = dateString; String filenas = s + prefix; //ไธŠไผ ๅˆฐ้กน็›ฎๅ†… static/assets/images File dest = new File(absolutePath +seq+filenas); file.transferTo(dest); System.out.println("ๆ–‡ไปถไธŠไผ ๆˆๅŠŸ!"); } // if (!file.isEmpty()) { // FileOutputStream out = null; // try { // File targetFile = new File(filePath); // String filename = file.getOriginalFilename(); // if (!targetFile.exists()) { // targetFile.mkdirs(); // } // out = new FileOutputStream(filePath + filename); // out.write(file.getBytes()); // out.flush(); // } catch (Exception e) { // e.printStackTrace(); // System.out.println("ๆ–‡ไปถไธŠไผ ๅคฑ่ดฅ!"); // return "ๆ–‡ไปถไธŠไผ ๅคฑ่ดฅ!"; // } finally { // out.close(); // } // // } return "ๆ‰‹ๆŒ็”จๆˆท"; } }
UTF-8
Java
3,405
java
QuickController.java
Java
[]
null
[]
package com.itheima.controller; import com.itheima.domain.StudentInfoDO; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; @RestController public class QuickController { @RequestMapping("/hello") public ModelAndView quick(){ return new ModelAndView ("index"); } public final static String IMG_PATH_PREFIX = "static/assets/images"; public static File getImgDirFile(String imgPath){ // ๆž„ๅปบไธŠไผ ๆ–‡ไปถ็š„ๅญ˜ๆ”พ "ๆ–‡ไปถๅคน" ่ทฏๅพ„s String fileDirPath = new String("src/main/resources/" + imgPath); File fileDir = new File(fileDirPath); if(!fileDir.exists()){ // ้€’ๅฝ’็”Ÿๆˆๆ–‡ไปถๅคน fileDir.mkdirs(); } return fileDir; } //@RequestMapping("/hello2") @RequestMapping(value = "/hello2",method = RequestMethod.POST) @ResponseBody public String quick2(MultipartFile file,StudentInfoDO user) throws IOException { System.err.println("่ฎฟ้—ฎไบ†11" + user); String filePath = "D://0331//"; Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HHmmssSSS"); String dateString=sdf.format(date); if (file!=null) { String contentType = file.getContentType(); //่Žทๅ–ๆ–‡ไปถๅ String filename = file.getOriginalFilename(); String prefix = filename.substring(filename.lastIndexOf("."));//ๆ–‡ไปถๅŽ็ผ€ // ๅญ˜ๆ”พไธŠไผ ๅ›พ็‰‡็š„ๆ–‡ไปถๅคน File fileDir = getImgDirFile(IMG_PATH_PREFIX); // ่พ“ๅ‡บๆ–‡ไปถๅคน็ปๅฏน่ทฏๅพ„ -- ่ฟ™้‡Œ็š„็ปๅฏน่ทฏๅพ„ๆ˜ฏ็›ธๅฝ“ไบŽๅฝ“ๅ‰้กน็›ฎ็š„่ทฏๅพ„่€Œไธๆ˜ฏโ€œๅฎนๅ™จโ€่ทฏๅพ„ String absolutePath = fileDir.getAbsolutePath(); String seq=File.separator; //ๆ–ฐๆ–‡ไปถๅ String s = dateString; String filenas = s + prefix; //ไธŠไผ ๅˆฐ้กน็›ฎๅ†… static/assets/images File dest = new File(absolutePath +seq+filenas); file.transferTo(dest); System.out.println("ๆ–‡ไปถไธŠไผ ๆˆๅŠŸ!"); } // if (!file.isEmpty()) { // FileOutputStream out = null; // try { // File targetFile = new File(filePath); // String filename = file.getOriginalFilename(); // if (!targetFile.exists()) { // targetFile.mkdirs(); // } // out = new FileOutputStream(filePath + filename); // out.write(file.getBytes()); // out.flush(); // } catch (Exception e) { // e.printStackTrace(); // System.out.println("ๆ–‡ไปถไธŠไผ ๅคฑ่ดฅ!"); // return "ๆ–‡ไปถไธŠไผ ๅคฑ่ดฅ!"; // } finally { // out.close(); // } // // } return "ๆ‰‹ๆŒ็”จๆˆท"; } }
3,405
0.600691
0.597864
93
33.225807
21.139643
84
false
false
0
0
0
0
0
0
0.55914
false
false
3
5cf5bf9c8630c5d596465150a8bdbf706d4e6a53
23,897,198,065,516
37b40af1a1f1da9f9526c1d24f2975c338bd5db3
/src/test/java/com/context/ShowData.java
67212c381d86764ccf35cbac845a415b1544e1cf
[ "Apache-2.0" ]
permissive
RanHuang/PraSMM
https://github.com/RanHuang/PraSMM
942a055826b3512e3796b3108e5de22f1901120b
83aaf3810f4f51385031e8e04f327e9b9c60f202
refs/heads/master
2022-04-28T18:43:15.438000
2019-11-17T09:31:58
2019-11-17T09:31:58
186,238,516
0
0
Apache-2.0
false
2022-04-23T01:44:37
2019-05-12T10:05:13
2019-11-17T09:32:17
2022-04-23T01:44:34
204
0
0
7
Java
false
false
package com.context; import com.alibaba.fastjson.JSON; import org.junit.After; import org.junit.Before; import java.util.List; /** * @author nick * @date 19-6-2 ๆ˜ŸๆœŸๆ—ฅ 12:12 **/ public abstract class ShowData { protected StringBuilder sb; @Before public void before() { sb = new StringBuilder(); } @After public void after() { System.out.println(sb.toString()); } public <T> void showData(String info, T data) { sb.append(info).append("\n"); sb.append(JSON.toJSONString(data)).append("\n"); } public <T> void showData(String info, List<T> lstData) { sb.append(info).append(", data size:").append(lstData.size()).append("\n"); sb.append(JSON.toJSONString(lstData)).append("\n"); } }
UTF-8
Java
787
java
ShowData.java
Java
[ { "context": "it.Before;\n\nimport java.util.List;\n\n/**\n * @author nick\n * @date 19-6-2 ๆ˜ŸๆœŸๆ—ฅ 12:12\n **/\npublic abstract cl", "end": 149, "score": 0.7745228409767151, "start": 145, "tag": "USERNAME", "value": "nick" } ]
null
[]
package com.context; import com.alibaba.fastjson.JSON; import org.junit.After; import org.junit.Before; import java.util.List; /** * @author nick * @date 19-6-2 ๆ˜ŸๆœŸๆ—ฅ 12:12 **/ public abstract class ShowData { protected StringBuilder sb; @Before public void before() { sb = new StringBuilder(); } @After public void after() { System.out.println(sb.toString()); } public <T> void showData(String info, T data) { sb.append(info).append("\n"); sb.append(JSON.toJSONString(data)).append("\n"); } public <T> void showData(String info, List<T> lstData) { sb.append(info).append(", data size:").append(lstData.size()).append("\n"); sb.append(JSON.toJSONString(lstData)).append("\n"); } }
787
0.615877
0.605634
35
21.314285
21.10487
83
false
false
0
0
0
0
0
0
0.428571
false
false
3
ed211b47f71c5e03eb88453f58564ab8cfc7362b
2,860,448,248,990
921e997f092ee13af57ee8d879f3d738b91e315f
/src/main/java/project/pageobjects/JBPMLoginPage.java
f28ca0eb3c1b95e40d92ede1d295ca7de55963f0
[]
no_license
rpradeep1/Serenity_Cucumber
https://github.com/rpradeep1/Serenity_Cucumber
873ee987d13812c37b7baf16e92440da93b79dc9
66db02025e1f8eb4582a2aaea06e0d4a35b870df
refs/heads/master
2020-03-28T13:48:21.512000
2018-09-25T07:32:18
2018-09-25T07:32:18
148,430,513
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package project.pageobjects; import java.util.concurrent.TimeUnit; import org.openqa.selenium.support.FindBy; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.core.pages.WebElementFacade; import net.thucydides.core.annotations.WhenPageOpens; import project.utilities.GenericUtils; import project.utilities.ProjectVariables; import project.utilities.SeleniumUtils; public class JBPMLoginPage extends PageObject { org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(LoginPage.class); SeleniumUtils oSeleniumUtils ; @FindBy(xpath = "//label[text()='User Name :']/../following-sibling::td//input") public WebElementFacade UserName_Txt; @FindBy(xpath = "//label[text()='Password :']/../following-sibling::td//input") public WebElementFacade Password_Txt; @FindBy(xpath = "//button[text()='Sign In']") public WebElementFacade Login_Btn; @FindBy(xpath = "//a[text()='Task Management']") public WebElementFacade JBPMHomePage; @WhenPageOpens public void LoginPageValidation() { UserName_Txt.waitUntilVisible(); } public boolean loginJBPM(String UserName) { getDriver().manage().window().maximize(); //Enter User name oSeleniumUtils.highlightElement(UserName_Txt); UserName_Txt.clear(); UserName_Txt.sendKeys(UserName); logger.info("User Name entered successfully :"+UserName); //Enter Password oSeleniumUtils.highlightElement(Password_Txt); Password_Txt.clear(); String sPassword = GenericUtils.decode(ProjectVariables.PASSWORD); Password_Txt.sendKeys(sPassword); logger.info("Password entered successfully"); oSeleniumUtils.Click_given_WebElement(Login_Btn); logger.info("Login Button clicked successfully."); return JBPMHomePage.withTimeoutOf(ProjectVariables.MIN_TIME_OUT, TimeUnit.SECONDS).waitUntilVisible().isDisplayed(); } }
UTF-8
Java
1,966
java
JBPMLoginPage.java
Java
[ { "context": "\t\tUserName_Txt.clear();\r\n\t\t\tUserName_Txt.sendKeys(UserName);\r\n\t\t\tlogger.info(\"User Name entered successfully", "end": 1363, "score": 0.7221933603286743, "start": 1355, "tag": "USERNAME", "value": "UserName" } ]
null
[]
package project.pageobjects; import java.util.concurrent.TimeUnit; import org.openqa.selenium.support.FindBy; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.core.pages.WebElementFacade; import net.thucydides.core.annotations.WhenPageOpens; import project.utilities.GenericUtils; import project.utilities.ProjectVariables; import project.utilities.SeleniumUtils; public class JBPMLoginPage extends PageObject { org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(LoginPage.class); SeleniumUtils oSeleniumUtils ; @FindBy(xpath = "//label[text()='User Name :']/../following-sibling::td//input") public WebElementFacade UserName_Txt; @FindBy(xpath = "//label[text()='Password :']/../following-sibling::td//input") public WebElementFacade Password_Txt; @FindBy(xpath = "//button[text()='Sign In']") public WebElementFacade Login_Btn; @FindBy(xpath = "//a[text()='Task Management']") public WebElementFacade JBPMHomePage; @WhenPageOpens public void LoginPageValidation() { UserName_Txt.waitUntilVisible(); } public boolean loginJBPM(String UserName) { getDriver().manage().window().maximize(); //Enter User name oSeleniumUtils.highlightElement(UserName_Txt); UserName_Txt.clear(); UserName_Txt.sendKeys(UserName); logger.info("User Name entered successfully :"+UserName); //Enter Password oSeleniumUtils.highlightElement(Password_Txt); Password_Txt.clear(); String sPassword = GenericUtils.decode(ProjectVariables.PASSWORD); Password_Txt.sendKeys(sPassword); logger.info("Password entered successfully"); oSeleniumUtils.Click_given_WebElement(Login_Btn); logger.info("Login Button clicked successfully."); return JBPMHomePage.withTimeoutOf(ProjectVariables.MIN_TIME_OUT, TimeUnit.SECONDS).waitUntilVisible().isDisplayed(); } }
1,966
0.715158
0.71414
71
25.690142
26.440788
118
false
false
0
0
0
0
0
0
1.774648
false
false
3
542c335caf6398af9a9396326760d81b1e7f2d80
5,600,637,404,764
ba0dbb748f44a73e261eec48e062f073e75f706d
/src/cz/vutbr/fit/pdb03/AnimalsDatabase.java
5bd888f8087f2a7154741a57d9996e0edc6cc9f7
[]
no_license
beny/PDB-projekt
https://github.com/beny/PDB-projekt
51d8275f0105db325558a05a53034ed7415ec910
dae3132db7cb53d70ec7c71287a3feae0766a497
refs/heads/master
2020-05-17T00:52:19.419000
2010-12-16T17:22:39
2010-12-16T17:22:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.vutbr.fit.pdb03; import java.awt.geom.Point2D; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JSplitPane; import cz.vutbr.fit.pdb03.controllers.MenuController; import cz.vutbr.fit.pdb03.controllers.WindowController; import cz.vutbr.fit.pdb03.dialogs.ConnectDialog; import cz.vutbr.fit.pdb03.dialogs.LoadingDialog; import cz.vutbr.fit.pdb03.gui.AnimalsPanel; import cz.vutbr.fit.pdb03.gui.GUIManager; import cz.vutbr.fit.pdb03.gui.JEntity; import cz.vutbr.fit.pdb03.gui.JMapPanel; import cz.vutbr.fit.pdb03.gui.PhotosPanel; /** * Hlavni trida zajistujici vykreselni hlavniho okna, rozdeleneho do tri * panelu. * * @author Ondล™ej Beneลก <xbenes00@stud.fit.vutbr.cz> * */ public class AnimalsDatabase extends JFrame { private static final long serialVersionUID = 1L; // search mody public final static int SEARCH_ALL = 0; public final static int SEARCH_BY_NAME = 1; public final static int SEARCH_BY_DESCRIPTION = 2; public final static int SEARCH_BY_PICTURE = 3; public final static int SEARCH_BY_PICTURE_DESCRIPTION = 4; public final static int SEARCH_CLOSE = 5; public final static int SEARCH_BIGGEST_AREA = 6; public final static int SEARCH_EXTINCT = 7; public final static int SEARCH_SAME_AREA = 8; public final static int SEARCH_IMAGE = 9; // komponenty jednotlivych casti hlavniho okna PhotosPanel photosPanel; JMapPanel mapPanel; AnimalsPanel animalsPanel; // map items JMapPanel map; // database items private DataBase db; // controllers MenuController menuController; // seznam zvirat private JList list; private Vector<Animal> vAnimals = new Vector<Animal>(); // pomocne promenne pro hledani private String searchGenus, searchSpecies, searchDescription, searchFilename, searchTable; private LoadingDialog dLoading = null; // druh hledani /** * Zakladni konstruktor, ktery naplni hlavni okno * @param title titulek hlavniho okna */ public AnimalsDatabase(String title) { super(title); // nastaveni vzhledu pro jednotlive systemy System.setProperty("apple.laf.useScreenMenuBar", "true"); // try { // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // } catch (Exception e) { // Log.error("Chyba pri nastaveni systemoveho vzhledu"); // } // ikona setIconImage(new ImageIcon(AnimalsDatabase.class.getResource("images/icon.png")).getImage()); // databaze db = new DataBase(); // mapa map = new JMapPanel(this); // nastaveni kontroleru new WindowController(this); menuController = new MenuController(this); // pridani rozdeleni do jednotlivych podoken photosPanel = new PhotosPanel(this); animalsPanel = new AnimalsPanel(this); mapPanel = map; // soupaci panely JSplitPane splitPaneH = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, photosPanel, animalsPanel); splitPaneH.setResizeWeight(0.5); splitPaneH.setDividerLocation(600); splitPaneH.setBorder(null); JSplitPane splitPaneV = new JSplitPane(JSplitPane.VERTICAL_SPLIT, splitPaneH, mapPanel); splitPaneV.setResizeWeight(0.3); splitPaneV.setDividerLocation(200); add(splitPaneV); // v zakladu zakaz vse co pouziva DB setEnable(false); // pokud neni pripojeni k DB, zobraz dialog if(!db.isConnected()){ javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ConnectDialog dConnect = new ConnectDialog(AnimalsDatabase.this, db); GUIManager.moveToCenter(dConnect, AnimalsDatabase.this); dConnect.setVisible(true); } }); } } /** * Hlavni main pro spusteni aplikace * @param args argumenty z prikazove radky */ public static void main(String[] args) { AnimalsDatabase aDb = new AnimalsDatabase("Databรกze zvรญล™at"); aDb.setVisible(true); } /** * Obnoveni seznamu zvirat */ public void reloadAnimalsList(final int searchType){ dLoading = new LoadingDialog("Probรญhรก hledรกnรญ v DB, prosรญm vyฤkejte"); GUIManager.moveToCenter(dLoading, this); new Thread(new Runnable() { @Override public void run() { ArrayList<Animal> dbAnimals = new ArrayList<Animal>(); Animal tempAnimal = null; map.clearMap(); photosPanel.clear(); // nalezeni zvirat try{ switch (searchType) { case SEARCH_ALL: db.searchAnimals(); break; case SEARCH_BY_NAME: db.searchAnimals(getSearchGenus(), getSearchSpecies()); break; case SEARCH_BY_DESCRIPTION: db.searchAnimals(getSearchDescription()); break; case SEARCH_BY_PICTURE: break; case SEARCH_BY_PICTURE_DESCRIPTION: db.searchAnimalsByPicture(getSearchDescription()); break; case SEARCH_BIGGEST_AREA: db.searchAnimalsByAreaSize(); break; case SEARCH_SAME_AREA: tempAnimal = getAnimalsPanel().getSelectedAnimal(); int id = tempAnimal.getId(); db.searchAnimalsOnArea(id); break; case SEARCH_CLOSE: JEntity myPosition = map.getMyPosition(); Point2D temp = new Point2D.Double(myPosition.getLat(),myPosition.getLon()); db.searchNearestAnimals(temp); break; case SEARCH_EXTINCT: db.searchExtinctAnimals(); break; case SEARCH_IMAGE: db.searchAnimalsByPicture(getSearchFilename(), getSearchTable()); break; } dbAnimals = (ArrayList<Animal>) db.searchResult; } catch(SQLException e){ Log.error("Chyba pri hledani zvirat: " + e.getMessage()); } catch(IOException e){ Log.error("Chyba pri cteni obrazku: " + e.getMessage()); } Log.info("Nalezeno "+ dbAnimals + " zvirat"); // nastaveni novych zvirat vAnimals.clear(); for (Animal animal: dbAnimals) { vAnimals.add(animal); } animalsPanel.setData(vAnimals); if(dLoading != null && dLoading.isVisible()){ dLoading.dispose(); } } }).start(); dLoading.setVisible(true); } /** * Ukonceni aplikace */ public void exitApp(){ if (db.isConnected()) { try { db.disconnect(); Log.info("Disconnected"); } catch (SQLException e) { System.err .println("Error while disconnection from DB: " + e.getMessage()); } } setVisible(false); dispose(); } @Override protected void finalize() throws Throwable { super.finalize(); exitApp(); } /** * Pridani zvirete do DB * @param animal */ public void addAnimal(Animal animal){ try { db.insertAnimal(animal); } catch (SQLException e) { Log.error("Chyba pri vkladani zvirete do DB: " + e.getMessage()); } reloadAnimalsList(AnimalsDatabase.SEARCH_ALL); } /** * Metoda upravujici zvire v DB * @param animal */ public void editAnimal(Animal animal){ int id = animal.getId(); // podiva se zda v DB existuje try{ db.searchAnimals(id); } catch (SQLException e) { System.err.println("Chyba hledani zvirete podle ID v DB: " + e.getMessage()); } if (id != 0) { Log.debug("Id zvirete ktere chci ulozit:" + id); try { db.updateAnimal(animal); } catch (SQLException e) { System.err.println("Chyba hledani zvirete podle ID v DB: " + e.getMessage()); } } reloadAnimalsList(AnimalsDatabase.SEARCH_ALL); } /** * Odstraneni zvirete z DB * @param animal */ public void deleteAnimal(Animal animal){ try{ db.deleteAnimal(animal.getId()); Log.debug("Mazu zvire s ID " + animal.getId()); } catch (SQLException e) { System.err.println("Chyba pri mazani zvirete z DB" + e.getMessage()); } reloadAnimalsList(AnimalsDatabase.SEARCH_ALL); } /** * Nastavovani zda jsou prvky k dispozici dle pripojeni * @param enable */ public void setEnable(boolean enable){ // disable/enable menu items menuController.setConnected(db.isConnected()); animalsPanel.setEnabled(enable); photosPanel.setEnabled(enable); } /** * Ziskani instance mapy * @return reference na objekt mapy */ public JMapPanel getMap() { return map; } /** * Ziskani instance databaze * @return reference na objekt databaze */ public DataBase getDb() { return db; } public void setList(JList list) { this.list = list; } public JList getList() { return list; } public MenuController getMenuController() { return menuController; } public PhotosPanel getPhotosPanel() { return photosPanel; } public AnimalsPanel getAnimalsPanel() { return animalsPanel; } public String getSearchGenus() { return searchGenus; } public void setSearchGenus(String searchGenus) { this.searchGenus = searchGenus; } public String getSearchSpecies() { return searchSpecies; } public void setSearchSpecies(String searchSpecies) { this.searchSpecies = searchSpecies; } public String getSearchDescription() { return searchDescription; } public void setSearchDescription(String searchDescription) { this.searchDescription = searchDescription; } public String getSearchFilename() { return searchFilename; } public void setSearchFilename(String searchFilename) { this.searchFilename = searchFilename; } public String getSearchTable() { return searchTable; } public void setSearchTable(String searchTable) { this.searchTable = searchTable; } }
UTF-8
Java
9,359
java
AnimalsDatabase.java
Java
[ { "context": " okna, rozdeleneho do tri\n * panelu.\n *\n * @author Ondล™ej Beneลก <xbenes00@stud.fit.vutbr.cz>\n *\n */\npublic class ", "end": 818, "score": 0.9999008178710938, "start": 806, "tag": "NAME", "value": "Ondล™ej Beneลก" }, { "context": "eho do tri\n * panelu.\n *\n * @author Ondล™ej Beneลก <xbenes00@stud.fit.vutbr.cz>\n *\n */\npublic class AnimalsDatabase extends JFra", "end": 846, "score": 0.9999344944953918, "start": 820, "tag": "EMAIL", "value": "xbenes00@stud.fit.vutbr.cz" } ]
null
[]
package cz.vutbr.fit.pdb03; import java.awt.geom.Point2D; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JSplitPane; import cz.vutbr.fit.pdb03.controllers.MenuController; import cz.vutbr.fit.pdb03.controllers.WindowController; import cz.vutbr.fit.pdb03.dialogs.ConnectDialog; import cz.vutbr.fit.pdb03.dialogs.LoadingDialog; import cz.vutbr.fit.pdb03.gui.AnimalsPanel; import cz.vutbr.fit.pdb03.gui.GUIManager; import cz.vutbr.fit.pdb03.gui.JEntity; import cz.vutbr.fit.pdb03.gui.JMapPanel; import cz.vutbr.fit.pdb03.gui.PhotosPanel; /** * Hlavni trida zajistujici vykreselni hlavniho okna, rozdeleneho do tri * panelu. * * @author <NAME> <<EMAIL>> * */ public class AnimalsDatabase extends JFrame { private static final long serialVersionUID = 1L; // search mody public final static int SEARCH_ALL = 0; public final static int SEARCH_BY_NAME = 1; public final static int SEARCH_BY_DESCRIPTION = 2; public final static int SEARCH_BY_PICTURE = 3; public final static int SEARCH_BY_PICTURE_DESCRIPTION = 4; public final static int SEARCH_CLOSE = 5; public final static int SEARCH_BIGGEST_AREA = 6; public final static int SEARCH_EXTINCT = 7; public final static int SEARCH_SAME_AREA = 8; public final static int SEARCH_IMAGE = 9; // komponenty jednotlivych casti hlavniho okna PhotosPanel photosPanel; JMapPanel mapPanel; AnimalsPanel animalsPanel; // map items JMapPanel map; // database items private DataBase db; // controllers MenuController menuController; // seznam zvirat private JList list; private Vector<Animal> vAnimals = new Vector<Animal>(); // pomocne promenne pro hledani private String searchGenus, searchSpecies, searchDescription, searchFilename, searchTable; private LoadingDialog dLoading = null; // druh hledani /** * Zakladni konstruktor, ktery naplni hlavni okno * @param title titulek hlavniho okna */ public AnimalsDatabase(String title) { super(title); // nastaveni vzhledu pro jednotlive systemy System.setProperty("apple.laf.useScreenMenuBar", "true"); // try { // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // } catch (Exception e) { // Log.error("Chyba pri nastaveni systemoveho vzhledu"); // } // ikona setIconImage(new ImageIcon(AnimalsDatabase.class.getResource("images/icon.png")).getImage()); // databaze db = new DataBase(); // mapa map = new JMapPanel(this); // nastaveni kontroleru new WindowController(this); menuController = new MenuController(this); // pridani rozdeleni do jednotlivych podoken photosPanel = new PhotosPanel(this); animalsPanel = new AnimalsPanel(this); mapPanel = map; // soupaci panely JSplitPane splitPaneH = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, photosPanel, animalsPanel); splitPaneH.setResizeWeight(0.5); splitPaneH.setDividerLocation(600); splitPaneH.setBorder(null); JSplitPane splitPaneV = new JSplitPane(JSplitPane.VERTICAL_SPLIT, splitPaneH, mapPanel); splitPaneV.setResizeWeight(0.3); splitPaneV.setDividerLocation(200); add(splitPaneV); // v zakladu zakaz vse co pouziva DB setEnable(false); // pokud neni pripojeni k DB, zobraz dialog if(!db.isConnected()){ javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ConnectDialog dConnect = new ConnectDialog(AnimalsDatabase.this, db); GUIManager.moveToCenter(dConnect, AnimalsDatabase.this); dConnect.setVisible(true); } }); } } /** * Hlavni main pro spusteni aplikace * @param args argumenty z prikazove radky */ public static void main(String[] args) { AnimalsDatabase aDb = new AnimalsDatabase("Databรกze zvรญล™at"); aDb.setVisible(true); } /** * Obnoveni seznamu zvirat */ public void reloadAnimalsList(final int searchType){ dLoading = new LoadingDialog("Probรญhรก hledรกnรญ v DB, prosรญm vyฤkejte"); GUIManager.moveToCenter(dLoading, this); new Thread(new Runnable() { @Override public void run() { ArrayList<Animal> dbAnimals = new ArrayList<Animal>(); Animal tempAnimal = null; map.clearMap(); photosPanel.clear(); // nalezeni zvirat try{ switch (searchType) { case SEARCH_ALL: db.searchAnimals(); break; case SEARCH_BY_NAME: db.searchAnimals(getSearchGenus(), getSearchSpecies()); break; case SEARCH_BY_DESCRIPTION: db.searchAnimals(getSearchDescription()); break; case SEARCH_BY_PICTURE: break; case SEARCH_BY_PICTURE_DESCRIPTION: db.searchAnimalsByPicture(getSearchDescription()); break; case SEARCH_BIGGEST_AREA: db.searchAnimalsByAreaSize(); break; case SEARCH_SAME_AREA: tempAnimal = getAnimalsPanel().getSelectedAnimal(); int id = tempAnimal.getId(); db.searchAnimalsOnArea(id); break; case SEARCH_CLOSE: JEntity myPosition = map.getMyPosition(); Point2D temp = new Point2D.Double(myPosition.getLat(),myPosition.getLon()); db.searchNearestAnimals(temp); break; case SEARCH_EXTINCT: db.searchExtinctAnimals(); break; case SEARCH_IMAGE: db.searchAnimalsByPicture(getSearchFilename(), getSearchTable()); break; } dbAnimals = (ArrayList<Animal>) db.searchResult; } catch(SQLException e){ Log.error("Chyba pri hledani zvirat: " + e.getMessage()); } catch(IOException e){ Log.error("Chyba pri cteni obrazku: " + e.getMessage()); } Log.info("Nalezeno "+ dbAnimals + " zvirat"); // nastaveni novych zvirat vAnimals.clear(); for (Animal animal: dbAnimals) { vAnimals.add(animal); } animalsPanel.setData(vAnimals); if(dLoading != null && dLoading.isVisible()){ dLoading.dispose(); } } }).start(); dLoading.setVisible(true); } /** * Ukonceni aplikace */ public void exitApp(){ if (db.isConnected()) { try { db.disconnect(); Log.info("Disconnected"); } catch (SQLException e) { System.err .println("Error while disconnection from DB: " + e.getMessage()); } } setVisible(false); dispose(); } @Override protected void finalize() throws Throwable { super.finalize(); exitApp(); } /** * Pridani zvirete do DB * @param animal */ public void addAnimal(Animal animal){ try { db.insertAnimal(animal); } catch (SQLException e) { Log.error("Chyba pri vkladani zvirete do DB: " + e.getMessage()); } reloadAnimalsList(AnimalsDatabase.SEARCH_ALL); } /** * Metoda upravujici zvire v DB * @param animal */ public void editAnimal(Animal animal){ int id = animal.getId(); // podiva se zda v DB existuje try{ db.searchAnimals(id); } catch (SQLException e) { System.err.println("Chyba hledani zvirete podle ID v DB: " + e.getMessage()); } if (id != 0) { Log.debug("Id zvirete ktere chci ulozit:" + id); try { db.updateAnimal(animal); } catch (SQLException e) { System.err.println("Chyba hledani zvirete podle ID v DB: " + e.getMessage()); } } reloadAnimalsList(AnimalsDatabase.SEARCH_ALL); } /** * Odstraneni zvirete z DB * @param animal */ public void deleteAnimal(Animal animal){ try{ db.deleteAnimal(animal.getId()); Log.debug("Mazu zvire s ID " + animal.getId()); } catch (SQLException e) { System.err.println("Chyba pri mazani zvirete z DB" + e.getMessage()); } reloadAnimalsList(AnimalsDatabase.SEARCH_ALL); } /** * Nastavovani zda jsou prvky k dispozici dle pripojeni * @param enable */ public void setEnable(boolean enable){ // disable/enable menu items menuController.setConnected(db.isConnected()); animalsPanel.setEnabled(enable); photosPanel.setEnabled(enable); } /** * Ziskani instance mapy * @return reference na objekt mapy */ public JMapPanel getMap() { return map; } /** * Ziskani instance databaze * @return reference na objekt databaze */ public DataBase getDb() { return db; } public void setList(JList list) { this.list = list; } public JList getList() { return list; } public MenuController getMenuController() { return menuController; } public PhotosPanel getPhotosPanel() { return photosPanel; } public AnimalsPanel getAnimalsPanel() { return animalsPanel; } public String getSearchGenus() { return searchGenus; } public void setSearchGenus(String searchGenus) { this.searchGenus = searchGenus; } public String getSearchSpecies() { return searchSpecies; } public void setSearchSpecies(String searchSpecies) { this.searchSpecies = searchSpecies; } public String getSearchDescription() { return searchDescription; } public void setSearchDescription(String searchDescription) { this.searchDescription = searchDescription; } public String getSearchFilename() { return searchFilename; } public void setSearchFilename(String searchFilename) { this.searchFilename = searchFilename; } public String getSearchTable() { return searchTable; } public void setSearchTable(String searchTable) { this.searchTable = searchTable; } }
9,332
0.697261
0.692234
407
21.96806
21.011322
97
false
false
0
0
0
0
0
0
2.110565
false
false
3
77e8d19385624afd505ea3dd8ce6b713b30bcfd3
12,850,542,151,796
ed8d877c814c9a33e8fbb480d24008fb851654af
/intentoVentana/src/vistas/ContenidoDeVentana.java
a49546adba6ab37ef0c063c1f5ca06305bfac0dd
[ "Apache-2.0" ]
permissive
malonemanuel/plan_de_estudios
https://github.com/malonemanuel/plan_de_estudios
5894fcb5f8b7e1e938b6540f28109c94b4936bfe
05eacb905e424f673085552be383e3e2ff3e59d0
refs/heads/master
2019-01-24T12:52:40.449000
2013-08-11T02:12:59
2013-08-11T02:12:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package vistas; import java.lang.reflect.Field; import javax.swing.JFrame; import java.awt.Component; import java.awt.LayoutManager; public abstract class ContenidoDeVentana { protected LayoutManager layout; public abstract void init(); public ContenidoDeVentana(){ init(); } public void setLayout(LayoutManager unLayout){ layout = unLayout; } public final void cargarVistaEn(JFrame unaVentana){ unaVentana.getContentPane().removeAll(); unaVentana.getContentPane().setLayout(this.layout); unaVentana.getContentPane().setVisible(false); unaVentana.getContentPane().setVisible(true); Field[] atributos = this.getClass().getDeclaredFields(); for (Field attr : atributos) { try { attr.setAccessible(true); Object valor = attr.get(this); if (valor instanceof Component); unaVentana.getContentPane().add((Component)valor); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } }
UTF-8
Java
1,032
java
ContenidoDeVentana.java
Java
[]
null
[]
package vistas; import java.lang.reflect.Field; import javax.swing.JFrame; import java.awt.Component; import java.awt.LayoutManager; public abstract class ContenidoDeVentana { protected LayoutManager layout; public abstract void init(); public ContenidoDeVentana(){ init(); } public void setLayout(LayoutManager unLayout){ layout = unLayout; } public final void cargarVistaEn(JFrame unaVentana){ unaVentana.getContentPane().removeAll(); unaVentana.getContentPane().setLayout(this.layout); unaVentana.getContentPane().setVisible(false); unaVentana.getContentPane().setVisible(true); Field[] atributos = this.getClass().getDeclaredFields(); for (Field attr : atributos) { try { attr.setAccessible(true); Object valor = attr.get(this); if (valor instanceof Component); unaVentana.getContentPane().add((Component)valor); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } }
1,032
0.718992
0.718992
46
21.434782
18.915892
58
false
false
0
0
0
0
0
0
2.108696
false
false
3
e03722cb69c94959b88aed6175ce84182e04ded0
6,322,191,919,814
43b25fcc8452d55c14a90136629fff6450563ac4
/app/src/main/java/com/gentlehealthcare/mobilecare/net/bean/SyncExecutioningWorkWorkBean.java
ba6391c8b4b2eb0776360e5e4f61bab96243e353
[]
no_license
wushanfa/CMS
https://github.com/wushanfa/CMS
aaba72121deab620b40a6706132adca423af6e8b
32443efdec80a22742c3af4da6f1a944ed8c38df
refs/heads/master
2021-01-20T10:19:30.787000
2017-06-14T06:35:53
2017-06-14T06:35:53
90,346,507
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gentlehealthcare.mobilecare.net.bean; import java.util.List; import com.gentlehealthcare.mobilecare.UserInfo; import com.gentlehealthcare.mobilecare.db.table.TB_ExecutionWork; /** * * @ClassName: SyncWillExecutionWorkBean * @Description: ๅŒๆญฅๅพ…ๆ‰ง่กŒๅทฅไฝœ ๅฎžไฝ“็ฑป * @author ouyang * @date 2015ๅนด3ๆœˆ10ๆ—ฅ ไธŠๅˆ9:14:20 * */ public class SyncExecutioningWorkWorkBean { private List<TB_ExecutionWork> executingWorkList; @Override public String toString() { // TODO Auto-generated method stub return "?username="+UserInfo.getUserName(); } public List<TB_ExecutionWork> getExecutingWorkList() { return executingWorkList; } public void setExecutingWorkList(List<TB_ExecutionWork> executingWorkList) { this.executingWorkList = executingWorkList; } }
UTF-8
Java
800
java
SyncExecutioningWorkWorkBean.java
Java
[ { "context": "nWorkBean \n * @Description: ๅŒๆญฅๅพ…ๆ‰ง่กŒๅทฅไฝœ ๅฎžไฝ“็ฑป\n * @author ouyang\n * @date 2015ๅนด3ๆœˆ10ๆ—ฅ ไธŠๅˆ9:14:20 \n *\n */\npublic clas", "end": 286, "score": 0.9991885423660278, "start": 280, "tag": "USERNAME", "value": "ouyang" } ]
null
[]
package com.gentlehealthcare.mobilecare.net.bean; import java.util.List; import com.gentlehealthcare.mobilecare.UserInfo; import com.gentlehealthcare.mobilecare.db.table.TB_ExecutionWork; /** * * @ClassName: SyncWillExecutionWorkBean * @Description: ๅŒๆญฅๅพ…ๆ‰ง่กŒๅทฅไฝœ ๅฎžไฝ“็ฑป * @author ouyang * @date 2015ๅนด3ๆœˆ10ๆ—ฅ ไธŠๅˆ9:14:20 * */ public class SyncExecutioningWorkWorkBean { private List<TB_ExecutionWork> executingWorkList; @Override public String toString() { // TODO Auto-generated method stub return "?username="+UserInfo.getUserName(); } public List<TB_ExecutionWork> getExecutingWorkList() { return executingWorkList; } public void setExecutingWorkList(List<TB_ExecutionWork> executingWorkList) { this.executingWorkList = executingWorkList; } }
800
0.767532
0.751948
35
21
22.605942
77
false
false
0
0
0
0
0
0
0.742857
false
false
3
01f17f89c5557cbba8479ca2127aea1e857f5d75
17,815,524,403,194
d339ad12c176a582898c398f471067cc20946a3a
/src/main/java/com/natanielmendes/labs/domain/Email_.java
3821313e31f57584765dd97411b7023715bdee89
[]
no_license
natanielmendes/criteria-query-sample
https://github.com/natanielmendes/criteria-query-sample
c85f3f8851ff2ec6539dbc220daa59b90cc89621
45a6ea999c2d47bc4960dd13b54de8f502c47194
refs/heads/master
2020-12-31T07:33:11.693000
2016-04-15T14:51:19
2016-04-15T14:51:20
56,324,128
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.natanielmendes.labs.domain; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @StaticMetamodel(Email.class) public abstract class Email_ { public static volatile SingularAttribute<Email, Long> id; public static volatile SingularAttribute<Email, String> email; public static volatile SingularAttribute<Email, UserEntity> entity; public static volatile SingularAttribute<Email, String> prefix; public static volatile SingularAttribute<Email, Long> entityId; public static volatile SingularAttribute<Email, String> provider; public static volatile SingularAttribute<Email, Integer> typeId; public static volatile SingularAttribute<Email, Boolean> master; }
UTF-8
Java
735
java
Email_.java
Java
[]
null
[]
package com.natanielmendes.labs.domain; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @StaticMetamodel(Email.class) public abstract class Email_ { public static volatile SingularAttribute<Email, Long> id; public static volatile SingularAttribute<Email, String> email; public static volatile SingularAttribute<Email, UserEntity> entity; public static volatile SingularAttribute<Email, String> prefix; public static volatile SingularAttribute<Email, Long> entityId; public static volatile SingularAttribute<Email, String> provider; public static volatile SingularAttribute<Email, Integer> typeId; public static volatile SingularAttribute<Email, Boolean> master; }
735
0.829932
0.829932
18
39.777779
27.025822
68
false
false
0
0
0
0
0
0
1.5
false
false
3
b115b0d310627b457bb069c59edf0b016a4f77d4
18,287,970,813,417
a85a5e0024c03dd63098802bcbd70bd315326b9e
/WoPeD-Editor/src/main/java/org/woped/editor/controller/vep/ApplicationEventProcessor.java
eff41346cef455f81b3afa2338697d0d8d19c6cd
[]
no_license
tfreytag/WoPeD
https://github.com/tfreytag/WoPeD
d2309ef561f366b0362f99f39a8c75a85b7ea1a8
6e2ed2e4661a1a62339e526eeb60811be2713f38
refs/heads/master
2023-08-31T11:49:48.511000
2023-01-04T23:19:19
2023-01-04T23:19:19
261,135,833
7
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.woped.editor.controller.vep; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.beans.PropertyChangeEvent; import java.util.Iterator; import org.woped.core.config.ConfigurationManager; import org.woped.core.controller.AbstractEventProcessor; import org.woped.core.controller.AbstractGraph; import org.woped.core.controller.AbstractViewEvent; import org.woped.core.controller.IEditor; import org.woped.core.model.petrinet.AbstractPetriNetElementModel; import org.woped.core.model.petrinet.OperatorTransitionModel; import org.woped.core.utilities.LoggerManager; import org.woped.core.utilities.Utils; import org.woped.editor.Constants; import org.woped.editor.controller.ApplicationMediator; import org.woped.editor.controller.VisualController; import org.woped.editor.controller.vc.ConfigVC; import org.woped.editor.controller.vc.EditorVC; public class ApplicationEventProcessor extends AbstractEventProcessor { private ApplicationMediator mediator = null; public ApplicationEventProcessor(ApplicationMediator mediator) { super(mediator); this.mediator = mediator; } public void processViewEvent(AbstractViewEvent event) { IEditor currentEditor; if (event.getSource() instanceof EditorVC) { currentEditor = (EditorVC) event.getSource(); } else { currentEditor = getMediator().getUi().getEditorFocus(); } switch (event.getOrder()) { case AbstractViewEvent.DRAWMODE_PLACE: if (currentEditor.getCreateElementType() != AbstractPetriNetElementModel.PLACE_TYPE) { currentEditor.setDrawMode(AbstractPetriNetElementModel.PLACE_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_TRANSITION: if (currentEditor.getCreateElementType() != AbstractPetriNetElementModel.TRANS_SIMPLE_TYPE) { currentEditor.setDrawMode(AbstractPetriNetElementModel.TRANS_SIMPLE_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_ANDJOIN: if (currentEditor.getCreateElementType() != OperatorTransitionModel.AND_JOIN_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.AND_JOIN_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_ANDSPLIT: if (currentEditor.getCreateElementType() != OperatorTransitionModel.AND_SPLIT_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.AND_SPLIT_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_ANDSPLITJOIN: if (currentEditor.getCreateElementType() != OperatorTransitionModel.AND_SPLITJOIN_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.AND_SPLITJOIN_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_XORJOIN: if (currentEditor.getCreateElementType() != OperatorTransitionModel.XOR_JOIN_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.XOR_JOIN_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_XORSPLIT: if (currentEditor.getCreateElementType() != OperatorTransitionModel.XOR_SPLIT_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.XOR_SPLIT_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_XORSPLITJOIN: if (currentEditor.getCreateElementType() != OperatorTransitionModel.XORJOIN_XORSPLIT_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.XORJOIN_XORSPLIT_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_ANDJOIN_XORSPLIT: if (currentEditor.getCreateElementType() != OperatorTransitionModel.ANDJOIN_XORSPLIT_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.ANDJOIN_XORSPLIT_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_XORJOIN_ANDSPLIT: if (currentEditor.getCreateElementType() != OperatorTransitionModel.XORJOIN_ANDSPLIT_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.XORJOIN_ANDSPLIT_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_SUB: if (currentEditor.getCreateElementType() != AbstractPetriNetElementModel.SUBP_TYPE) { currentEditor.setDrawMode(AbstractPetriNetElementModel.SUBP_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.CONFIG: ConfigVC config = ((ConfigVC) getMediator().getViewController(ConfigVC.ID_PREFIX)); if (config == null) { config = (ConfigVC) getWopedMediator() .createViewController(ApplicationMediator.VIEWCONTROLLER_CONFIG); } if (getMediator().getUi() != null) { config.setLocation( Utils.getCenterPoint(getMediator().getUi().getBounds(), config.getSize())); } config.setVisible(true); break; case AbstractViewEvent.EXIT: getMediator().getUi().quit(); break; case AbstractViewEvent.UPDATE: for (Iterator<IEditor> iter = getMediator().getUi().getAllEditors().iterator(); iter.hasNext(); ) { currentEditor = iter.next(); currentEditor .getGraph() .setGridVisible(ConfigurationManager.getConfiguration().isShowGrid()); for (Iterator<String> iterator = currentEditor .getModelProcessor() .getElementContainer() .getArcMap() .keySet() .iterator(); iterator.hasNext(); ) { currentEditor .getModelProcessor() .getElementContainer() .getArcById(iterator.next()) .initAttributes(); } currentEditor.updateNet(); VisualController.getInstance() .propertyChange(new PropertyChangeEvent(this, "Update", null, null)); } break; case AbstractViewEvent.CASCADE: getMediator().getUi().cascadeFrames(); break; case AbstractViewEvent.ARRANGE: getMediator().getUi().arrangeFrames(); break; case AbstractViewEvent.PRINT: print(currentEditor); break; /* * SCREENSHOT m_controlledWindow.makeScreenshot(); } * OLDUserInterface.getInstance().getActiveEditor().removePoint(); } * else if (targetEvent == CASCADE_WINDOWS) { * OLDUserInterface.getInstance().cascadeFrames(); } else if * (targetEvent == ARRANGE_WINDOWS) { * OLDUserInterface.getInstance().arrangeFrames(); * * CASCADE super("Action.Frames.Cascade"); * VisualController.getInstance().addElement(this, * VisualController.WITH_EDITOR, VisualController.IGNORE, * VisualController.IGNORE); * * ARRANGE super("Action.Frames.Arrange"); * VisualController.getInstance().addElement(this, * VisualController.WITH_EDITOR, VisualController.IGNORE, * VisualController.IGNORE); * * */ default: break; } } /** * TODO: DOCUMENTATION (alexnagy) * * @param editor */ public void print(IEditor editor) { AbstractGraph graph = editor.getGraph(); if (graph != null) { PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintable(graph); if (printJob.printDialog()) { try { printJob.print(); } catch (PrinterException e) { LoggerManager.warn(Constants.EDITOR_LOGGER, "Could not Print"); LoggerManager.debug(Constants.EDITOR_LOGGER, "Exception" + e); } } } } /* private void setDrawMode(int type, boolean active) { EditorVC currentEditor; for (Iterator<IEditor> iter = getMediator().getUi().getAllEditors().iterator(); iter.hasNext();) { currentEditor = (EditorVC) iter.next(); currentEditor.setDrawingMode(active); currentEditor.setCreateElementType(type); } }*/ /** * @return Returns the mediator. */ private ApplicationMediator getWopedMediator() { return mediator; } }
UTF-8
Java
8,898
java
ApplicationEventProcessor.java
Java
[ { "context": "break;\n }\n }\n\n /**\n * TODO: DOCUMENTATION (alexnagy)\n *\n * @param editor\n */\n public void prin", "end": 7879, "score": 0.971827507019043, "start": 7871, "tag": "USERNAME", "value": "alexnagy" } ]
null
[]
package org.woped.editor.controller.vep; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.beans.PropertyChangeEvent; import java.util.Iterator; import org.woped.core.config.ConfigurationManager; import org.woped.core.controller.AbstractEventProcessor; import org.woped.core.controller.AbstractGraph; import org.woped.core.controller.AbstractViewEvent; import org.woped.core.controller.IEditor; import org.woped.core.model.petrinet.AbstractPetriNetElementModel; import org.woped.core.model.petrinet.OperatorTransitionModel; import org.woped.core.utilities.LoggerManager; import org.woped.core.utilities.Utils; import org.woped.editor.Constants; import org.woped.editor.controller.ApplicationMediator; import org.woped.editor.controller.VisualController; import org.woped.editor.controller.vc.ConfigVC; import org.woped.editor.controller.vc.EditorVC; public class ApplicationEventProcessor extends AbstractEventProcessor { private ApplicationMediator mediator = null; public ApplicationEventProcessor(ApplicationMediator mediator) { super(mediator); this.mediator = mediator; } public void processViewEvent(AbstractViewEvent event) { IEditor currentEditor; if (event.getSource() instanceof EditorVC) { currentEditor = (EditorVC) event.getSource(); } else { currentEditor = getMediator().getUi().getEditorFocus(); } switch (event.getOrder()) { case AbstractViewEvent.DRAWMODE_PLACE: if (currentEditor.getCreateElementType() != AbstractPetriNetElementModel.PLACE_TYPE) { currentEditor.setDrawMode(AbstractPetriNetElementModel.PLACE_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_TRANSITION: if (currentEditor.getCreateElementType() != AbstractPetriNetElementModel.TRANS_SIMPLE_TYPE) { currentEditor.setDrawMode(AbstractPetriNetElementModel.TRANS_SIMPLE_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_ANDJOIN: if (currentEditor.getCreateElementType() != OperatorTransitionModel.AND_JOIN_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.AND_JOIN_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_ANDSPLIT: if (currentEditor.getCreateElementType() != OperatorTransitionModel.AND_SPLIT_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.AND_SPLIT_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_ANDSPLITJOIN: if (currentEditor.getCreateElementType() != OperatorTransitionModel.AND_SPLITJOIN_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.AND_SPLITJOIN_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_XORJOIN: if (currentEditor.getCreateElementType() != OperatorTransitionModel.XOR_JOIN_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.XOR_JOIN_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_XORSPLIT: if (currentEditor.getCreateElementType() != OperatorTransitionModel.XOR_SPLIT_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.XOR_SPLIT_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_XORSPLITJOIN: if (currentEditor.getCreateElementType() != OperatorTransitionModel.XORJOIN_XORSPLIT_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.XORJOIN_XORSPLIT_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_ANDJOIN_XORSPLIT: if (currentEditor.getCreateElementType() != OperatorTransitionModel.ANDJOIN_XORSPLIT_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.ANDJOIN_XORSPLIT_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_XORJOIN_ANDSPLIT: if (currentEditor.getCreateElementType() != OperatorTransitionModel.XORJOIN_ANDSPLIT_TYPE) { currentEditor.setDrawMode(OperatorTransitionModel.XORJOIN_ANDSPLIT_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.DRAWMODE_SUB: if (currentEditor.getCreateElementType() != AbstractPetriNetElementModel.SUBP_TYPE) { currentEditor.setDrawMode(AbstractPetriNetElementModel.SUBP_TYPE, true); } else { currentEditor.setDrawMode(-1, false); } break; case AbstractViewEvent.CONFIG: ConfigVC config = ((ConfigVC) getMediator().getViewController(ConfigVC.ID_PREFIX)); if (config == null) { config = (ConfigVC) getWopedMediator() .createViewController(ApplicationMediator.VIEWCONTROLLER_CONFIG); } if (getMediator().getUi() != null) { config.setLocation( Utils.getCenterPoint(getMediator().getUi().getBounds(), config.getSize())); } config.setVisible(true); break; case AbstractViewEvent.EXIT: getMediator().getUi().quit(); break; case AbstractViewEvent.UPDATE: for (Iterator<IEditor> iter = getMediator().getUi().getAllEditors().iterator(); iter.hasNext(); ) { currentEditor = iter.next(); currentEditor .getGraph() .setGridVisible(ConfigurationManager.getConfiguration().isShowGrid()); for (Iterator<String> iterator = currentEditor .getModelProcessor() .getElementContainer() .getArcMap() .keySet() .iterator(); iterator.hasNext(); ) { currentEditor .getModelProcessor() .getElementContainer() .getArcById(iterator.next()) .initAttributes(); } currentEditor.updateNet(); VisualController.getInstance() .propertyChange(new PropertyChangeEvent(this, "Update", null, null)); } break; case AbstractViewEvent.CASCADE: getMediator().getUi().cascadeFrames(); break; case AbstractViewEvent.ARRANGE: getMediator().getUi().arrangeFrames(); break; case AbstractViewEvent.PRINT: print(currentEditor); break; /* * SCREENSHOT m_controlledWindow.makeScreenshot(); } * OLDUserInterface.getInstance().getActiveEditor().removePoint(); } * else if (targetEvent == CASCADE_WINDOWS) { * OLDUserInterface.getInstance().cascadeFrames(); } else if * (targetEvent == ARRANGE_WINDOWS) { * OLDUserInterface.getInstance().arrangeFrames(); * * CASCADE super("Action.Frames.Cascade"); * VisualController.getInstance().addElement(this, * VisualController.WITH_EDITOR, VisualController.IGNORE, * VisualController.IGNORE); * * ARRANGE super("Action.Frames.Arrange"); * VisualController.getInstance().addElement(this, * VisualController.WITH_EDITOR, VisualController.IGNORE, * VisualController.IGNORE); * * */ default: break; } } /** * TODO: DOCUMENTATION (alexnagy) * * @param editor */ public void print(IEditor editor) { AbstractGraph graph = editor.getGraph(); if (graph != null) { PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintable(graph); if (printJob.printDialog()) { try { printJob.print(); } catch (PrinterException e) { LoggerManager.warn(Constants.EDITOR_LOGGER, "Could not Print"); LoggerManager.debug(Constants.EDITOR_LOGGER, "Exception" + e); } } } } /* private void setDrawMode(int type, boolean active) { EditorVC currentEditor; for (Iterator<IEditor> iter = getMediator().getUi().getAllEditors().iterator(); iter.hasNext();) { currentEditor = (EditorVC) iter.next(); currentEditor.setDrawingMode(active); currentEditor.setCreateElementType(type); } }*/ /** * @return Returns the mediator. */ private ApplicationMediator getWopedMediator() { return mediator; } }
8,898
0.646437
0.645201
238
36.386555
27.017612
102
false
false
0
0
0
0
0
0
0.579832
false
false
3
015412c2b431eeb70059c17bdaa65f5c20b21a29
29,248,727,351,470
4ab7f59294a57518ffb1c8323a76991f15a601f0
/db.test.datamap/src/main/java/com/aliyun/ext/jtester/hamcrest/core/AnyOf.java
36230845277f2a399522940190f6931fd8856359
[]
no_license
aliyun/unit_test_db
https://github.com/aliyun/unit_test_db
15f241ac11dcd8f414b38f3599b21e667ba2d25a
ac4036faf09d523a0114c2df5b55f3431927bcb3
refs/heads/master
2023-03-12T23:57:27.612000
2018-06-08T06:29:33
2018-06-08T06:29:33
136,114,524
3
1
null
false
2022-06-20T23:53:07
2018-06-05T03:26:48
2020-12-21T12:15:37
2022-06-20T23:53:06
3,420
3
0
1
Java
false
false
package com.aliyun.ext.jtester.hamcrest.core; import java.util.Arrays; import com.aliyun.ext.jtester.hamcrest.Description; import com.aliyun.ext.jtester.hamcrest.Factory; import com.aliyun.ext.jtester.hamcrest.Matcher; /** * Calculates the logical disjunction of multiple matchers. Evaluation is * shortcut, so subsequent matchers are not called if an earlier matcher returns * <code>true</code>. */ @SuppressWarnings({ "rawtypes" }) public class AnyOf<T> extends ShortcutCombination<T> { public AnyOf(Iterable<Matcher> matchers) { super(matchers); } @Override public boolean matches(Object o) { return matches(o, true); } @Override public void describeTo(Description description) { describeTo(description, "or"); } /** * Evaluates to true if ANY of the passed in matchers evaluate to true. */ @Factory public static <T> AnyOf<T> anyOf(Iterable<Matcher> matchers) { return new AnyOf<T>(matchers); } /** * Evaluates to true if ANY of the passed in matchers evaluate to true. */ @Factory public static <T> AnyOf<T> anyOf(Matcher... matchers) { return anyOf(Arrays.asList(matchers)); } @Factory public static <T> Matcher notAny(Iterable<Matcher> matchers) { Matcher matcher = IsNot.not(AnyOf.anyOf(matchers)); return matcher; } }
UTF-8
Java
1,392
java
AnyOf.java
Java
[]
null
[]
package com.aliyun.ext.jtester.hamcrest.core; import java.util.Arrays; import com.aliyun.ext.jtester.hamcrest.Description; import com.aliyun.ext.jtester.hamcrest.Factory; import com.aliyun.ext.jtester.hamcrest.Matcher; /** * Calculates the logical disjunction of multiple matchers. Evaluation is * shortcut, so subsequent matchers are not called if an earlier matcher returns * <code>true</code>. */ @SuppressWarnings({ "rawtypes" }) public class AnyOf<T> extends ShortcutCombination<T> { public AnyOf(Iterable<Matcher> matchers) { super(matchers); } @Override public boolean matches(Object o) { return matches(o, true); } @Override public void describeTo(Description description) { describeTo(description, "or"); } /** * Evaluates to true if ANY of the passed in matchers evaluate to true. */ @Factory public static <T> AnyOf<T> anyOf(Iterable<Matcher> matchers) { return new AnyOf<T>(matchers); } /** * Evaluates to true if ANY of the passed in matchers evaluate to true. */ @Factory public static <T> AnyOf<T> anyOf(Matcher... matchers) { return anyOf(Arrays.asList(matchers)); } @Factory public static <T> Matcher notAny(Iterable<Matcher> matchers) { Matcher matcher = IsNot.not(AnyOf.anyOf(matchers)); return matcher; } }
1,392
0.670977
0.670977
52
25.76923
25.124777
80
false
false
0
0
0
0
0
0
0.288462
false
false
3
0de1608f120c3d24ebd18a8c150d8823b8e31415
12,489,764,929,585
c483dd5bcf53a4b8df9dc0858ef7133235062b36
/src/main/java/be/normegil/mylibrary/ApplicationProperties.java
1e73e5c942ad516a5203af9615a40835b7cb5a89
[ "Unlicense" ]
permissive
Normegil/MyLibrary-Java
https://github.com/Normegil/MyLibrary-Java
96668797136dc0446f16e426aec3be3c20b00ede
4e8403709a86ea38abb24c07cf251dbeaaabf0a8
refs/heads/master
2021-01-17T06:55:09.441000
2015-01-13T14:09:32
2015-01-13T14:09:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package be.normegil.mylibrary; import org.apache.commons.lang3.builder.ToStringStyle; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import java.time.Duration; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAmount; @ApplicationPath(ApplicationProperties.BASE_PATH) public class ApplicationProperties extends Application { protected static final String BASE_PATH = "/rest"; public static final String PERSISTENCE_UNIT_NAME = "MainPU"; public static final DateTimeFormatter STANDARD_TIME_FORMAT = DateTimeFormatter.ISO_INSTANT; public static final ToStringStyle TO_STRING_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; public class REST { public static final int DEFAULT_LIMIT = 25; public static final int MAX_LIMIT = 500; } public static class Security { public static class JSonWebToken { public static final TemporalAmount TOKEN_VALIDITY_PERIOD = Duration.of(2, ChronoUnit.DAYS); } } }
UTF-8
Java
1,002
java
ApplicationProperties.java
Java
[]
null
[]
package be.normegil.mylibrary; import org.apache.commons.lang3.builder.ToStringStyle; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import java.time.Duration; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAmount; @ApplicationPath(ApplicationProperties.BASE_PATH) public class ApplicationProperties extends Application { protected static final String BASE_PATH = "/rest"; public static final String PERSISTENCE_UNIT_NAME = "MainPU"; public static final DateTimeFormatter STANDARD_TIME_FORMAT = DateTimeFormatter.ISO_INSTANT; public static final ToStringStyle TO_STRING_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; public class REST { public static final int DEFAULT_LIMIT = 25; public static final int MAX_LIMIT = 500; } public static class Security { public static class JSonWebToken { public static final TemporalAmount TOKEN_VALIDITY_PERIOD = Duration.of(2, ChronoUnit.DAYS); } } }
1,002
0.798403
0.791417
30
32.400002
27.900537
94
false
false
0
0
0
0
0
0
1.166667
false
false
3
3c2484213d77a4aefe0d3c8d6d3c711f711b152e
11,244,224,420,521
43e744ba2a19763e87be750621c02e717313f820
/src/main/java/com/mt/sx/service/impl/SxUserAddressServiceImpl.java
05693729f7fae3675f192e318665dd514a485b37
[]
no_license
ftk112233/sx-
https://github.com/ftk112233/sx-
360505b5938efa383700c15cfe6b238c94c9622c
fc7e70b2264b7e57a2f62374ea851c6fa74b07a8
refs/heads/master
2022-07-02T21:50:18.823000
2019-12-28T06:45:27
2019-12-28T06:45:27
227,544,727
0
0
null
false
2022-06-21T02:25:52
2019-12-12T07:19:23
2019-12-28T06:45:56
2022-06-21T02:25:49
341
0
0
3
Java
false
false
package com.mt.sx.service.impl; import com.mt.sx.mapper.SxAddressInfoMapper; import com.mt.sx.pojo.SxAddressInfo; import com.mt.sx.service.SxUserAddressService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import static com.mt.sx.common.util.UserUtils.getUser; @Service public class SxUserAddressServiceImpl implements SxUserAddressService { @Autowired SxAddressInfoMapper sxAddressInfoMapper; @Override public List<SxAddressInfo> addressList() { SxAddressInfo sxAddressInfo = new SxAddressInfo(); sxAddressInfo.setShopId(getUser().getRelateId()); return sxAddressInfoMapper.select(sxAddressInfo); } @Override public Integer insert(SxAddressInfo sxAddressInfo) { sxAddressInfo.setShopId(getUser().getRelateId()); sxAddressInfo.setCreateTime(new Date()); return sxAddressInfoMapper.insert(sxAddressInfo); } @Override public Integer update(SxAddressInfo sxAddressInfo) { sxAddressInfo.setUpdateTime(new Date()); return sxAddressInfoMapper.updateByPrimaryKeySelective(sxAddressInfo); } @Override public Integer deletedForUser(Integer id) { return sxAddressInfoMapper.deleteByPrimaryKey(id); } @Override public SxAddressInfo selectById(Integer id) { return sxAddressInfoMapper.selectByPrimaryKey(id); } }
UTF-8
Java
1,471
java
SxUserAddressServiceImpl.java
Java
[]
null
[]
package com.mt.sx.service.impl; import com.mt.sx.mapper.SxAddressInfoMapper; import com.mt.sx.pojo.SxAddressInfo; import com.mt.sx.service.SxUserAddressService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import static com.mt.sx.common.util.UserUtils.getUser; @Service public class SxUserAddressServiceImpl implements SxUserAddressService { @Autowired SxAddressInfoMapper sxAddressInfoMapper; @Override public List<SxAddressInfo> addressList() { SxAddressInfo sxAddressInfo = new SxAddressInfo(); sxAddressInfo.setShopId(getUser().getRelateId()); return sxAddressInfoMapper.select(sxAddressInfo); } @Override public Integer insert(SxAddressInfo sxAddressInfo) { sxAddressInfo.setShopId(getUser().getRelateId()); sxAddressInfo.setCreateTime(new Date()); return sxAddressInfoMapper.insert(sxAddressInfo); } @Override public Integer update(SxAddressInfo sxAddressInfo) { sxAddressInfo.setUpdateTime(new Date()); return sxAddressInfoMapper.updateByPrimaryKeySelective(sxAddressInfo); } @Override public Integer deletedForUser(Integer id) { return sxAddressInfoMapper.deleteByPrimaryKey(id); } @Override public SxAddressInfo selectById(Integer id) { return sxAddressInfoMapper.selectByPrimaryKey(id); } }
1,471
0.746431
0.746431
49
29.020409
24.739038
78
false
false
0
0
0
0
0
0
0.408163
false
false
3
3cc1d3b42eb91cf56c13a674c56a593bf3466de4
31,224,412,272,560
c65963e81a35008f28b53da1d0cf68f4d209d46a
/src/main/java/com/ll/stock/monitor/service/IMonitorService.java
30f820069a21632748fe7d32c8ebc652640168b0
[]
no_license
fengyuwuyu/stock
https://github.com/fengyuwuyu/stock
75d67b6a1d9b517baaa5b73184b3a4ba1fb27316
4a382c1960b934b2d6254339a65ed5249593724d
refs/heads/master
2021-01-01T16:21:28.660000
2019-01-23T10:04:00
2019-01-23T10:04:00
97,810,071
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ll.stock.monitor.service; public interface IMonitorService { void add(); }
UTF-8
Java
90
java
IMonitorService.java
Java
[]
null
[]
package com.ll.stock.monitor.service; public interface IMonitorService { void add(); }
90
0.755556
0.755556
6
14
15.779734
37
false
false
0
0
0
0
0
0
0.5
false
false
3
d1d07455a90de05012b47e9482697267e465d41b
11,072,425,695,682
e91c4ac11e33e005fabba1963de4d543e544a892
/lavajatogit/src/Testes/ClienteDAO/TestaClienteDAOgrava.java
4a5bacddd53c71024edf18d8d60a53251165ef05
[]
no_license
kurtye/lavajato
https://github.com/kurtye/lavajato
6d735f848755c2a90886b5c7c2a4f94d9f39e338
9b52919bef2a03bd932bcfe5ab5ad066011e07c5
refs/heads/master
2016-08-05T21:48:32.550000
2015-11-09T23:24:03
2015-11-09T23:24:03
42,899,186
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Testes.ClienteDAO; import Modelo.Cliente; import Persistencia.ClienteDAO; /** * * @author laecio */ public class TestaClienteDAOgrava { public static void main(String[] args) { Cliente cliente = new Cliente(); cliente.setNome("Maria da bala"); cliente.setCpf("202020"); cliente.setRg("1234"); cliente.setUf_rg("DF"); cliente.setData_nascimento("20/20/2020"); cliente.setTel1("12234"); cliente.setTel2("1233546"); cliente.setEndereco("rua 50"); System.out.println(ClienteDAO.grava(cliente)); } }
UTF-8
Java
839
java
TestaClienteDAOgrava.java
Java
[ { "context": "rt Persistencia.ClienteDAO;\r\n\r\n/**\r\n *\r\n * @author laecio\r\n */\r\npublic class TestaClienteDAOgrava {\r\n \r\n", "end": 305, "score": 0.9982234835624695, "start": 299, "tag": "USERNAME", "value": "laecio" }, { "context": "liente = new Cliente();\r\n cliente.setNome(\"Maria da bala\");\r\n cliente.setCpf(\"202020\");\r\n cl", "end": 487, "score": 0.9998530149459839, "start": 474, "tag": "NAME", "value": "Maria da bala" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Testes.ClienteDAO; import Modelo.Cliente; import Persistencia.ClienteDAO; /** * * @author laecio */ public class TestaClienteDAOgrava { public static void main(String[] args) { Cliente cliente = new Cliente(); cliente.setNome("<NAME>"); cliente.setCpf("202020"); cliente.setRg("1234"); cliente.setUf_rg("DF"); cliente.setData_nascimento("20/20/2020"); cliente.setTel1("12234"); cliente.setTel2("1233546"); cliente.setEndereco("rua 50"); System.out.println(ClienteDAO.grava(cliente)); } }
832
0.611442
0.570918
33
23.424242
20.563324
79
false
false
0
0
0
0
0
0
0.484848
false
false
3
bb45d2dc58b12e2652b28d5e7419b8a1f2b6be17
11,072,425,699,977
fd96bf2065fa700d883636dcb1f6dfe216b27f12
/src/main/java/com/base/lang/StringUtils.java
e5da132cf3277986fd0d177b41c89effa1bdb295
[]
no_license
glsgolden/simple-base
https://github.com/glsgolden/simple-base
18a23832b54f78a883311f87585f246ecf16b455
86ba5c6002e3e168cbce33ac472d050493fa3a8c
refs/heads/master
2016-09-08T08:34:03.813000
2015-04-15T13:07:56
2015-04-15T13:07:56
33,222,154
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * @(#)StringUtils.java Oct 6, 2011 * * Copyright 2011-2016 Morningstar, Inc. All rights reserved. */ package com.base.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.collections.CollectionUtils; /** * @author Samon Liang * * @see org.apache.commons.lang.StringUtils */ public class StringUtils extends org.apache.commons.lang.StringUtils { public static final char[] WHITE_CHARACTER = { 160, 9135, 8239, 8194, 8195, 8201 }; public static final Map<Integer, Integer> WHITE_CHARACTER_MAP = new HashMap<Integer, Integer>(); static { for (char c : WHITE_CHARACTER) { WHITE_CHARACTER_MAP.put((int) c, (int) c); } } public static String matchAny(String str, String[] searchString) { if (str == null || str.length() == 0 || searchString == null || searchString.length == 0) { return null; } searchString = searchString.clone(); Arrays.sort(searchString, StringUtils.getStringLengthDescComparator()); for (int i = 0; i < str.length(); i++) { for (int j = 0; j < searchString.length; j++) { if (str.indexOf(searchString[j]) > -1) { return searchString[j]; } } } return null; } public static String getEquals(String str, String[] searchString) { if (str == null || str.length() == 0 || searchString == null || searchString.length == 0) { return null; } for (int i = 0; i < str.length(); i++) { for (int j = 0; j < searchString.length; j++) { if (str.equalsIgnoreCase(searchString[j])) { return searchString[j]; } } } return null; } public static boolean equalsAny(String str, String[] searchString) { String result = getEquals(str, searchString); return (result != null && str.equalsIgnoreCase(result)); } public static java.util.Comparator<String> getStringLengthDescComparator() { java.util.Comparator<String> cp = new java.util.Comparator<String>() { public int compare(String o1, String o2) { if (o1 == null && o2 != null) { return 1; } else if (o1 != null && o2 == null) { return -1; } else if (o1 == null && o2 == null) { return 0; } else if (o1.equals(o2)) { return 0; } if (o1.length() == o2.length()) { return 0; } if (o1.length() < o2.length()) { return 1; } if (o1.length() > o2.length()) { return -1; } return 0; } }; return cp; } public static boolean containsAny(String str, char[] chars) { if (str == null || str.length() == 0 || chars == null || chars.length == 0) { return false; } for (int i = 0; i < str.length(); i++) { for (int j = 0; j < chars.length; j++) { if (str.indexOf(String.valueOf(chars[j])) > -1) { return true; } } } return false; } public static boolean containsAny(String str, String[] searchString, boolean ignoreCase) { if (str == null || str.length() == 0 || searchString == null || searchString.length == 0) { return false; } for (int i = 0; i < str.length(); i++) { for (int j = 0; j < searchString.length; j++) { if (ignoreCase) { if (str.toLowerCase() .indexOf(searchString[j].toLowerCase()) > -1) { return true; } } else { if (str.indexOf(searchString[j]) > -1) { return true; } } } } return false; } public static boolean containsAny(String str, String[] searchString) { return containsAny(str, searchString, false); } /** * return string with normal blank character * * @param str * @return */ public static String replaceFullWidthBlank(String str) { StringBuffer sb = new StringBuffer(str.length()); for (char c : str.toCharArray()) { sb.append(WHITE_CHARACTER_MAP.get((int) c) != null ? ' ' : c); } return sb.toString(); } /** * * @param input * @param pattern * @param replace * @return */ public static String replaceAll(String input, String pattern, String replace, boolean ingoreCase) { if (StringUtils.isEmpty(input) || StringUtils.isEmpty(pattern)) return input; Pattern pat = null; if (!ingoreCase) { pat = Pattern.compile(pattern); } else { pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); } Matcher m = pat.matcher(input); return m.replaceAll(replace); } /** * * @param input * @param pattern * @param replace * @return */ public static String replaceAll(String input, String pattern, String replace) { if (StringUtils.isEmpty(input) || StringUtils.isEmpty(pattern)) return input; return input.replaceAll(pattern, replace); } /** * <p> * Replace the string that match the pattern and case is insensitive. * </p> * * @param input * @param pattern * @param replaceStr * @return */ public static String replaceIngoreCase(String input, String pattern, String replace) { return replaceAll(input, pattern, replace, true); } public static String replaceIngoreCase(String input, String pattern, String replace, boolean clearBlank) { if (isNotEmpty(input)) { if (clearBlank) { input = input.replace(" ", ""); pattern = pattern.replace(" ", ""); } return replaceIngoreCase(input, pattern, replace); } return input; } public static String trimLeft(String str) { return str.replaceAll("^\\s+", ""); } public static String trimRight(String str) { return str.replaceAll("\\s+$", ""); } /** * * @param str * @return */ public static String lowerFirstChar(String str) { if (isEmpty(str) || str.length() == 0) return str; return str.substring(0, 1).toLowerCase() + str.substring(1); } /** * * @param str * @param startIndex * @param endIndex * @return */ public static String lower(String str, int startIndex, int endIndex) { if (isEmpty(str) || str.length() == 0) return str; if (startIndex <= 0) startIndex = 0; if (endIndex > str.length()) endIndex = str.length(); if (startIndex > endIndex) { int temp = startIndex; endIndex = startIndex; startIndex = temp; } return str.substring(0, startIndex) + str.substring(startIndex, endIndex).toLowerCase() + str.substring(endIndex, str.length()); } /** * * @param str * @return */ public static String removeAllSpace(String str) { if (str == null) return ""; return str.replaceAll("\\s", ""); } /** * replace non-ansi blank character to non-ansi * * @param str * @return */ public static String replaceWhiteCharacter(String str) { if (str == null) { return ""; } StringBuffer sb = new StringBuffer(str.length()); for (char c : str.toCharArray()) { if (Character.isWhitespace(c) && c != ' ' && c != '\n' && c != '\t' && c != '\r') { sb.append(' '); } else { sb.append(c); } } return sb.toString(); } /** * * @param str * @return */ public static String keepOneSpace(String str) { if (str == null) return ""; return str.replaceAll("\\s{2,}", " "); } /** * Check that the given CharSequence is neither <code>null</code> nor of * length 0. Note: Will return <code>true</code> for a CharSequence that * purely consists of whitespace. * <p> * * <pre> * StringUtils.hasLength(null) = false * StringUtils.hasLength("") = false * StringUtils.hasLength(" ") = true * StringUtils.hasLength("Hello") = true * </pre> * * @param str * the CharSequence to check (may be <code>null</code>) * @return <code>true</code> if the CharSequence is not null and has length * @see #hasText(String) */ public static boolean hasLength(CharSequence str) { return (str != null && str.length() > 0); } /** * Check that the given String is neither <code>null</code> nor of length 0. * Note: Will return <code>true</code> for a String that purely consists of * whitespace. * * @param str * the String to check (may be <code>null</code>) * @return <code>true</code> if the String is not null and has length * @see #hasLength(CharSequence) */ public static boolean hasLength(String str) { return hasLength((CharSequence) str); } /** * Check whether the given CharSequence has actual text. More specifically, * returns <code>true</code> if the string not <code>null</code>, its length * is greater than 0, and it contains at least one non-whitespace character. * <p> * * <pre> * StringUtils.hasText(null) = false * StringUtils.hasText("") = false * StringUtils.hasText(" ") = false * StringUtils.hasText("12345") = true * StringUtils.hasText(" 12345 ") = true * </pre> * * @param str * the CharSequence to check (may be <code>null</code>) * @return <code>true</code> if the CharSequence is not <code>null</code>, * its length is greater than 0, and it does not contain whitespace * only * @see java.lang.Character#isWhitespace */ public static boolean hasText(CharSequence str) { if (!hasLength(str)) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * Check whether the given String has actual text. More specifically, * returns <code>true</code> if the string not <code>null</code>, its length * is greater than 0, and it contains at least one non-whitespace character. * * @param str * the String to check (may be <code>null</code>) * @return <code>true</code> if the String is not <code>null</code>, its * length is greater than 0, and it does not contain whitespace only * @see #hasText(CharSequence) */ public static boolean hasText(String str) { return hasText((CharSequence) str); } /** * Quote the given String with single quotes. * * @param str * the input String (e.g. "myString") * @return the quoted String (e.g. "'myString'"), or * <code>null<code> if the input was <code>null</code> */ public static String quote(String str) { return (str != null ? "'" + str + "'" : null); } /** * Remove duplicate Strings from the given array. Also sorts the array, as * it uses a TreeSet. * * @param array * the String array * @return an array without duplicates, in natural sort order */ public static String[] removeDuplicateStrings(String[] array) { if (ArrayUtils.isEmpty(array)) { return array; } Set<String> set = new TreeSet<String>(); for (String element : array) { set.add(element); } return toStringArray(set); } /** * Copy the given Collection into a String array. The Collection must * contain String elements only. * * @param collection * the Collection to copy * @return the String array (<code>null</code> if the passed-in Collection * was <code>null</code>) */ public static String[] toStringArray(Collection<String> collection) { if (collection == null) { return null; } return collection.toArray(new String[collection.size()]); } /** * Copy the given Enumeration into a String array. The Enumeration must * contain String elements only. * * @param enumeration * the Enumeration to copy * @return the String array (<code>null</code> if the passed-in Enumeration * was <code>null</code>) */ public static String[] toStringArray(Enumeration<String> enumeration) { if (enumeration == null) { return null; } List<String> list = Collections.list(enumeration); return list.toArray(new String[list.size()]); } /** * Trim the elements of the given String array, calling * <code>String.trim()</code> on each of them. * * @param array * the original String array * @return the resulting array (of the same size) with trimmed elements */ public static String[] trimArrayElements(String[] array) { if (ArrayUtils.isEmpty(array)) { return new String[0]; } String[] result = new String[array.length]; for (int i = 0; i < array.length; i++) { String element = array[i]; result[i] = (element != null ? element.trim() : null); } return result; } /** * Take a String which is a delimited list and convert it to a String array. * <p> * A single delimiter can consists of more than one character: It will still * be considered as single delimiter string, rather than as bunch of * potential delimiter characters - in contrast to * <code>tokenizeToStringArray</code>. * * @param str * the input String * @param delimiter * the delimiter between elements (this is a single delimiter, * rather than a bunch individual delimiter characters) * @return an array of the tokens in the list * @see #tokenizeToStringArray */ public static String[] delimitedListToStringArray(String str, String delimiter) { return delimitedListToStringArray(str, delimiter, null); } /** * Delete any character in a given String. * * @param inString * the original String * @param charsToDelete * a set of characters to delete. E.g. "az\n" will delete 'a's, * 'z's and new lines. * @return the resulting String */ public static String deleteAny(String inString, String charsToDelete) { if (!hasLength(inString) || !hasLength(charsToDelete)) { return inString; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < inString.length(); i++) { char c = inString.charAt(i); if (charsToDelete.indexOf(c) == -1) { sb.append(c); } } return sb.toString(); } /** * Take a String which is a delimited list and convert it to a String array. * <p> * A single delimiter can consists of more than one character: It will still * be considered as single delimiter string, rather than as bunch of * potential delimiter characters - in contrast to * <code>tokenizeToStringArray</code>. * * @param str * the input String * @param delimiter * the delimiter between elements (this is a single delimiter, * rather than a bunch individual delimiter characters) * @param charsToDelete * a set of characters to delete. Useful for deleting unwanted * line breaks: e.g. "\r\n\f" will delete all new lines and line * feeds in a String. * @return an array of the tokens in the list * @see #tokenizeToStringArray */ public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) { if (str == null) { return new String[0]; } if (delimiter == null) { return new String[] { str }; } List<String> result = new ArrayList<String>(); if ("".equals(delimiter)) { for (int i = 0; i < str.length(); i++) { result.add(deleteAny(str.substring(i, i + 1), charsToDelete)); } } else { int pos = 0; int delPos; while ((delPos = str.indexOf(delimiter, pos)) != -1) { result.add(deleteAny(str.substring(pos, delPos), charsToDelete)); pos = delPos + delimiter.length(); } if (str.length() > 0 && pos <= str.length()) { // Add rest of String, but not in case of empty input. result.add(deleteAny(str.substring(pos), charsToDelete)); } } return toStringArray(result); } /** * Convert a CSV list into an array of Strings. * * @param str * the input String * @return an array of Strings, or the empty array in case of empty input */ public static String[] commaDelimitedListToStringArray(String str) { return delimitedListToStringArray(str, ","); } /** * Convenience method to convert a CSV string list to a set. Note that this * will suppress duplicates. * * @param str * the input String * @return a Set of String entries in the list */ public static Set<String> commaDelimitedListToSet(String str) { Set<String> set = new TreeSet<String>(); String[] tokens = commaDelimitedListToStringArray(str); for (String token : tokens) { set.add(token); } return set; } /** * Convenience method to return a Collection as a delimited (e.g. CSV) * String. E.g. useful for <code>toString()</code> implementations. * * @param coll * the Collection to display * @param delim * the delimiter to use (probably a ",") * @param prefix * the String to start each element with * @param suffix * the String to end each element with * @return the delimited String */ public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) { if (CollectionUtils.isEmpty(coll)) { return ""; } StringBuilder sb = new StringBuilder(); Iterator it = coll.iterator(); while (it.hasNext()) { sb.append(prefix).append(it.next()).append(suffix); if (it.hasNext()) { sb.append(delim); } } return sb.toString(); } /** * Convenience method to return a Collection as a delimited (e.g. CSV) * String. E.g. useful for <code>toString()</code> implementations. * * @param coll * the Collection to display * @param delim * the delimiter to use (probably a ",") * @return the delimited String */ public static String collectionToDelimitedString(Collection coll, String delim) { return collectionToDelimitedString(coll, delim, "", ""); } /** * Convenience method to return a Collection as a CSV String. E.g. useful * for <code>toString()</code> implementations. * * @param coll * the Collection to display * @return the delimited String */ public static String collectionToCommaDelimitedString(Collection coll) { return collectionToDelimitedString(coll, ","); } /** * Convenience method to return a String array as a delimited (e.g. CSV) * String. E.g. useful for <code>toString()</code> implementations. * * @param arr * the array to display * @param delim * the delimiter to use (probably a ",") * @return the delimited String */ public static String arrayToDelimitedString(Object[] arr, String delim) { if (ArrayUtils.isEmpty(arr)) { return ""; } if (arr.length == 1) { return ObjectUtils.nullSafeToString(arr[0]); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (i > 0) { sb.append(delim); } sb.append(arr[i]); } return sb.toString(); } /** * Convenience method to return a String array as a CSV String. E.g. useful * for <code>toString()</code> implementations. * * @param arr * the array to display * @return the delimited String */ public static String arrayToCommaDelimitedString(Object[] arr) { return arrayToDelimitedString(arr, ","); } /** * Check whether the given CharSequence contains any whitespace characters. * * @param str * the CharSequence to check (may be <code>null</code>) * @return <code>true</code> if the CharSequence is not empty and contains * at least 1 whitespace character * @see java.lang.Character#isWhitespace */ public static boolean containsWhitespace(CharSequence str) { if (!hasLength(str)) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * Check whether the given String contains any whitespace characters. * * @param str * the String to check (may be <code>null</code>) * @return <code>true</code> if the String is not empty and contains at * least 1 whitespace character * @see #containsWhitespace(CharSequence) */ public static boolean containsWhitespace(String str) { return containsWhitespace((CharSequence) str); } /** * Trim leading and trailing whitespace from the given String. * * @param str * the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) { buf.deleteCharAt(0); } while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) { buf.deleteCharAt(buf.length() - 1); } return buf.toString(); } /** * Trim <i>all</i> whitespace from the given String: leading, trailing, and * inbetween characters. * * @param str * the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimAllWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); int index = 0; while (buf.length() > index) { if (Character.isWhitespace(buf.charAt(index))) { buf.deleteCharAt(index); } else { index++; } } return buf.toString(); } /** * Trim leading whitespace from the given String. * * @param str * the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimLeadingWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) { buf.deleteCharAt(0); } return buf.toString(); } /** * Trim trailing whitespace from the given String. * * @param str * the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimTrailingWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) { buf.deleteCharAt(buf.length() - 1); } return buf.toString(); } /** * Trim all occurences of the supplied leading character from the given * String. * * @param str * the String to check * @param leadingCharacter * the leading character to be trimmed * @return the trimmed String */ public static String trimLeadingCharacter(String str, char leadingCharacter) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) { buf.deleteCharAt(0); } return buf.toString(); } /** * Trim all occurences of the supplied trailing character from the given * String. * * @param str * the String to check * @param trailingCharacter * the trailing character to be trimmed * @return the trimmed String */ public static String trimTrailingCharacter(String str, char trailingCharacter) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && buf.charAt(buf.length() - 1) == trailingCharacter) { buf.deleteCharAt(buf.length() - 1); } return buf.toString(); } /** * Test if the given String starts with the specified prefix, ignoring * upper/lower case. * * @param str * the String to check * @param prefix * the prefix to look for * @see java.lang.String#startsWith */ public static boolean startsWithIgnoreCase(String str, String prefix) { if (str == null || prefix == null) { return false; } if (str.startsWith(prefix)) { return true; } if (str.length() < prefix.length()) { return false; } String lcStr = str.substring(0, prefix.length()).toLowerCase(); String lcPrefix = prefix.toLowerCase(); return lcStr.equals(lcPrefix); } /** * Test if the given String ends with the specified suffix, ignoring * upper/lower case. * * @param str * the String to check * @param suffix * the suffix to look for * @see java.lang.String#endsWith */ public static boolean endsWithIgnoreCase(String str, String suffix) { if (str == null || suffix == null) { return false; } if (str.endsWith(suffix)) { return true; } if (str.length() < suffix.length()) { return false; } String lcStr = str.substring(str.length() - suffix.length()) .toLowerCase(); String lcSuffix = suffix.toLowerCase(); return lcStr.equals(lcSuffix); } /** * Test whether the given string matches the given substring at the given * index. * * @param str * the original string (or StringBuffer) * @param index * the index in the original string to start matching against * @param substring * the substring to match at the given index */ public static boolean substringMatch(CharSequence str, int index, CharSequence substring) { for (int j = 0; j < substring.length(); j++) { int i = index + j; if (i >= str.length() || str.charAt(i) != substring.charAt(j)) { return false; } } return true; } /** * Turn the given Object into a String with single quotes if it is a String; * keeping the Object as-is else. * * @param obj * the input Object (e.g. "myString") * @return the quoted String (e.g. "'myString'"), or the input object as-is * if not a String */ public static Object quoteIfString(Object obj) { return (obj instanceof String ? quote((String) obj) : obj); } /** * check Chinese * * @param s * @return */ public static boolean containsChinese(String s) { Pattern pat = Pattern.compile("[\u4E00-\u9FA5]"); Matcher m = pat.matcher(s); while (m.find()) { return true; } return false; } /** * get similarity for two string. * * @param str1 * @param str2 * @return */ public static float getSimilarity(String str1, String str2) { int len1 = str1.length(); int len2 = str2.length(); if (str1.trim().equals(str2.trim())) { return 1; } int[][] dif = new int[len1 + 1][len2 + 1]; for (int a = 0; a <= len1; a++) { dif[a][0] = a; } for (int a = 0; a <= len2; a++) { dif[0][a] = a; } int temp; for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) { temp = 0; } else { temp = 1; } dif[i][j] = min(dif[i - 1][j - 1] + temp, dif[i][j - 1] + 1, dif[i - 1][j] + 1); } } float similarity = 1 - (float) dif[len1][len2] / Math.max(str1.length(), str2.length()); return similarity; } private static int min(int... is) { int min = Integer.MAX_VALUE; for (int i : is) { if (min > i) { min = i; } } return min; } }
UTF-8
Java
28,302
java
StringUtils.java
Java
[ { "context": "mons.collections.CollectionUtils;\n\n\n/**\n * @author Samon Liang\n * \n * @see org.apache.commons.lang.StringUtils\n ", "end": 569, "score": 0.9997731447219849, "start": 558, "tag": "NAME", "value": "Samon Liang" } ]
null
[]
/* * @(#)StringUtils.java Oct 6, 2011 * * Copyright 2011-2016 Morningstar, Inc. All rights reserved. */ package com.base.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.collections.CollectionUtils; /** * @author <NAME> * * @see org.apache.commons.lang.StringUtils */ public class StringUtils extends org.apache.commons.lang.StringUtils { public static final char[] WHITE_CHARACTER = { 160, 9135, 8239, 8194, 8195, 8201 }; public static final Map<Integer, Integer> WHITE_CHARACTER_MAP = new HashMap<Integer, Integer>(); static { for (char c : WHITE_CHARACTER) { WHITE_CHARACTER_MAP.put((int) c, (int) c); } } public static String matchAny(String str, String[] searchString) { if (str == null || str.length() == 0 || searchString == null || searchString.length == 0) { return null; } searchString = searchString.clone(); Arrays.sort(searchString, StringUtils.getStringLengthDescComparator()); for (int i = 0; i < str.length(); i++) { for (int j = 0; j < searchString.length; j++) { if (str.indexOf(searchString[j]) > -1) { return searchString[j]; } } } return null; } public static String getEquals(String str, String[] searchString) { if (str == null || str.length() == 0 || searchString == null || searchString.length == 0) { return null; } for (int i = 0; i < str.length(); i++) { for (int j = 0; j < searchString.length; j++) { if (str.equalsIgnoreCase(searchString[j])) { return searchString[j]; } } } return null; } public static boolean equalsAny(String str, String[] searchString) { String result = getEquals(str, searchString); return (result != null && str.equalsIgnoreCase(result)); } public static java.util.Comparator<String> getStringLengthDescComparator() { java.util.Comparator<String> cp = new java.util.Comparator<String>() { public int compare(String o1, String o2) { if (o1 == null && o2 != null) { return 1; } else if (o1 != null && o2 == null) { return -1; } else if (o1 == null && o2 == null) { return 0; } else if (o1.equals(o2)) { return 0; } if (o1.length() == o2.length()) { return 0; } if (o1.length() < o2.length()) { return 1; } if (o1.length() > o2.length()) { return -1; } return 0; } }; return cp; } public static boolean containsAny(String str, char[] chars) { if (str == null || str.length() == 0 || chars == null || chars.length == 0) { return false; } for (int i = 0; i < str.length(); i++) { for (int j = 0; j < chars.length; j++) { if (str.indexOf(String.valueOf(chars[j])) > -1) { return true; } } } return false; } public static boolean containsAny(String str, String[] searchString, boolean ignoreCase) { if (str == null || str.length() == 0 || searchString == null || searchString.length == 0) { return false; } for (int i = 0; i < str.length(); i++) { for (int j = 0; j < searchString.length; j++) { if (ignoreCase) { if (str.toLowerCase() .indexOf(searchString[j].toLowerCase()) > -1) { return true; } } else { if (str.indexOf(searchString[j]) > -1) { return true; } } } } return false; } public static boolean containsAny(String str, String[] searchString) { return containsAny(str, searchString, false); } /** * return string with normal blank character * * @param str * @return */ public static String replaceFullWidthBlank(String str) { StringBuffer sb = new StringBuffer(str.length()); for (char c : str.toCharArray()) { sb.append(WHITE_CHARACTER_MAP.get((int) c) != null ? ' ' : c); } return sb.toString(); } /** * * @param input * @param pattern * @param replace * @return */ public static String replaceAll(String input, String pattern, String replace, boolean ingoreCase) { if (StringUtils.isEmpty(input) || StringUtils.isEmpty(pattern)) return input; Pattern pat = null; if (!ingoreCase) { pat = Pattern.compile(pattern); } else { pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); } Matcher m = pat.matcher(input); return m.replaceAll(replace); } /** * * @param input * @param pattern * @param replace * @return */ public static String replaceAll(String input, String pattern, String replace) { if (StringUtils.isEmpty(input) || StringUtils.isEmpty(pattern)) return input; return input.replaceAll(pattern, replace); } /** * <p> * Replace the string that match the pattern and case is insensitive. * </p> * * @param input * @param pattern * @param replaceStr * @return */ public static String replaceIngoreCase(String input, String pattern, String replace) { return replaceAll(input, pattern, replace, true); } public static String replaceIngoreCase(String input, String pattern, String replace, boolean clearBlank) { if (isNotEmpty(input)) { if (clearBlank) { input = input.replace(" ", ""); pattern = pattern.replace(" ", ""); } return replaceIngoreCase(input, pattern, replace); } return input; } public static String trimLeft(String str) { return str.replaceAll("^\\s+", ""); } public static String trimRight(String str) { return str.replaceAll("\\s+$", ""); } /** * * @param str * @return */ public static String lowerFirstChar(String str) { if (isEmpty(str) || str.length() == 0) return str; return str.substring(0, 1).toLowerCase() + str.substring(1); } /** * * @param str * @param startIndex * @param endIndex * @return */ public static String lower(String str, int startIndex, int endIndex) { if (isEmpty(str) || str.length() == 0) return str; if (startIndex <= 0) startIndex = 0; if (endIndex > str.length()) endIndex = str.length(); if (startIndex > endIndex) { int temp = startIndex; endIndex = startIndex; startIndex = temp; } return str.substring(0, startIndex) + str.substring(startIndex, endIndex).toLowerCase() + str.substring(endIndex, str.length()); } /** * * @param str * @return */ public static String removeAllSpace(String str) { if (str == null) return ""; return str.replaceAll("\\s", ""); } /** * replace non-ansi blank character to non-ansi * * @param str * @return */ public static String replaceWhiteCharacter(String str) { if (str == null) { return ""; } StringBuffer sb = new StringBuffer(str.length()); for (char c : str.toCharArray()) { if (Character.isWhitespace(c) && c != ' ' && c != '\n' && c != '\t' && c != '\r') { sb.append(' '); } else { sb.append(c); } } return sb.toString(); } /** * * @param str * @return */ public static String keepOneSpace(String str) { if (str == null) return ""; return str.replaceAll("\\s{2,}", " "); } /** * Check that the given CharSequence is neither <code>null</code> nor of * length 0. Note: Will return <code>true</code> for a CharSequence that * purely consists of whitespace. * <p> * * <pre> * StringUtils.hasLength(null) = false * StringUtils.hasLength("") = false * StringUtils.hasLength(" ") = true * StringUtils.hasLength("Hello") = true * </pre> * * @param str * the CharSequence to check (may be <code>null</code>) * @return <code>true</code> if the CharSequence is not null and has length * @see #hasText(String) */ public static boolean hasLength(CharSequence str) { return (str != null && str.length() > 0); } /** * Check that the given String is neither <code>null</code> nor of length 0. * Note: Will return <code>true</code> for a String that purely consists of * whitespace. * * @param str * the String to check (may be <code>null</code>) * @return <code>true</code> if the String is not null and has length * @see #hasLength(CharSequence) */ public static boolean hasLength(String str) { return hasLength((CharSequence) str); } /** * Check whether the given CharSequence has actual text. More specifically, * returns <code>true</code> if the string not <code>null</code>, its length * is greater than 0, and it contains at least one non-whitespace character. * <p> * * <pre> * StringUtils.hasText(null) = false * StringUtils.hasText("") = false * StringUtils.hasText(" ") = false * StringUtils.hasText("12345") = true * StringUtils.hasText(" 12345 ") = true * </pre> * * @param str * the CharSequence to check (may be <code>null</code>) * @return <code>true</code> if the CharSequence is not <code>null</code>, * its length is greater than 0, and it does not contain whitespace * only * @see java.lang.Character#isWhitespace */ public static boolean hasText(CharSequence str) { if (!hasLength(str)) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * Check whether the given String has actual text. More specifically, * returns <code>true</code> if the string not <code>null</code>, its length * is greater than 0, and it contains at least one non-whitespace character. * * @param str * the String to check (may be <code>null</code>) * @return <code>true</code> if the String is not <code>null</code>, its * length is greater than 0, and it does not contain whitespace only * @see #hasText(CharSequence) */ public static boolean hasText(String str) { return hasText((CharSequence) str); } /** * Quote the given String with single quotes. * * @param str * the input String (e.g. "myString") * @return the quoted String (e.g. "'myString'"), or * <code>null<code> if the input was <code>null</code> */ public static String quote(String str) { return (str != null ? "'" + str + "'" : null); } /** * Remove duplicate Strings from the given array. Also sorts the array, as * it uses a TreeSet. * * @param array * the String array * @return an array without duplicates, in natural sort order */ public static String[] removeDuplicateStrings(String[] array) { if (ArrayUtils.isEmpty(array)) { return array; } Set<String> set = new TreeSet<String>(); for (String element : array) { set.add(element); } return toStringArray(set); } /** * Copy the given Collection into a String array. The Collection must * contain String elements only. * * @param collection * the Collection to copy * @return the String array (<code>null</code> if the passed-in Collection * was <code>null</code>) */ public static String[] toStringArray(Collection<String> collection) { if (collection == null) { return null; } return collection.toArray(new String[collection.size()]); } /** * Copy the given Enumeration into a String array. The Enumeration must * contain String elements only. * * @param enumeration * the Enumeration to copy * @return the String array (<code>null</code> if the passed-in Enumeration * was <code>null</code>) */ public static String[] toStringArray(Enumeration<String> enumeration) { if (enumeration == null) { return null; } List<String> list = Collections.list(enumeration); return list.toArray(new String[list.size()]); } /** * Trim the elements of the given String array, calling * <code>String.trim()</code> on each of them. * * @param array * the original String array * @return the resulting array (of the same size) with trimmed elements */ public static String[] trimArrayElements(String[] array) { if (ArrayUtils.isEmpty(array)) { return new String[0]; } String[] result = new String[array.length]; for (int i = 0; i < array.length; i++) { String element = array[i]; result[i] = (element != null ? element.trim() : null); } return result; } /** * Take a String which is a delimited list and convert it to a String array. * <p> * A single delimiter can consists of more than one character: It will still * be considered as single delimiter string, rather than as bunch of * potential delimiter characters - in contrast to * <code>tokenizeToStringArray</code>. * * @param str * the input String * @param delimiter * the delimiter between elements (this is a single delimiter, * rather than a bunch individual delimiter characters) * @return an array of the tokens in the list * @see #tokenizeToStringArray */ public static String[] delimitedListToStringArray(String str, String delimiter) { return delimitedListToStringArray(str, delimiter, null); } /** * Delete any character in a given String. * * @param inString * the original String * @param charsToDelete * a set of characters to delete. E.g. "az\n" will delete 'a's, * 'z's and new lines. * @return the resulting String */ public static String deleteAny(String inString, String charsToDelete) { if (!hasLength(inString) || !hasLength(charsToDelete)) { return inString; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < inString.length(); i++) { char c = inString.charAt(i); if (charsToDelete.indexOf(c) == -1) { sb.append(c); } } return sb.toString(); } /** * Take a String which is a delimited list and convert it to a String array. * <p> * A single delimiter can consists of more than one character: It will still * be considered as single delimiter string, rather than as bunch of * potential delimiter characters - in contrast to * <code>tokenizeToStringArray</code>. * * @param str * the input String * @param delimiter * the delimiter between elements (this is a single delimiter, * rather than a bunch individual delimiter characters) * @param charsToDelete * a set of characters to delete. Useful for deleting unwanted * line breaks: e.g. "\r\n\f" will delete all new lines and line * feeds in a String. * @return an array of the tokens in the list * @see #tokenizeToStringArray */ public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) { if (str == null) { return new String[0]; } if (delimiter == null) { return new String[] { str }; } List<String> result = new ArrayList<String>(); if ("".equals(delimiter)) { for (int i = 0; i < str.length(); i++) { result.add(deleteAny(str.substring(i, i + 1), charsToDelete)); } } else { int pos = 0; int delPos; while ((delPos = str.indexOf(delimiter, pos)) != -1) { result.add(deleteAny(str.substring(pos, delPos), charsToDelete)); pos = delPos + delimiter.length(); } if (str.length() > 0 && pos <= str.length()) { // Add rest of String, but not in case of empty input. result.add(deleteAny(str.substring(pos), charsToDelete)); } } return toStringArray(result); } /** * Convert a CSV list into an array of Strings. * * @param str * the input String * @return an array of Strings, or the empty array in case of empty input */ public static String[] commaDelimitedListToStringArray(String str) { return delimitedListToStringArray(str, ","); } /** * Convenience method to convert a CSV string list to a set. Note that this * will suppress duplicates. * * @param str * the input String * @return a Set of String entries in the list */ public static Set<String> commaDelimitedListToSet(String str) { Set<String> set = new TreeSet<String>(); String[] tokens = commaDelimitedListToStringArray(str); for (String token : tokens) { set.add(token); } return set; } /** * Convenience method to return a Collection as a delimited (e.g. CSV) * String. E.g. useful for <code>toString()</code> implementations. * * @param coll * the Collection to display * @param delim * the delimiter to use (probably a ",") * @param prefix * the String to start each element with * @param suffix * the String to end each element with * @return the delimited String */ public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) { if (CollectionUtils.isEmpty(coll)) { return ""; } StringBuilder sb = new StringBuilder(); Iterator it = coll.iterator(); while (it.hasNext()) { sb.append(prefix).append(it.next()).append(suffix); if (it.hasNext()) { sb.append(delim); } } return sb.toString(); } /** * Convenience method to return a Collection as a delimited (e.g. CSV) * String. E.g. useful for <code>toString()</code> implementations. * * @param coll * the Collection to display * @param delim * the delimiter to use (probably a ",") * @return the delimited String */ public static String collectionToDelimitedString(Collection coll, String delim) { return collectionToDelimitedString(coll, delim, "", ""); } /** * Convenience method to return a Collection as a CSV String. E.g. useful * for <code>toString()</code> implementations. * * @param coll * the Collection to display * @return the delimited String */ public static String collectionToCommaDelimitedString(Collection coll) { return collectionToDelimitedString(coll, ","); } /** * Convenience method to return a String array as a delimited (e.g. CSV) * String. E.g. useful for <code>toString()</code> implementations. * * @param arr * the array to display * @param delim * the delimiter to use (probably a ",") * @return the delimited String */ public static String arrayToDelimitedString(Object[] arr, String delim) { if (ArrayUtils.isEmpty(arr)) { return ""; } if (arr.length == 1) { return ObjectUtils.nullSafeToString(arr[0]); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (i > 0) { sb.append(delim); } sb.append(arr[i]); } return sb.toString(); } /** * Convenience method to return a String array as a CSV String. E.g. useful * for <code>toString()</code> implementations. * * @param arr * the array to display * @return the delimited String */ public static String arrayToCommaDelimitedString(Object[] arr) { return arrayToDelimitedString(arr, ","); } /** * Check whether the given CharSequence contains any whitespace characters. * * @param str * the CharSequence to check (may be <code>null</code>) * @return <code>true</code> if the CharSequence is not empty and contains * at least 1 whitespace character * @see java.lang.Character#isWhitespace */ public static boolean containsWhitespace(CharSequence str) { if (!hasLength(str)) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * Check whether the given String contains any whitespace characters. * * @param str * the String to check (may be <code>null</code>) * @return <code>true</code> if the String is not empty and contains at * least 1 whitespace character * @see #containsWhitespace(CharSequence) */ public static boolean containsWhitespace(String str) { return containsWhitespace((CharSequence) str); } /** * Trim leading and trailing whitespace from the given String. * * @param str * the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) { buf.deleteCharAt(0); } while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) { buf.deleteCharAt(buf.length() - 1); } return buf.toString(); } /** * Trim <i>all</i> whitespace from the given String: leading, trailing, and * inbetween characters. * * @param str * the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimAllWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); int index = 0; while (buf.length() > index) { if (Character.isWhitespace(buf.charAt(index))) { buf.deleteCharAt(index); } else { index++; } } return buf.toString(); } /** * Trim leading whitespace from the given String. * * @param str * the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimLeadingWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) { buf.deleteCharAt(0); } return buf.toString(); } /** * Trim trailing whitespace from the given String. * * @param str * the String to check * @return the trimmed String * @see java.lang.Character#isWhitespace */ public static String trimTrailingWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) { buf.deleteCharAt(buf.length() - 1); } return buf.toString(); } /** * Trim all occurences of the supplied leading character from the given * String. * * @param str * the String to check * @param leadingCharacter * the leading character to be trimmed * @return the trimmed String */ public static String trimLeadingCharacter(String str, char leadingCharacter) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) { buf.deleteCharAt(0); } return buf.toString(); } /** * Trim all occurences of the supplied trailing character from the given * String. * * @param str * the String to check * @param trailingCharacter * the trailing character to be trimmed * @return the trimmed String */ public static String trimTrailingCharacter(String str, char trailingCharacter) { if (!hasLength(str)) { return str; } StringBuffer buf = new StringBuffer(str); while (buf.length() > 0 && buf.charAt(buf.length() - 1) == trailingCharacter) { buf.deleteCharAt(buf.length() - 1); } return buf.toString(); } /** * Test if the given String starts with the specified prefix, ignoring * upper/lower case. * * @param str * the String to check * @param prefix * the prefix to look for * @see java.lang.String#startsWith */ public static boolean startsWithIgnoreCase(String str, String prefix) { if (str == null || prefix == null) { return false; } if (str.startsWith(prefix)) { return true; } if (str.length() < prefix.length()) { return false; } String lcStr = str.substring(0, prefix.length()).toLowerCase(); String lcPrefix = prefix.toLowerCase(); return lcStr.equals(lcPrefix); } /** * Test if the given String ends with the specified suffix, ignoring * upper/lower case. * * @param str * the String to check * @param suffix * the suffix to look for * @see java.lang.String#endsWith */ public static boolean endsWithIgnoreCase(String str, String suffix) { if (str == null || suffix == null) { return false; } if (str.endsWith(suffix)) { return true; } if (str.length() < suffix.length()) { return false; } String lcStr = str.substring(str.length() - suffix.length()) .toLowerCase(); String lcSuffix = suffix.toLowerCase(); return lcStr.equals(lcSuffix); } /** * Test whether the given string matches the given substring at the given * index. * * @param str * the original string (or StringBuffer) * @param index * the index in the original string to start matching against * @param substring * the substring to match at the given index */ public static boolean substringMatch(CharSequence str, int index, CharSequence substring) { for (int j = 0; j < substring.length(); j++) { int i = index + j; if (i >= str.length() || str.charAt(i) != substring.charAt(j)) { return false; } } return true; } /** * Turn the given Object into a String with single quotes if it is a String; * keeping the Object as-is else. * * @param obj * the input Object (e.g. "myString") * @return the quoted String (e.g. "'myString'"), or the input object as-is * if not a String */ public static Object quoteIfString(Object obj) { return (obj instanceof String ? quote((String) obj) : obj); } /** * check Chinese * * @param s * @return */ public static boolean containsChinese(String s) { Pattern pat = Pattern.compile("[\u4E00-\u9FA5]"); Matcher m = pat.matcher(s); while (m.find()) { return true; } return false; } /** * get similarity for two string. * * @param str1 * @param str2 * @return */ public static float getSimilarity(String str1, String str2) { int len1 = str1.length(); int len2 = str2.length(); if (str1.trim().equals(str2.trim())) { return 1; } int[][] dif = new int[len1 + 1][len2 + 1]; for (int a = 0; a <= len1; a++) { dif[a][0] = a; } for (int a = 0; a <= len2; a++) { dif[0][a] = a; } int temp; for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) { temp = 0; } else { temp = 1; } dif[i][j] = min(dif[i - 1][j - 1] + temp, dif[i][j - 1] + 1, dif[i - 1][j] + 1); } } float similarity = 1 - (float) dif[len1][len2] / Math.max(str1.length(), str2.length()); return similarity; } private static int min(int... is) { int min = Integer.MAX_VALUE; for (int i : is) { if (min > i) { min = i; } } return min; } }
28,297
0.599074
0.59229
1,009
27.049555
23.533699
100
false
false
0
0
0
0
0
0
0.888008
false
false
3
fb34870c907028e3ccbe01075b16e7ec3acb28a0
9,320,079,037,757
91aaf09590692a3f35ab43cbd81acab3ecf3b932
/hexagon-ddd-commons/src/main/java/org/hexagonframework/ddd/domain/AggregateRoot.java
c8a4a3fe59de591eef2c41d433d8d2a9919b9d08
[ "Apache-2.0" ]
permissive
hexagonframework/hexagon-framework
https://github.com/hexagonframework/hexagon-framework
3751bf800aa3636658ccf4d6fbbf26c6f23cbdf1
86e6305a1967b595410eee4a5c55d611fdbae2d1
refs/heads/master
2020-06-01T06:32:23.897000
2018-04-08T01:45:21
2018-04-08T01:45:21
94,065,287
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.hexagonframework.ddd.domain; import java.io.Serializable; /** * @author Xuegui Yuan */ public interface AggregateRoot<ID extends Serializable> extends Entity<ID> { void apply(DomainEvent domainEvent); }
UTF-8
Java
225
java
AggregateRoot.java
Java
[ { "context": "ain;\n\nimport java.io.Serializable;\n\n/**\n * @author Xuegui Yuan\n */\npublic interface AggregateRoot<ID extends Ser", "end": 98, "score": 0.999832034111023, "start": 87, "tag": "NAME", "value": "Xuegui Yuan" } ]
null
[]
package org.hexagonframework.ddd.domain; import java.io.Serializable; /** * @author <NAME> */ public interface AggregateRoot<ID extends Serializable> extends Entity<ID> { void apply(DomainEvent domainEvent); }
220
0.755556
0.755556
12
17.75
23.241934
76
false
false
0
0
0
0
0
0
0.25
false
false
3
9302fe4760b746c2449d018f75b907f5d9989d86
13,958,643,715,956
61775d5ab720aaba9280f8bd3cc327498c10d96e
/src/com.mentor.nucleus.bp.ui.explorer/src/com/mentor/nucleus/bp/ui/explorer/ui/actions/ExplorerPasteAction.java
a6dd1b9ef46af6786ddfd9e6883853dd14a06bb4
[ "Apache-2.0" ]
permissive
NDGuthrie/bposs
https://github.com/NDGuthrie/bposs
bf1cbec3d0bd5373edecfbe87906417b5e14d9f1
2c47abf74a3e6fadb174b08e57aa66a209400606
refs/heads/master
2016-09-05T17:26:54.796000
2014-11-17T15:24:00
2014-11-17T15:24:00
28,010,057
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//======================================================================== // //File: $RCSfile: ExplorerPasteAction.java,v $ //Version: $Revision: 1.5 $ //Modified: $Date: 2013/01/10 23:15:51 $ // //(c) Copyright 2005-2014 by Mentor Graphics Corp. All rights reserved. // //======================================================================== // 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.mentor.nucleus.bp.ui.explorer.ui.actions; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import com.mentor.nucleus.bp.core.CorePlugin; import com.mentor.nucleus.bp.core.common.NonRootModelElement; import com.mentor.nucleus.bp.core.common.TransactionManager; import com.mentor.nucleus.bp.core.ui.PasteAction; import com.mentor.nucleus.bp.core.ui.Selection; import com.mentor.nucleus.bp.core.util.CoreUtil; import com.mentor.nucleus.bp.core.util.OoaofgraphicsUtil; public class ExplorerPasteAction extends PasteAction { @Override public List<NonRootModelElement> getDestinations() { List<NonRootModelElement> list = new ArrayList<NonRootModelElement>(); NonRootModelElement[] selected = Selection.getInstance() .getSelectedNonRootModelElements(); for (int i = 0; i < selected.length; i++) { list.add(selected[i]); } return list; } @Override public TransactionManager getTransactionManager() { return TransactionManager.getSingleton(); } @Override public void runSubtypeProcessing(NonRootModelElement destination) { // move graphical data if present Class<?> canvasPasteActionClass = OoaofgraphicsUtil .getCanvasPasteActionClass(); try { Method method = canvasPasteActionClass.getMethod( "handleNonDiagramElementAsDestination", new Class<?>[] { NonRootModelElement.class, HashMap.class }); method.invoke(null, new Object[] { destination, processorMap }); } catch (SecurityException e) { CorePlugin.logError("Unable to move graphical data on paste", e); } catch (NoSuchMethodException e) { CorePlugin.logError("Unable to move graphical data on paste", e); } catch (IllegalArgumentException e) { CorePlugin.logError("Unable to move graphical data on paste", e); } catch (IllegalAccessException e) { CorePlugin.logError("Unable to move graphical data on paste", e); } catch (InvocationTargetException e) { CorePlugin.logError("Unable to move graphical data on paste", e); } } private boolean clipboardCanBePastedIntoSelection() { Clipboard cb = CorePlugin.getSystemClipboard(); if(cb == null || cb.isDisposed()) return false; boolean result = true; Object contents = cb .getContents(TextTransfer.getInstance()); for(NonRootModelElement destination : getDestinations()) { if (contents instanceof String) { String types[] = getClipboardTypes((String) contents, destination); for (int i = 0; i < types.length; i++) { result = CoreUtil.supportsPaste(destination, types[i], true); if(!result) break; } if(types.length == 0) result = false; if(!result) { return false; } } else { result = false; } } return result; } @Override public boolean isEnabled() { if(!super.isEnabled()) { return false; } return clipboardCanBePastedIntoSelection(); } }
UTF-8
Java
4,150
java
ExplorerPasteAction.java
Java
[]
null
[]
//======================================================================== // //File: $RCSfile: ExplorerPasteAction.java,v $ //Version: $Revision: 1.5 $ //Modified: $Date: 2013/01/10 23:15:51 $ // //(c) Copyright 2005-2014 by Mentor Graphics Corp. All rights reserved. // //======================================================================== // 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.mentor.nucleus.bp.ui.explorer.ui.actions; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import com.mentor.nucleus.bp.core.CorePlugin; import com.mentor.nucleus.bp.core.common.NonRootModelElement; import com.mentor.nucleus.bp.core.common.TransactionManager; import com.mentor.nucleus.bp.core.ui.PasteAction; import com.mentor.nucleus.bp.core.ui.Selection; import com.mentor.nucleus.bp.core.util.CoreUtil; import com.mentor.nucleus.bp.core.util.OoaofgraphicsUtil; public class ExplorerPasteAction extends PasteAction { @Override public List<NonRootModelElement> getDestinations() { List<NonRootModelElement> list = new ArrayList<NonRootModelElement>(); NonRootModelElement[] selected = Selection.getInstance() .getSelectedNonRootModelElements(); for (int i = 0; i < selected.length; i++) { list.add(selected[i]); } return list; } @Override public TransactionManager getTransactionManager() { return TransactionManager.getSingleton(); } @Override public void runSubtypeProcessing(NonRootModelElement destination) { // move graphical data if present Class<?> canvasPasteActionClass = OoaofgraphicsUtil .getCanvasPasteActionClass(); try { Method method = canvasPasteActionClass.getMethod( "handleNonDiagramElementAsDestination", new Class<?>[] { NonRootModelElement.class, HashMap.class }); method.invoke(null, new Object[] { destination, processorMap }); } catch (SecurityException e) { CorePlugin.logError("Unable to move graphical data on paste", e); } catch (NoSuchMethodException e) { CorePlugin.logError("Unable to move graphical data on paste", e); } catch (IllegalArgumentException e) { CorePlugin.logError("Unable to move graphical data on paste", e); } catch (IllegalAccessException e) { CorePlugin.logError("Unable to move graphical data on paste", e); } catch (InvocationTargetException e) { CorePlugin.logError("Unable to move graphical data on paste", e); } } private boolean clipboardCanBePastedIntoSelection() { Clipboard cb = CorePlugin.getSystemClipboard(); if(cb == null || cb.isDisposed()) return false; boolean result = true; Object contents = cb .getContents(TextTransfer.getInstance()); for(NonRootModelElement destination : getDestinations()) { if (contents instanceof String) { String types[] = getClipboardTypes((String) contents, destination); for (int i = 0; i < types.length; i++) { result = CoreUtil.supportsPaste(destination, types[i], true); if(!result) break; } if(types.length == 0) result = false; if(!result) { return false; } } else { result = false; } } return result; } @Override public boolean isEnabled() { if(!super.isEnabled()) { return false; } return clipboardCanBePastedIntoSelection(); } }
4,150
0.667711
0.660241
118
33.169491
25.409296
80
false
false
0
0
0
0
75
0.053976
2.110169
false
false
3
0ec2e025f655a9484142c413591c759503b1bb94
7,773,890,813,325
e103ff7c35074afbb2f94c87fded0d0603191dc6
/src/Main.java
7bc191f2294a69bc2b821d92b734e7f48bb655e6
[]
no_license
SeifIbrahim/telegram_lumberjack_bot
https://github.com/SeifIbrahim/telegram_lumberjack_bot
a2f61b5b8128e73e286b4202012c5be1022e8d1d
30136513092ddc7648e7bd2e7b394c8968d9422b
refs/heads/master
2020-03-25T03:30:46.879000
2018-08-02T21:16:39
2018-08-02T21:16:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.*; public class Main { public static void main(String[] args) { Robot robot = null; boolean left = true; try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); } int counter = 0; int delay = 70; int ycoord = 365; while (true) { if (counter == 200) { delay = 50; ycoord = 343; } if (counter == 400){ delay = 40; ycoord = 335; } counter++; PointerInfo a = MouseInfo.getPointerInfo(); Point b = a.getLocation(); int x = (int) b.getX(); int y = (int) b.getY(); // System.out.println(x + ", " + y); if (!robot.getPixelColor(610, ycoord).equals(new Color(202, 245, 253))) { robot.keyPress(39); left = false; } else if (!robot.getPixelColor(780, ycoord).equals(new Color(202, 245, 253))) { robot.keyPress(37); left = true; } else if (left) { robot.keyPress(37); } else { robot.keyPress(39); } try { Thread.sleep(delay); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
UTF-8
Java
1,083
java
Main.java
Java
[]
null
[]
import java.awt.*; public class Main { public static void main(String[] args) { Robot robot = null; boolean left = true; try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); } int counter = 0; int delay = 70; int ycoord = 365; while (true) { if (counter == 200) { delay = 50; ycoord = 343; } if (counter == 400){ delay = 40; ycoord = 335; } counter++; PointerInfo a = MouseInfo.getPointerInfo(); Point b = a.getLocation(); int x = (int) b.getX(); int y = (int) b.getY(); // System.out.println(x + ", " + y); if (!robot.getPixelColor(610, ycoord).equals(new Color(202, 245, 253))) { robot.keyPress(39); left = false; } else if (!robot.getPixelColor(780, ycoord).equals(new Color(202, 245, 253))) { robot.keyPress(37); left = true; } else if (left) { robot.keyPress(37); } else { robot.keyPress(39); } try { Thread.sleep(delay); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
1,083
0.576177
0.526316
49
21.102041
16.117229
83
false
false
0
0
0
0
0
0
3.408163
false
false
3
8e6e5541911f3f25be4a3902ff6abb48c0aa9c7e
23,665,269,822,394
b217881f9f07f35295fa3a38cc4a3926fbd684e4
/SavingAcc.java
72b8ece582c43722c1ec98291fa13c815fa2ecc2
[]
no_license
Anindya96ghosh/FrameWork-Case-Study-II
https://github.com/Anindya96ghosh/FrameWork-Case-Study-II
7155cb937860f6a6769874d9305a4a9340d34ea1
7179a2977e6ef564e2421d4d419a4f134323a35e
refs/heads/master
2020-03-25T02:21:49.051000
2018-08-07T16:56:34
2018-08-07T16:56:34
143,286,377
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.BankController; public abstract class SavingAcc extends BankAcc{ private boolean isSalary; private static final float MINBAL=1000; //Parameterized Constructor public SavingAcc(int accNo, String accNm, float accBal, boolean isSalary) { super(accNo, accNm, accBal); this.isSalary = isSalary; } //Overridden withdraw method @Override abstract public void withdraw(float money); //Overridden toString method @Override public String toString() { return "SavingAcc [isSalary=" + isSalary + "]"; } }
UTF-8
Java
564
java
SavingAcc.java
Java
[]
null
[]
package com.BankController; public abstract class SavingAcc extends BankAcc{ private boolean isSalary; private static final float MINBAL=1000; //Parameterized Constructor public SavingAcc(int accNo, String accNm, float accBal, boolean isSalary) { super(accNo, accNm, accBal); this.isSalary = isSalary; } //Overridden withdraw method @Override abstract public void withdraw(float money); //Overridden toString method @Override public String toString() { return "SavingAcc [isSalary=" + isSalary + "]"; } }
564
0.703901
0.696809
27
18.888889
20.024675
76
false
false
0
0
0
0
0
0
1.296296
false
false
3
fac48d7ec9e37ed50299b0c493e8db6498866a88
29,394,756,201,897
f8d9410bd068a66f53ce3010e4e3d34407270bcb
/src/main/java/nl/daaannn/testingstuff/TestingStuff.java
fb07aa9fbef71009ff2e43833a8be5733ff72b03
[]
no_license
Daaannn/TestingStuff
https://github.com/Daaannn/TestingStuff
590eeea7cf85237d4705db05bb32e0daa433ccbe
369f323f9923d181b69fee65192e543482421fa8
refs/heads/master
2020-03-17T03:03:51.756000
2018-05-13T08:14:33
2018-05-13T08:14:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nl.daaannn.testingstuff; import org.bukkit.plugin.java.JavaPlugin; public class TestingStuff extends JavaPlugin { @Override public void onEnable() { // Plugin startup logic } @Override public void onDisable() { // Plugin shutdown logic } }
UTF-8
Java
293
java
TestingStuff.java
Java
[ { "context": "package nl.daaannn.testingstuff;\n\nimport org.bukkit.plugin.java.Java", "end": 18, "score": 0.6026010513305664, "start": 14, "tag": "USERNAME", "value": "annn" } ]
null
[]
package nl.daaannn.testingstuff; import org.bukkit.plugin.java.JavaPlugin; public class TestingStuff extends JavaPlugin { @Override public void onEnable() { // Plugin startup logic } @Override public void onDisable() { // Plugin shutdown logic } }
293
0.658703
0.658703
17
16.235294
15.976193
46
false
false
0
0
0
0
0
0
0.117647
false
false
3
ee1ce8a2c1edb57b984090c3a2c3dd85c98c2492
10,617,159,188,551
575fbea221642a662134f2a4d2015b3582548562
/app/src/main/java/com/example/thsk/hareskovskole/commercials/ScreenSliderAdapter.java
e9b2561cf6d357bde317620621951f6245b1f3ef
[]
no_license
TSkogemann/HareskovSkole
https://github.com/TSkogemann/HareskovSkole
9484fd73ab067adb2e42784405dad56c339486de
f81b41bc15e9cca8dfe909bc42e5f511be972d23
refs/heads/master
2020-09-11T23:55:40.379000
2017-08-09T22:16:15
2017-08-09T22:16:15
94,455,959
1
0
null
false
2017-06-15T16:37:50
2017-06-15T15:58:35
2017-06-15T16:10:48
2017-06-15T16:37:09
0
1
0
1
Java
null
null
package com.example.thsk.hareskovskole.commercials; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import com.bumptech.glide.Glide; import com.example.thsk.hareskovskole.R; import java.util.List; /** * Created by thsk on 25/06/2017. */ public class ScreenSliderAdapter extends PagerAdapter { Context mContext; List<String> commercialExtraPictures; public ScreenSliderAdapter(Context mContext, List<String> commercialExtraPictures) { this.mContext = mContext; this.commercialExtraPictures = commercialExtraPictures; notifyDataSetChanged(); } @Override public int getCount() { return commercialExtraPictures.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { LayoutInflater mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = mLayoutInflater.inflate(R.layout.item_commercial_detail, container, false); ImageView imageView = (ImageView) itemView.findViewById(R.id.commercial_detail_item_image_view); Glide.with(mContext) .load(commercialExtraPictures.get(position)) .placeholder(R.drawable.ic_menu_camera) .error(R.drawable.ic_menu_send) .into(imageView); container.addView(itemView); return itemView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((LinearLayout) object); } }
UTF-8
Java
1,855
java
ScreenSliderAdapter.java
Java
[ { "context": "kole.R;\n\nimport java.util.List;\n\n/**\n * Created by thsk on 25/06/2017.\n */\n\npublic class ScreenSliderAdap", "end": 414, "score": 0.9996147155761719, "start": 410, "tag": "USERNAME", "value": "thsk" } ]
null
[]
package com.example.thsk.hareskovskole.commercials; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import com.bumptech.glide.Glide; import com.example.thsk.hareskovskole.R; import java.util.List; /** * Created by thsk on 25/06/2017. */ public class ScreenSliderAdapter extends PagerAdapter { Context mContext; List<String> commercialExtraPictures; public ScreenSliderAdapter(Context mContext, List<String> commercialExtraPictures) { this.mContext = mContext; this.commercialExtraPictures = commercialExtraPictures; notifyDataSetChanged(); } @Override public int getCount() { return commercialExtraPictures.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { LayoutInflater mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = mLayoutInflater.inflate(R.layout.item_commercial_detail, container, false); ImageView imageView = (ImageView) itemView.findViewById(R.id.commercial_detail_item_image_view); Glide.with(mContext) .load(commercialExtraPictures.get(position)) .placeholder(R.drawable.ic_menu_camera) .error(R.drawable.ic_menu_send) .into(imageView); container.addView(itemView); return itemView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((LinearLayout) object); } }
1,855
0.712668
0.707817
59
30.440678
28.581297
117
false
false
0
0
0
0
0
0
0.542373
false
false
3
0ef36d0144402ced510bb202b3845c3b0fcc9a0e
10,617,159,184,381
8585ffe1c22e8e14b17b0f5125e1f912d78e6597
/GPS_LMS/src/com/youbus/jsontest/CharacterEncodingFilter.java
b88622c3c083056c780599c28ccb946dd2affeb0
[]
no_license
shijie-rock/WH-HUAYUE
https://github.com/shijie-rock/WH-HUAYUE
01723c8a760826a244ab71bec5036c39c918820e
e5d6681648d9ddac92e239bcf452796dc1473e62
refs/heads/master
2022-03-03T18:01:38.476000
2019-11-11T08:37:48
2019-11-11T08:37:48
105,342,406
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * ้กน็›ฎๅ็งฐ:AGENT_CENTER * ๅŒ… ๅ:com.youbus.framework.comm * ๆ–‡ ไปถ ๅ:CharacterEncodingFilter.java * ๅˆ› ๅปบๆ—ฅๆœŸ:2015ๅนด4ๆœˆ15ๆ—ฅ-ไธ‹ๅˆ11:17:17 * Copyright @ 2015-YouBus.com.cn */ package com.youbus.jsontest; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * ็ฑปๅ็งฐ:CharacterEncodingFilter * ็ฑปๆ่ฟฐ: * ๅˆ›ๅปบไบบ:rock * ไฟฎๆ”นไบบ:rock * ไฟฎๆ”นๆ—ถ้—ด:2015ๅนด4ๆœˆ15ๆ—ฅ ไธ‹ๅˆ11:17:17 * ไฟฎๆ”นๅค‡ๆณจ: * @version 1.0.0 */ public class CharacterEncodingFilter implements Filter { /** * ๅˆ›ๅปบไธ€ไธชๆ–ฐ็š„ๅฎžไพ‹ CharacterEncodingFilter. * */ public CharacterEncodingFilter() { // TODO Auto-generated constructor stub } private String encoding = null; /* (non-Javadoc) * @see javax.servlet.Filter#destroy() */ @Override public void destroy() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub request.setCharacterEncoding(encoding); response.setContentType("text/html;charset="+encoding); chain.doFilter(request, response); } /* (non-Javadoc) * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub this.encoding = filterConfig.getInitParameter("encoding"); } }
GB18030
Java
1,856
java
CharacterEncodingFilter.java
Java
[]
null
[]
/** * ้กน็›ฎๅ็งฐ:AGENT_CENTER * ๅŒ… ๅ:com.youbus.framework.comm * ๆ–‡ ไปถ ๅ:CharacterEncodingFilter.java * ๅˆ› ๅปบๆ—ฅๆœŸ:2015ๅนด4ๆœˆ15ๆ—ฅ-ไธ‹ๅˆ11:17:17 * Copyright @ 2015-YouBus.com.cn */ package com.youbus.jsontest; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * ็ฑปๅ็งฐ:CharacterEncodingFilter * ็ฑปๆ่ฟฐ: * ๅˆ›ๅปบไบบ:rock * ไฟฎๆ”นไบบ:rock * ไฟฎๆ”นๆ—ถ้—ด:2015ๅนด4ๆœˆ15ๆ—ฅ ไธ‹ๅˆ11:17:17 * ไฟฎๆ”นๅค‡ๆณจ: * @version 1.0.0 */ public class CharacterEncodingFilter implements Filter { /** * ๅˆ›ๅปบไธ€ไธชๆ–ฐ็š„ๅฎžไพ‹ CharacterEncodingFilter. * */ public CharacterEncodingFilter() { // TODO Auto-generated constructor stub } private String encoding = null; /* (non-Javadoc) * @see javax.servlet.Filter#destroy() */ @Override public void destroy() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub request.setCharacterEncoding(encoding); response.setContentType("text/html;charset="+encoding); chain.doFilter(request, response); } /* (non-Javadoc) * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub this.encoding = filterConfig.getInitParameter("encoding"); } }
1,856
0.713227
0.694413
68
23.794117
23.328573
126
false
false
0
0
0
0
0
0
0.941176
false
false
3
57d1c80f00ba0941b39f934749577e3444a97c60
13,288,628,838,722
a9a9dadc20ce5a11ef5c556999def04b74f0c6df
/four/validateBST.java
9dcf1045ef30fb610ac7ec74e4e098f6e028c64b
[]
no_license
lijia577/Test
https://github.com/lijia577/Test
e5a197727ceb7825a75a17554ff0360624dd5eb2
7c6671ff7620d829000e2d49b7c757acd05b713a
refs/heads/master
2021-01-25T08:59:50.303000
2015-04-06T21:09:54
2015-04-06T21:09:54
31,445,437
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; class TreeNode{ int data; TreeNode left; TreeNode right; public TreeNode(int data){ this.data = data; } } class validateBST{ //The defintion of BST: FOR ALL NODE, all the left subnode<= NODE, all the right subnode > Node. // The idea is to check the boundary of a node. For example, in tree with 3 nodes. a.left = b, a.right = c. The boundry for b is (-inf,a) public boolean validate(TreeNode root, int min, int max){ if(root ==null) return true; //root should be contained in the range, s.t. min<root.data<=max if(root.data>max || root.data<=min) return false; if(!validate(root.left,min,root.data)) return false; if(!validate(root.right,root.data, max)) return false; return true; } //Assume all value in the tree is unique. We can modify In Order Trasversal. The in order traversal of a BST will be in ascending order. So we can just check the current //value should always be greater than the previous value. public static int prev = Integer.MIN_VALUE; public boolean validate2(TreeNode root){ if(root==null) return true; //recurse to the left if(this.validate2(root.left)==false) return false; //compare the root with prev, the first time prev is the -infinity. if(root.data<=prev) return false; prev = root.data; if(this.validate2(root.right)==false) return false; return true; } public static void main(String args[]){ TreeNode m = new TreeNode(10); TreeNode n = new TreeNode(10); m.right = n; validateBST inst = new validateBST(); System.out.println("False? " + inst.validate(m,Integer.MIN_VALUE, Integer.MAX_VALUE)); TreeNode a = new TreeNode(20); TreeNode b = new TreeNode(10); TreeNode c = new TreeNode(30); TreeNode d = new TreeNode(25); a.left = b; a.right = c; b.right = d; System.out.println("False? " + inst.validate(a,Integer.MIN_VALUE, Integer.MAX_VALUE)); System.out.println("False? " + inst.validate2(a)); } }
UTF-8
Java
1,960
java
validateBST.java
Java
[]
null
[]
import java.util.*; class TreeNode{ int data; TreeNode left; TreeNode right; public TreeNode(int data){ this.data = data; } } class validateBST{ //The defintion of BST: FOR ALL NODE, all the left subnode<= NODE, all the right subnode > Node. // The idea is to check the boundary of a node. For example, in tree with 3 nodes. a.left = b, a.right = c. The boundry for b is (-inf,a) public boolean validate(TreeNode root, int min, int max){ if(root ==null) return true; //root should be contained in the range, s.t. min<root.data<=max if(root.data>max || root.data<=min) return false; if(!validate(root.left,min,root.data)) return false; if(!validate(root.right,root.data, max)) return false; return true; } //Assume all value in the tree is unique. We can modify In Order Trasversal. The in order traversal of a BST will be in ascending order. So we can just check the current //value should always be greater than the previous value. public static int prev = Integer.MIN_VALUE; public boolean validate2(TreeNode root){ if(root==null) return true; //recurse to the left if(this.validate2(root.left)==false) return false; //compare the root with prev, the first time prev is the -infinity. if(root.data<=prev) return false; prev = root.data; if(this.validate2(root.right)==false) return false; return true; } public static void main(String args[]){ TreeNode m = new TreeNode(10); TreeNode n = new TreeNode(10); m.right = n; validateBST inst = new validateBST(); System.out.println("False? " + inst.validate(m,Integer.MIN_VALUE, Integer.MAX_VALUE)); TreeNode a = new TreeNode(20); TreeNode b = new TreeNode(10); TreeNode c = new TreeNode(30); TreeNode d = new TreeNode(25); a.left = b; a.right = c; b.right = d; System.out.println("False? " + inst.validate(a,Integer.MIN_VALUE, Integer.MAX_VALUE)); System.out.println("False? " + inst.validate2(a)); } }
1,960
0.688265
0.679592
70
27
32.930229
171
false
false
0
0
0
0
0
0
1.942857
false
false
3
d4a623515f7b22be48255a39661cfec40bd1826a
21,646,635,204,159
33cc4a8ac423d232a1f13b1498988230a339deb4
/src/main/java/coderpad/BinaryTreeMirror.java
13ab0efb4bb0374841980169a7f44981425f0432
[]
no_license
viktorijat/oracle-certified-professional-questions
https://github.com/viktorijat/oracle-certified-professional-questions
7576d75fe5fc89118b1aa06d3c90360ff423e8f4
432a93caa585706993d9c3676462e37f7b2932d6
refs/heads/master
2020-04-07T09:26:02.401000
2019-04-14T18:04:20
2019-04-14T18:04:20
158,251,805
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package coderpad; class BSTNode { int data; Node left, right; BSTNode(int data) { this.data = data; this.left = this.right = null; } public void print(String prefix, Node n, boolean isLeft) { if (n != null) { System.out.println(prefix + (isLeft ? "|-- " : "\\-- ") + n.data); print(prefix + (isLeft ? "| " : " "), n.left, true); print(prefix + (isLeft ? "| " : " "), n.right, false); } } } public class BinaryTreeMirror { Node root; private static void printAscending(Node node) { // is there actually a node here // or was this called from a node with no children if (node != null) { // print everything that's earlier than this node printAscending(node.left); // print this node's value System.out.println(node.data); // print everything that's afterthan this node printAscending(node.right); } } private static Node mirror(Node node) { if (node == null) { return node; } Node left = mirror(node.left); Node right = mirror(node.right); node.left = right; node.right = left; return node; } public static void main(String[] args) { BinarySearchTree bst = new BinarySearchTree(); BinarySearchTree.root = new Node(4); BinarySearchTree.root.left = new Node(2); BinarySearchTree.root.right = new Node(5); BinarySearchTree.root.left.left = new Node(1); BinarySearchTree.root.left.right = new Node(3); printAscending(BinarySearchTree.root); System.out.println(mirror(BinarySearchTree.root)); printAscending(BinarySearchTree.root); } }
UTF-8
Java
1,827
java
BinaryTreeMirror.java
Java
[]
null
[]
package coderpad; class BSTNode { int data; Node left, right; BSTNode(int data) { this.data = data; this.left = this.right = null; } public void print(String prefix, Node n, boolean isLeft) { if (n != null) { System.out.println(prefix + (isLeft ? "|-- " : "\\-- ") + n.data); print(prefix + (isLeft ? "| " : " "), n.left, true); print(prefix + (isLeft ? "| " : " "), n.right, false); } } } public class BinaryTreeMirror { Node root; private static void printAscending(Node node) { // is there actually a node here // or was this called from a node with no children if (node != null) { // print everything that's earlier than this node printAscending(node.left); // print this node's value System.out.println(node.data); // print everything that's afterthan this node printAscending(node.right); } } private static Node mirror(Node node) { if (node == null) { return node; } Node left = mirror(node.left); Node right = mirror(node.right); node.left = right; node.right = left; return node; } public static void main(String[] args) { BinarySearchTree bst = new BinarySearchTree(); BinarySearchTree.root = new Node(4); BinarySearchTree.root.left = new Node(2); BinarySearchTree.root.right = new Node(5); BinarySearchTree.root.left.left = new Node(1); BinarySearchTree.root.left.right = new Node(3); printAscending(BinarySearchTree.root); System.out.println(mirror(BinarySearchTree.root)); printAscending(BinarySearchTree.root); } }
1,827
0.558292
0.555556
76
23.039474
22.924614
78
false
false
0
0
0
0
0
0
0.486842
false
false
3
c6a8f262e57bab448630ba7ec6a6548fc693499b
36,962,488,555,485
83d568b653bf5a71bd6504d8e1802e4048f4755f
/Event_Management-backend/src/main/java/com/team1/backend/controllers/UserController.java
0a2c7a15b5b6caeb9a8dd6f815cba02d183aa8a5
[ "Apache-2.0" ]
permissive
tbarua1/Event_Management_team-1
https://github.com/tbarua1/Event_Management_team-1
f3faa102fd221764726aab179a9995857d342ae1
3e8751f3765692815b00494717f6d2a1ce7d7c74
refs/heads/main
2023-06-06T09:07:05.674000
2021-06-30T03:37:15
2021-06-30T03:37:15
377,742,136
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.team1.backend.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.team1.backend.model.User; import com.team1.backend.repository.UserRepository; @CrossOrigin(origins = "http://localhost:3000") @RestController public class UserController { @Autowired private UserRepository repo; @RequestMapping(value = "/user", method = RequestMethod.GET) public List<User> userList() { return repo.findAll(); } @PostMapping("/user") public User userPost(@RequestBody User User) { return repo.save(User); } @DeleteMapping("/user") public String userDelete(@RequestParam Long id) { repo.deleteById(id); return "Record No. "+id+" has been Deleted"; } @PutMapping("/user") public User userPut(@RequestBody User User) { return repo.save(User); } }
UTF-8
Java
1,426
java
UserController.java
Java
[]
null
[]
package com.team1.backend.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.team1.backend.model.User; import com.team1.backend.repository.UserRepository; @CrossOrigin(origins = "http://localhost:3000") @RestController public class UserController { @Autowired private UserRepository repo; @RequestMapping(value = "/user", method = RequestMethod.GET) public List<User> userList() { return repo.findAll(); } @PostMapping("/user") public User userPost(@RequestBody User User) { return repo.save(User); } @DeleteMapping("/user") public String userDelete(@RequestParam Long id) { repo.deleteById(id); return "Record No. "+id+" has been Deleted"; } @PutMapping("/user") public User userPut(@RequestBody User User) { return repo.save(User); } }
1,426
0.765778
0.76087
43
31.069767
22.868071
62
false
false
0
0
0
0
0
0
1.093023
false
false
3
cfe58817a51a097d23962478f7ef7face6aee57d
34,351,148,467,645
841ee64e6f8dd355271dba7d1bda85030d497abf
/src/main/java/com/epam/library/command/ReportCommand.java
12759b36ec4a36303f8f34b4786550898da6625d
[]
no_license
Shiler/library
https://github.com/Shiler/library
580cf5b143eb28a0d8778a6e9b95fd604f9784d7
22851235c148bbe287a9ac2456f737acf7286716
refs/heads/master
2020-05-26T15:22:19.271000
2017-03-30T00:34:06
2017-03-30T00:34:06
85,010,253
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.epam.library.command; import com.epam.library.exception.ServiceException; import com.epam.library.service.impl.EmployeeService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * */ public class ReportCommand implements ICommand { private static final Logger LOG = LogManager.getLogger(); @Override public String execute(String params) { String reportString = ""; EmployeeService employeeService = new EmployeeService(); try { switch (params) { case AvailableOperations.MORE_THAN_1_PARAM: reportString = EmployeeService.listToString(employeeService.employeesWithMoreThanOneBook()); break; case AvailableOperations.LESS_OR_EQ_THAN_2_PARAM: reportString = EmployeeService.listToString(employeeService.employeesWithLessOrEqThanTwoBooks()); break; default: reportString = AvailableOperations.INVALID_PARAMETER_LIST_MESSAGE; } } catch (ServiceException e) { LOG.error("Error while executing report command.", e); } return reportString; } }
UTF-8
Java
1,238
java
ReportCommand.java
Java
[]
null
[]
package com.epam.library.command; import com.epam.library.exception.ServiceException; import com.epam.library.service.impl.EmployeeService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * */ public class ReportCommand implements ICommand { private static final Logger LOG = LogManager.getLogger(); @Override public String execute(String params) { String reportString = ""; EmployeeService employeeService = new EmployeeService(); try { switch (params) { case AvailableOperations.MORE_THAN_1_PARAM: reportString = EmployeeService.listToString(employeeService.employeesWithMoreThanOneBook()); break; case AvailableOperations.LESS_OR_EQ_THAN_2_PARAM: reportString = EmployeeService.listToString(employeeService.employeesWithLessOrEqThanTwoBooks()); break; default: reportString = AvailableOperations.INVALID_PARAMETER_LIST_MESSAGE; } } catch (ServiceException e) { LOG.error("Error while executing report command.", e); } return reportString; } }
1,238
0.646204
0.642973
34
35.441177
30.418833
117
false
false
0
0
0
0
0
0
0.470588
false
false
3
66fc7e0d31bf66bc223b0e0d0624228b1d5ab9a0
19,507,741,522,325
a0baa9fb848e4d5dc02486125760432c8ff1c12c
/src/main/java/com/andrewsears/novus/bc/EquationPart.java
256c0aff2ac318c76f6b965b88e9f758fa9ae755
[]
no_license
andrewsears/novus-bc
https://github.com/andrewsears/novus-bc
9607f06f61e33acb956eaa25d03c25f0d3ad67b3
3ed326fc8a86dc86394c1e27622b78d4be910331
refs/heads/master
2016-09-06T05:07:16.731000
2015-03-14T17:01:46
2015-03-14T17:01:46
32,200,914
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Andrew Sears * Copyright 2015 * Created on Mar 13, 2015 */ package com.andrewsears.novus.bc; import java.io.Serializable; import java.math.BigDecimal; /** * POJO that handles both halves of an equation and the operation * * @author Andrew Sears <a href="mailto=andrew@andrewsears.com">andrew@andrewsears.com</a> */ public class EquationPart implements Serializable { private static final long serialVersionUID = -4451742653280386788L; private Operation operation; private String left; private String right; /** * Default constructor */ public EquationPart(Operation operation, String left, String right) { this.operation = operation; this.left = left; this.right = right; } /* * Helper Methods */ /** * Helper method that converts the left number as a {@link BigDecimal}. * @return The left as a BigDecimal */ public BigDecimal getLeftAsBigDecimal() { return new BigDecimal(this.left); } /** * Helper method that converts the right number as a {@link BigDecimal}. * @return The right as a BigDecimal */ public BigDecimal getRightAsBigDecimal() { return new BigDecimal(this.right); } /** * Helper method that determines the scale to use between to two numbers. * @return The scale */ public int getScale() { int scaleLeft = this.left.contains(".") ? this.left.length()-this.left.indexOf(".")-1 : 0; int scaleRight = this.right.contains(".") ? this.right.length()-this.right.indexOf(".")-1 : 0; return Math.max(scaleLeft, scaleRight); } /* * Getter and Setters */ /** * Returns the operation. * @return The operation */ public Operation getOperation() { return this.operation; } /** * Sets the operation. * @param operation The operation */ public void setOperation(Operation operation) { this.operation = operation; } /** * Returns the left. * @return The left */ public String getLeft() { return this.left; } /** * Sets the left. * @param left The left */ public void setLeft(String left) { this.left = left; } /** * Returns the right. * @return The right */ public String getRight() { return this.right; } /** * Sets the right. * @param right The right */ public void setRight(String right) { this.right = right; } }
UTF-8
Java
2,289
java
EquationPart.java
Java
[ { "context": "/*\n * Andrew Sears\n * Copyright 2015\n * Created on Mar 13, 2015\n */\n", "end": 18, "score": 0.9998581409454346, "start": 6, "tag": "NAME", "value": "Andrew Sears" }, { "context": "es of an equation and the operation\n * \n * @author Andrew Sears <a href=\"mailto=andrew@andrewsears.com\">andrew@an", "end": 260, "score": 0.9998693466186523, "start": 248, "tag": "NAME", "value": "Andrew Sears" }, { "context": "ation\n * \n * @author Andrew Sears <a href=\"mailto=andrew@andrewsears.com\">andrew@andrewsears.com</a>\n */\npublic class Equa", "end": 299, "score": 0.9999290108680725, "start": 277, "tag": "EMAIL", "value": "andrew@andrewsears.com" }, { "context": "rew Sears <a href=\"mailto=andrew@andrewsears.com\">andrew@andrewsears.com</a>\n */\npublic class EquationPart implements Seri", "end": 323, "score": 0.9999318718910217, "start": 301, "tag": "EMAIL", "value": "andrew@andrewsears.com" } ]
null
[]
/* * <NAME> * Copyright 2015 * Created on Mar 13, 2015 */ package com.andrewsears.novus.bc; import java.io.Serializable; import java.math.BigDecimal; /** * POJO that handles both halves of an equation and the operation * * @author <NAME> <a href="mailto=<EMAIL>"><EMAIL></a> */ public class EquationPart implements Serializable { private static final long serialVersionUID = -4451742653280386788L; private Operation operation; private String left; private String right; /** * Default constructor */ public EquationPart(Operation operation, String left, String right) { this.operation = operation; this.left = left; this.right = right; } /* * Helper Methods */ /** * Helper method that converts the left number as a {@link BigDecimal}. * @return The left as a BigDecimal */ public BigDecimal getLeftAsBigDecimal() { return new BigDecimal(this.left); } /** * Helper method that converts the right number as a {@link BigDecimal}. * @return The right as a BigDecimal */ public BigDecimal getRightAsBigDecimal() { return new BigDecimal(this.right); } /** * Helper method that determines the scale to use between to two numbers. * @return The scale */ public int getScale() { int scaleLeft = this.left.contains(".") ? this.left.length()-this.left.indexOf(".")-1 : 0; int scaleRight = this.right.contains(".") ? this.right.length()-this.right.indexOf(".")-1 : 0; return Math.max(scaleLeft, scaleRight); } /* * Getter and Setters */ /** * Returns the operation. * @return The operation */ public Operation getOperation() { return this.operation; } /** * Sets the operation. * @param operation The operation */ public void setOperation(Operation operation) { this.operation = operation; } /** * Returns the left. * @return The left */ public String getLeft() { return this.left; } /** * Sets the left. * @param left The left */ public void setLeft(String left) { this.left = left; } /** * Returns the right. * @return The right */ public String getRight() { return this.right; } /** * Sets the right. * @param right The right */ public void setRight(String right) { this.right = right; } }
2,247
0.670599
0.656182
116
18.732759
21.792658
96
false
false
0
0
0
0
0
0
1.12931
false
false
3
95342e9f787deab766181935015d09d2ddfc7ccf
36,532,991,839,956
fd16312397056999339d05c12e012db3b9a5c08b
/actionold/LoginAction.java
fd3f4f696c2c78aaa24dc4401b42978664b8cb7d
[]
no_license
Deniel089/horse-totalizator
https://github.com/Deniel089/horse-totalizator
44f7c2614feac2dd39f63db1b62658352fb8fb75
64e9559640c6eba2322fd14a19d5d7a9fee92680
refs/heads/master
2021-07-03T20:54:30.884000
2019-08-31T17:21:23
2019-08-31T17:21:23
91,186,997
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smirnou.fourthlab.actionold; import com.smirnou.fourthlab.model.User; import com.smirnou.fourthlab.exception.HorseRaceException; import org.apache.log4j.Logger; import com.smirnou.fourthlab.service.ServiceFactoryImpl; import com.smirnou.fourthlab.service.api.UserService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginAction implements Action { private Logger logger = Logger.getLogger(LoginAction.class); private ServiceFactoryImpl serviceFactory; private User user; public LoginAction(ServiceFactoryImpl serviceFactory) { this.serviceFactory = serviceFactory; } @Override public String performAction(HttpServletRequest req, HttpServletResponse resp) throws HorseRaceException { com.smirnou.fourthlab.service.UserService userService = serviceFactory.getService(UserService.class); String login = req.getParameter("login"); String pass = req.getParameter("password"); user = userService.findByLoginPass(login, pass); if (user == null) { //TODO ัะบะฐะทะฐั‚ัŒ, ั‡ั‚ะพ ัะฐะผ ะดัƒั€ะฐะบ } else if (user.getRole() == 0) { return "admin"; } else if (user.getRole() == 1) { return "bookmaker"; } return "WEB-INF/jsp/login.jsp"; } }
UTF-8
Java
1,351
java
LoginAction.java
Java
[]
null
[]
package com.smirnou.fourthlab.actionold; import com.smirnou.fourthlab.model.User; import com.smirnou.fourthlab.exception.HorseRaceException; import org.apache.log4j.Logger; import com.smirnou.fourthlab.service.ServiceFactoryImpl; import com.smirnou.fourthlab.service.api.UserService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginAction implements Action { private Logger logger = Logger.getLogger(LoginAction.class); private ServiceFactoryImpl serviceFactory; private User user; public LoginAction(ServiceFactoryImpl serviceFactory) { this.serviceFactory = serviceFactory; } @Override public String performAction(HttpServletRequest req, HttpServletResponse resp) throws HorseRaceException { com.smirnou.fourthlab.service.UserService userService = serviceFactory.getService(UserService.class); String login = req.getParameter("login"); String pass = req.getParameter("password"); user = userService.findByLoginPass(login, pass); if (user == null) { //TODO ัะบะฐะทะฐั‚ัŒ, ั‡ั‚ะพ ัะฐะผ ะดัƒั€ะฐะบ } else if (user.getRole() == 0) { return "admin"; } else if (user.getRole() == 1) { return "bookmaker"; } return "WEB-INF/jsp/login.jsp"; } }
1,351
0.717179
0.714929
37
35.027027
27.320408
109
false
false
0
0
0
0
0
0
0.594595
false
false
3
c96c0ea9e8ef78ed8a4a7b729bb531ac617ec4a7
36,017,595,768,993
edc8a642bab3a82a398023d86bc5bffcacb2efe9
/NibllBojanActivities/app/src/main/java/com/example/bojan/nibllbojanactivities/device.java
99c8122c63f94568a6dd5a3e40798e4e62973efd
[]
no_license
TheMrL14/Nibll
https://github.com/TheMrL14/Nibll
14a24a3bdc9959c3d1eb3dd5cbcecb8ae3f229b8
816dc7f407ceeec0fdcf16142c2394873a2e8484
refs/heads/master
2021-09-03T20:02:48.255000
2018-01-11T15:34:01
2018-01-11T15:34:01
114,631,471
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.bojan.nibllbojanactivities; import android.content.Intent; import android.os.CountDownTimer; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.StringRequest; import com.example.bojan.nibllbojanactivities.Adapter.DeviceArrayAdapter; import com.example.bojan.nibllbojanactivities.model.Device; import com.example.bojan.nibllbojanactivities.model.Sensor; import com.example.bojan.nibllbojanactivities.utils.MySingleton; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class device extends AppCompatActivity { CountDownTimer countDownTimer; List<Object> alleObject; Boolean requestDeviceComplete; Boolean requestSensorComplete; List<Device> alleDevice; List<Sensor> alleSensor; JsonArrayRequest jsonSensorRequest; JsonArrayRequest jsonDeviceRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_device); Thread mijnThread = new Thread(new Runnable() { @Override public void run() { getAllDevice(); } }); //haal devices op in aparte thread mijnThread.start(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.addDevice); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intentLoadNewActivity = new Intent(device.this, DeviceAddActivity.class); startActivity(intentLoadNewActivity); } }); countDownTimer = new CountDownTimer(500, 500) { //haal elke 2 seconden alle apparaten opnieuw op, voor de laatste status te weten @Override public void onTick(long l) { } public void onFinish() { getAllDevice(); } }; } private void vulLijstOp() { //vul de lijst van alle apparaten op for(Device device : alleDevice){ alleObject.add(device); } for(Sensor sensor : alleSensor) { alleObject.add(sensor); } DeviceArrayAdapter mijnAdapter = new DeviceArrayAdapter(this, alleObject); GridView mijnAdapterView = (GridView) findViewById(R.id.deviceGridview); mijnAdapterView.setAdapter(mijnAdapter); Log.d("lol", "vulLijstOp: "); } private void turnDeviceOnOff(Boolean on, int deviceId) { //voer een post request uit voor een apparaat aan/uit te zetten String url = "http://192.168.1.128:8080/device/statusChangeById?"; url += "id=" + deviceId; if(on){ url += "&status=1"; }else{ url += "&status=0"; } StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.d("Response", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } } ); MySingleton.getInstance(this).addToRequestQueue(postRequest); } private void getAllDevice(){ //hierin word de json file met alle apparaten die zich in de database bevinden, opgehaald requestDeviceComplete = false; requestSensorComplete = false; alleObject = new ArrayList<Object>(); jsonSensorRequest = new JsonArrayRequest (Request.Method.GET, "http://192.168.1.128:8080/sensor/getAll", null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { alleSensor = new ArrayList<Sensor>(); for (int i = 0; i < response.length(); i++) { try { JSONObject responseObject = response.getJSONObject(i); alleSensor.add(new Sensor(Integer.parseInt(responseObject.getString("sensorID")), responseObject.getString("naamSensor"), Double.parseDouble(responseObject.getString("inputWaarde")), Integer.parseInt(responseObject.getString("status")))); } catch (JSONException e) { e.printStackTrace(); } } if(requestDeviceComplete){ vulLijstOp(); } requestSensorComplete = true; } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub Log.d("lol", "onErrorResponse: " + error); } }); jsonDeviceRequest = new JsonArrayRequest (Request.Method.GET, "http://192.168.1.128:8080/device/getAll", null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { alleDevice = new ArrayList<Device>(); for (int i = 0; i < response.length(); i++) { try { JSONObject responseObject = response.getJSONObject(i); alleDevice.add(new Device(Integer.parseInt(responseObject.get("deviceId").toString()), R.drawable.lamp_icon, R.drawable.lamp_scroll_off, responseObject.get("naamDevice").toString(), Boolean.parseBoolean(responseObject.get("status").toString()))); } catch (JSONException e) { e.printStackTrace(); } } if(requestSensorComplete){ vulLijstOp(); } requestDeviceComplete = true; countDownTimer.start(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub Log.d("lol", "onErrorResponse: " + error); } }); MySingleton.getInstance(device.this).addToRequestQueue(jsonDeviceRequest); MySingleton.getInstance(device.this).addToRequestQueue(jsonSensorRequest); GridView lstDevices = (GridView) findViewById(R.id.deviceGridview); lstDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() { boolean click = false; @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //als er op een apparaat geklikt wordt, wordt dit aan/uitgezet List<Object> alleObject; Device device; if(parent.getItemAtPosition(position).getClass() == Device.class){ device = (Device) parent.getItemAtPosition(position); Device mijnGeselecteerdeDevice = (Device) parent.getItemAtPosition(position); turnDeviceOnOff(!mijnGeselecteerdeDevice.getStatus() ,mijnGeselecteerdeDevice.getDeviceId()); } } }); lstDevices.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { //als er lang op een apparaat wordt gedrukt, dan zal er een detail pagina over het apparaat openenen if (parent.getItemAtPosition(position).getClass() == Device.class) { Intent intentLoadNewActivity = new Intent(device.this, devicesettings.class); Device mijnGeselecteerdeDevice = (Device) parent.getItemAtPosition(position); intentLoadNewActivity.putExtra("device", mijnGeselecteerdeDevice); startActivity(intentLoadNewActivity); } return false; } // // }); } }
UTF-8
Java
9,099
java
device.java
Java
[ { "context": "t aan/uit te zetten\n String url = \"http://192.168.1.128:8080/device/statusChangeById?\";\n url += \"i", "end": 3081, "score": 0.9996798634529114, "start": 3068, "tag": "IP_ADDRESS", "value": "192.168.1.128" }, { "context": "uest\n (Request.Method.GET, \"http://192.168.1.128:8080/sensor/getAll\", null, new Response.Listener<", "end": 4331, "score": 0.999718964099884, "start": 4318, "tag": "IP_ADDRESS", "value": "192.168.1.128" }, { "context": " (Request.Method.GET, \"http://192.168.1.128:8080/sensor/getAll\", null, new Response.Listener<JSONA", "end": 4336, "score": 0.9738990664482117, "start": 4335, "tag": "IP_ADDRESS", "value": "0" }, { "context": "uest\n (Request.Method.GET, \"http://192.168.1.128:8080/device/getAll\", null, new Response.Listener<", "end": 5807, "score": 0.9995925426483154, "start": 5794, "tag": "IP_ADDRESS", "value": "192.168.1.128" } ]
null
[]
package com.example.bojan.nibllbojanactivities; import android.content.Intent; import android.os.CountDownTimer; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.StringRequest; import com.example.bojan.nibllbojanactivities.Adapter.DeviceArrayAdapter; import com.example.bojan.nibllbojanactivities.model.Device; import com.example.bojan.nibllbojanactivities.model.Sensor; import com.example.bojan.nibllbojanactivities.utils.MySingleton; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class device extends AppCompatActivity { CountDownTimer countDownTimer; List<Object> alleObject; Boolean requestDeviceComplete; Boolean requestSensorComplete; List<Device> alleDevice; List<Sensor> alleSensor; JsonArrayRequest jsonSensorRequest; JsonArrayRequest jsonDeviceRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_device); Thread mijnThread = new Thread(new Runnable() { @Override public void run() { getAllDevice(); } }); //haal devices op in aparte thread mijnThread.start(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.addDevice); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intentLoadNewActivity = new Intent(device.this, DeviceAddActivity.class); startActivity(intentLoadNewActivity); } }); countDownTimer = new CountDownTimer(500, 500) { //haal elke 2 seconden alle apparaten opnieuw op, voor de laatste status te weten @Override public void onTick(long l) { } public void onFinish() { getAllDevice(); } }; } private void vulLijstOp() { //vul de lijst van alle apparaten op for(Device device : alleDevice){ alleObject.add(device); } for(Sensor sensor : alleSensor) { alleObject.add(sensor); } DeviceArrayAdapter mijnAdapter = new DeviceArrayAdapter(this, alleObject); GridView mijnAdapterView = (GridView) findViewById(R.id.deviceGridview); mijnAdapterView.setAdapter(mijnAdapter); Log.d("lol", "vulLijstOp: "); } private void turnDeviceOnOff(Boolean on, int deviceId) { //voer een post request uit voor een apparaat aan/uit te zetten String url = "http://192.168.1.128:8080/device/statusChangeById?"; url += "id=" + deviceId; if(on){ url += "&status=1"; }else{ url += "&status=0"; } StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.d("Response", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", error.toString()); } } ); MySingleton.getInstance(this).addToRequestQueue(postRequest); } private void getAllDevice(){ //hierin word de json file met alle apparaten die zich in de database bevinden, opgehaald requestDeviceComplete = false; requestSensorComplete = false; alleObject = new ArrayList<Object>(); jsonSensorRequest = new JsonArrayRequest (Request.Method.GET, "http://192.168.1.128:8080/sensor/getAll", null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { alleSensor = new ArrayList<Sensor>(); for (int i = 0; i < response.length(); i++) { try { JSONObject responseObject = response.getJSONObject(i); alleSensor.add(new Sensor(Integer.parseInt(responseObject.getString("sensorID")), responseObject.getString("naamSensor"), Double.parseDouble(responseObject.getString("inputWaarde")), Integer.parseInt(responseObject.getString("status")))); } catch (JSONException e) { e.printStackTrace(); } } if(requestDeviceComplete){ vulLijstOp(); } requestSensorComplete = true; } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub Log.d("lol", "onErrorResponse: " + error); } }); jsonDeviceRequest = new JsonArrayRequest (Request.Method.GET, "http://192.168.1.128:8080/device/getAll", null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { alleDevice = new ArrayList<Device>(); for (int i = 0; i < response.length(); i++) { try { JSONObject responseObject = response.getJSONObject(i); alleDevice.add(new Device(Integer.parseInt(responseObject.get("deviceId").toString()), R.drawable.lamp_icon, R.drawable.lamp_scroll_off, responseObject.get("naamDevice").toString(), Boolean.parseBoolean(responseObject.get("status").toString()))); } catch (JSONException e) { e.printStackTrace(); } } if(requestSensorComplete){ vulLijstOp(); } requestDeviceComplete = true; countDownTimer.start(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub Log.d("lol", "onErrorResponse: " + error); } }); MySingleton.getInstance(device.this).addToRequestQueue(jsonDeviceRequest); MySingleton.getInstance(device.this).addToRequestQueue(jsonSensorRequest); GridView lstDevices = (GridView) findViewById(R.id.deviceGridview); lstDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() { boolean click = false; @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //als er op een apparaat geklikt wordt, wordt dit aan/uitgezet List<Object> alleObject; Device device; if(parent.getItemAtPosition(position).getClass() == Device.class){ device = (Device) parent.getItemAtPosition(position); Device mijnGeselecteerdeDevice = (Device) parent.getItemAtPosition(position); turnDeviceOnOff(!mijnGeselecteerdeDevice.getStatus() ,mijnGeselecteerdeDevice.getDeviceId()); } } }); lstDevices.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { //als er lang op een apparaat wordt gedrukt, dan zal er een detail pagina over het apparaat openenen if (parent.getItemAtPosition(position).getClass() == Device.class) { Intent intentLoadNewActivity = new Intent(device.this, devicesettings.class); Device mijnGeselecteerdeDevice = (Device) parent.getItemAtPosition(position); intentLoadNewActivity.putExtra("device", mijnGeselecteerdeDevice); startActivity(intentLoadNewActivity); } return false; } // // }); } }
9,099
0.577646
0.571711
232
38.215519
39.30151
278
false
false
0
0
0
0
0
0
0.590517
false
false
3
df8f3e1a6893685e46bb4e735fac6022b6651cb2
35,802,847,399,364
0c26117c2feda9515b0db00476667c2232012f99
/app/src/main/java/com/gracepsy/knarfytrebil/player/module/my/AccountRecordPageCount.java
3fde472bfa4f9e9c6792e9f477b666313d768378
[ "MIT" ]
permissive
caijun820/firstproject
https://github.com/caijun820/firstproject
b775991899b29af4fbbac095681ddebf2461e4a0
7b2253ab5b6774b1a40bdfd39869f7b9c64aa417
refs/heads/master
2016-08-11T18:43:02.105000
2016-03-30T03:37:04
2016-03-30T03:37:04
55,026,925
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gracepsy.knarfytrebil.player.module.my; import com.gracepsy.knarfytrebil.player.my.AccountRecordBean; import java.util.ArrayList; import java.util.List; /** * Created by guling on 15-9-30. */ public class AccountRecordPageCount { private int pageCount; private List<AccountRecordBean> list=new ArrayList<AccountRecordBean>(); public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public List<AccountRecordBean> getList() { return list; } public void setList(List<AccountRecordBean> list) { this.list = list; } }
UTF-8
Java
671
java
AccountRecordPageCount.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by guling on 15-9-30.\n */\npublic class AccountRecordPageCou", "end": 192, "score": 0.9995388984680176, "start": 186, "tag": "USERNAME", "value": "guling" } ]
null
[]
package com.gracepsy.knarfytrebil.player.module.my; import com.gracepsy.knarfytrebil.player.my.AccountRecordBean; import java.util.ArrayList; import java.util.List; /** * Created by guling on 15-9-30. */ public class AccountRecordPageCount { private int pageCount; private List<AccountRecordBean> list=new ArrayList<AccountRecordBean>(); public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public List<AccountRecordBean> getList() { return list; } public void setList(List<AccountRecordBean> list) { this.list = list; } }
671
0.691505
0.684054
30
21.366667
21.451469
76
false
false
0
0
0
0
0
0
0.333333
false
false
3
ecb6f707cb349f7a3df71a01b44026b80e71491d
25,795,573,640,767
fa23d64ad6df10fb0949863c1e722d0c722e2fbe
/tianZhongYunBao7/src/main/java/com/expai/tianzhongyunbao/util/DistanceActionSheet.java
642dff0c579a9ea79bf6b9cd78ef8e4a7eecf426
[]
no_license
yunlonggmail/TianZhongYunBao7
https://github.com/yunlonggmail/TianZhongYunBao7
8a2be2e8f0e26e0059780e13d1d0b5edd8c4d11b
110da14644a5998660446df94e250c15e4aeaa94
refs/heads/master
2016-09-16T16:13:02.101000
2016-08-18T13:37:29
2016-08-18T13:37:29
62,721,348
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.expai.tianzhongyunbao.util; import com.expai.tianzhongyunbao.R; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface.OnCancelListener; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; public class DistanceActionSheet { public interface OnDistanceActionSheetSelected { void onDistanceMenuItemClick(int whichButton); } private DistanceActionSheet() { } @SuppressLint("InflateParams") public static Dialog showSheet(Context context, final OnDistanceActionSheetSelected actionSheetSelected, OnCancelListener cancelListener) { final Dialog dlg = new Dialog(context, R.style.ActionSheet); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout layout = (LinearLayout) inflater.inflate( R.layout.distance_actionsheet, null); final int cFullFillWidth = 10000; layout.setMinimumWidth(cFullFillWidth); TextView tv_200 = (TextView) layout.findViewById(R.id.tv_distance_200); TextView tv_500 = (TextView) layout.findViewById(R.id.tv_distance_500); TextView tv_1000 = (TextView) layout .findViewById(R.id.tv_distance_1000); TextView tv_2000 = (TextView) layout .findViewById(R.id.tv_distance_2000); TextView tv_3000 = (TextView) layout .findViewById(R.id.tv_distance_3000); TextView tv_4000 = (TextView) layout .findViewById(R.id.tv_distance_4000); TextView tv_other = (TextView) layout .findViewById(R.id.tv_distance_other); TextView tv_cancle = (TextView) layout .findViewById(R.id.tv_distance_cancel); tv_200.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(1); dlg.dismiss(); } }); tv_500.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(2); dlg.dismiss(); } }); tv_1000.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(3); dlg.dismiss(); } }); tv_2000.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(4); dlg.dismiss(); } }); tv_3000.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(5); dlg.dismiss(); } }); tv_4000.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(6); dlg.dismiss(); } }); tv_other.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(7); dlg.dismiss(); } }); tv_cancle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(8); dlg.dismiss(); } }); Window w = dlg.getWindow(); WindowManager.LayoutParams lp = w.getAttributes(); lp.x = 0; final int cMakeBottom = -1000; lp.y = cMakeBottom; lp.gravity = Gravity.BOTTOM; dlg.onWindowAttributesChanged(lp); dlg.setCanceledOnTouchOutside(false); if (cancelListener != null) dlg.setOnCancelListener(cancelListener); dlg.setContentView(layout); dlg.show(); return dlg; } }
UTF-8
Java
4,159
java
DistanceActionSheet.java
Java
[]
null
[]
package com.expai.tianzhongyunbao.util; import com.expai.tianzhongyunbao.R; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface.OnCancelListener; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; public class DistanceActionSheet { public interface OnDistanceActionSheetSelected { void onDistanceMenuItemClick(int whichButton); } private DistanceActionSheet() { } @SuppressLint("InflateParams") public static Dialog showSheet(Context context, final OnDistanceActionSheetSelected actionSheetSelected, OnCancelListener cancelListener) { final Dialog dlg = new Dialog(context, R.style.ActionSheet); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout layout = (LinearLayout) inflater.inflate( R.layout.distance_actionsheet, null); final int cFullFillWidth = 10000; layout.setMinimumWidth(cFullFillWidth); TextView tv_200 = (TextView) layout.findViewById(R.id.tv_distance_200); TextView tv_500 = (TextView) layout.findViewById(R.id.tv_distance_500); TextView tv_1000 = (TextView) layout .findViewById(R.id.tv_distance_1000); TextView tv_2000 = (TextView) layout .findViewById(R.id.tv_distance_2000); TextView tv_3000 = (TextView) layout .findViewById(R.id.tv_distance_3000); TextView tv_4000 = (TextView) layout .findViewById(R.id.tv_distance_4000); TextView tv_other = (TextView) layout .findViewById(R.id.tv_distance_other); TextView tv_cancle = (TextView) layout .findViewById(R.id.tv_distance_cancel); tv_200.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(1); dlg.dismiss(); } }); tv_500.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(2); dlg.dismiss(); } }); tv_1000.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(3); dlg.dismiss(); } }); tv_2000.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(4); dlg.dismiss(); } }); tv_3000.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(5); dlg.dismiss(); } }); tv_4000.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(6); dlg.dismiss(); } }); tv_other.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(7); dlg.dismiss(); } }); tv_cancle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub actionSheetSelected.onDistanceMenuItemClick(8); dlg.dismiss(); } }); Window w = dlg.getWindow(); WindowManager.LayoutParams lp = w.getAttributes(); lp.x = 0; final int cMakeBottom = -1000; lp.y = cMakeBottom; lp.gravity = Gravity.BOTTOM; dlg.onWindowAttributesChanged(lp); dlg.setCanceledOnTouchOutside(false); if (cancelListener != null) dlg.setOnCancelListener(cancelListener); dlg.setContentView(layout); dlg.show(); return dlg; } }
4,159
0.70666
0.686463
145
26.682758
19.559883
73
false
false
0
0
0
0
0
0
2.537931
false
false
3
d015c64d708fce127ffb357f433f79548e9ce8ff
37,520,834,311,709
6c72b9fe32468c6526fa6493e284a8dfedc25b6e
/leetcode/recover_bst/java/Solution.java
429c95eabdb1b1cde14c6c3277a16bd685e55e51
[]
no_license
xxiao23/xiao-puzzle
https://github.com/xxiao23/xiao-puzzle
dd44bd897960261388d30eb0232e52793ef42afb
623b3a5d9a7dfdc58c9aba6496bf63fab0bebadd
refs/heads/master
2016-09-06T11:48:14.381000
2014-03-17T17:17:40
2014-03-17T17:17:40
1,697,727
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Solution { TreeNode cur = null; TreeNode prev = null; TreeNode n1 = null; TreeNode n2 = null; public void recoverTree(TreeNode root) { // Start typing your Java solution below // DO NOT write main() function this.cur = null; this.prev = null; this.n1 = null; this.n2 = null; inorder(root); if (n1 != null && n2 != null) { int tmp = n1.val; n1.val = n2.val; n2.val = tmp; } } private void inorder(TreeNode root) { if (root == null) { return; } inorder(root.left); prev = cur; cur = root; if (prev != null && cur != null) { if (prev.val > cur.val) { if (n1 == null) { n1 = prev; } n2 = cur; } } inorder(root.right); } }
UTF-8
Java
871
java
Solution.java
Java
[]
null
[]
public class Solution { TreeNode cur = null; TreeNode prev = null; TreeNode n1 = null; TreeNode n2 = null; public void recoverTree(TreeNode root) { // Start typing your Java solution below // DO NOT write main() function this.cur = null; this.prev = null; this.n1 = null; this.n2 = null; inorder(root); if (n1 != null && n2 != null) { int tmp = n1.val; n1.val = n2.val; n2.val = tmp; } } private void inorder(TreeNode root) { if (root == null) { return; } inorder(root.left); prev = cur; cur = root; if (prev != null && cur != null) { if (prev.val > cur.val) { if (n1 == null) { n1 = prev; } n2 = cur; } } inorder(root.right); } }
871
0.463835
0.448909
43
19.255814
12.302567
48
false
false
0
0
0
0
0
0
1.348837
false
false
3
4b6cf0b9af420dcc15f4bedd5331d5734c506383
26,027,501,869,367
3915515e2b655ce8c6d74600411186b0adc16d34
/demmo1/src/InterviewPrograms_TechnicalRoundQuestions/Program4.java
6adef276307362fb456c4898913094c00b188c16
[]
no_license
deepeshdk/USTGlobal-16Sep19-Deepesh-Khandelwal
https://github.com/deepeshdk/USTGlobal-16Sep19-Deepesh-Khandelwal
e11c4c434e94ca12eacbcb840a4ce7cc3a17d3b3
4eb6ff3f8d5eb9ad269e63a3baf36e1970dd1750
refs/heads/master
2023-01-13T09:41:55.474000
2020-06-05T13:18:02
2020-06-05T13:18:02
215,532,209
0
0
null
false
2023-01-07T18:51:06
2019-10-16T11:31:22
2020-06-05T13:18:25
2023-01-07T18:51:04
23,003
0
0
210
CSS
false
false
package InterviewPrograms_TechnicalRoundQuestions; public class Program4 { public static void main(String[] args) { int x=2; //if(x=2)//Type mismatch: cannot convert from int to boolean System.out.println("Megan Fox"); } }
UTF-8
Java
235
java
Program4.java
Java
[ { "context": "onvert from int to boolean\n\t\t\tSystem.out.println(\"Megan Fox\");\n\t}\n\n}\n", "end": 225, "score": 0.9998444318771362, "start": 216, "tag": "NAME", "value": "Megan Fox" } ]
null
[]
package InterviewPrograms_TechnicalRoundQuestions; public class Program4 { public static void main(String[] args) { int x=2; //if(x=2)//Type mismatch: cannot convert from int to boolean System.out.println("<NAME>"); } }
232
0.723404
0.710638
11
20.363636
21.579758
62
false
false
0
0
0
0
0
0
1.181818
false
false
3
e2c8da5d3ad4fcc0f91d2e671988c8632cdd510c
36,472,862,305,490
45ea4ba787257a2471ce378b2a6a7f52bb9fb49f
/COMP445_fun/src/http/ResponseParser.java
ff637122b6e1bee312c6c99d363ab92bc233c954
[]
no_license
samgo1/Comp445
https://github.com/samgo1/Comp445
a5175d6ff98ef117dedde1c3a79e5bd0f1554ce1
35018faadfc8e31e1e2e399fc589cc2a935cb562
refs/heads/master
2020-12-21T11:59:28.845000
2020-04-06T16:45:20
2020-04-06T16:45:20
236,423,584
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package http; import java.io.InputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class ResponseParser { private InputStream mInputStream; private String mVersion; private int mStatusCode; private String mPhrase; private String mBody; private HashMap<String, String> mHeaders; private final String END_OF_HEADERS = ""; public ResponseParser(InputStream aInputStream) { mInputStream = aInputStream; mHeaders = new HashMap<>(); mBody = ""; // parsing the returned response parse(); } private void parse() { BufferedReader lBuffReader = new BufferedReader(new InputStreamReader(mInputStream)); String lLine; int lCounter = 0; try { boolean lNeedToProcessHeaders = true; boolean lNeedToProcessBody = false; while ((lLine = lBuffReader.readLine()) != null) { if (lCounter == 0) { // lLine is status line mVersion = lLine.substring(0, lLine.indexOf(' ')); mStatusCode = Integer.parseInt (lLine.substring(lLine.indexOf(' ')+1,lLine.indexOf(' ') + 4)); mPhrase = lLine.substring(lLine.indexOf(Integer.toString(mStatusCode)) + 3); lCounter++; continue; } if (!lLine.equals(END_OF_HEADERS) && lNeedToProcessHeaders) { // grab the headers String lHeaderKey = lLine.substring(0, lLine.indexOf(':')); String lHeaderVal = lLine.substring(lLine.indexOf(':')+1); mHeaders.put(lHeaderKey, lHeaderVal); lCounter++; continue; } if (lLine.equals(END_OF_HEADERS) && lNeedToProcessBody == false) { lCounter++; lNeedToProcessHeaders = false; lNeedToProcessBody = true; continue; // next one is body } mBody += lLine + "\n"; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void print(boolean aVerbose) { if (aVerbose) { // print all of the request System.out.println(mVersion + " " + mStatusCode + " " + mPhrase); // printing the headers Iterator lIt = mHeaders.entrySet().iterator(); while (lIt.hasNext()) { Map.Entry<String, String> lMapEntry = (Map.Entry)lIt.next(); String lHeader = lMapEntry.getKey(); String lValue = lMapEntry.getValue(); System.out.println(lHeader + ":" + lValue); } System.out.println(); } System.out.print(mBody); } }
UTF-8
Java
2,468
java
ResponseParser.java
Java
[]
null
[]
package http; import java.io.InputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class ResponseParser { private InputStream mInputStream; private String mVersion; private int mStatusCode; private String mPhrase; private String mBody; private HashMap<String, String> mHeaders; private final String END_OF_HEADERS = ""; public ResponseParser(InputStream aInputStream) { mInputStream = aInputStream; mHeaders = new HashMap<>(); mBody = ""; // parsing the returned response parse(); } private void parse() { BufferedReader lBuffReader = new BufferedReader(new InputStreamReader(mInputStream)); String lLine; int lCounter = 0; try { boolean lNeedToProcessHeaders = true; boolean lNeedToProcessBody = false; while ((lLine = lBuffReader.readLine()) != null) { if (lCounter == 0) { // lLine is status line mVersion = lLine.substring(0, lLine.indexOf(' ')); mStatusCode = Integer.parseInt (lLine.substring(lLine.indexOf(' ')+1,lLine.indexOf(' ') + 4)); mPhrase = lLine.substring(lLine.indexOf(Integer.toString(mStatusCode)) + 3); lCounter++; continue; } if (!lLine.equals(END_OF_HEADERS) && lNeedToProcessHeaders) { // grab the headers String lHeaderKey = lLine.substring(0, lLine.indexOf(':')); String lHeaderVal = lLine.substring(lLine.indexOf(':')+1); mHeaders.put(lHeaderKey, lHeaderVal); lCounter++; continue; } if (lLine.equals(END_OF_HEADERS) && lNeedToProcessBody == false) { lCounter++; lNeedToProcessHeaders = false; lNeedToProcessBody = true; continue; // next one is body } mBody += lLine + "\n"; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void print(boolean aVerbose) { if (aVerbose) { // print all of the request System.out.println(mVersion + " " + mStatusCode + " " + mPhrase); // printing the headers Iterator lIt = mHeaders.entrySet().iterator(); while (lIt.hasNext()) { Map.Entry<String, String> lMapEntry = (Map.Entry)lIt.next(); String lHeader = lMapEntry.getKey(); String lValue = lMapEntry.getValue(); System.out.println(lHeader + ":" + lValue); } System.out.println(); } System.out.print(mBody); } }
2,468
0.661264
0.658023
94
25.25532
20.639734
87
false
false
0
0
0
0
0
0
3.234043
false
false
3
2ddc2858ba75cf5b4ccb0ce4b6e357ca906f1619
35,570,919,168,107
8a0a6129500af8a48df10a0376b36843ae6d585d
/byte-buddy-use/src/main/java/com/xuesran/chapter13/test/StringValueTest.java
a4c79fbfef11f21cfc9f1ff6b8282778ace86e26
[]
no_license
xueshun/agent-use
https://github.com/xueshun/agent-use
0ec7f9ad9fe6de4aebb4732e1fedb48e6f8d5d1b
c02b38662d508ec820b47a94ecddb8f81513efa5
refs/heads/main
2023-01-11T04:25:11.725000
2020-11-17T13:08:22
2020-11-17T13:08:22
313,213,871
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xuesran.chapter13.test; import com.xuesran.chapter12.allotter.ToStringAssigner; import com.xuesran.chapter13.entity.StringTest; import com.xuesran.chapter13.paramBinder.StringValueBinder; import net.bytebuddy.ByteBuddy; import net.bytebuddy.implementation.MethodDelegation; import net.bytebuddy.matcher.ElementMatchers; import java.io.File; import java.io.IOException; public class StringValueTest { public static void main(String[] args) throws IOException, IllegalAccessException, InstantiationException { StringTest toString = new ByteBuddy().subclass(StringTest.class) .method(ElementMatchers.named("toString").and(ElementMatchers.isVarArgs())) .intercept(MethodDelegation.withDefaultConfiguration() .withBinders(StringValueBinder.INSTANCE) .to(ToStringInterceptor.class)) .make() //.saveIn(new File("G://byte-buddy//chapter13")); .load(StringValueTest.class.getClassLoader()) .getLoaded() .newInstance(); System.out.println(toString.toString()); toString.setName("111"); System.out.println(toString.toString()); // } }
UTF-8
Java
1,250
java
StringValueTest.java
Java
[]
null
[]
package com.xuesran.chapter13.test; import com.xuesran.chapter12.allotter.ToStringAssigner; import com.xuesran.chapter13.entity.StringTest; import com.xuesran.chapter13.paramBinder.StringValueBinder; import net.bytebuddy.ByteBuddy; import net.bytebuddy.implementation.MethodDelegation; import net.bytebuddy.matcher.ElementMatchers; import java.io.File; import java.io.IOException; public class StringValueTest { public static void main(String[] args) throws IOException, IllegalAccessException, InstantiationException { StringTest toString = new ByteBuddy().subclass(StringTest.class) .method(ElementMatchers.named("toString").and(ElementMatchers.isVarArgs())) .intercept(MethodDelegation.withDefaultConfiguration() .withBinders(StringValueBinder.INSTANCE) .to(ToStringInterceptor.class)) .make() //.saveIn(new File("G://byte-buddy//chapter13")); .load(StringValueTest.class.getClassLoader()) .getLoaded() .newInstance(); System.out.println(toString.toString()); toString.setName("111"); System.out.println(toString.toString()); // } }
1,250
0.676
0.6656
31
39.258064
27.691814
111
false
false
0
0
0
0
0
0
0.516129
false
false
3
a93748111d39735c3b5d13b864df0af8757afce0
38,938,173,527,883
7234a8ff870d5cfab3779d8fd19915d93229bab4
/src/main/java/FindRightInterval.java
895849fd2a81712b81d0df6545b955ec28d283f5
[]
no_license
snehasishroy/leetcode-practice
https://github.com/snehasishroy/leetcode-practice
6b723b2366cdacd9864e2807f99d4e9bbd66f8cb
2116625b77af211897036df0539df257826b1245
refs/heads/master
2023-03-10T03:06:04.726000
2023-03-08T19:42:51
2023-03-08T19:42:51
181,065,505
15
3
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Arrays; import java.util.Comparator; /** * https://leetcode.com/problems/find-right-interval/ * <p> * Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger * than or equal to the end point of the interval i, which can be called that j is on the "right" of i. * <p> * For any interval i, you need to store the minimum interval j's index, which means that the interval j * has the minimum start point to build the "right" relationship for interval i. If the interval j doesn't exist, store -1 for the interval i. * Finally, you need output the stored value of each interval as an array. * <p> * Note: * <p> * You may assume the interval's end point is always bigger than its start point. * You may assume none of these intervals have the same start point. * <p> * Input: [ [3,4], [2,3], [1,2] ] * <p> * Output: [-1, 0, 1] * <p> * Explanation: There is no satisfied "right" interval for [3,4]. * For [2,3], the interval [3,4] has minimum-"right" start point; * For [1,2], the interval [2,3] has minimum-"right" start point. */ public class FindRightInterval { /** * Approach, since we are interested in the index of the next right interval, sorting comes into mind. * But sorting will change the original indexes, so we need to store the original indices somewhere * <p> * Another simplified way of solving this would be to leverage TreeMap to find the interval >= current interval using ceilingEntry() */ public int[] findRightInterval(int[][] intervals) { Point[] points = new Point[intervals.length]; for (int i = 0; i < intervals.length; i++) { points[i] = new Point(intervals[i][0], intervals[i][1], i); } Arrays.sort(points, Comparator.comparingInt(o -> o.x)); //sort by start time int[] result = new int[intervals.length]; Arrays.fill(result, -1); for (int i = 0; i < intervals.length; i++) { //need to find the point whose x index >= current y index int index = Arrays.binarySearch(points, new Point(points[i].y, -1, -1), Comparator.comparingInt(o -> o.x)); if (index == -1 * (intervals.length + 1)) { //if current y is the largest value continue; } if (index < 0) { index = -1 * index - 1; } /* This is not required as the start points are guaranteed to be unique, but during my first implementation, I thought otherwise Upon reading the doc of binary search, it's mentioned that if their are duplicate keys present, any of them can be returned But since we are interested in the first right index instead, we need the leftmost one So iterate left until we find such character, care must be taken to handle the case when index equals the current index as well while (index - 1>= 0 && points[index-1].x >= points[i].y) { index--; } if (index == i & index + 1 < intervals.length && points[index + 1].x >= points[i].y) { index++; }*/ result[points[i].index] = points[index].index; } return result; } private static class Point { int x; int y; int index; public Point(int x, int y, int index) { this.x = x; this.y = y; this.index = index; } } }
UTF-8
Java
3,514
java
FindRightInterval.java
Java
[]
null
[]
import java.util.Arrays; import java.util.Comparator; /** * https://leetcode.com/problems/find-right-interval/ * <p> * Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger * than or equal to the end point of the interval i, which can be called that j is on the "right" of i. * <p> * For any interval i, you need to store the minimum interval j's index, which means that the interval j * has the minimum start point to build the "right" relationship for interval i. If the interval j doesn't exist, store -1 for the interval i. * Finally, you need output the stored value of each interval as an array. * <p> * Note: * <p> * You may assume the interval's end point is always bigger than its start point. * You may assume none of these intervals have the same start point. * <p> * Input: [ [3,4], [2,3], [1,2] ] * <p> * Output: [-1, 0, 1] * <p> * Explanation: There is no satisfied "right" interval for [3,4]. * For [2,3], the interval [3,4] has minimum-"right" start point; * For [1,2], the interval [2,3] has minimum-"right" start point. */ public class FindRightInterval { /** * Approach, since we are interested in the index of the next right interval, sorting comes into mind. * But sorting will change the original indexes, so we need to store the original indices somewhere * <p> * Another simplified way of solving this would be to leverage TreeMap to find the interval >= current interval using ceilingEntry() */ public int[] findRightInterval(int[][] intervals) { Point[] points = new Point[intervals.length]; for (int i = 0; i < intervals.length; i++) { points[i] = new Point(intervals[i][0], intervals[i][1], i); } Arrays.sort(points, Comparator.comparingInt(o -> o.x)); //sort by start time int[] result = new int[intervals.length]; Arrays.fill(result, -1); for (int i = 0; i < intervals.length; i++) { //need to find the point whose x index >= current y index int index = Arrays.binarySearch(points, new Point(points[i].y, -1, -1), Comparator.comparingInt(o -> o.x)); if (index == -1 * (intervals.length + 1)) { //if current y is the largest value continue; } if (index < 0) { index = -1 * index - 1; } /* This is not required as the start points are guaranteed to be unique, but during my first implementation, I thought otherwise Upon reading the doc of binary search, it's mentioned that if their are duplicate keys present, any of them can be returned But since we are interested in the first right index instead, we need the leftmost one So iterate left until we find such character, care must be taken to handle the case when index equals the current index as well while (index - 1>= 0 && points[index-1].x >= points[i].y) { index--; } if (index == i & index + 1 < intervals.length && points[index + 1].x >= points[i].y) { index++; }*/ result[points[i].index] = points[index].index; } return result; } private static class Point { int x; int y; int index; public Point(int x, int y, int index) { this.x = x; this.y = y; this.index = index; } } }
3,514
0.608139
0.59761
78
44.051281
41.014664
142
false
false
0
0
0
0
0
0
0.833333
false
false
3
70e59ac3f7c60c5424caa24d149c25bc9ab5d8c9
11,733,850,678,200
55f5071e46a1100da96d14034d0ef1fef0a4db18
/src/modelo/CartaMonstruo.java
10979a58aafe1772250c826a53118b1ae492f611
[]
no_license
victorbravoarroyo/TP2-Algo3
https://github.com/victorbravoarroyo/TP2-Algo3
dbef910cd06c2670c5845cfe65300389e22c16ff
ca3f4ebc2d7e30328276020ac3302d68336c6451
refs/heads/master
2020-03-21T07:55:39.671000
2018-06-21T07:47:00
2018-06-21T07:47:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package modelo; import java.util.ArrayList; import java.util.Collection; public class CartaMonstruo extends Carta { protected int ataque; protected int defensa; protected Jugador duenio; protected Estado estado; protected Nivel nivel; protected Collection<CartaMonstruo> sacrificios; public CartaMonstruo(String nombre, int ataque, int defensa, int nivel) { super(nombre); this.ataque = ataque; this.defensa = defensa; this.nivel = Nivel.crearNivel(nivel); this.estado = new EstadoAtaque(); this.sacrificios = new ArrayList<CartaMonstruo>(); } public void asignarEstado(Estado estado) { this.estado = estado; } public void cambiarAPosicionDeAtaque() { this.estado = new EstadoAtaque(); } public boolean estaEnPosicionDeAtaque() { return this.estado.enPosicionDeAtaque(); } public void cambiarAPosicionDeDefensa() { this.estado = new EstadoDefensa(); } public boolean estaEnPosicionDeDefensa() { return !this.estado.enPosicionDeAtaque(); } public void asignarDuenio(Jugador duenio) { this.duenio = duenio; } public void atacarA(CartaMonstruo monstruoAtacado) { this.estado.atacarA(monstruoAtacado, this); } public void destruir() { Lado lado = this.duenio.obtenerLado(); lado.destruir(this); } public void agregarSacrificio(CartaMonstruo monstruo) { this.sacrificios.add(monstruo); } public void sacrificarSacricios() { this.nivel.sacrificar(this.sacrificios); this.sacrificios = new ArrayList<CartaMonstruo>(); } public void aumentarAtaque(int aumento){ this.ataque = this.ataque + aumento; } public void aumentarDefensa(int aumento){ this.defensa = this.defensa + aumento; } public int extraerPuntosAtaque(){ return this.ataque; } public int extraerPuntosDefensa(){ return this.defensa; } public void enfrentarA(CartaMonstruo monstruoAtacante) { this.estado.enfrentarA(monstruoAtacante, this); } public void recibirDanioAPuntosDeAtaque(int ataqueRecibido) { int puntosResistidos = this.ataque - ataqueRecibido; if (puntosResistidos <= 0) { this.duenio.disminuirVidaEn(-puntosResistidos); this.destruir(); } } public void recibirDanioAPuntosDeDefensa(int ataqueRecibido) { int puntosResistidos = this.defensa - ataqueRecibido; if (puntosResistidos <= 0) { this.destruir(); } } }
UTF-8
Java
2,318
java
CartaMonstruo.java
Java
[]
null
[]
package modelo; import java.util.ArrayList; import java.util.Collection; public class CartaMonstruo extends Carta { protected int ataque; protected int defensa; protected Jugador duenio; protected Estado estado; protected Nivel nivel; protected Collection<CartaMonstruo> sacrificios; public CartaMonstruo(String nombre, int ataque, int defensa, int nivel) { super(nombre); this.ataque = ataque; this.defensa = defensa; this.nivel = Nivel.crearNivel(nivel); this.estado = new EstadoAtaque(); this.sacrificios = new ArrayList<CartaMonstruo>(); } public void asignarEstado(Estado estado) { this.estado = estado; } public void cambiarAPosicionDeAtaque() { this.estado = new EstadoAtaque(); } public boolean estaEnPosicionDeAtaque() { return this.estado.enPosicionDeAtaque(); } public void cambiarAPosicionDeDefensa() { this.estado = new EstadoDefensa(); } public boolean estaEnPosicionDeDefensa() { return !this.estado.enPosicionDeAtaque(); } public void asignarDuenio(Jugador duenio) { this.duenio = duenio; } public void atacarA(CartaMonstruo monstruoAtacado) { this.estado.atacarA(monstruoAtacado, this); } public void destruir() { Lado lado = this.duenio.obtenerLado(); lado.destruir(this); } public void agregarSacrificio(CartaMonstruo monstruo) { this.sacrificios.add(monstruo); } public void sacrificarSacricios() { this.nivel.sacrificar(this.sacrificios); this.sacrificios = new ArrayList<CartaMonstruo>(); } public void aumentarAtaque(int aumento){ this.ataque = this.ataque + aumento; } public void aumentarDefensa(int aumento){ this.defensa = this.defensa + aumento; } public int extraerPuntosAtaque(){ return this.ataque; } public int extraerPuntosDefensa(){ return this.defensa; } public void enfrentarA(CartaMonstruo monstruoAtacante) { this.estado.enfrentarA(monstruoAtacante, this); } public void recibirDanioAPuntosDeAtaque(int ataqueRecibido) { int puntosResistidos = this.ataque - ataqueRecibido; if (puntosResistidos <= 0) { this.duenio.disminuirVidaEn(-puntosResistidos); this.destruir(); } } public void recibirDanioAPuntosDeDefensa(int ataqueRecibido) { int puntosResistidos = this.defensa - ataqueRecibido; if (puntosResistidos <= 0) { this.destruir(); } } }
2,318
0.74245
0.741588
101
21.950495
20.466043
74
false
false
0
0
0
0
0
0
1.574257
false
false
3
ce8d1507235bf0b9cf3a31733695688b0c7389a8
32,633,161,542,236
1912c29f438f87454ef3f3d2c99b438bc49c5d63
/Bank Project Hibernet/src/bean/TransactionDetails.java
95b538568691ba08e2f910e674cf89529d9b1ecf
[]
no_license
dolasairam/capgemini
https://github.com/dolasairam/capgemini
2b8415610793f50be2e858cf061115b51cc88a93
a8e581af39ca674721c30fc72ee2512f03c8c21e
refs/heads/master
2020-04-28T03:06:26.572000
2019-05-02T07:41:39
2019-05-02T07:41:39
174,923,515
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bean; import java.sql.Timestamp; //import java.util.Date; 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.PrePersist; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.sql.Timestamp; //import javax.persistence.JoinColumn; //import javax.persistence.ManyToOne; //import javax.persistence.OneToMany; @Entity @Table(name = "transactions") public class TransactionDetails { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Long accountId; private String type; private Double amount; @Column @Temporal(TemporalType.TIMESTAMP) private Date time=new Timestamp(System.currentTimeMillis()); public TransactionDetails() { super(); } public TransactionDetails(Long accountId, String type, Double amount) { super(); this.accountId = accountId; this.type = type; this.amount = amount; } public Long getAccountId() { return accountId; } public void setAccountId(Long accountId) { this.accountId = accountId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public Date getDate() { return time; } public void setDate(Timestamp date) { this.time = date; } @Override public String toString() { return accountId+"\t" + type + "\t" + amount + "\t" + time+"\n"; } }
UTF-8
Java
1,664
java
TransactionDetails.java
Java
[]
null
[]
package bean; import java.sql.Timestamp; //import java.util.Date; 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.PrePersist; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.sql.Timestamp; //import javax.persistence.JoinColumn; //import javax.persistence.ManyToOne; //import javax.persistence.OneToMany; @Entity @Table(name = "transactions") public class TransactionDetails { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Long accountId; private String type; private Double amount; @Column @Temporal(TemporalType.TIMESTAMP) private Date time=new Timestamp(System.currentTimeMillis()); public TransactionDetails() { super(); } public TransactionDetails(Long accountId, String type, Double amount) { super(); this.accountId = accountId; this.type = type; this.amount = amount; } public Long getAccountId() { return accountId; } public void setAccountId(Long accountId) { this.accountId = accountId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public Date getDate() { return time; } public void setDate(Timestamp date) { this.time = date; } @Override public String toString() { return accountId+"\t" + type + "\t" + amount + "\t" + time+"\n"; } }
1,664
0.73738
0.73738
84
18.809525
16.998934
72
false
false
0
0
0
0
0
0
1.202381
false
false
3
802bcf2eac167fbb28fc29866a707ceb1c898447
22,067,541,992,735
844b2f89b1518691f67176d4ac771e42946dc568
/src/main/java/com/rsupport/rsupporthomework/controller/MypageController.java
1b11e4de5d017ca31b704e1e9cdb4f1f177db5a9
[]
no_license
cocodevs/spring-notice-homework
https://github.com/cocodevs/spring-notice-homework
90697c1bca1bacdd93645f40f29220e48898dbec
c5eb00e1fa471f821dc41a932eb05b3e96e37911
refs/heads/master
2023-06-18T10:29:24.519000
2021-07-22T15:46:22
2021-07-22T15:46:22
387,377,968
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rsupport.rsupporthomework.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class MypageController { @GetMapping("/mypage") public String mypage() { return "/mypage/index"; } }
UTF-8
Java
301
java
MypageController.java
Java
[]
null
[]
package com.rsupport.rsupporthomework.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class MypageController { @GetMapping("/mypage") public String mypage() { return "/mypage/index"; } }
301
0.754153
0.754153
12
24.083334
19.863947
58
false
false
0
0
0
0
0
0
0.333333
false
false
3
6f9ca2093ae48d383470a0ae94ef5898eeccf762
26,233,660,279,241
a911c396727271722c133e8240c382917ea5a06a
/src/main/java/com/sharing/controller/UploadController.java
cd2cecb39811cd118833e49c1838340c08f27fa4
[]
no_license
Mahi509/filesharing
https://github.com/Mahi509/filesharing
b8735ddd3393275e4a62f16a5c95665c4e7cb20f
df642610417e82136b0402a1e2bf91cde166d1f1
refs/heads/master
2016-08-12T17:41:57.165000
2015-11-25T06:27:58
2015-11-25T06:27:58
44,516,024
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sharing.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import com.sharing.model.UploadedFile; import com.sharing.validator.FileValidator; import com.sharing.service.MainService; @Controller public class UploadController { @Autowired FileValidator fileValidator; @Autowired MainService mainService; static MultipartFile file; InputStream inputStream = null; OutputStream outputStream = null; OutputStream op=null; public UploadController() { // TODO Auto-generated constructor stub } public UploadController(MultipartFile file) { UploadController.file=file; } @RequestMapping("/fileUploadForm") public String getUploadForm( @ModelAttribute("uploadedFile") UploadedFile uploadedFile, BindingResult result) { return "uploadForm"; } @RequestMapping(value={"/fileUpload","/main/fileUpload"}) public String fileUploaded( @ModelAttribute("uploadedFile") UploadedFile uploadedFile, BindingResult result,HttpSession session,Model model) throws IOException { MultipartFile file = uploadedFile.getFile(); inputStream = file.getInputStream(); UploadController up=new UploadController(file); fileValidator.validate(uploadedFile, result); String userName=(String) session.getAttribute("userName"); if(userName!=null) { String fileName = file.getOriginalFilename(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); double fileSize = ((file.getSize()) / 1048576); String currentDate = dateFormat.format(date); Integer userId=(Integer) session.getAttribute("userId"); mainService.setFilesUpload(fileName, fileSize, currentDate,userId); try { File f=new File("/home/webwerks/Prakash/apache-tomcat-7.0.62/webapps/files/",fileName); File newFile = new File( "/home/webwerks/Prakash/apache-tomcat-7.0.62/webapps/files/"+userName+"/"); File myFile=new File(newFile,fileName); if (!newFile.exists()) { newFile.mkdir(); myFile.createNewFile(); f.createNewFile(); } outputStream = new FileOutputStream(myFile); op= new FileOutputStream(f); int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); op.write(bytes,0,read); } model.addAttribute("message", fileName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "redirect:/main/userfiledetails"; } return "showFile"; } public void temp(Model model,HttpSession session) throws IOException { String fileName = file.getOriginalFilename(); String user=(String) session.getAttribute("userName"); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); double fileSize = ((file.getSize()) / 1048576); String currentDate = dateFormat.format(date); if(user!=null) { System.out.println(" USER NAME "+session.getAttribute("userName")); Integer userId=(Integer) session.getAttribute("userId"); mainService.setFilesUpload(fileName, fileSize, currentDate,userId); /*if (result.hasErrors()) { return "uploadForm"; }*/ try { File f=new File("/home/webwerks/Prakash/apache-tomcat-7.0.62/webapps/files/",fileName); File newFile = new File( "/home/webwerks/Prakash/apache-tomcat-7.0.62/webapps/files/"+user+"/"); File myFile=new File(newFile,fileName); if (!newFile.exists()) { newFile.mkdir(); myFile.createNewFile(); f.createNewFile(); } outputStream = new FileOutputStream(myFile); op= new FileOutputStream(f); int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); op.write(bytes,0,read); } model.addAttribute("message", fileName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { model.addAttribute("message", " Sorry you need to Login First "); } } }
UTF-8
Java
4,754
java
UploadController.java
Java
[ { "context": "e();\n\t\tString user=(String) session.getAttribute(\"userName\");\n\t\n\t\tDateFormat dateFormat = new SimpleDateForm", "end": 3382, "score": 0.9966922998428345, "start": 3374, "tag": "USERNAME", "value": "userName" }, { "context": "m.out.println(\" USER NAME \"+session.getAttribute(\"userName\"));\n\t\t\t\tInteger userId=(Integer) session.getAttri", "end": 3679, "score": 0.6905074119567871, "start": 3671, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.sharing.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import com.sharing.model.UploadedFile; import com.sharing.validator.FileValidator; import com.sharing.service.MainService; @Controller public class UploadController { @Autowired FileValidator fileValidator; @Autowired MainService mainService; static MultipartFile file; InputStream inputStream = null; OutputStream outputStream = null; OutputStream op=null; public UploadController() { // TODO Auto-generated constructor stub } public UploadController(MultipartFile file) { UploadController.file=file; } @RequestMapping("/fileUploadForm") public String getUploadForm( @ModelAttribute("uploadedFile") UploadedFile uploadedFile, BindingResult result) { return "uploadForm"; } @RequestMapping(value={"/fileUpload","/main/fileUpload"}) public String fileUploaded( @ModelAttribute("uploadedFile") UploadedFile uploadedFile, BindingResult result,HttpSession session,Model model) throws IOException { MultipartFile file = uploadedFile.getFile(); inputStream = file.getInputStream(); UploadController up=new UploadController(file); fileValidator.validate(uploadedFile, result); String userName=(String) session.getAttribute("userName"); if(userName!=null) { String fileName = file.getOriginalFilename(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); double fileSize = ((file.getSize()) / 1048576); String currentDate = dateFormat.format(date); Integer userId=(Integer) session.getAttribute("userId"); mainService.setFilesUpload(fileName, fileSize, currentDate,userId); try { File f=new File("/home/webwerks/Prakash/apache-tomcat-7.0.62/webapps/files/",fileName); File newFile = new File( "/home/webwerks/Prakash/apache-tomcat-7.0.62/webapps/files/"+userName+"/"); File myFile=new File(newFile,fileName); if (!newFile.exists()) { newFile.mkdir(); myFile.createNewFile(); f.createNewFile(); } outputStream = new FileOutputStream(myFile); op= new FileOutputStream(f); int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); op.write(bytes,0,read); } model.addAttribute("message", fileName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "redirect:/main/userfiledetails"; } return "showFile"; } public void temp(Model model,HttpSession session) throws IOException { String fileName = file.getOriginalFilename(); String user=(String) session.getAttribute("userName"); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); double fileSize = ((file.getSize()) / 1048576); String currentDate = dateFormat.format(date); if(user!=null) { System.out.println(" USER NAME "+session.getAttribute("userName")); Integer userId=(Integer) session.getAttribute("userId"); mainService.setFilesUpload(fileName, fileSize, currentDate,userId); /*if (result.hasErrors()) { return "uploadForm"; }*/ try { File f=new File("/home/webwerks/Prakash/apache-tomcat-7.0.62/webapps/files/",fileName); File newFile = new File( "/home/webwerks/Prakash/apache-tomcat-7.0.62/webapps/files/"+user+"/"); File myFile=new File(newFile,fileName); if (!newFile.exists()) { newFile.mkdir(); myFile.createNewFile(); f.createNewFile(); } outputStream = new FileOutputStream(myFile); op= new FileOutputStream(f); int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); op.write(bytes,0,read); } model.addAttribute("message", fileName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { model.addAttribute("message", " Sorry you need to Login First "); } } }
4,754
0.701725
0.692049
199
22.894472
22.844545
91
false
false
0
0
0
0
0
0
2.547739
false
false
3
6235f37336ce9b6c43fa83deb3eeaf5ce1f78b46
11,081,015,658,466
08419b38d42357621813b41fc97d0741deb42ed1
/src/main/java/fi/bizhop/kiekkohamsteri/security/JWTAuthentication.java
f2f37a691b9d977bcfa943d7961d8346a5572750
[]
no_license
Bizhop/kiekkohamsteri
https://github.com/Bizhop/kiekkohamsteri
17ec81e81e18876d5358e21c5a6c6b6b081cfec4
707ac7c24a48b81d30c1a66d2bd136921fa26585
refs/heads/main
2023-07-27T08:20:14.141000
2023-04-05T13:39:13
2023-04-05T13:39:13
88,643,898
1
0
null
false
2023-07-05T21:48:34
2017-04-18T15:56:41
2023-01-31T16:49:18
2023-07-05T21:48:34
882
1
0
2
Java
false
false
package fi.bizhop.kiekkohamsteri.security; import fi.bizhop.kiekkohamsteri.ShutdownManager; import fi.bizhop.kiekkohamsteri.security.provider.JWTSecretKeyProvider; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import java.security.Key; import java.util.Date; @Component public class JWTAuthentication { private static final Logger LOG = LogManager.getLogger(JWTAuthentication.class); private static final long EXPIRATION_TIME = 1209600000L; //14 days public static final String JWT_TOKEN_PREFIX = "jwt"; private final Key JWT_KEY; private final ShutdownManager shutdownManager; public JWTAuthentication(ShutdownManager shutdownManager, JWTSecretKeyProvider JWTSecretKeyProvider) { this.shutdownManager = shutdownManager; this.JWT_KEY = getJwtKey(JWTSecretKeyProvider.getKey()); } //initialize JWT key or fail fast private Key getJwtKey(String base64) { try { var decoded = Decoders.BASE64.decode(base64); return Keys.hmacShaKeyFor(decoded); } catch (Exception e) { LOG.error("Error initializing JWT key", e); shutdownManager.shutdown(); } return null; } public String getJwtForEmail(String email) { var claims = Jwts.claims(); claims.put("email", email); var jwt = Jwts.builder() .setSubject(email) .setClaims(claims) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(JWT_KEY) .compact(); return String.format("%s%s", JWT_TOKEN_PREFIX, jwt); } public String getUserEmail(String token) { var claims = getClaims(token); if(claims == null || claims.get("email") == null) { return null; } return (String)claims.get("email"); } private Claims getClaims(String token) { if(token == null) { return null; } try { return Jwts.parserBuilder() .setSigningKey(JWT_KEY) .build() .parseClaimsJws(token.replaceFirst(JWT_TOKEN_PREFIX,"")) .getBody(); } catch (RuntimeException e) { LOG.warn("Invalid jwt token: {}", token); return null; } } }
UTF-8
Java
2,549
java
JWTAuthentication.java
Java
[]
null
[]
package fi.bizhop.kiekkohamsteri.security; import fi.bizhop.kiekkohamsteri.ShutdownManager; import fi.bizhop.kiekkohamsteri.security.provider.JWTSecretKeyProvider; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import java.security.Key; import java.util.Date; @Component public class JWTAuthentication { private static final Logger LOG = LogManager.getLogger(JWTAuthentication.class); private static final long EXPIRATION_TIME = 1209600000L; //14 days public static final String JWT_TOKEN_PREFIX = "jwt"; private final Key JWT_KEY; private final ShutdownManager shutdownManager; public JWTAuthentication(ShutdownManager shutdownManager, JWTSecretKeyProvider JWTSecretKeyProvider) { this.shutdownManager = shutdownManager; this.JWT_KEY = getJwtKey(JWTSecretKeyProvider.getKey()); } //initialize JWT key or fail fast private Key getJwtKey(String base64) { try { var decoded = Decoders.BASE64.decode(base64); return Keys.hmacShaKeyFor(decoded); } catch (Exception e) { LOG.error("Error initializing JWT key", e); shutdownManager.shutdown(); } return null; } public String getJwtForEmail(String email) { var claims = Jwts.claims(); claims.put("email", email); var jwt = Jwts.builder() .setSubject(email) .setClaims(claims) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(JWT_KEY) .compact(); return String.format("%s%s", JWT_TOKEN_PREFIX, jwt); } public String getUserEmail(String token) { var claims = getClaims(token); if(claims == null || claims.get("email") == null) { return null; } return (String)claims.get("email"); } private Claims getClaims(String token) { if(token == null) { return null; } try { return Jwts.parserBuilder() .setSigningKey(JWT_KEY) .build() .parseClaimsJws(token.replaceFirst(JWT_TOKEN_PREFIX,"")) .getBody(); } catch (RuntimeException e) { LOG.warn("Invalid jwt token: {}", token); return null; } } }
2,549
0.63672
0.628874
82
30.085365
23.51087
106
false
false
0
0
0
0
0
0
0.536585
false
false
3
5ca1f57ef3e7ea094f2e29aac9bb83c826f4ab26
11,081,015,658,373
d2242545df402608e2fbe53e87400ac028b22cda
/src/main/java/cn/tico/iot/configmanger/module/mao/redis/KindManager.java
0b43da2af0a00e19b3663f330d8ba106cf835cdc
[]
no_license
loveexception/config_manager
https://github.com/loveexception/config_manager
01cf8e7d89039fe6d802b7614784ff561bdea6e0
0e49704538cadd3f2c322bf095874f1d038d1930
refs/heads/master
2022-10-06T09:57:07.070000
2021-04-07T10:44:40
2021-04-07T10:44:40
195,495,226
1
0
null
false
2022-09-01T23:09:24
2019-07-06T03:57:14
2021-11-03T18:05:15
2022-09-01T23:09:23
9,673
1
0
8
JavaScript
false
false
package cn.tico.iot.configmanger.module.mao.redis; import cn.tico.iot.configmanger.module.iot.models.base.Kind; import cn.tico.iot.configmanger.module.iot.models.base.Location; import cn.tico.iot.configmanger.module.iot.services.KindService; import cn.tico.iot.configmanger.module.iot.services.LocationService; import cn.tico.iot.configmanger.module.mao.common.BaseManager; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.nutz.ioc.aop.Aop; import org.nutz.ioc.impl.PropertiesProxy; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.json.Json; import org.nutz.lang.Lang; import org.nutz.lang.Strings; import org.nutz.lang.util.NutMap; import org.nutz.log.Logs; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import static org.nutz.integration.jedis.RedisInterceptor.jedis; @IocBean(create = "init") public class KindManager extends BaseManager { @Inject PropertiesProxy conf; @Inject KindService kindService; String KEY_PATH ; static final String REG_STAT = ".*("; static final String REG_END = ").*"; static final String SPLIT =":"; @Aop("redis") public void init(){ // Logs.get().debugf("location redis path : %s ",KEY_PATH); // // KEY_PATH = conf.get("redis.pre.key.kind"); // // Set<String> keys= jedis().keys(KEY_PATH+"*"); // Logs.get().debugf("keys",keys); // keys.stream().forEach(key->jedis().del(key)); // // List <Kind> all = kindService.findAllKinds(); // List<Kind> copy = Lists.newArrayList(all); // all = all.stream() // .map(kind -> findAncestors(kind,copy)) // .map(kind -> fatherName(kind)) // .collect(Collectors.toList()); // all = children(all); // // all.forEach(location -> jedis().set(KEY_PATH+location.getId(),Json.toJson(location))); } /** * ่กฅๅฎŒๆ‰€ๆœ‰็š„็ฅ–่Š‚็‚น * @param me * @param all * @return */ public Kind findAncestors(Kind me ,List<Kind> all) { List<Kind> list = getAncestorsLocationsByMe(me,all); Map<String,Kind> parents = list .stream() .collect(Collectors.toMap( kind-> kind.getLevel(), kind->kind) ); me.setParents(parents); return me; } /** * ่กฅๅฎŒๆ‰€ๆœ‰็š„ๅญ่Š‚็‚น * @param all * @return */ public List<Kind> children(List<Kind> all){ Map<String,Kind > map = all.stream().collect(Collectors.toMap(kind->kind.getId(),kind->kind)); List<Kind> result = all.stream().map(kind ->{ String id = kind.getParentId(); if(Strings.isBlank(id)||Strings.equals("0",id)){ return kind; } Kind father = map.get(id); if(Lang.isEmpty(father.getChildren())){ father.setChildren(Lists.newArrayList()); } father.getChildren().add(kind); return kind; }).collect(Collectors.toList()); return result; } /** * ็”Ÿๆˆๆ ‘็š„ๆ นๆ•ฐๆฎ * @param id * @param all * @return */ public Kind zip(String id ,List<Kind> all){ List<Kind> root = children (all); return root.stream() .filter(location -> Strings.equals(id,location.getId())) .findFirst() .get(); } /** * ็”Ÿๆˆๅ•็‹ฌๆ•ฐๆฎ * @param id * @return */ @Aop("redis") public Kind get(String id){ String json = jedis().get(KEY_PATH+id); if(Strings.isBlank(json)){ return null; } return Json.fromJson(Kind.class,json); } /** * ๆŸฅๅฏปๆ‰€ๆœ‰ๅทฒ็Ÿฅ็š„KEY * @return */ @Aop("redis") public Set<String> keys(){ Set<String> set = jedis().keys(KEY_PATH+"*"); if(Lang.isEmpty(set)){ return Sets.newHashSet(); } return set.stream().map(key-> Strings.replaceBy(key, NutMap.NEW().addv(KEY_PATH,""))).collect(Collectors.toSet()); } public Kind byName(String longSplitName,List<Kind> all){ String[] array =Strings.splitIgnoreBlank(longSplitName,SPLIT); List<String> names = Lang.array2list(array); String last = Lists.newLinkedList(names).getLast(); List<Kind> ones = all.stream() .filter(one-> isMatchByKey(last, one.getCnName())) .filter(one ->{ String langName = Strings.sBlank(one.getParentName(),"")+SPLIT+one.getCnName(); boolean b = names.stream().allMatch(name -> isMatchByKey(name, langName)); return b; }).collect(Collectors.toList()); if(Lang.isEmpty(ones)){ return null; } if(ones.size()!=1){ return null; } return ones.get(0); //return ones.get(0); } public static boolean isMatchByKey(String last, String cnName) { return Strings.isMatch(Pattern.compile(REG_STAT + last + REG_END), cnName); } /** * ๆ‰€ๆœ‰็š„ๅœฐ็†ไฝๅˆถ * @return */ public List<Kind> all() { Set<String> keys = keys(); return keys.stream().map(key-> get(key)).collect(Collectors.toList()); } /** * ้ ็ˆถ็›ฎๅฝ•ๆ•ฐๆฎ่กฅๅฎŒ * fatherName * ๅญ—ๆฎต * @param kind */ public Kind fatherName(Kind kind) { Map<String,Object> map = kind.getParents(); if(Lang.isEmpty(map)){ return kind; } List<String> list = map.values() .stream() .map(value->Lang.obj2nutmap(value).getString("cnName")) .collect(Collectors.toList()); String fatherName = Strings.join(SPLIT,list); kind.setParentName(fatherName); return kind; } /** * ่ทŸๆฎ LOCATION ๅพ—ๅˆฐๆ‰€ๆœ‰็š„ Location ็ˆถๆ•ฐๆฎ * @param kindId * @return */ public List<Kind> allFamilyWithMe(String kindId) { Kind me = get(kindId); List<Kind> result = getAncestorsLocationsByMe(me,all()); result.add(me); return result ; } public List<Kind> getAncestorsLocationsByMe(Kind me,List<Kind> all) { return all .stream() .filter(kind ->isMatchByKey( kind.getId() ,me.getAncestors())) .collect(Collectors.toList()); } }
UTF-8
Java
6,759
java
KindManager.java
Java
[]
null
[]
package cn.tico.iot.configmanger.module.mao.redis; import cn.tico.iot.configmanger.module.iot.models.base.Kind; import cn.tico.iot.configmanger.module.iot.models.base.Location; import cn.tico.iot.configmanger.module.iot.services.KindService; import cn.tico.iot.configmanger.module.iot.services.LocationService; import cn.tico.iot.configmanger.module.mao.common.BaseManager; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.nutz.ioc.aop.Aop; import org.nutz.ioc.impl.PropertiesProxy; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.json.Json; import org.nutz.lang.Lang; import org.nutz.lang.Strings; import org.nutz.lang.util.NutMap; import org.nutz.log.Logs; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import static org.nutz.integration.jedis.RedisInterceptor.jedis; @IocBean(create = "init") public class KindManager extends BaseManager { @Inject PropertiesProxy conf; @Inject KindService kindService; String KEY_PATH ; static final String REG_STAT = ".*("; static final String REG_END = ").*"; static final String SPLIT =":"; @Aop("redis") public void init(){ // Logs.get().debugf("location redis path : %s ",KEY_PATH); // // KEY_PATH = conf.get("redis.pre.key.kind"); // // Set<String> keys= jedis().keys(KEY_PATH+"*"); // Logs.get().debugf("keys",keys); // keys.stream().forEach(key->jedis().del(key)); // // List <Kind> all = kindService.findAllKinds(); // List<Kind> copy = Lists.newArrayList(all); // all = all.stream() // .map(kind -> findAncestors(kind,copy)) // .map(kind -> fatherName(kind)) // .collect(Collectors.toList()); // all = children(all); // // all.forEach(location -> jedis().set(KEY_PATH+location.getId(),Json.toJson(location))); } /** * ่กฅๅฎŒๆ‰€ๆœ‰็š„็ฅ–่Š‚็‚น * @param me * @param all * @return */ public Kind findAncestors(Kind me ,List<Kind> all) { List<Kind> list = getAncestorsLocationsByMe(me,all); Map<String,Kind> parents = list .stream() .collect(Collectors.toMap( kind-> kind.getLevel(), kind->kind) ); me.setParents(parents); return me; } /** * ่กฅๅฎŒๆ‰€ๆœ‰็š„ๅญ่Š‚็‚น * @param all * @return */ public List<Kind> children(List<Kind> all){ Map<String,Kind > map = all.stream().collect(Collectors.toMap(kind->kind.getId(),kind->kind)); List<Kind> result = all.stream().map(kind ->{ String id = kind.getParentId(); if(Strings.isBlank(id)||Strings.equals("0",id)){ return kind; } Kind father = map.get(id); if(Lang.isEmpty(father.getChildren())){ father.setChildren(Lists.newArrayList()); } father.getChildren().add(kind); return kind; }).collect(Collectors.toList()); return result; } /** * ็”Ÿๆˆๆ ‘็š„ๆ นๆ•ฐๆฎ * @param id * @param all * @return */ public Kind zip(String id ,List<Kind> all){ List<Kind> root = children (all); return root.stream() .filter(location -> Strings.equals(id,location.getId())) .findFirst() .get(); } /** * ็”Ÿๆˆๅ•็‹ฌๆ•ฐๆฎ * @param id * @return */ @Aop("redis") public Kind get(String id){ String json = jedis().get(KEY_PATH+id); if(Strings.isBlank(json)){ return null; } return Json.fromJson(Kind.class,json); } /** * ๆŸฅๅฏปๆ‰€ๆœ‰ๅทฒ็Ÿฅ็š„KEY * @return */ @Aop("redis") public Set<String> keys(){ Set<String> set = jedis().keys(KEY_PATH+"*"); if(Lang.isEmpty(set)){ return Sets.newHashSet(); } return set.stream().map(key-> Strings.replaceBy(key, NutMap.NEW().addv(KEY_PATH,""))).collect(Collectors.toSet()); } public Kind byName(String longSplitName,List<Kind> all){ String[] array =Strings.splitIgnoreBlank(longSplitName,SPLIT); List<String> names = Lang.array2list(array); String last = Lists.newLinkedList(names).getLast(); List<Kind> ones = all.stream() .filter(one-> isMatchByKey(last, one.getCnName())) .filter(one ->{ String langName = Strings.sBlank(one.getParentName(),"")+SPLIT+one.getCnName(); boolean b = names.stream().allMatch(name -> isMatchByKey(name, langName)); return b; }).collect(Collectors.toList()); if(Lang.isEmpty(ones)){ return null; } if(ones.size()!=1){ return null; } return ones.get(0); //return ones.get(0); } public static boolean isMatchByKey(String last, String cnName) { return Strings.isMatch(Pattern.compile(REG_STAT + last + REG_END), cnName); } /** * ๆ‰€ๆœ‰็š„ๅœฐ็†ไฝๅˆถ * @return */ public List<Kind> all() { Set<String> keys = keys(); return keys.stream().map(key-> get(key)).collect(Collectors.toList()); } /** * ้ ็ˆถ็›ฎๅฝ•ๆ•ฐๆฎ่กฅๅฎŒ * fatherName * ๅญ—ๆฎต * @param kind */ public Kind fatherName(Kind kind) { Map<String,Object> map = kind.getParents(); if(Lang.isEmpty(map)){ return kind; } List<String> list = map.values() .stream() .map(value->Lang.obj2nutmap(value).getString("cnName")) .collect(Collectors.toList()); String fatherName = Strings.join(SPLIT,list); kind.setParentName(fatherName); return kind; } /** * ่ทŸๆฎ LOCATION ๅพ—ๅˆฐๆ‰€ๆœ‰็š„ Location ็ˆถๆ•ฐๆฎ * @param kindId * @return */ public List<Kind> allFamilyWithMe(String kindId) { Kind me = get(kindId); List<Kind> result = getAncestorsLocationsByMe(me,all()); result.add(me); return result ; } public List<Kind> getAncestorsLocationsByMe(Kind me,List<Kind> all) { return all .stream() .filter(kind ->isMatchByKey( kind.getId() ,me.getAncestors())) .collect(Collectors.toList()); } }
6,759
0.557365
0.55646
235
27.225533
23.842663
122
false
false
0
0
0
0
0
0
0.489362
false
false
3
46186f6e52700780461f7b3d8bb67152b648b2bd
8,581,344,687,261
d439307f1a01064cef6713347ff05e2b47f2e13e
/RAD75BLACK/DirectTalent_DataAccess/src/com/manpower/portal/mpnet/dao/interfaces/RecruiterCommentsDAO.java
27c074c15ae6a51a2cb81883a752802b7b967a0d
[]
no_license
ermakovmaxim/WorkSpaces
https://github.com/ermakovmaxim/WorkSpaces
d7cf417543521b6a7ca66f9305fbb2127072327c
3b2c8c8dde34d9e1203f0796795dbafc4b17eaae
refs/heads/master
2020-03-09T10:26:44.089000
2013-04-29T18:03:10
2013-04-29T18:03:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Created on Jul 9, 2007 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.manpower.portal.mpnet.dao.interfaces; import java.util.List; import com.manpower.portal.mpnet.hbn.beans.AdvertisementContact; /** * @author mstoffel * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Style - Code Templates */ public interface RecruiterCommentsDAO extends DAO { public List findAllCommentsByRecruiter(AdvertisementContact adContact); }
UTF-8
Java
588
java
RecruiterCommentsDAO.java
Java
[ { "context": "et.hbn.beans.AdvertisementContact;\n\n/**\n * @author mstoffel\n * \n * TODO To change the template for this gener", "end": 322, "score": 0.9995083808898926, "start": 314, "tag": "USERNAME", "value": "mstoffel" } ]
null
[]
/* * Created on Jul 9, 2007 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.manpower.portal.mpnet.dao.interfaces; import java.util.List; import com.manpower.portal.mpnet.hbn.beans.AdvertisementContact; /** * @author mstoffel * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Style - Code Templates */ public interface RecruiterCommentsDAO extends DAO { public List findAllCommentsByRecruiter(AdvertisementContact adContact); }
588
0.755102
0.746599
21
27
27.79003
77
false
false
0
0
0
0
0
0
0.285714
false
false
3
ff8e3f40fbcdf2ed9989e92b71f45b6d381efaa6
9,603,546,906,937
ac5b9523455735ca8c12f2ab03735329aab67887
/android/org/godotengine/godot/GpgsModule.java
57ffc14eae784ce4f24f7a24e40a5b8549ae60e4
[ "MIT" ]
permissive
bluwork/godot_android_gpgs
https://github.com/bluwork/godot_android_gpgs
6743a12492bc4246a8ef8edd110696628ea641d1
b5254268c5b6ad7dff2ff236a49d083a30320974
refs/heads/master
2020-04-13T18:39:04.676000
2020-01-20T00:20:35
2020-01-20T00:20:35
163,380,994
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.godotengine.godot; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import androidx.annotation.NonNull; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.games.AchievementsClient; import com.google.android.gms.games.Games; import com.google.android.gms.games.GamesActivityResultCodes; import com.google.android.gms.games.LeaderboardsClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import javax.microedition.khronos.opengles.GL10; public class GpgsModule extends Godot.SingletonBase { private static final String TAG = "PlayServices"; private static final int RC_SIGN_IN = 9001; private static final int RC_ACHIEVEMENT_UI = 9002; private static final int RC_LEADERBOARD_UI = 9003; protected Activity appActivity; protected Context appContext; private Godot activity = null; private int instanceId = 0; private LeaderboardsClient leaderboardsClient; private AchievementsClient achievementsClient; public GpgsModule(Activity pActivity) { registerClass("PlayServices", new String[]{ "init", "isSignedIn", "signIn", "signOut", "showAchievements", "unlockAchievement", "incrementAchievement", "showLeaderboard", "submitScore", }); this.appActivity = pActivity; this.appContext = appActivity.getApplicationContext(); this.activity = (Godot) pActivity; } static public Godot.SingletonBase initialize(Activity activity) { return new GpgsModule(activity); } public void init(final int pInstanceId) { instanceId = pInstanceId; //Log.d(TAG, String.format("Instance id: %s", instanceId)); signInSilently(); } private void signIn() { startSignInIntent(); } private void signOut() { saveLoginState(false); GoogleSignInClient signInClient = GoogleSignIn.getClient(appContext, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN); signInClient.signOut().addOnCompleteListener(appActivity, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { onDisconnected(); } }); } private void showAchievements() { if (achievementsClient != null) { achievementsClient.getAchievementsIntent() .addOnSuccessListener(new OnSuccessListener<Intent>() { @Override public void onSuccess(Intent intent) { appActivity.startActivityForResult(intent, RC_ACHIEVEMENT_UI); } }); } else { startSignInIntent(); } } private void unlockAchievement(String achievementId) { if (achievementsClient != null) { achievementsClient.unlock(achievementId); } else { startSignInIntent(); } } private void incrementAchievement(String achievementId, int increment_step) { if (achievementsClient != null) { achievementsClient.increment(achievementId, increment_step); } else { startSignInIntent(); } } private void showLeaderboard(String leaderboardId) { if (leaderboardsClient != null) { leaderboardsClient.getLeaderboardIntent(leaderboardId) .addOnSuccessListener(new OnSuccessListener<Intent>() { @Override public void onSuccess(Intent intent) { activity.startActivityForResult(intent, RC_LEADERBOARD_UI); } }); } else { startSignInIntent(); } } private void submitScore(String leaderboardId, int score) { if (leaderboardsClient != null) { leaderboardsClient.submitScore(leaderboardId, score); } else { startSignInIntent(); } } private void signInSilently() { GoogleSignInOptions signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN; GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(appContext); if (GoogleSignIn.hasPermissions(account, signInOptions.getScopeArray())) { // Already signed in. // The signed in account is stored in the 'account' variable. onConnected(account); //Log.d(TAG, "Signed in."); } else { // Haven't been signed-in before. Try the silent sign-in first. GoogleSignInClient signInClient = GoogleSignIn.getClient(appActivity, signInOptions); signInClient .silentSignIn() .addOnCompleteListener( appActivity, new OnCompleteListener<GoogleSignInAccount>() { @Override public void onComplete(@NonNull Task<GoogleSignInAccount> task) { if (task.isSuccessful()) { // The signed in account is stored in the task's result. onConnected(task.getResult()); } else { //Log.d(TAG, "Not Signed in."); } } }) .addOnFailureListener(appActivity, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { //Log.d(TAG, "Sign in failure. E: " + e.toString()); } }); } } private void startSignInIntent() { saveLoginState(true); GoogleSignInClient signInClient = GoogleSignIn.getClient(appActivity, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN); Intent intent = signInClient.getSignInIntent(); appActivity.startActivityForResult(intent, RC_SIGN_IN); } private boolean isSignedIn() { return GoogleSignIn.getLastSignedInAccount(appContext) != null; } private void onConnected(GoogleSignInAccount account) { //Log.d(TAG, "Client connected."); achievementsClient = Games.getAchievementsClient(appContext, account); leaderboardsClient = Games.getLeaderboardsClient(appContext, account); propagate("connected", "yes"); } private void onDisconnected() { //Log.d(TAG, "Client disconnected."); achievementsClient = null; leaderboardsClient = null; propagate("connected", "no"); } private void saveLoginState(boolean allowed) { appActivity.getSharedPreferences("gpgs", Context.MODE_PRIVATE) .edit().putBoolean("silent_login", allowed).apply(); } private boolean canLogin() { return appActivity.getSharedPreferences("gpgs", Context.MODE_PRIVATE).getBoolean("silent_login", true); } // Forwarded callbacks you can reimplement, as SDKs often need them. protected void onMainActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) { // The signed in account is stored in the result. onConnected(result.getSignInAccount()); //Log.d(TAG, "Signed after explicit call."); } else { //Log.d(TAG, "Not signed in after explicit call."); } } if (requestCode == RC_ACHIEVEMENT_UI || requestCode == RC_LEADERBOARD_UI) { if (resultCode == GamesActivityResultCodes.RESULT_RECONNECT_REQUIRED) { //Log.d(TAG, "User explicitly logged out from GPGS. Saving decision..."); saveLoginState(false); onDisconnected(); } } } protected void onMainRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { } protected void onMainPause() { } protected void onMainResume() { //Log.d(TAG, "On main resume."); if (canLogin()) { signInSilently(); } } protected void onMainDestroy() { } protected void onGLDrawFrame(GL10 gl) { } protected void onGLSurfaceChanged(GL10 gl, int width, int height) { } // Singletons will always miss first 'onGLSurfaceChanged' call. public void propagate(String from, String what) { GodotLib.calldeferred(instanceId, "_from_services", new Object[]{from, what}); //Log.d(TAG, "Back to Godot - instance_id: " + instanceId + " from: " + from + ": " + what + "."); } }
UTF-8
Java
9,616
java
GpgsModule.java
Java
[]
null
[]
package org.godotengine.godot; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import androidx.annotation.NonNull; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.games.AchievementsClient; import com.google.android.gms.games.Games; import com.google.android.gms.games.GamesActivityResultCodes; import com.google.android.gms.games.LeaderboardsClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import javax.microedition.khronos.opengles.GL10; public class GpgsModule extends Godot.SingletonBase { private static final String TAG = "PlayServices"; private static final int RC_SIGN_IN = 9001; private static final int RC_ACHIEVEMENT_UI = 9002; private static final int RC_LEADERBOARD_UI = 9003; protected Activity appActivity; protected Context appContext; private Godot activity = null; private int instanceId = 0; private LeaderboardsClient leaderboardsClient; private AchievementsClient achievementsClient; public GpgsModule(Activity pActivity) { registerClass("PlayServices", new String[]{ "init", "isSignedIn", "signIn", "signOut", "showAchievements", "unlockAchievement", "incrementAchievement", "showLeaderboard", "submitScore", }); this.appActivity = pActivity; this.appContext = appActivity.getApplicationContext(); this.activity = (Godot) pActivity; } static public Godot.SingletonBase initialize(Activity activity) { return new GpgsModule(activity); } public void init(final int pInstanceId) { instanceId = pInstanceId; //Log.d(TAG, String.format("Instance id: %s", instanceId)); signInSilently(); } private void signIn() { startSignInIntent(); } private void signOut() { saveLoginState(false); GoogleSignInClient signInClient = GoogleSignIn.getClient(appContext, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN); signInClient.signOut().addOnCompleteListener(appActivity, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { onDisconnected(); } }); } private void showAchievements() { if (achievementsClient != null) { achievementsClient.getAchievementsIntent() .addOnSuccessListener(new OnSuccessListener<Intent>() { @Override public void onSuccess(Intent intent) { appActivity.startActivityForResult(intent, RC_ACHIEVEMENT_UI); } }); } else { startSignInIntent(); } } private void unlockAchievement(String achievementId) { if (achievementsClient != null) { achievementsClient.unlock(achievementId); } else { startSignInIntent(); } } private void incrementAchievement(String achievementId, int increment_step) { if (achievementsClient != null) { achievementsClient.increment(achievementId, increment_step); } else { startSignInIntent(); } } private void showLeaderboard(String leaderboardId) { if (leaderboardsClient != null) { leaderboardsClient.getLeaderboardIntent(leaderboardId) .addOnSuccessListener(new OnSuccessListener<Intent>() { @Override public void onSuccess(Intent intent) { activity.startActivityForResult(intent, RC_LEADERBOARD_UI); } }); } else { startSignInIntent(); } } private void submitScore(String leaderboardId, int score) { if (leaderboardsClient != null) { leaderboardsClient.submitScore(leaderboardId, score); } else { startSignInIntent(); } } private void signInSilently() { GoogleSignInOptions signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN; GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(appContext); if (GoogleSignIn.hasPermissions(account, signInOptions.getScopeArray())) { // Already signed in. // The signed in account is stored in the 'account' variable. onConnected(account); //Log.d(TAG, "Signed in."); } else { // Haven't been signed-in before. Try the silent sign-in first. GoogleSignInClient signInClient = GoogleSignIn.getClient(appActivity, signInOptions); signInClient .silentSignIn() .addOnCompleteListener( appActivity, new OnCompleteListener<GoogleSignInAccount>() { @Override public void onComplete(@NonNull Task<GoogleSignInAccount> task) { if (task.isSuccessful()) { // The signed in account is stored in the task's result. onConnected(task.getResult()); } else { //Log.d(TAG, "Not Signed in."); } } }) .addOnFailureListener(appActivity, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { //Log.d(TAG, "Sign in failure. E: " + e.toString()); } }); } } private void startSignInIntent() { saveLoginState(true); GoogleSignInClient signInClient = GoogleSignIn.getClient(appActivity, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN); Intent intent = signInClient.getSignInIntent(); appActivity.startActivityForResult(intent, RC_SIGN_IN); } private boolean isSignedIn() { return GoogleSignIn.getLastSignedInAccount(appContext) != null; } private void onConnected(GoogleSignInAccount account) { //Log.d(TAG, "Client connected."); achievementsClient = Games.getAchievementsClient(appContext, account); leaderboardsClient = Games.getLeaderboardsClient(appContext, account); propagate("connected", "yes"); } private void onDisconnected() { //Log.d(TAG, "Client disconnected."); achievementsClient = null; leaderboardsClient = null; propagate("connected", "no"); } private void saveLoginState(boolean allowed) { appActivity.getSharedPreferences("gpgs", Context.MODE_PRIVATE) .edit().putBoolean("silent_login", allowed).apply(); } private boolean canLogin() { return appActivity.getSharedPreferences("gpgs", Context.MODE_PRIVATE).getBoolean("silent_login", true); } // Forwarded callbacks you can reimplement, as SDKs often need them. protected void onMainActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) { // The signed in account is stored in the result. onConnected(result.getSignInAccount()); //Log.d(TAG, "Signed after explicit call."); } else { //Log.d(TAG, "Not signed in after explicit call."); } } if (requestCode == RC_ACHIEVEMENT_UI || requestCode == RC_LEADERBOARD_UI) { if (resultCode == GamesActivityResultCodes.RESULT_RECONNECT_REQUIRED) { //Log.d(TAG, "User explicitly logged out from GPGS. Saving decision..."); saveLoginState(false); onDisconnected(); } } } protected void onMainRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { } protected void onMainPause() { } protected void onMainResume() { //Log.d(TAG, "On main resume."); if (canLogin()) { signInSilently(); } } protected void onMainDestroy() { } protected void onGLDrawFrame(GL10 gl) { } protected void onGLSurfaceChanged(GL10 gl, int width, int height) { } // Singletons will always miss first 'onGLSurfaceChanged' call. public void propagate(String from, String what) { GodotLib.calldeferred(instanceId, "_from_services", new Object[]{from, what}); //Log.d(TAG, "Back to Godot - instance_id: " + instanceId + " from: " + from + ": " + what + "."); } }
9,616
0.59765
0.595674
280
33.342857
28.783247
111
false
false
0
0
0
0
0
0
0.528571
false
false
3
df4d0134dfb9d8b5ba09818277cf830cea068150
20,401,094,688,750
4b02716fe4b91399d2bfda4dda3becc31a9d793a
/huigou-uasp/src/main/java/com/huigou/uasp/exception/VerifyCodeException.java
9b0d823108f14784ef9ad9665976efb3fe9c7e71
[]
no_license
wuyounan/drawio
https://github.com/wuyounan/drawio
19867894fef13596be31f4f5db4296030f2a19b6
d0d1a0836e6b3602c27a53846a472a0adbe15e93
refs/heads/develop
2022-12-22T05:12:08.062000
2020-02-06T07:28:12
2020-02-06T07:28:12
241,046,824
0
2
null
false
2022-12-16T12:13:57
2020-02-17T07:38:48
2020-02-17T07:39:31
2022-12-16T12:13:54
26,419
0
2
34
JavaScript
false
false
package com.huigou.uasp.exception; import com.huigou.context.MessageSourceContext; /** * ้ชŒ่ฏ็ ่พ“ๅ…ฅ้”™่ฏฏ * * @author xx */ public class VerifyCodeException extends RuntimeException { private static final long serialVersionUID = 1L; public VerifyCodeException() { super(MessageSourceContext.getMessageAsDefault("common.verifyCode.exception")); } public VerifyCodeException(String message) { super(message); } public VerifyCodeException(String message, Throwable throwable) { super(message, throwable); } public VerifyCodeException(Throwable throwable) { super(throwable); } }
UTF-8
Java
661
java
VerifyCodeException.java
Java
[ { "context": "ssageSourceContext;\n\n/**\n * ้ชŒ่ฏ็ ่พ“ๅ…ฅ้”™่ฏฏ\n * \n * @author xx\n */\npublic class VerifyCodeException extends Runt", "end": 117, "score": 0.9825093746185303, "start": 115, "tag": "USERNAME", "value": "xx" } ]
null
[]
package com.huigou.uasp.exception; import com.huigou.context.MessageSourceContext; /** * ้ชŒ่ฏ็ ่พ“ๅ…ฅ้”™่ฏฏ * * @author xx */ public class VerifyCodeException extends RuntimeException { private static final long serialVersionUID = 1L; public VerifyCodeException() { super(MessageSourceContext.getMessageAsDefault("common.verifyCode.exception")); } public VerifyCodeException(String message) { super(message); } public VerifyCodeException(String message, Throwable throwable) { super(message, throwable); } public VerifyCodeException(Throwable throwable) { super(throwable); } }
661
0.706337
0.704791
29
21.310345
24.69553
87
false
false
0
0
0
0
0
0
0.310345
false
false
3
62bba3531a14c81d5983172fa016490e30cf4917
9,294,309,263,195
1692c23ee224b6a670510ac78884c63ab9fc6bf7
/playlist-service/src/main/java/com/example/playlistservice/services/PlaylistServiceImpl.java
4cfc31998bd849c4c86e25a1e1eec8cf76b012f0
[]
no_license
sofsin96/MusicAPI
https://github.com/sofsin96/MusicAPI
02c150db01f632aec940d860f1ec3faaa329c509
9a407d4172f59b9198ea19059eb256d9cf0af047
refs/heads/master
2023-03-13T07:33:58.228000
2021-03-09T08:09:42
2021-03-09T08:09:42
345,667,145
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.playlistservice.services; import com.example.playlistservice.dtos.PlaylistDto; import com.example.playlistservice.mappers.PlaylistMapper; import com.example.playlistservice.models.Playlist; import com.example.playlistservice.repositories.PlaylistRepository; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import java.util.List; import java.util.Optional; @Service public class PlaylistServiceImpl implements PlaylistService{ private final PlaylistMapper playlistMapper; private final PlaylistRepository playlistRepository; public PlaylistServiceImpl(PlaylistMapper playlistMapper, PlaylistRepository playlistRepository) { this.playlistMapper = playlistMapper; this.playlistRepository = playlistRepository; } @Override public List<PlaylistDto> getAllPlaylists() { return playlistMapper.mapp(playlistRepository.findAll()); } @Override public Optional<PlaylistDto> getOne(Long id) { return playlistMapper.mapp(playlistRepository.findById(id)); } @Override public PlaylistDto createPlaylist(PlaylistDto playlistDto) { if (playlistDto.getName().isEmpty()) throw new RuntimeException(); return playlistMapper.mapp(playlistRepository.save(playlistMapper.mapp(playlistDto))); } @Override public void delete(Long id) { playlistRepository.deleteById(id); } @Override public PlaylistDto replace(Long id, PlaylistDto playlistDto) { Optional<Playlist> playlist = playlistRepository.findById(id); if(playlist.isPresent()) { Playlist updatedPlaylist = playlist.get(); updatedPlaylist.setName(playlistDto.getName()); return playlistMapper.mapp(playlistRepository.save(updatedPlaylist)); } else throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Id " + id + " not found."); } @Override public PlaylistDto update(Long id, PlaylistDto playlistDto) { Optional<Playlist> playlist = playlistRepository.findById(id); if(playlist.isPresent()) { Playlist updatedPlaylist = playlist.get(); if(playlistDto.getName() != null) updatedPlaylist.setName(playlistDto.getName()); return playlistMapper.mapp(playlistRepository.save(updatedPlaylist)); } else throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Id " + id + " not found."); } @Override public List<PlaylistDto> search(String name) { return playlistMapper.mapp(playlistRepository.findAllByName(name)); } }
UTF-8
Java
2,745
java
PlaylistServiceImpl.java
Java
[]
null
[]
package com.example.playlistservice.services; import com.example.playlistservice.dtos.PlaylistDto; import com.example.playlistservice.mappers.PlaylistMapper; import com.example.playlistservice.models.Playlist; import com.example.playlistservice.repositories.PlaylistRepository; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import java.util.List; import java.util.Optional; @Service public class PlaylistServiceImpl implements PlaylistService{ private final PlaylistMapper playlistMapper; private final PlaylistRepository playlistRepository; public PlaylistServiceImpl(PlaylistMapper playlistMapper, PlaylistRepository playlistRepository) { this.playlistMapper = playlistMapper; this.playlistRepository = playlistRepository; } @Override public List<PlaylistDto> getAllPlaylists() { return playlistMapper.mapp(playlistRepository.findAll()); } @Override public Optional<PlaylistDto> getOne(Long id) { return playlistMapper.mapp(playlistRepository.findById(id)); } @Override public PlaylistDto createPlaylist(PlaylistDto playlistDto) { if (playlistDto.getName().isEmpty()) throw new RuntimeException(); return playlistMapper.mapp(playlistRepository.save(playlistMapper.mapp(playlistDto))); } @Override public void delete(Long id) { playlistRepository.deleteById(id); } @Override public PlaylistDto replace(Long id, PlaylistDto playlistDto) { Optional<Playlist> playlist = playlistRepository.findById(id); if(playlist.isPresent()) { Playlist updatedPlaylist = playlist.get(); updatedPlaylist.setName(playlistDto.getName()); return playlistMapper.mapp(playlistRepository.save(updatedPlaylist)); } else throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Id " + id + " not found."); } @Override public PlaylistDto update(Long id, PlaylistDto playlistDto) { Optional<Playlist> playlist = playlistRepository.findById(id); if(playlist.isPresent()) { Playlist updatedPlaylist = playlist.get(); if(playlistDto.getName() != null) updatedPlaylist.setName(playlistDto.getName()); return playlistMapper.mapp(playlistRepository.save(updatedPlaylist)); } else throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Id " + id + " not found."); } @Override public List<PlaylistDto> search(String name) { return playlistMapper.mapp(playlistRepository.findAllByName(name)); } }
2,745
0.712568
0.712568
78
34.192307
29.487093
102
false
false
0
0
0
0
0
0
0.448718
false
false
3
4e00f3f74c76063a642e09649e490729f4d4bcd9
6,803,228,231,432
46ab66a06534c752c146e90fa5aea10ba5e55838
/src/main/java/com/lawsystem/lawserver/model/content/RemoveMemberContent.java
f048f02075df06f786f610c997d4ae779ea9afa8
[]
no_license
democrasim/server
https://github.com/democrasim/server
46b5b207512e5d3b2152642261b055f1c789100d
30668ab01800322adbb236c28c6cd79f56c151c3
refs/heads/master
2023-07-11T08:31:43.674000
2021-08-11T12:07:32
2021-08-11T12:07:32
359,477,690
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lawsystem.lawserver.model.content; import com.lawsystem.lawserver.model.Member; import lombok.Data; @Data public class RemoveMemberContent extends DescribedContent{ private Member member; }
UTF-8
Java
208
java
RemoveMemberContent.java
Java
[]
null
[]
package com.lawsystem.lawserver.model.content; import com.lawsystem.lawserver.model.Member; import lombok.Data; @Data public class RemoveMemberContent extends DescribedContent{ private Member member; }
208
0.817308
0.817308
9
22.111111
21.288727
58
false
false
0
0
0
0
0
0
0.444444
false
false
3
8ed2c99b5c840cf1df9eb12a4f7e93d1a5c7ef28
5,875,515,324,126
9c9646b36b69afa215e290a7678b7f43c5c93a5b
/src/main/java/com/iutiao/exception/APIException.java
981611028c1e79b6c2c0d4d8a972b7416dd6ad2e
[]
no_license
yxy/iutiao
https://github.com/yxy/iutiao
f0fbb58f2c30899e2895ba431c181976a51d6acd
261b0367c1b103f53d90463d04daf964aff38ce4
refs/heads/master
2020-03-03T22:37:24.761000
2016-06-01T08:46:16
2016-06-01T08:46:16
44,441,494
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.iutiao.exception; /** * Created by yxy on 15/10/13. */ public class APIException extends UTiaoException { private static final long serialVersionUID = 1L; public APIException(String message, String requestId, Integer statusCode, Throwable e) { super(message, requestId, statusCode, e); this.setCode(statusCode); } }
UTF-8
Java
362
java
APIException.java
Java
[ { "context": "package com.iutiao.exception;\n\n/**\n * Created by yxy on 15/10/13.\n */\npublic class APIException extend", "end": 52, "score": 0.9994810819625854, "start": 49, "tag": "USERNAME", "value": "yxy" } ]
null
[]
package com.iutiao.exception; /** * Created by yxy on 15/10/13. */ public class APIException extends UTiaoException { private static final long serialVersionUID = 1L; public APIException(String message, String requestId, Integer statusCode, Throwable e) { super(message, requestId, statusCode, e); this.setCode(statusCode); } }
362
0.70442
0.685083
15
23.133333
26.976204
92
false
false
0
0
0
0
0
0
0.666667
false
false
3
511abe5e5d949d3aba2c9ac1670d5ebc9c357a4b
7,954,279,501,037
e36d8d06eeca75633419743accda20c31c94fc4d
/src/main/java/methods/LogoutMethod.java
c2d47174172c80c11a3dd3e5274103cfdfa4a8e7
[]
no_license
Kuzma2103/guru99demoQA
https://github.com/Kuzma2103/guru99demoQA
dbcbc4ff57e678792402b14773e7a0f0aed36717
b3a966cc9feeb2ea696fa65961114b01fdd8d87a
refs/heads/main
2023-06-23T03:45:45.841000
2021-07-13T08:23:49
2021-07-13T08:23:49
379,525,344
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package methods; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import pages.BasePage; public class LogoutMethod extends BasePage { public LogoutMethod(WebDriver driver) { super(driver); } By accountBy = By.xpath("//div[@class='account-cart-wrapper']/a[@data-target-element='#header-account']"); By logoutBy = By.xpath("//a[@title='Log Out']"); public LogoutMethod logout() { click(accountBy); click(logoutBy); return this; } }
UTF-8
Java
512
java
LogoutMethod.java
Java
[]
null
[]
package methods; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import pages.BasePage; public class LogoutMethod extends BasePage { public LogoutMethod(WebDriver driver) { super(driver); } By accountBy = By.xpath("//div[@class='account-cart-wrapper']/a[@data-target-element='#header-account']"); By logoutBy = By.xpath("//a[@title='Log Out']"); public LogoutMethod logout() { click(accountBy); click(logoutBy); return this; } }
512
0.658203
0.658203
22
22.272728
25.204945
110
false
false
0
0
0
0
0
0
0.454545
false
false
3
7918466b6bc74e6784613d0d771c809d46a300e1
30,176,440,226,627
473b76b1043df2f09214f8c335d4359d3a8151e0
/benchmark/bigclonebenchdata_partial/10567003.java
fc0f105b58dbbc664f87be867421ed630b081035
[]
no_license
whatafree/JCoffee
https://github.com/whatafree/JCoffee
08dc47f79f8369af32e755de01c52d9a8479d44c
fa7194635a5bd48259d325e5b0a190780a53c55f
refs/heads/master
2022-11-16T01:58:04.254000
2020-07-13T20:11:17
2020-07-13T20:11:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class c10567003 { private InputStream loadSource(String url) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(HTTP.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)"); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); return entity.getContent(); } }
UTF-8
Java
489
java
10567003.java
Java
[]
null
[]
class c10567003 { private InputStream loadSource(String url) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(HTTP.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)"); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); return entity.getContent(); } }
489
0.691207
0.662577
12
39.5
36.197376
116
false
false
0
0
0
0
0
0
0.833333
false
false
3
848382e31759f192d2ed0e3d5b2cca54c5c42f4e
27,857,157,950,461
6f0ae943dd696aadf309418661f0083ffb9438b3
/src/main/java/com/milind/sample/oauth/config/CustomUserDetails.java
965b215f73cf37d38eaf4a3f515e74b485fa89ba
[]
no_license
milindbharambe/samples
https://github.com/milindbharambe/samples
e2b3b559526fa3255a57c06517bc85e4d0f7a2a1
f49eaabe70d6631283dafb804fde354a75345224
refs/heads/master
2020-08-16T17:35:28.533000
2019-10-16T11:33:49
2019-10-16T11:33:49
215,533,000
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.milind.sample.oauth.config; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import com.milind.sample.oauth.domain.User; public class CustomUserDetails implements UserDetails { /** * */ private static final long serialVersionUID = 1L; private String username; private String password; private Collection<? extends GrantedAuthority> authorities; public CustomUserDetails(User user) { this.username = user.getUsername(); // encode password: Mandatory now PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); this.password = encoder.encode(user.getPassword()); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); user.getRoles().forEach(role -> authorities.add(new SimpleGrantedAuthority(role))); this.authorities = authorities; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
UTF-8
Java
1,953
java
CustomUserDetails.java
Java
[ { "context": "\n public String getUsername() {\r\n return username;\r\n }\r\n\r\n @Override\r\n public boolean isAc", "end": 1585, "score": 0.9350152611732483, "start": 1577, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.milind.sample.oauth.config; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import com.milind.sample.oauth.domain.User; public class CustomUserDetails implements UserDetails { /** * */ private static final long serialVersionUID = 1L; private String username; private String password; private Collection<? extends GrantedAuthority> authorities; public CustomUserDetails(User user) { this.username = user.getUsername(); // encode password: Mandatory now PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); this.password = encoder.encode(user.getPassword()); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); user.getRoles().forEach(role -> authorities.add(new SimpleGrantedAuthority(role))); this.authorities = authorities; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
1,953
0.684076
0.683564
69
26.304348
25.292093
93
false
false
0
0
0
0
0
0
0.391304
false
false
3
40ab7366a0d31fe627c8833ab68000ea1745e295
29,892,972,442,562
ed32e54b8d82afb64664543f69a55de78fc362ea
/src/SumofLeftLeaves.java
b227a1556de911f4201f37154748e7d92c86ec9c
[]
no_license
Manaswi94/Algorithms-Trees
https://github.com/Manaswi94/Algorithms-Trees
1388b3222534cd248405430a27f698604e401388
280ce1ec7edc3ce83b9d2dc6048d308724d47e50
refs/heads/master
2017-12-30T19:55:10.375000
2016-11-11T08:47:38
2016-11-11T08:47:38
69,764,165
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// 404. Sum of Left Leaves public class SumofLeftLeaves { public static int sumOfLeftLeaves(TreeNode root) { int sumL = 0, sumR = 0; if (root == null) return 0; if (root.left != null) { if (root.left.right == null && root.left.left == null) sumL = root.left.val + sumOfLeftLeaves(root.left); else sumL = sumOfLeftLeaves(root.left); } if (root.right != null) sumR = sumOfLeftLeaves(root.right); return sumL + sumR; } public static void main(String[] args) { // TODO Auto-generated method stub TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); // root.left.left.left = new TreeNode(2); // root.left.left.right = new TreeNode(5); // root.right.left = new TreeNode(13); // root.right.right = new TreeNode(20); // root.right.left.left = new TreeNode(11); // root.right.left.right = new TreeNode(14); System.out.println(sumOfLeftLeaves(root)); } }
UTF-8
Java
1,019
java
SumofLeftLeaves.java
Java
[]
null
[]
// 404. Sum of Left Leaves public class SumofLeftLeaves { public static int sumOfLeftLeaves(TreeNode root) { int sumL = 0, sumR = 0; if (root == null) return 0; if (root.left != null) { if (root.left.right == null && root.left.left == null) sumL = root.left.val + sumOfLeftLeaves(root.left); else sumL = sumOfLeftLeaves(root.left); } if (root.right != null) sumR = sumOfLeftLeaves(root.right); return sumL + sumR; } public static void main(String[] args) { // TODO Auto-generated method stub TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); // root.left.left.left = new TreeNode(2); // root.left.left.right = new TreeNode(5); // root.right.left = new TreeNode(13); // root.right.right = new TreeNode(20); // root.right.left.left = new TreeNode(11); // root.right.left.right = new TreeNode(14); System.out.println(sumOfLeftLeaves(root)); } }
1,019
0.655545
0.634936
36
27.305555
17.468733
57
false
false
0
0
0
0
0
0
2.25
false
false
3
553fd7b79d957a27e1a086355e8a46b083bfd7d0
11,699,490,915,869
7a41c5051f8db434dee47fa7e65625a3ce841124
/src/main/java/com/aillkeen/tiraduvida/TiraDuvidaApplication.java
db19d0d70e23beff3eb91b8ae5c4048c17a39fd0
[]
no_license
Aillkeen/daca-backend
https://github.com/Aillkeen/daca-backend
b121361405ae4235a96e5e71ee4bee8f7bacf396
8200cf5f3536c94054a9f32419ceac47d4686761
refs/heads/master
2020-03-23T18:59:13.564000
2018-08-07T03:40:08
2018-08-07T03:40:08
141,946,595
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aillkeen.tiraduvida; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.password.PasswordEncoder; import com.aillkeen.tiraduvida.entity.Papel; import com.aillkeen.tiraduvida.entity.Usuario; import com.aillkeen.tiraduvida.repository.UsuarioRepository; @SpringBootApplication public class TiraDuvidaApplication { public static void main(String[] args) { SpringApplication.run(TiraDuvidaApplication.class, args); } @Bean CommandLineRunner init(UsuarioRepository userRepository, PasswordEncoder passwordEncoder) { return args -> { initUsers(userRepository, passwordEncoder); }; } private void initUsers(UsuarioRepository userRepository, PasswordEncoder passwordEncoder) { Usuario admin = new Usuario(); admin.setEmail("professor@tiraduvida.com"); admin.setPassword(passwordEncoder.encode("123456")); admin.setPapel(Papel.ROLE_PROFESSOR); Usuario find = userRepository.findByEmail("professor@tiraduvida.com"); if (find == null) { userRepository.save(admin); } } }
UTF-8
Java
1,322
java
TiraDuvidaApplication.java
Java
[ { "context": "o admin = new Usuario();\n\t admin.setEmail(\"professor@tiraduvida.com\");\n\t admin.setPassword(passwordEncoder.enc", "end": 1037, "score": 0.9999330639839172, "start": 1013, "tag": "EMAIL", "value": "professor@tiraduvida.com" }, { "context": " admin.setPassword(passwordEncoder.encode(\"123456\"));\t\n\t admin.setPapel(Papel.ROLE_PROFESSOR", "end": 1098, "score": 0.9989392757415771, "start": 1092, "tag": "PASSWORD", "value": "123456" }, { "context": " Usuario find = userRepository.findByEmail(\"professor@tiraduvida.com\");\n\t if (find == null) {\n\t user", "end": 1228, "score": 0.9999330639839172, "start": 1204, "tag": "EMAIL", "value": "professor@tiraduvida.com" } ]
null
[]
package com.aillkeen.tiraduvida; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.password.PasswordEncoder; import com.aillkeen.tiraduvida.entity.Papel; import com.aillkeen.tiraduvida.entity.Usuario; import com.aillkeen.tiraduvida.repository.UsuarioRepository; @SpringBootApplication public class TiraDuvidaApplication { public static void main(String[] args) { SpringApplication.run(TiraDuvidaApplication.class, args); } @Bean CommandLineRunner init(UsuarioRepository userRepository, PasswordEncoder passwordEncoder) { return args -> { initUsers(userRepository, passwordEncoder); }; } private void initUsers(UsuarioRepository userRepository, PasswordEncoder passwordEncoder) { Usuario admin = new Usuario(); admin.setEmail("<EMAIL>"); admin.setPassword(passwordEncoder.encode("<PASSWORD>")); admin.setPapel(Papel.ROLE_PROFESSOR); Usuario find = userRepository.findByEmail("<EMAIL>"); if (find == null) { userRepository.save(admin); } } }
1,292
0.747352
0.742814
39
32.897434
27.767159
93
false
false
0
0
0
0
0
0
1.230769
false
false
3
d07dc00d356cce54af958e1e48086f5f07ca88b6
21,079,699,544,865
8fc353fcca109517b84f890df1f9e1f8a90adc78
/src/main/java/com/surekam/modules/cms/web/CategoryRoleUserController.java
a49dc46625bfd44ae127b276c436af5abaf097d3
[]
no_license
yycGitHub/production-process
https://github.com/yycGitHub/production-process
6ecd5ac15087288763cd8d7abe83d706f8f8e6f5
58a8628ef2f53164571b42f2629d23fb4b881e12
refs/heads/master
2022-12-08T16:55:34.955000
2020-08-31T09:03:34
2020-08-31T09:03:36
291,583,078
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.surekam.modules.cms.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.surekam.common.config.Global; import com.surekam.common.persistence.Page; import com.surekam.common.utils.StringUtils; import com.surekam.common.web.BaseController; import com.surekam.modules.cms.entity.CategoryRoleUser; import com.surekam.modules.cms.service.CategoryRoleUserService; import com.surekam.modules.sys.entity.Role; import com.surekam.modules.sys.entity.User; import com.surekam.modules.sys.service.SystemService; /** * ๆ ็›ฎ็ฎก็†ๅ‘˜Controller * @author liuyi * @version 2018-01-29 */ @Controller @RequestMapping(value = "${adminPath}/cms/categoryRoleUser") public class CategoryRoleUserController extends BaseController { @Autowired private CategoryRoleUserService categoryRoleUserService; @Autowired private SystemService systemService; @ModelAttribute public CategoryRoleUser get(@RequestParam(required=false) String id) { if (StringUtils.isNotBlank(id)){ return categoryRoleUserService.get(id); }else{ return new CategoryRoleUser(); } } @RequiresPermissions("cms:category:edit") @RequestMapping(value = {"list", ""}) public String list(CategoryRoleUser categoryRoleUser, HttpServletRequest request, HttpServletResponse response, Model model) { Page<CategoryRoleUser> page = categoryRoleUserService.find(new Page<CategoryRoleUser>(request, response), categoryRoleUser); model.addAttribute("page", page); return "modules/" + "cms/categoryRoleUserList"; } @RequiresPermissions("cms:category:edit") @RequestMapping(value = "form") public String form(CategoryRoleUser categoryRoleUser, Model model) { model.addAttribute("categoryRoleUser", categoryRoleUser); return "modules/" + "cms/categoryRoleUserForm"; } @RequiresPermissions("cms:category:edit") @RequestMapping(value = "information") public String information(CategoryRoleUser categoryRoleUser, Model model) { model.addAttribute("categoryRoleUser", categoryRoleUser); return "modules/" + "cms/categoryRoleUserInformation"; } @RequiresPermissions("cms:category:edit") @RequestMapping(value = "save") public String save(CategoryRoleUser categoryRoleUser, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, categoryRoleUser)){ return form(categoryRoleUser, model); } categoryRoleUserService.save(categoryRoleUser); addMessage(redirectAttributes, "ไฟๅญ˜ๆ ็›ฎ็ฎก็†ๅ‘˜ๆˆๅŠŸ"); return "redirect:"+Global.getAdminPath()+"/cms/categoryRoleUser/?repage"; } @RequiresPermissions("cms:category:edit") @RequestMapping(value = "delete") public String delete(String id, RedirectAttributes redirectAttributes) { //categoryRoleUserService.delete(id); addMessage(redirectAttributes, "ๅˆ ้™คๆ ็›ฎ็ฎก็†ๅ‘˜ๆˆๅŠŸ"); return "redirect:"+Global.getAdminPath()+"/cms/categoryRoleUser/?repage"; } /** * ่ทณ่ฝฌๅˆฐๆทปๅŠ ๆ ็›ฎ็ฎก็†ๅ‘˜ * * */ @RequiresPermissions("cms:category:edit") @RequestMapping(value = "toPlateAdmin") public String toPlateAdmin(String id,User user, Model model,HttpServletRequest request, HttpServletResponse response) { CategoryRoleUser categoryRoleUser =new CategoryRoleUser(); //categoryRoleUser.setCategoryId(Integer.parseInt(id)); categoryRoleUser = categoryRoleUserService.findObjByCategoryId(Integer.parseInt(id)); //ๆ นๆฎcategoryIdๆŸฅ่ฏข,่Žทๅ–็”จๆˆทๅˆ—่กจ๏ผŒๅ…ถไธญ่ขซ่ฎพ็ฝฎไธบๆŸไธชๆ ็›ฎ็‰ˆไธป็š„็”จๆˆทๅฐ†ๆŽ’ๅˆ—ๅœจๆœ€ๅ‰้ข List<User> list = categoryRoleUserService.findListByCategoryId(Integer.parseInt(id),user); //User currentUser = UserUtils.getUser(); //Page<User> page = systemService.findUser(new Page<User>(request, response), new User()); //่ฎพ็ฝฎๅˆ†้กต Page<User> page = categoryRoleUserService.setPageList(new Page<User>(request, response),request,response,list); //if(categoryRoleUser==null){ //categoryRoleUser = new CategoryRoleUser(); //} //categoryRoleUser.setCategoryId(Integer.parseInt(id)); model.addAttribute("page", page); model.addAttribute("user", user); model.addAttribute("categoryId", id); model.addAttribute("categoryRoleUser", categoryRoleUser); //model.addAttribute("allRoles", systemService.findAllRole()); return "modules/cms/categoryUserForm"; } /** * ็ป‘ๅฎš่ง’่‰ฒ * * */ @RequiresPermissions("cms:category:edit") @RequestMapping(value = "addPlateAdminRole") public String addPlateAdminRole(CategoryRoleUser categoryRoleUser, User user, Model model,HttpServletRequest request, HttpServletResponse response) { CategoryRoleUser category =new CategoryRoleUser(); category = categoryRoleUserService.findObjByCategoryId(categoryRoleUser.getCategoryId()); List<Role> roleIdList = categoryRoleUser.getRoleList(); String roleStr=""; if(roleIdList!=null && roleIdList.size()>0){ for (Role role : roleIdList) { roleStr+=role.getId()+","; } roleStr = roleStr.substring(0, roleStr.length()-1); } //ๅฆ‚ๆžœ่ฟ˜ๆœช่ฎพ็ฝฎ็‰ˆไธป่ง’่‰ฒๅˆ™ไฟๅญ˜categoryRoleUser๏ผŒๅฆ‚ๆžœๅทฒ็ป่ฎพ็ฝฎไบ†็‰ˆไธป่ง’่‰ฒๅˆ™ๆ›ดๆ–ฐcategoryRoleUser if(category!=null){ categoryRoleUserService.updateRole(roleStr,category); }else{ categoryRoleUser.setRoleId(roleStr); categoryRoleUserService.save(categoryRoleUser); } //category = categoryRoleUserService.findObjByCategoryId(categoryRoleUser.getCategoryId()); //categoryRoleUser.setCategoryId(Integer.parseInt(id)); //ๆ นๆฎcategoryIdๆŸฅ่ฏข List<User> list = categoryRoleUserService.findListByCategoryId(categoryRoleUser.getCategoryId(),user); //่ฎพ็ฝฎๅˆ†้กต Page<User> page = categoryRoleUserService.setPageList(new Page<User>(request, response),request,response,list); model.addAttribute("page", page); model.addAttribute("user", user); model.addAttribute("categoryRoleUser", categoryRoleUser); //model.addAttribute("allRoles", systemService.findAllRole()); addMessage(model, "็ป‘ๅฎšๆˆๅŠŸ๏ผ"); return "modules/cms/categoryUserForm"; } /** * ๆŒ‡ๅฎš็‰ˆไธป * * */ @RequiresPermissions("cms:category:edit") @RequestMapping(value = "addPlateAdmin") public String addPlateAdmin(String userId,String exUserIds,String add,String categoryId,User user, Model model,HttpServletRequest request, HttpServletResponse response) { CategoryRoleUser category =new CategoryRoleUser(); category = categoryRoleUserService.findObjByCategoryId(Integer.parseInt(categoryId)); if(category.getCategoryId()==null){ category.setCategoryId(Integer.parseInt(categoryId)); categoryRoleUserService.save(category); //addMessage(model, "่ฏฅๆ ็›ฎ่ฟ˜ๆœช็ป‘ๅฎš็‰ˆไธป่ง’่‰ฒ๏ผŒ่ฏทๅ…ˆ็ป‘ๅฎš่ง’่‰ฒ๏ผ"); //return toPlateAdmin(categoryId, user, model, request, response); } String UserIds=""; //ๅขžๅŠ ็‰ˆไธป if("1".equals(add)){ if("".equals(exUserIds)){ UserIds = userId; }else{ UserIds = exUserIds+","+userId; } }else{//ๅˆ ้™ค็‰ˆไธป UserIds = (exUserIds+",").replace((userId+","), ""); if(UserIds.endsWith(",")){ UserIds = UserIds.substring(0, UserIds.length()-1); } if(UserIds.startsWith(",")){ UserIds = UserIds.substring(1, UserIds.length()); } } category.setUserId(UserIds); categoryRoleUserService.updatePlate(category); //categoryRoleUser.setCategoryId(Integer.parseInt(id)); //ๆ นๆฎcategoryIdๆŸฅ่ฏข List<User> list = categoryRoleUserService.findListByCategoryId(category.getCategoryId(),user); //่ฎพ็ฝฎๅˆ†้กต Page<User> page = categoryRoleUserService.setPageList(new Page<User>(request, response),request,response,list); model.addAttribute("page", page); model.addAttribute("user", user); model.addAttribute("categoryId", categoryId); model.addAttribute("categoryRoleUser", category); //model.addAttribute("allRoles", systemService.findAllRole()); if("1".equals(add)){ addMessage(model, "ๆทปๅŠ ็‰ˆไธปๆˆๅŠŸ๏ผ"); }else{ addMessage(model, "ๅ–ๆถˆ็‰ˆไธปๆˆๅŠŸ๏ผ"); } return "modules/cms/categoryUserForm"; } }
UTF-8
Java
8,820
java
CategoryRoleUserController.java
Java
[ { "context": ".SystemService;\n\n/**\n * ๆ ็›ฎ็ฎก็†ๅ‘˜Controller\n * @author liuyi\n * @version 2018-01-29\n */\n@Controller\n@RequestMa", "end": 1105, "score": 0.9970535635948181, "start": 1100, "tag": "USERNAME", "value": "liuyi" } ]
null
[]
package com.surekam.modules.cms.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.surekam.common.config.Global; import com.surekam.common.persistence.Page; import com.surekam.common.utils.StringUtils; import com.surekam.common.web.BaseController; import com.surekam.modules.cms.entity.CategoryRoleUser; import com.surekam.modules.cms.service.CategoryRoleUserService; import com.surekam.modules.sys.entity.Role; import com.surekam.modules.sys.entity.User; import com.surekam.modules.sys.service.SystemService; /** * ๆ ็›ฎ็ฎก็†ๅ‘˜Controller * @author liuyi * @version 2018-01-29 */ @Controller @RequestMapping(value = "${adminPath}/cms/categoryRoleUser") public class CategoryRoleUserController extends BaseController { @Autowired private CategoryRoleUserService categoryRoleUserService; @Autowired private SystemService systemService; @ModelAttribute public CategoryRoleUser get(@RequestParam(required=false) String id) { if (StringUtils.isNotBlank(id)){ return categoryRoleUserService.get(id); }else{ return new CategoryRoleUser(); } } @RequiresPermissions("cms:category:edit") @RequestMapping(value = {"list", ""}) public String list(CategoryRoleUser categoryRoleUser, HttpServletRequest request, HttpServletResponse response, Model model) { Page<CategoryRoleUser> page = categoryRoleUserService.find(new Page<CategoryRoleUser>(request, response), categoryRoleUser); model.addAttribute("page", page); return "modules/" + "cms/categoryRoleUserList"; } @RequiresPermissions("cms:category:edit") @RequestMapping(value = "form") public String form(CategoryRoleUser categoryRoleUser, Model model) { model.addAttribute("categoryRoleUser", categoryRoleUser); return "modules/" + "cms/categoryRoleUserForm"; } @RequiresPermissions("cms:category:edit") @RequestMapping(value = "information") public String information(CategoryRoleUser categoryRoleUser, Model model) { model.addAttribute("categoryRoleUser", categoryRoleUser); return "modules/" + "cms/categoryRoleUserInformation"; } @RequiresPermissions("cms:category:edit") @RequestMapping(value = "save") public String save(CategoryRoleUser categoryRoleUser, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, categoryRoleUser)){ return form(categoryRoleUser, model); } categoryRoleUserService.save(categoryRoleUser); addMessage(redirectAttributes, "ไฟๅญ˜ๆ ็›ฎ็ฎก็†ๅ‘˜ๆˆๅŠŸ"); return "redirect:"+Global.getAdminPath()+"/cms/categoryRoleUser/?repage"; } @RequiresPermissions("cms:category:edit") @RequestMapping(value = "delete") public String delete(String id, RedirectAttributes redirectAttributes) { //categoryRoleUserService.delete(id); addMessage(redirectAttributes, "ๅˆ ้™คๆ ็›ฎ็ฎก็†ๅ‘˜ๆˆๅŠŸ"); return "redirect:"+Global.getAdminPath()+"/cms/categoryRoleUser/?repage"; } /** * ่ทณ่ฝฌๅˆฐๆทปๅŠ ๆ ็›ฎ็ฎก็†ๅ‘˜ * * */ @RequiresPermissions("cms:category:edit") @RequestMapping(value = "toPlateAdmin") public String toPlateAdmin(String id,User user, Model model,HttpServletRequest request, HttpServletResponse response) { CategoryRoleUser categoryRoleUser =new CategoryRoleUser(); //categoryRoleUser.setCategoryId(Integer.parseInt(id)); categoryRoleUser = categoryRoleUserService.findObjByCategoryId(Integer.parseInt(id)); //ๆ นๆฎcategoryIdๆŸฅ่ฏข,่Žทๅ–็”จๆˆทๅˆ—่กจ๏ผŒๅ…ถไธญ่ขซ่ฎพ็ฝฎไธบๆŸไธชๆ ็›ฎ็‰ˆไธป็š„็”จๆˆทๅฐ†ๆŽ’ๅˆ—ๅœจๆœ€ๅ‰้ข List<User> list = categoryRoleUserService.findListByCategoryId(Integer.parseInt(id),user); //User currentUser = UserUtils.getUser(); //Page<User> page = systemService.findUser(new Page<User>(request, response), new User()); //่ฎพ็ฝฎๅˆ†้กต Page<User> page = categoryRoleUserService.setPageList(new Page<User>(request, response),request,response,list); //if(categoryRoleUser==null){ //categoryRoleUser = new CategoryRoleUser(); //} //categoryRoleUser.setCategoryId(Integer.parseInt(id)); model.addAttribute("page", page); model.addAttribute("user", user); model.addAttribute("categoryId", id); model.addAttribute("categoryRoleUser", categoryRoleUser); //model.addAttribute("allRoles", systemService.findAllRole()); return "modules/cms/categoryUserForm"; } /** * ็ป‘ๅฎš่ง’่‰ฒ * * */ @RequiresPermissions("cms:category:edit") @RequestMapping(value = "addPlateAdminRole") public String addPlateAdminRole(CategoryRoleUser categoryRoleUser, User user, Model model,HttpServletRequest request, HttpServletResponse response) { CategoryRoleUser category =new CategoryRoleUser(); category = categoryRoleUserService.findObjByCategoryId(categoryRoleUser.getCategoryId()); List<Role> roleIdList = categoryRoleUser.getRoleList(); String roleStr=""; if(roleIdList!=null && roleIdList.size()>0){ for (Role role : roleIdList) { roleStr+=role.getId()+","; } roleStr = roleStr.substring(0, roleStr.length()-1); } //ๅฆ‚ๆžœ่ฟ˜ๆœช่ฎพ็ฝฎ็‰ˆไธป่ง’่‰ฒๅˆ™ไฟๅญ˜categoryRoleUser๏ผŒๅฆ‚ๆžœๅทฒ็ป่ฎพ็ฝฎไบ†็‰ˆไธป่ง’่‰ฒๅˆ™ๆ›ดๆ–ฐcategoryRoleUser if(category!=null){ categoryRoleUserService.updateRole(roleStr,category); }else{ categoryRoleUser.setRoleId(roleStr); categoryRoleUserService.save(categoryRoleUser); } //category = categoryRoleUserService.findObjByCategoryId(categoryRoleUser.getCategoryId()); //categoryRoleUser.setCategoryId(Integer.parseInt(id)); //ๆ นๆฎcategoryIdๆŸฅ่ฏข List<User> list = categoryRoleUserService.findListByCategoryId(categoryRoleUser.getCategoryId(),user); //่ฎพ็ฝฎๅˆ†้กต Page<User> page = categoryRoleUserService.setPageList(new Page<User>(request, response),request,response,list); model.addAttribute("page", page); model.addAttribute("user", user); model.addAttribute("categoryRoleUser", categoryRoleUser); //model.addAttribute("allRoles", systemService.findAllRole()); addMessage(model, "็ป‘ๅฎšๆˆๅŠŸ๏ผ"); return "modules/cms/categoryUserForm"; } /** * ๆŒ‡ๅฎš็‰ˆไธป * * */ @RequiresPermissions("cms:category:edit") @RequestMapping(value = "addPlateAdmin") public String addPlateAdmin(String userId,String exUserIds,String add,String categoryId,User user, Model model,HttpServletRequest request, HttpServletResponse response) { CategoryRoleUser category =new CategoryRoleUser(); category = categoryRoleUserService.findObjByCategoryId(Integer.parseInt(categoryId)); if(category.getCategoryId()==null){ category.setCategoryId(Integer.parseInt(categoryId)); categoryRoleUserService.save(category); //addMessage(model, "่ฏฅๆ ็›ฎ่ฟ˜ๆœช็ป‘ๅฎš็‰ˆไธป่ง’่‰ฒ๏ผŒ่ฏทๅ…ˆ็ป‘ๅฎš่ง’่‰ฒ๏ผ"); //return toPlateAdmin(categoryId, user, model, request, response); } String UserIds=""; //ๅขžๅŠ ็‰ˆไธป if("1".equals(add)){ if("".equals(exUserIds)){ UserIds = userId; }else{ UserIds = exUserIds+","+userId; } }else{//ๅˆ ้™ค็‰ˆไธป UserIds = (exUserIds+",").replace((userId+","), ""); if(UserIds.endsWith(",")){ UserIds = UserIds.substring(0, UserIds.length()-1); } if(UserIds.startsWith(",")){ UserIds = UserIds.substring(1, UserIds.length()); } } category.setUserId(UserIds); categoryRoleUserService.updatePlate(category); //categoryRoleUser.setCategoryId(Integer.parseInt(id)); //ๆ นๆฎcategoryIdๆŸฅ่ฏข List<User> list = categoryRoleUserService.findListByCategoryId(category.getCategoryId(),user); //่ฎพ็ฝฎๅˆ†้กต Page<User> page = categoryRoleUserService.setPageList(new Page<User>(request, response),request,response,list); model.addAttribute("page", page); model.addAttribute("user", user); model.addAttribute("categoryId", categoryId); model.addAttribute("categoryRoleUser", category); //model.addAttribute("allRoles", systemService.findAllRole()); if("1".equals(add)){ addMessage(model, "ๆทปๅŠ ็‰ˆไธปๆˆๅŠŸ๏ผ"); }else{ addMessage(model, "ๅ–ๆถˆ็‰ˆไธปๆˆๅŠŸ๏ผ"); } return "modules/cms/categoryUserForm"; } }
8,820
0.73008
0.728194
226
36.539822
31.677589
171
false
false
0
0
0
0
0
0
1.800885
false
false
3
02c27eef426d3679e0e7f7dfea1d11f9d815f0aa
30,004,641,530,677
77ba7725783a6f5a4cb3b46420dda766c14f194b
/fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/MonitorController.java
870ea18581c4e64f7c6d96d1ef21eac4a95b946e
[ "Apache-2.0" ]
permissive
zhp8341/FATE-Serving
https://github.com/zhp8341/FATE-Serving
78532c2f90906fce9208815c88b50faae649b04c
3a81bc16f907a42fdb34835b84630a1c25722c19
refs/heads/master
2023-07-23T08:53:58.632000
2021-06-28T02:31:45
2021-06-28T02:31:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2019 The FATE Authors. All Rights Reserved. * * 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.webank.ai.fate.serving.admin.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.webank.ai.fate.api.networking.common.CommonServiceGrpc; import com.webank.ai.fate.api.networking.common.CommonServiceProto; import com.webank.ai.fate.serving.admin.services.ComponentService; import com.webank.ai.fate.serving.common.flow.JvmInfo; import com.webank.ai.fate.serving.common.flow.MetricNode; import com.webank.ai.fate.serving.core.bean.Dict; import com.webank.ai.fate.serving.core.bean.GrpcConnectionPool; import com.webank.ai.fate.serving.core.bean.MetaInfo; import com.webank.ai.fate.serving.core.bean.ReturnResult; import com.webank.ai.fate.serving.core.constant.StatusCode; import com.webank.ai.fate.serving.core.exceptions.RemoteRpcException; import com.webank.ai.fate.serving.core.exceptions.SysException; import com.webank.ai.fate.serving.core.utils.JsonUtil; import com.webank.ai.fate.serving.core.utils.NetUtils; import io.grpc.ManagedChannel; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @RequestMapping("/api") @RestController public class MonitorController { GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool(); @Autowired ComponentService componentService; @GetMapping("/monitor/queryJvm") public ReturnResult queryJvmData(String host, int port) { CommonServiceGrpc.CommonServiceBlockingStub blockingStub = getMonitorServiceBlockStub(host, port); blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS); CommonServiceProto.QueryJvmInfoRequest.Builder builder = CommonServiceProto.QueryJvmInfoRequest.newBuilder(); CommonServiceProto.CommonResponse commonResponse = blockingStub.queryJvmInfo(builder.build()); List<JvmInfo> resultList = Lists.newArrayList(); if (commonResponse.getData() != null && !commonResponse.getData().toStringUtf8().equals("null")) { List<JvmInfo> resultData = JsonUtil.json2List(commonResponse.getData().toStringUtf8(), new TypeReference<List<JvmInfo>>() { }); if (resultData != null) { resultList = resultData; } resultList = resultList.stream() .sorted(((o1, o2) -> o1.getTimestamp() == o2.getTimestamp() ? 0 : ((o1.getTimestamp() - o2.getTimestamp()) > 0 ? 1 : -1))) .collect(Collectors.toList()); } Map map = Maps.newHashMap(); map.put("total", resultList.size()); map.put("rows", resultList); return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, map); } @GetMapping("/monitor/query") public ReturnResult queryMonitorData(String host, int port, String source) { CommonServiceGrpc.CommonServiceBlockingStub blockingStub = getMonitorServiceBlockStub(host, port); blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS); CommonServiceProto.QueryMetricRequest.Builder builder = CommonServiceProto.QueryMetricRequest.newBuilder(); long now = System.currentTimeMillis(); builder.setBeginMs(now - 15000); builder.setEndMs(now); if (StringUtils.isNotBlank(source)) { builder.setSource(source); } builder.setType(CommonServiceProto.MetricType.INTERFACE); CommonServiceProto.CommonResponse commonResponse = blockingStub.queryMetrics(builder.build()); List<MetricNode> metricNodes = Lists.newArrayList(); if (commonResponse.getData() != null && !commonResponse.getData().toStringUtf8().equals("null")) { List<MetricNode> resultData = JsonUtil.json2List(commonResponse.getData().toStringUtf8(), new TypeReference<List<MetricNode>>() { }); if (resultData != null) { metricNodes = resultData; } } metricNodes = metricNodes.stream() .sorted(((o1, o2) -> o1.getTimestamp() == o2.getTimestamp() ? 0 : ((o1.getTimestamp() - o2.getTimestamp()) > 0 ? 1 : -1))) .collect(Collectors.toList()); Map<String, Object> dataMap = Maps.newHashMap(); if (metricNodes != null) { metricNodes.forEach(metricNode -> { List<MetricNode> nodes = (List<MetricNode>) dataMap.get(metricNode.getResource()); if (nodes == null) { nodes = Lists.newArrayList(); } nodes.add(metricNode); dataMap.put(metricNode.getResource(), nodes); }); } return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, dataMap); } @GetMapping("/monitor/queryModel") public ReturnResult queryModelMonitorData(String host, int port, String source) { Preconditions.checkArgument(StringUtils.isNotBlank(source), "parameter source is blank"); CommonServiceGrpc.CommonServiceBlockingStub blockingStub = getMonitorServiceBlockStub(host, port); blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS); CommonServiceProto.QueryMetricRequest.Builder builder = CommonServiceProto.QueryMetricRequest.newBuilder(); long now = System.currentTimeMillis(); builder.setBeginMs(now - 15000); builder.setEndMs(now); if (StringUtils.isNotBlank(source)) { builder.setSource(source); } builder.setType(CommonServiceProto.MetricType.MODEL); CommonServiceProto.CommonResponse commonResponse = blockingStub.queryMetrics(builder.build()); List<MetricNode> metricNodes = Lists.newArrayList(); if (commonResponse.getData() != null && !commonResponse.getData().toStringUtf8().equals("null")) { List<MetricNode> resultData = JsonUtil.json2List(commonResponse.getData().toStringUtf8(), new TypeReference<List<MetricNode>>() { }); if (resultData != null) { metricNodes = resultData; } } metricNodes = metricNodes.stream() .sorted(((o1, o2) -> o1.getTimestamp() == o2.getTimestamp() ? 0 : ((o1.getTimestamp() - o2.getTimestamp()) > 0 ? 1 : -1))) .collect(Collectors.toList()); Map<String, Object> dataMap = Maps.newHashMap(); if (metricNodes != null) { metricNodes.forEach(metricNode -> { List<MetricNode> nodes = (List<MetricNode>) dataMap.get(metricNode.getResource()); if (nodes == null) { nodes = Lists.newArrayList(); } nodes.add(metricNode); dataMap.put(metricNode.getResource(), nodes); }); } return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, dataMap); } private CommonServiceGrpc.CommonServiceBlockingStub getMonitorServiceBlockStub(String host, int port) { Preconditions.checkArgument(StringUtils.isNotBlank(host), "parameter host is blank"); Preconditions.checkArgument(port != 0, "parameter port was wrong"); if (!NetUtils.isValidAddress(host + ":" + port)) { throw new SysException("invalid address"); } if (!componentService.isAllowAccess(host, port)) { throw new RemoteRpcException("no allow access, target: " + host + ":" + port); } ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port); CommonServiceGrpc.CommonServiceBlockingStub blockingStub = CommonServiceGrpc.newBlockingStub(managedChannel); return blockingStub; } }
UTF-8
Java
8,758
java
MonitorController.java
Java
[]
null
[]
/* * Copyright 2019 The FATE Authors. All Rights Reserved. * * 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.webank.ai.fate.serving.admin.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.webank.ai.fate.api.networking.common.CommonServiceGrpc; import com.webank.ai.fate.api.networking.common.CommonServiceProto; import com.webank.ai.fate.serving.admin.services.ComponentService; import com.webank.ai.fate.serving.common.flow.JvmInfo; import com.webank.ai.fate.serving.common.flow.MetricNode; import com.webank.ai.fate.serving.core.bean.Dict; import com.webank.ai.fate.serving.core.bean.GrpcConnectionPool; import com.webank.ai.fate.serving.core.bean.MetaInfo; import com.webank.ai.fate.serving.core.bean.ReturnResult; import com.webank.ai.fate.serving.core.constant.StatusCode; import com.webank.ai.fate.serving.core.exceptions.RemoteRpcException; import com.webank.ai.fate.serving.core.exceptions.SysException; import com.webank.ai.fate.serving.core.utils.JsonUtil; import com.webank.ai.fate.serving.core.utils.NetUtils; import io.grpc.ManagedChannel; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @RequestMapping("/api") @RestController public class MonitorController { GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool(); @Autowired ComponentService componentService; @GetMapping("/monitor/queryJvm") public ReturnResult queryJvmData(String host, int port) { CommonServiceGrpc.CommonServiceBlockingStub blockingStub = getMonitorServiceBlockStub(host, port); blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS); CommonServiceProto.QueryJvmInfoRequest.Builder builder = CommonServiceProto.QueryJvmInfoRequest.newBuilder(); CommonServiceProto.CommonResponse commonResponse = blockingStub.queryJvmInfo(builder.build()); List<JvmInfo> resultList = Lists.newArrayList(); if (commonResponse.getData() != null && !commonResponse.getData().toStringUtf8().equals("null")) { List<JvmInfo> resultData = JsonUtil.json2List(commonResponse.getData().toStringUtf8(), new TypeReference<List<JvmInfo>>() { }); if (resultData != null) { resultList = resultData; } resultList = resultList.stream() .sorted(((o1, o2) -> o1.getTimestamp() == o2.getTimestamp() ? 0 : ((o1.getTimestamp() - o2.getTimestamp()) > 0 ? 1 : -1))) .collect(Collectors.toList()); } Map map = Maps.newHashMap(); map.put("total", resultList.size()); map.put("rows", resultList); return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, map); } @GetMapping("/monitor/query") public ReturnResult queryMonitorData(String host, int port, String source) { CommonServiceGrpc.CommonServiceBlockingStub blockingStub = getMonitorServiceBlockStub(host, port); blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS); CommonServiceProto.QueryMetricRequest.Builder builder = CommonServiceProto.QueryMetricRequest.newBuilder(); long now = System.currentTimeMillis(); builder.setBeginMs(now - 15000); builder.setEndMs(now); if (StringUtils.isNotBlank(source)) { builder.setSource(source); } builder.setType(CommonServiceProto.MetricType.INTERFACE); CommonServiceProto.CommonResponse commonResponse = blockingStub.queryMetrics(builder.build()); List<MetricNode> metricNodes = Lists.newArrayList(); if (commonResponse.getData() != null && !commonResponse.getData().toStringUtf8().equals("null")) { List<MetricNode> resultData = JsonUtil.json2List(commonResponse.getData().toStringUtf8(), new TypeReference<List<MetricNode>>() { }); if (resultData != null) { metricNodes = resultData; } } metricNodes = metricNodes.stream() .sorted(((o1, o2) -> o1.getTimestamp() == o2.getTimestamp() ? 0 : ((o1.getTimestamp() - o2.getTimestamp()) > 0 ? 1 : -1))) .collect(Collectors.toList()); Map<String, Object> dataMap = Maps.newHashMap(); if (metricNodes != null) { metricNodes.forEach(metricNode -> { List<MetricNode> nodes = (List<MetricNode>) dataMap.get(metricNode.getResource()); if (nodes == null) { nodes = Lists.newArrayList(); } nodes.add(metricNode); dataMap.put(metricNode.getResource(), nodes); }); } return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, dataMap); } @GetMapping("/monitor/queryModel") public ReturnResult queryModelMonitorData(String host, int port, String source) { Preconditions.checkArgument(StringUtils.isNotBlank(source), "parameter source is blank"); CommonServiceGrpc.CommonServiceBlockingStub blockingStub = getMonitorServiceBlockStub(host, port); blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS); CommonServiceProto.QueryMetricRequest.Builder builder = CommonServiceProto.QueryMetricRequest.newBuilder(); long now = System.currentTimeMillis(); builder.setBeginMs(now - 15000); builder.setEndMs(now); if (StringUtils.isNotBlank(source)) { builder.setSource(source); } builder.setType(CommonServiceProto.MetricType.MODEL); CommonServiceProto.CommonResponse commonResponse = blockingStub.queryMetrics(builder.build()); List<MetricNode> metricNodes = Lists.newArrayList(); if (commonResponse.getData() != null && !commonResponse.getData().toStringUtf8().equals("null")) { List<MetricNode> resultData = JsonUtil.json2List(commonResponse.getData().toStringUtf8(), new TypeReference<List<MetricNode>>() { }); if (resultData != null) { metricNodes = resultData; } } metricNodes = metricNodes.stream() .sorted(((o1, o2) -> o1.getTimestamp() == o2.getTimestamp() ? 0 : ((o1.getTimestamp() - o2.getTimestamp()) > 0 ? 1 : -1))) .collect(Collectors.toList()); Map<String, Object> dataMap = Maps.newHashMap(); if (metricNodes != null) { metricNodes.forEach(metricNode -> { List<MetricNode> nodes = (List<MetricNode>) dataMap.get(metricNode.getResource()); if (nodes == null) { nodes = Lists.newArrayList(); } nodes.add(metricNode); dataMap.put(metricNode.getResource(), nodes); }); } return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, dataMap); } private CommonServiceGrpc.CommonServiceBlockingStub getMonitorServiceBlockStub(String host, int port) { Preconditions.checkArgument(StringUtils.isNotBlank(host), "parameter host is blank"); Preconditions.checkArgument(port != 0, "parameter port was wrong"); if (!NetUtils.isValidAddress(host + ":" + port)) { throw new SysException("invalid address"); } if (!componentService.isAllowAccess(host, port)) { throw new RemoteRpcException("no allow access, target: " + host + ":" + port); } ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port); CommonServiceGrpc.CommonServiceBlockingStub blockingStub = CommonServiceGrpc.newBlockingStub(managedChannel); return blockingStub; } }
8,758
0.68543
0.678694
182
47.12088
36.385403
142
false
false
0
0
0
0
0
0
0.725275
false
false
3
9bbc6c2ddef5f970676dd3bc905559ae85774a7a
32,452,772,953,940
7fa7b9119573c20b74b7a28093bc387f66f34267
/edusession/src/main/java/pl/edusession/domain/cms/articles/ArticleCreator.java
f13b134e36b5df88172683f4438fb503ed4b8c84
[]
no_license
mwarycha/edusession.pl
https://github.com/mwarycha/edusession.pl
9af4c56ebf22cc785333bed9f96f0988b76caadf
319e8d4bccf5221775c2ccf29a6f1b7b0ab5b349
refs/heads/master
2018-12-26T20:29:27.546000
2018-12-24T13:43:46
2018-12-24T13:43:46
126,728,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.edusession.domain.cms.articles; import org.springframework.webflow.execution.RequestContext; import pl.edusession.domain.cms.comparators.MapComparatorSortBySectionEntityId; import pl.edusession.domain.cms.comparators.SetComparatorSortBySectionId; import pl.edusession.domain.entities.ArticleEntity; import pl.edusession.domain.entities.SectionEntity; import pl.edusession.domain.entities.TrainingEntity; import pl.edusession.domain.spring.data.repository.ArticleRepo; import pl.edusession.domain.spring.data.repository.SectionRepo; import pl.edusession.domain.spring.data.repository.TrainingRepo; import javax.faces.context.FacesContext; import java.util.*; import java.util.List; import pl.edusession.helpers.ColorConsoleHelper; import pl.edusession.helpers.I18NHelper; import pl.edusession.service.TrainingService; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import static pl.edusession.helpers.StaticVariablesControllerHelper.INSERTED_CHANGES_MUST_BE_CONFIRMED; @ManagedBean @ViewScoped public class ArticleCreator { @Autowired TrainingRepo trainingRepo; @Autowired TrainingService trainingService; @Autowired SectionRepo sectionRepo; @Autowired ArticleRepo articleRepo; //sectionEntityRemoveSet marked as to be removed by user private Set<SectionEntity> sectionEntityRemoveSet = new HashSet(); //editors that have been edited, mapping status from JSF to id from database using counterPrintedEditors private Map<Integer,Integer> editedEditors; //mapping editor status index to section type private Map<Integer, TYPE_SECTION> sectionTypes; //editors, mapping counter from counter = 0 to editor id from database private Map<Integer,Integer> counterPrintedEditors; //map status.index to active or inactive checkbox private Map<String,Boolean> checkBoxes; private String articleTitle; private String trainingId; private String articleId; private List<String> editors; public ArticleCreator() { //nothing to do } private ArticleEntity getLastNewArticle() { TrainingEntity trainingEntityWithNewArticle = refreshEntity(); ArticleEntity lastAddedArticle = null; for(ArticleEntity articleEntity : trainingEntityWithNewArticle.getArticleEntities()) { if(lastAddedArticle == null) { lastAddedArticle = articleEntity; continue; } if(articleEntity.getArticleId() > lastAddedArticle.getArticleId()) { lastAddedArticle = articleEntity; } } return lastAddedArticle; } //get article entity according to request articleId aram private ArticleEntity getArticleEntity() { ArticleEntity articleEntity; final String NEW_ARICLE = "new"; if(articleId.equals(NEW_ARICLE)) { articleEntity = articleRepo.getByArticleId(getLastNewArticle().getArticleId()); } else { //get articleId from request articleEntity = articleRepo.getByArticleId(Integer.parseInt(articleId)); } return articleEntity; } //get training entity using trainingId private TrainingEntity refreshEntity() { return trainingRepo.getByCode(trainingId); } private ArticleEntity createNewArticle(TrainingEntity trainingEntity) { //create dummy article ArticleEntity newArticleEntity = new ArticleEntity(); newArticleEntity.setTrainingEntity(trainingEntity); //create dummy section SectionEntity sectionEntity = new SectionEntity(); sectionEntity.setArticleEntity(newArticleEntity); newArticleEntity.addSection(sectionEntity); //set relation trainingEntity.addArticle(newArticleEntity); trainingRepo.save(trainingEntity); return getLastNewArticle(); } // load all sections type from database private void fillCheckBoxesMapWithInitValues(Map<Integer, String> sortedCheckBoxesMap) { //if training article is new, the checkbox map with sections type is null! final String NEW_ARICLE = "new"; if(articleId.equals(NEW_ARICLE)) { return; } int counter = 0; final String PUBLIC_SECTION = "PUBLIC"; final boolean ACTIVE = true; final boolean INACTIVE = false; for(String type: sortedCheckBoxesMap.values()) { if(type == null) { //if type of section not be set by user the default type of section is public checkBoxes.put("active-" + counter, ACTIVE); checkBoxes.put("inactive-" + counter, INACTIVE); continue; } if(type.equals(PUBLIC_SECTION)) { checkBoxes.put("active-" + counter, ACTIVE); checkBoxes.put("inactive-" + counter, INACTIVE); } else { checkBoxes.put("active-" + counter, INACTIVE); checkBoxes.put("inactive-" + counter, ACTIVE); } counter ++; } } @PostConstruct public void init() { final int START_INDEX = 0; final String NEW_ARICLE = "new"; // read editors editors = new ArrayList(); //edited editors counterPrintedEditors = new HashMap(); editedEditors = new HashMap(); checkBoxes = new HashMap(); //sectionType mapping sectionTypes = new HashMap(); //get request get training parameter trainingId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("training"); //get request get article id parameter articleId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("article_id"); //if request param parameters are null if(trainingId == null || articleId == null) { return; } //find by trainingId in order to load all program items TrainingEntity trainingEntity = refreshEntity(); ArticleEntity newArticleEntity = null; if(articleId.equals(NEW_ARICLE)) { newArticleEntity = createNewArticle(trainingEntity); //refresh entity trainingEntity = refreshEntity(); } //get all articles associated with property training Set<ArticleEntity> articleEntities = trainingEntity.getArticleEntities(); //find all sections associated with property article ArticleEntity candidate = null; for(ArticleEntity articleEntity: articleEntities) { if(articleEntity.getArticleId().toString().equals(articleId)) { candidate = articleEntity; break; } } //if not found article candidate is a new article if(candidate == null) { candidate = newArticleEntity; } //get title from article & set current title articleTitle = candidate.getTitle(); //get all sections Set<SectionEntity> sectionEntities = candidate.getSectionEntitySet(); //counter printed editors int counterEditor = START_INDEX; //sorted EditorMap Map<Integer, String> sortedEditorMap = new TreeMap(new MapComparatorSortBySectionEntityId()); Map<Integer, String> sortedCheckBoxTypeMap = new TreeMap(new MapComparatorSortBySectionEntityId()); Set<SectionEntity> sortedSectionEditorSet = new TreeSet(new SetComparatorSortBySectionId()); sortedSectionEditorSet.addAll(sectionEntities); // load sections for(SectionEntity sectionEntity: sortedSectionEditorSet) { // add counter to map according to sectionId counterPrintedEditors.put(counterEditor, sectionEntity.getSectionId()); // mapping sectionId to sectionText sortedEditorMap.put(sectionEntity.getSectionId(), sectionEntity.getText()); // mapping sectionId to sectionType sortedCheckBoxTypeMap.put(sectionEntity.getSectionId(),sectionEntity.getType()); counterEditor++; } //add sections editors.addAll(sortedEditorMap.values()); //fill checkbox map with property type from database fillCheckBoxesMapWithInitValues(sortedCheckBoxTypeMap); } //add new item public void extendForm(RequestContext context) { editors.add(" "); } public void handleEditorEvent(int currentStatusIndex) { // editors if (editors.isEmpty()) { // nothing to do } else { if (counterPrintedEditors.isEmpty()) { // nothing to do } else { // mapping currentStatusIndex & id from database if (counterPrintedEditors.get(currentStatusIndex) != null) { editedEditors.put(currentStatusIndex, counterPrintedEditors.get(currentStatusIndex)); } } } } //remove current item public void rmItem(String index) { ColorConsoleHelper.getGreenLog(checkBoxes); // add section entity to hashSet collection that must be removed SectionEntity sectionEntity = sectionRepo.getByText(editors.get(Integer.parseInt(index))); final String NEW_ARICLE = "new"; if(!articleId.equals(NEW_ARICLE)) { sectionEntityRemoveSet.add(sectionEntity); } // remove from list editors.remove(Integer.parseInt(index)); } @Transactional public String submit(RequestContext context) { ColorConsoleHelper.getGreenLog(sectionTypes); final int START_INDEX = 0; int itemCounter = START_INDEX; for (String currentEditor : editors) { ColorConsoleHelper.getGreenLog(editors + "all editors"); //[edited] editor if (editedEditors.containsKey(itemCounter)) { ColorConsoleHelper.getGreenLog(editedEditors + "edited editors"); SectionEntity sectionEntity = getSectionEntityById(editedEditors.get(itemCounter)); sectionEntity.setText(currentEditor); sectionEntity.setEdited_date(new Date()); // section type has been edited ColorConsoleHelper.getGreenLog(itemCounter + "itemCounter edited editor"); if(sectionTypes.containsKey(itemCounter)) { sectionEntity.setType(sectionTypes.get(itemCounter).toString()); } sectionRepo.save(sectionEntity); } //[no edited] editor if (!editedEditors.containsKey(itemCounter)) { TrainingEntity trainingEntity = refreshEntity(); // persist only if editor not already exist in database // new added editor it is a section considered as a non edited editor SectionEntity checkedSectionEntityByText = sectionRepo.getByText(currentEditor); if(checkedSectionEntityByText== null) { ArticleEntity articleEntity = getArticleEntity(); SectionEntity sectionEntity = new SectionEntity(); sectionEntity.setText(currentEditor); sectionEntity.setEdited_date(new Date()); // new added section type has been edited ColorConsoleHelper.getGreenLog(itemCounter + "itemCounter non edited editor"); ColorConsoleHelper.getGreenLog(sectionTypes); if(sectionTypes.containsKey(itemCounter)) { sectionEntity.setType(sectionTypes.get(itemCounter).toString()); } sectionEntity.setArticleEntity(articleEntity); articleEntity.addSection(sectionEntity); trainingEntity.addArticle(articleEntity); trainingRepo.save(trainingEntity); } //editor not edited by user, check now if section type has been modified. else { if(sectionTypes.containsKey(itemCounter)) { checkedSectionEntityByText.setType(sectionTypes.get(itemCounter).toString()); } sectionRepo.save(checkedSectionEntityByText); } } itemCounter++; } ArticleEntity articleEntity = getArticleEntity(); articleEntity.setTitle(articleTitle); ColorConsoleHelper.getGreenLog(articleEntity.getSectionEntitySet() + "BEFORE"); TreeSet sectionEntityRemoveTreeSet = new TreeSet(new SetComparatorSortBySectionId()); sectionEntityRemoveTreeSet.addAll(sectionEntityRemoveSet); articleEntity.getSectionEntitySet().removeAll(sectionEntityRemoveTreeSet); ColorConsoleHelper.getGreenLog(articleEntity.getSectionEntitySet() + "AFTER"); articleEntity.getSectionEntitySet().removeAll(sectionEntityRemoveSet); articleRepo.save(articleEntity); Locale currentLocale = FacesContext.getCurrentInstance().getViewRoot().getLocale(); return I18NHelper.getI18nMessage(currentLocale, INSERTED_CHANGES_MUST_BE_CONFIRMED); } //function split string: active-currentIndex or inactive-currentIndex and return currentIndex private String getByCurrentStatusIndex(String keyCheckBox) { final String DASH_SEPARATOR = "-"; final int CURRENT_STATUS_INDEX = 1; String[] partsCurrentStatusIndex = keyCheckBox.split(DASH_SEPARATOR); return partsCurrentStatusIndex[CURRENT_STATUS_INDEX]; } public void onActiveStatusChange(String currentStatusIndex) { final Boolean ACTIVE = true; final Boolean INACTIVE = false; checkBoxes.put(currentStatusIndex, ACTIVE); checkBoxes.put("inactive" + "-" + getByCurrentStatusIndex(currentStatusIndex), INACTIVE); sectionTypes.put(Integer.parseInt(getByCurrentStatusIndex(currentStatusIndex)), TYPE_SECTION.PUBLIC); ColorConsoleHelper.getGreenLog(checkBoxes); } public void onInactiveStatusChange(String currentStatusIndex) { final Boolean ACTIVE = true; final Boolean INACTIVE = false; checkBoxes.put(currentStatusIndex, ACTIVE); checkBoxes.put("active" + "-" + getByCurrentStatusIndex(currentStatusIndex), INACTIVE); sectionTypes.put(Integer.parseInt(getByCurrentStatusIndex(currentStatusIndex)), TYPE_SECTION.PRIVATE); ColorConsoleHelper.getGreenLog(checkBoxes); } /* * ************************************** * Setters and Getters * ************************************** */ public SectionEntity getSectionEntityById(int id) { return sectionRepo.getBySectionId(id); } public List<String> getEditors() { return editors; } public void setEditors(List<String> editors) { this.editors = editors; } public Map<String, Boolean> getCheckBoxes() { return checkBoxes; } public void setCheckBoxes(Map<String, Boolean> checkBoxes) { this.checkBoxes = checkBoxes; } public String getArticleTitle() { return articleTitle; } public void setArticleTitle(String articleTitle) { this.articleTitle = articleTitle; } // type of section private enum TYPE_SECTION { PRIVATE, PUBLIC } }
UTF-8
Java
15,864
java
ArticleCreator.java
Java
[]
null
[]
package pl.edusession.domain.cms.articles; import org.springframework.webflow.execution.RequestContext; import pl.edusession.domain.cms.comparators.MapComparatorSortBySectionEntityId; import pl.edusession.domain.cms.comparators.SetComparatorSortBySectionId; import pl.edusession.domain.entities.ArticleEntity; import pl.edusession.domain.entities.SectionEntity; import pl.edusession.domain.entities.TrainingEntity; import pl.edusession.domain.spring.data.repository.ArticleRepo; import pl.edusession.domain.spring.data.repository.SectionRepo; import pl.edusession.domain.spring.data.repository.TrainingRepo; import javax.faces.context.FacesContext; import java.util.*; import java.util.List; import pl.edusession.helpers.ColorConsoleHelper; import pl.edusession.helpers.I18NHelper; import pl.edusession.service.TrainingService; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import static pl.edusession.helpers.StaticVariablesControllerHelper.INSERTED_CHANGES_MUST_BE_CONFIRMED; @ManagedBean @ViewScoped public class ArticleCreator { @Autowired TrainingRepo trainingRepo; @Autowired TrainingService trainingService; @Autowired SectionRepo sectionRepo; @Autowired ArticleRepo articleRepo; //sectionEntityRemoveSet marked as to be removed by user private Set<SectionEntity> sectionEntityRemoveSet = new HashSet(); //editors that have been edited, mapping status from JSF to id from database using counterPrintedEditors private Map<Integer,Integer> editedEditors; //mapping editor status index to section type private Map<Integer, TYPE_SECTION> sectionTypes; //editors, mapping counter from counter = 0 to editor id from database private Map<Integer,Integer> counterPrintedEditors; //map status.index to active or inactive checkbox private Map<String,Boolean> checkBoxes; private String articleTitle; private String trainingId; private String articleId; private List<String> editors; public ArticleCreator() { //nothing to do } private ArticleEntity getLastNewArticle() { TrainingEntity trainingEntityWithNewArticle = refreshEntity(); ArticleEntity lastAddedArticle = null; for(ArticleEntity articleEntity : trainingEntityWithNewArticle.getArticleEntities()) { if(lastAddedArticle == null) { lastAddedArticle = articleEntity; continue; } if(articleEntity.getArticleId() > lastAddedArticle.getArticleId()) { lastAddedArticle = articleEntity; } } return lastAddedArticle; } //get article entity according to request articleId aram private ArticleEntity getArticleEntity() { ArticleEntity articleEntity; final String NEW_ARICLE = "new"; if(articleId.equals(NEW_ARICLE)) { articleEntity = articleRepo.getByArticleId(getLastNewArticle().getArticleId()); } else { //get articleId from request articleEntity = articleRepo.getByArticleId(Integer.parseInt(articleId)); } return articleEntity; } //get training entity using trainingId private TrainingEntity refreshEntity() { return trainingRepo.getByCode(trainingId); } private ArticleEntity createNewArticle(TrainingEntity trainingEntity) { //create dummy article ArticleEntity newArticleEntity = new ArticleEntity(); newArticleEntity.setTrainingEntity(trainingEntity); //create dummy section SectionEntity sectionEntity = new SectionEntity(); sectionEntity.setArticleEntity(newArticleEntity); newArticleEntity.addSection(sectionEntity); //set relation trainingEntity.addArticle(newArticleEntity); trainingRepo.save(trainingEntity); return getLastNewArticle(); } // load all sections type from database private void fillCheckBoxesMapWithInitValues(Map<Integer, String> sortedCheckBoxesMap) { //if training article is new, the checkbox map with sections type is null! final String NEW_ARICLE = "new"; if(articleId.equals(NEW_ARICLE)) { return; } int counter = 0; final String PUBLIC_SECTION = "PUBLIC"; final boolean ACTIVE = true; final boolean INACTIVE = false; for(String type: sortedCheckBoxesMap.values()) { if(type == null) { //if type of section not be set by user the default type of section is public checkBoxes.put("active-" + counter, ACTIVE); checkBoxes.put("inactive-" + counter, INACTIVE); continue; } if(type.equals(PUBLIC_SECTION)) { checkBoxes.put("active-" + counter, ACTIVE); checkBoxes.put("inactive-" + counter, INACTIVE); } else { checkBoxes.put("active-" + counter, INACTIVE); checkBoxes.put("inactive-" + counter, ACTIVE); } counter ++; } } @PostConstruct public void init() { final int START_INDEX = 0; final String NEW_ARICLE = "new"; // read editors editors = new ArrayList(); //edited editors counterPrintedEditors = new HashMap(); editedEditors = new HashMap(); checkBoxes = new HashMap(); //sectionType mapping sectionTypes = new HashMap(); //get request get training parameter trainingId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("training"); //get request get article id parameter articleId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("article_id"); //if request param parameters are null if(trainingId == null || articleId == null) { return; } //find by trainingId in order to load all program items TrainingEntity trainingEntity = refreshEntity(); ArticleEntity newArticleEntity = null; if(articleId.equals(NEW_ARICLE)) { newArticleEntity = createNewArticle(trainingEntity); //refresh entity trainingEntity = refreshEntity(); } //get all articles associated with property training Set<ArticleEntity> articleEntities = trainingEntity.getArticleEntities(); //find all sections associated with property article ArticleEntity candidate = null; for(ArticleEntity articleEntity: articleEntities) { if(articleEntity.getArticleId().toString().equals(articleId)) { candidate = articleEntity; break; } } //if not found article candidate is a new article if(candidate == null) { candidate = newArticleEntity; } //get title from article & set current title articleTitle = candidate.getTitle(); //get all sections Set<SectionEntity> sectionEntities = candidate.getSectionEntitySet(); //counter printed editors int counterEditor = START_INDEX; //sorted EditorMap Map<Integer, String> sortedEditorMap = new TreeMap(new MapComparatorSortBySectionEntityId()); Map<Integer, String> sortedCheckBoxTypeMap = new TreeMap(new MapComparatorSortBySectionEntityId()); Set<SectionEntity> sortedSectionEditorSet = new TreeSet(new SetComparatorSortBySectionId()); sortedSectionEditorSet.addAll(sectionEntities); // load sections for(SectionEntity sectionEntity: sortedSectionEditorSet) { // add counter to map according to sectionId counterPrintedEditors.put(counterEditor, sectionEntity.getSectionId()); // mapping sectionId to sectionText sortedEditorMap.put(sectionEntity.getSectionId(), sectionEntity.getText()); // mapping sectionId to sectionType sortedCheckBoxTypeMap.put(sectionEntity.getSectionId(),sectionEntity.getType()); counterEditor++; } //add sections editors.addAll(sortedEditorMap.values()); //fill checkbox map with property type from database fillCheckBoxesMapWithInitValues(sortedCheckBoxTypeMap); } //add new item public void extendForm(RequestContext context) { editors.add(" "); } public void handleEditorEvent(int currentStatusIndex) { // editors if (editors.isEmpty()) { // nothing to do } else { if (counterPrintedEditors.isEmpty()) { // nothing to do } else { // mapping currentStatusIndex & id from database if (counterPrintedEditors.get(currentStatusIndex) != null) { editedEditors.put(currentStatusIndex, counterPrintedEditors.get(currentStatusIndex)); } } } } //remove current item public void rmItem(String index) { ColorConsoleHelper.getGreenLog(checkBoxes); // add section entity to hashSet collection that must be removed SectionEntity sectionEntity = sectionRepo.getByText(editors.get(Integer.parseInt(index))); final String NEW_ARICLE = "new"; if(!articleId.equals(NEW_ARICLE)) { sectionEntityRemoveSet.add(sectionEntity); } // remove from list editors.remove(Integer.parseInt(index)); } @Transactional public String submit(RequestContext context) { ColorConsoleHelper.getGreenLog(sectionTypes); final int START_INDEX = 0; int itemCounter = START_INDEX; for (String currentEditor : editors) { ColorConsoleHelper.getGreenLog(editors + "all editors"); //[edited] editor if (editedEditors.containsKey(itemCounter)) { ColorConsoleHelper.getGreenLog(editedEditors + "edited editors"); SectionEntity sectionEntity = getSectionEntityById(editedEditors.get(itemCounter)); sectionEntity.setText(currentEditor); sectionEntity.setEdited_date(new Date()); // section type has been edited ColorConsoleHelper.getGreenLog(itemCounter + "itemCounter edited editor"); if(sectionTypes.containsKey(itemCounter)) { sectionEntity.setType(sectionTypes.get(itemCounter).toString()); } sectionRepo.save(sectionEntity); } //[no edited] editor if (!editedEditors.containsKey(itemCounter)) { TrainingEntity trainingEntity = refreshEntity(); // persist only if editor not already exist in database // new added editor it is a section considered as a non edited editor SectionEntity checkedSectionEntityByText = sectionRepo.getByText(currentEditor); if(checkedSectionEntityByText== null) { ArticleEntity articleEntity = getArticleEntity(); SectionEntity sectionEntity = new SectionEntity(); sectionEntity.setText(currentEditor); sectionEntity.setEdited_date(new Date()); // new added section type has been edited ColorConsoleHelper.getGreenLog(itemCounter + "itemCounter non edited editor"); ColorConsoleHelper.getGreenLog(sectionTypes); if(sectionTypes.containsKey(itemCounter)) { sectionEntity.setType(sectionTypes.get(itemCounter).toString()); } sectionEntity.setArticleEntity(articleEntity); articleEntity.addSection(sectionEntity); trainingEntity.addArticle(articleEntity); trainingRepo.save(trainingEntity); } //editor not edited by user, check now if section type has been modified. else { if(sectionTypes.containsKey(itemCounter)) { checkedSectionEntityByText.setType(sectionTypes.get(itemCounter).toString()); } sectionRepo.save(checkedSectionEntityByText); } } itemCounter++; } ArticleEntity articleEntity = getArticleEntity(); articleEntity.setTitle(articleTitle); ColorConsoleHelper.getGreenLog(articleEntity.getSectionEntitySet() + "BEFORE"); TreeSet sectionEntityRemoveTreeSet = new TreeSet(new SetComparatorSortBySectionId()); sectionEntityRemoveTreeSet.addAll(sectionEntityRemoveSet); articleEntity.getSectionEntitySet().removeAll(sectionEntityRemoveTreeSet); ColorConsoleHelper.getGreenLog(articleEntity.getSectionEntitySet() + "AFTER"); articleEntity.getSectionEntitySet().removeAll(sectionEntityRemoveSet); articleRepo.save(articleEntity); Locale currentLocale = FacesContext.getCurrentInstance().getViewRoot().getLocale(); return I18NHelper.getI18nMessage(currentLocale, INSERTED_CHANGES_MUST_BE_CONFIRMED); } //function split string: active-currentIndex or inactive-currentIndex and return currentIndex private String getByCurrentStatusIndex(String keyCheckBox) { final String DASH_SEPARATOR = "-"; final int CURRENT_STATUS_INDEX = 1; String[] partsCurrentStatusIndex = keyCheckBox.split(DASH_SEPARATOR); return partsCurrentStatusIndex[CURRENT_STATUS_INDEX]; } public void onActiveStatusChange(String currentStatusIndex) { final Boolean ACTIVE = true; final Boolean INACTIVE = false; checkBoxes.put(currentStatusIndex, ACTIVE); checkBoxes.put("inactive" + "-" + getByCurrentStatusIndex(currentStatusIndex), INACTIVE); sectionTypes.put(Integer.parseInt(getByCurrentStatusIndex(currentStatusIndex)), TYPE_SECTION.PUBLIC); ColorConsoleHelper.getGreenLog(checkBoxes); } public void onInactiveStatusChange(String currentStatusIndex) { final Boolean ACTIVE = true; final Boolean INACTIVE = false; checkBoxes.put(currentStatusIndex, ACTIVE); checkBoxes.put("active" + "-" + getByCurrentStatusIndex(currentStatusIndex), INACTIVE); sectionTypes.put(Integer.parseInt(getByCurrentStatusIndex(currentStatusIndex)), TYPE_SECTION.PRIVATE); ColorConsoleHelper.getGreenLog(checkBoxes); } /* * ************************************** * Setters and Getters * ************************************** */ public SectionEntity getSectionEntityById(int id) { return sectionRepo.getBySectionId(id); } public List<String> getEditors() { return editors; } public void setEditors(List<String> editors) { this.editors = editors; } public Map<String, Boolean> getCheckBoxes() { return checkBoxes; } public void setCheckBoxes(Map<String, Boolean> checkBoxes) { this.checkBoxes = checkBoxes; } public String getArticleTitle() { return articleTitle; } public void setArticleTitle(String articleTitle) { this.articleTitle = articleTitle; } // type of section private enum TYPE_SECTION { PRIVATE, PUBLIC } }
15,864
0.647756
0.647063
471
32.68153
30.285486
118
false
false
0
0
0
0
0
0
0.435244
false
false
3
9dfd25908500297343e30bd4d92772d71be6cc30
1,992,864,850,532
aef3f5cfabcfb6a56671f5a4e48d0c9f032247ae
/src/com/dev/jbooklib/controller/RootLayoutController.java
2fd7d13cca3947220244f8989d6179eb8582c3b9
[]
no_license
vetal71/JBookLibrary
https://github.com/vetal71/JBookLibrary
be00aa93a1f392baa6fe49383ac6029a56a7c10d
2cb4c53cb793ba0fadd29aeb58887d15a0fa6b10
refs/heads/master
2021-01-19T11:11:54.050000
2017-04-12T15:01:49
2017-04-12T15:01:49
87,555,636
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dev.jbooklib.controller; import com.dev.jbooklib.MainApp; import com.dev.jbooklib.service.BookService; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Separator; import org.controlsfx.control.StatusBar; import static com.dev.jbooklib.util.Contants.COUNT_RECORD_INFO; import static com.dev.jbooklib.util.Contants.DB_NAME; import static com.dev.jbooklib.util.Contants.DB_NAME_INFO; import static com.dev.jbooklib.util.MyUtils.showInfo; import static javafx.geometry.Orientation.VERTICAL; /** * ะšะปะฐัั ะบะพั€ะฝะตะฒะพะณะพ ัะปะตะผะตะฝั‚ะฐ ะธะฝั‚ะตั€ั„ะตะนัะฐ ะฟั€ะธะปะพะถะตะฝะธั * Created by kolesnik on 11/04/2017. */ public class RootLayoutController { private MainApp mainApp; private Label lblDBInfo; private Label lblTotalCountInfo; @FXML private StatusBar sbMain; @FXML private void handleExit() { System.exit(0); } @FXML private void handleSyncLib() { showInfo("ะกะธะฝั…ั€ะพะฝะธะทะฐั†ะธั....", ""); } public void initControls() { lblDBInfo = new Label(String.format(DB_NAME_INFO, DB_NAME)); lblTotalCountInfo = new Label(String.format(COUNT_RECORD_INFO, BookService.getBookCount())); sbMain.getRightItems().add(new Separator(VERTICAL)); sbMain.getRightItems().add(lblTotalCountInfo); sbMain.getRightItems().add(new Separator(VERTICAL)); sbMain.getRightItems().add(lblDBInfo); } public void setMainApp(MainApp mainApp) { this.mainApp = mainApp; } public void setStatusInfo(String msg) { sbMain.setText(msg); } public void setDBInfo(String msg) { lblDBInfo.setText(msg); } public void setTotalCountInfo(String msg) { lblTotalCountInfo.setText(msg); } }
UTF-8
Java
1,811
java
RootLayoutController.java
Java
[ { "context": "ะตะฒะพะณะพ ัะปะตะผะตะฝั‚ะฐ ะธะฝั‚ะตั€ั„ะตะนัะฐ ะฟั€ะธะปะพะถะตะฝะธั\n * Created by kolesnik on 11/04/2017.\n */\npublic class RootLayoutControl", "end": 617, "score": 0.9995532035827637, "start": 609, "tag": "USERNAME", "value": "kolesnik" } ]
null
[]
package com.dev.jbooklib.controller; import com.dev.jbooklib.MainApp; import com.dev.jbooklib.service.BookService; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Separator; import org.controlsfx.control.StatusBar; import static com.dev.jbooklib.util.Contants.COUNT_RECORD_INFO; import static com.dev.jbooklib.util.Contants.DB_NAME; import static com.dev.jbooklib.util.Contants.DB_NAME_INFO; import static com.dev.jbooklib.util.MyUtils.showInfo; import static javafx.geometry.Orientation.VERTICAL; /** * ะšะปะฐัั ะบะพั€ะฝะตะฒะพะณะพ ัะปะตะผะตะฝั‚ะฐ ะธะฝั‚ะตั€ั„ะตะนัะฐ ะฟั€ะธะปะพะถะตะฝะธั * Created by kolesnik on 11/04/2017. */ public class RootLayoutController { private MainApp mainApp; private Label lblDBInfo; private Label lblTotalCountInfo; @FXML private StatusBar sbMain; @FXML private void handleExit() { System.exit(0); } @FXML private void handleSyncLib() { showInfo("ะกะธะฝั…ั€ะพะฝะธะทะฐั†ะธั....", ""); } public void initControls() { lblDBInfo = new Label(String.format(DB_NAME_INFO, DB_NAME)); lblTotalCountInfo = new Label(String.format(COUNT_RECORD_INFO, BookService.getBookCount())); sbMain.getRightItems().add(new Separator(VERTICAL)); sbMain.getRightItems().add(lblTotalCountInfo); sbMain.getRightItems().add(new Separator(VERTICAL)); sbMain.getRightItems().add(lblDBInfo); } public void setMainApp(MainApp mainApp) { this.mainApp = mainApp; } public void setStatusInfo(String msg) { sbMain.setText(msg); } public void setDBInfo(String msg) { lblDBInfo.setText(msg); } public void setTotalCountInfo(String msg) { lblTotalCountInfo.setText(msg); } }
1,811
0.703872
0.698747
66
25.60606
22.88567
100
false
false
0
0
0
0
0
0
0.469697
false
false
3
65809ba5c9dd6adf7e987c7d76f393aa11f06506
17,695,265,278,757
970610a2ffe92b1e28ccf5c52cd18165448e9820
/src/main/java/faultdiagnosis/FaultDiagnosisMode3.java
54bd1016e8af9f4c44de410e2cfcec2d3ff97a5b
[]
no_license
Tarrei/LogFlash
https://github.com/Tarrei/LogFlash
f85106d469140b2b067d82024a8f7a649e3468b1
fe495d39a326513b07e3f75812b2b8b658a24e71
refs/heads/master
2023-03-26T14:21:30.970000
2020-09-24T13:55:49
2020-09-24T13:55:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package faultdiagnosis; import TCFGmodel.TCFG; import org.apache.flink.api.java.tuple.Tuple7; import java.util.List; import java.util.Map; public class FaultDiagnosisMode3 implements FaultDiagnosis{ @Override public double calProbability(double ti, double tj, double alphaji, long timeWindow, long delta) { return 0; } @Override public double calProbabilityOfCurrentEntry(List<Tuple7> logList, Map<String, Map<String, Double>> paramMatrix, long timeWindow, long delta) { return 0; } @Override public List<Tuple7> detectSuspiciousRequest(TCFG tcfg, List<Tuple7> logList) { return null; } @Override public Anomaly faultDiagnosisProcess(TCFG tcfg, List<Tuple7> tempList) { return null; } }
UTF-8
Java
774
java
FaultDiagnosisMode3.java
Java
[]
null
[]
package faultdiagnosis; import TCFGmodel.TCFG; import org.apache.flink.api.java.tuple.Tuple7; import java.util.List; import java.util.Map; public class FaultDiagnosisMode3 implements FaultDiagnosis{ @Override public double calProbability(double ti, double tj, double alphaji, long timeWindow, long delta) { return 0; } @Override public double calProbabilityOfCurrentEntry(List<Tuple7> logList, Map<String, Map<String, Double>> paramMatrix, long timeWindow, long delta) { return 0; } @Override public List<Tuple7> detectSuspiciousRequest(TCFG tcfg, List<Tuple7> logList) { return null; } @Override public Anomaly faultDiagnosisProcess(TCFG tcfg, List<Tuple7> tempList) { return null; } }
774
0.710594
0.700258
30
24.799999
34.139324
145
false
false
0
0
0
0
0
0
0.666667
false
false
3
796428688a88da734a87e87e6a72baf1894bb21f
21,784,074,151,774
7983039bb5d02aded648572d6b9b49ceb8879e67
/LiteLoader/trunk/java/common/com/mumfrey/liteloader/core/Containers.java
4238d5a6378f33c0f2d6aaf4032a15e7305827cd
[]
no_license
svn2github/liteloader
https://github.com/svn2github/liteloader
251faf2c428f1b900e0f7b0a369c6b48ae9fe8ab
5f936435fcade2dd8dfbfe5904f6be92a766eb25
refs/heads/master
2021-01-19T17:17:34.912000
2015-09-09T10:36:19
2015-09-09T10:36:19
41,661,022
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mumfrey.liteloader.core; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.mumfrey.liteloader.api.ContainerRegistry; import com.mumfrey.liteloader.interfaces.Loadable; import com.mumfrey.liteloader.interfaces.LoadableMod; import com.mumfrey.liteloader.interfaces.TweakContainer; /** * Implementation of ContainerRegistry for LiteLoaderEnumerator * * @author Adam Mummery-Smith */ class Containers implements ContainerRegistry { /** * Mod containers which are disabled */ private final Map<String, ModInfo<Loadable<?>>> disabledContainers = new HashMap<String, ModInfo<Loadable<?>>>(); /** * Mapping of identifiers to mod containers */ private final Map<String, LoadableMod<?>> enabledContainers = new HashMap<String, LoadableMod<?>>(); /** * Map of containers which cannot be loaded to reasons */ private final Set<ModInfo<Loadable<?>>> badContainers = new HashSet<ModInfo<Loadable<?>>>(); /** * Tweaks to inject */ private final List<TweakContainer<File>> tweakContainers = new ArrayList<TweakContainer<File>>(); /** * Other tweak-containing jars which we have injected */ private final List<ModInfo<Loadable<?>>> injectedTweaks = new ArrayList<ModInfo<Loadable<?>>>(); /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getDisabledContainers() */ @Override public Collection<? extends ModInfo<Loadable<?>>> getDisabledContainers() { return this.disabledContainers.values(); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getEnabledContainers() */ @Override public Collection<? extends LoadableMod<?>> getEnabledContainers() { return this.enabledContainers.values(); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getBadContainers() */ @Override public Collection<? extends ModInfo<Loadable<?>>> getBadContainers() { return this.badContainers; } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getTweakContainers() */ @Override public List<TweakContainer<File>> getTweakContainers() { return this.tweakContainers; } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getInjectedTweaks() */ @Override public List<? extends ModInfo<Loadable<?>>> getInjectedTweaks() { return this.injectedTweaks; } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#isDisabledContainer(com.mumfrey.liteloader.interfaces.LoadableMod) */ @Override public boolean isDisabledContainer(LoadableMod<?> container) { return this.disabledContainers.containsValue(container); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getEnabledContainer(java.lang.String) */ @Override public LoadableMod<?> getEnabledContainer(String identifier) { LoadableMod<?> container = this.enabledContainers.get(identifier); return container != null ? container : LoadableMod.NONE; } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#registerBadContainer(com.mumfrey.liteloader.interfaces.Loadable, java.lang.String) */ @Override public void registerBadContainer(Loadable<?> container, String reason) { this.badContainers.add(new BadContainerInfo(container, reason)); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#registerEnabledContainer(com.mumfrey.liteloader.interfaces.LoadableMod) */ @Override public void registerEnabledContainer(LoadableMod<?> container) { this.disabledContainers.remove(container.getIdentifier()); this.enabledContainers.put(container.getIdentifier(), container); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#registerDisabledContainer(com.mumfrey.liteloader.interfaces.LoadableMod, com.mumfrey.liteloader.api.ContainerRegistry.DisabledReason) */ @Override public void registerDisabledContainer(LoadableMod<?> container, DisabledReason reason) { this.enabledContainers.remove(container.getIdentifier()); this.disabledContainers.put(container.getIdentifier(), new NonMod(container, false)); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#registerTweakContainer(com.mumfrey.liteloader.interfaces.TweakContainer) */ @Override public void registerTweakContainer(TweakContainer<File> container) { this.tweakContainers.add(container); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#registerInjectedTweak(com.mumfrey.liteloader.interfaces.TweakContainer) */ @Override public void registerInjectedTweak(TweakContainer<File> container) { this.injectedTweaks.add(new NonMod(container, true)); } }
UTF-8
Java
4,958
java
Containers.java
Java
[ { "context": "Registry for LiteLoaderEnumerator\r\n * \r\n * @author Adam Mummery-Smith\r\n */\r\nclass Containers implements ContainerRegist", "end": 572, "score": 0.9995613694190979, "start": 554, "tag": "NAME", "value": "Adam Mummery-Smith" } ]
null
[]
package com.mumfrey.liteloader.core; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.mumfrey.liteloader.api.ContainerRegistry; import com.mumfrey.liteloader.interfaces.Loadable; import com.mumfrey.liteloader.interfaces.LoadableMod; import com.mumfrey.liteloader.interfaces.TweakContainer; /** * Implementation of ContainerRegistry for LiteLoaderEnumerator * * @author <NAME> */ class Containers implements ContainerRegistry { /** * Mod containers which are disabled */ private final Map<String, ModInfo<Loadable<?>>> disabledContainers = new HashMap<String, ModInfo<Loadable<?>>>(); /** * Mapping of identifiers to mod containers */ private final Map<String, LoadableMod<?>> enabledContainers = new HashMap<String, LoadableMod<?>>(); /** * Map of containers which cannot be loaded to reasons */ private final Set<ModInfo<Loadable<?>>> badContainers = new HashSet<ModInfo<Loadable<?>>>(); /** * Tweaks to inject */ private final List<TweakContainer<File>> tweakContainers = new ArrayList<TweakContainer<File>>(); /** * Other tweak-containing jars which we have injected */ private final List<ModInfo<Loadable<?>>> injectedTweaks = new ArrayList<ModInfo<Loadable<?>>>(); /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getDisabledContainers() */ @Override public Collection<? extends ModInfo<Loadable<?>>> getDisabledContainers() { return this.disabledContainers.values(); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getEnabledContainers() */ @Override public Collection<? extends LoadableMod<?>> getEnabledContainers() { return this.enabledContainers.values(); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getBadContainers() */ @Override public Collection<? extends ModInfo<Loadable<?>>> getBadContainers() { return this.badContainers; } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getTweakContainers() */ @Override public List<TweakContainer<File>> getTweakContainers() { return this.tweakContainers; } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getInjectedTweaks() */ @Override public List<? extends ModInfo<Loadable<?>>> getInjectedTweaks() { return this.injectedTweaks; } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#isDisabledContainer(com.mumfrey.liteloader.interfaces.LoadableMod) */ @Override public boolean isDisabledContainer(LoadableMod<?> container) { return this.disabledContainers.containsValue(container); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#getEnabledContainer(java.lang.String) */ @Override public LoadableMod<?> getEnabledContainer(String identifier) { LoadableMod<?> container = this.enabledContainers.get(identifier); return container != null ? container : LoadableMod.NONE; } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#registerBadContainer(com.mumfrey.liteloader.interfaces.Loadable, java.lang.String) */ @Override public void registerBadContainer(Loadable<?> container, String reason) { this.badContainers.add(new BadContainerInfo(container, reason)); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#registerEnabledContainer(com.mumfrey.liteloader.interfaces.LoadableMod) */ @Override public void registerEnabledContainer(LoadableMod<?> container) { this.disabledContainers.remove(container.getIdentifier()); this.enabledContainers.put(container.getIdentifier(), container); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#registerDisabledContainer(com.mumfrey.liteloader.interfaces.LoadableMod, com.mumfrey.liteloader.api.ContainerRegistry.DisabledReason) */ @Override public void registerDisabledContainer(LoadableMod<?> container, DisabledReason reason) { this.enabledContainers.remove(container.getIdentifier()); this.disabledContainers.put(container.getIdentifier(), new NonMod(container, false)); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#registerTweakContainer(com.mumfrey.liteloader.interfaces.TweakContainer) */ @Override public void registerTweakContainer(TweakContainer<File> container) { this.tweakContainers.add(container); } /* (non-Javadoc) * @see com.mumfrey.liteloader.api.ContainerRegistry#registerInjectedTweak(com.mumfrey.liteloader.interfaces.TweakContainer) */ @Override public void registerInjectedTweak(TweakContainer<File> container) { this.injectedTweaks.add(new NonMod(container, true)); } }
4,946
0.736789
0.736789
159
29.18239
35.936501
187
false
false
0
0
0
0
0
0
1.169811
false
false
3
cd9dbe69a9cb942614bf5e1c93b74e0534d4ab99
25,563,645,355,889
11dd04d13180cab5b68db8338c982e3c8742a6eb
/app/src/main/java/com/app/mcworlduser/Activities/OrderHistoryActivity.java
4b5066f560c559ddf3e8bf2bb8c8d44e0c695a95
[]
no_license
abhilashasharma2021/MC-World-User
https://github.com/abhilashasharma2021/MC-World-User
a0a60553fd5c700cb012c73187aaf8efe5d29cac
b01167677987dca5882d4c6d8bf354352da26437
refs/heads/master
2023-04-12T16:02:12.486000
2021-05-05T05:46:05
2021-05-05T05:46:05
364,473,382
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.mcworlduser.Activities; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONArrayRequestListener; import com.app.mcworlduser.Adapters.OrderHistoryAdapter; import com.app.mcworlduser.OrderHistoryModal; import com.app.mcworlduser.R; import com.app.mcworlduser.Api; import com.app.mcworlduser.AppConstant; import com.facebook.shimmer.ShimmerFrameLayout; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; public class OrderHistoryActivity extends AppCompatActivity { RecyclerView recycler_order_hostory; LinearLayoutManager layoutManager; ImageView img_back; private ShimmerFrameLayout shimmerView; OrderHistoryAdapter orderHistoryAdapter; ArrayList<OrderHistoryModal> orderhistoryArrayList = new ArrayList<>(); String strUserId=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_history); getSupportActionBar().hide(); AppConstant.sharedpreferences =getSharedPreferences(AppConstant.MyPREFERENCES, Context.MODE_PRIVATE); strUserId = AppConstant.sharedpreferences.getString(AppConstant.Userid, ""); Log.e("fdgvfd",strUserId); recycler_order_hostory = findViewById(R.id.recycler_order_hostory); shimmerView = findViewById(R.id.shimmerView); img_back = findViewById(R.id.img_back); img_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); layoutManager = new LinearLayoutManager(OrderHistoryActivity.this, RecyclerView.VERTICAL, false); recycler_order_hostory.setLayoutManager(layoutManager); recycler_order_hostory.setHasFixedSize(true); ShowHistory(); } public void ShowHistory() { Log.e("dkjdfj",strUserId); shimmerView.startShimmerAnimation(); AndroidNetworking.post(Api.serverLink) .addBodyParameter("control","show_user_orders") .addBodyParameter("user_id",strUserId) .setTag("History") .setPriority(Priority.HIGH) .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { Log.e("tgfrdgf", response.toString()); try { orderhistoryArrayList = new ArrayList<>(); for (int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.getJSONObject(i); String id_new=jsonObject.getString("id"); String user_id=jsonObject.getString("user_id"); String order_id=jsonObject.getString("order_id"); String total_amount=jsonObject.getString("total_amount"); String status=jsonObject.getString("status"); String address=jsonObject.getString("address"); String latitude=jsonObject.getString("latitude"); String longitude=jsonObject.getString("longitude"); String order_type=jsonObject.getString("order_type"); String product=jsonObject.getString("product"); JSONArray jsonArray=new JSONArray(product); for (int j=0;j<jsonArray.length();j++){ JSONObject object=jsonArray.getJSONObject(j); String id=object.getString("id"); String shop_id=object.getString("shop_id"); String name=object.getString("name"); String price=object.getString("price"); String stock=object.getString("stock"); String category_id=object.getString("category_id"); String image=object.getString("image"); String description=object.getString("description"); String gst=object.getString("gst"); String total_price=object.getString("total_price"); String status1=object.getString("status"); String category_name=object.getString("category_name"); String cart_quantity=object.getString("cart_quantity"); String cart_price=object.getString("cart_price"); String path=object.getString("path"); String cart_order_date=object.getString("cart_order_date"); String cart_order_id=object.getString("cart_order_id"); String cart_totalprice=object.getString("cart_totalprice"); OrderHistoryModal orderModel = new OrderHistoryModal(); orderModel.setId(jsonObject.getString("id")); orderModel.setName(object.getString("name"));/*Veg*/ orderModel.setPath(object.getString("path")); orderModel.setImage(object.getString("image")); orderModel.setTotalAmount(jsonObject.getString("total_amount")); orderModel.setOrderId(object.getString("cart_order_id")); orderModel.setOrderDate(object.getString("cart_order_date")); orderhistoryArrayList.add(orderModel); } } if (response.length()==0){ } else{ orderHistoryAdapter = new OrderHistoryAdapter(orderhistoryArrayList, OrderHistoryActivity.this); recycler_order_hostory.setAdapter(orderHistoryAdapter); shimmerView.stopShimmerAnimation(); shimmerView.setVisibility(View.GONE); recycler_order_hostory.setVisibility(View.VISIBLE); } } catch (Exception ex) { Log.e("sdfgdg", ex.getMessage()); } } @Override public void onError(ANError anError) { Log.e("dfdgf", anError.getMessage()); } }); } }
UTF-8
Java
7,534
java
OrderHistoryActivity.java
Java
[]
null
[]
package com.app.mcworlduser.Activities; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONArrayRequestListener; import com.app.mcworlduser.Adapters.OrderHistoryAdapter; import com.app.mcworlduser.OrderHistoryModal; import com.app.mcworlduser.R; import com.app.mcworlduser.Api; import com.app.mcworlduser.AppConstant; import com.facebook.shimmer.ShimmerFrameLayout; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; public class OrderHistoryActivity extends AppCompatActivity { RecyclerView recycler_order_hostory; LinearLayoutManager layoutManager; ImageView img_back; private ShimmerFrameLayout shimmerView; OrderHistoryAdapter orderHistoryAdapter; ArrayList<OrderHistoryModal> orderhistoryArrayList = new ArrayList<>(); String strUserId=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_history); getSupportActionBar().hide(); AppConstant.sharedpreferences =getSharedPreferences(AppConstant.MyPREFERENCES, Context.MODE_PRIVATE); strUserId = AppConstant.sharedpreferences.getString(AppConstant.Userid, ""); Log.e("fdgvfd",strUserId); recycler_order_hostory = findViewById(R.id.recycler_order_hostory); shimmerView = findViewById(R.id.shimmerView); img_back = findViewById(R.id.img_back); img_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); layoutManager = new LinearLayoutManager(OrderHistoryActivity.this, RecyclerView.VERTICAL, false); recycler_order_hostory.setLayoutManager(layoutManager); recycler_order_hostory.setHasFixedSize(true); ShowHistory(); } public void ShowHistory() { Log.e("dkjdfj",strUserId); shimmerView.startShimmerAnimation(); AndroidNetworking.post(Api.serverLink) .addBodyParameter("control","show_user_orders") .addBodyParameter("user_id",strUserId) .setTag("History") .setPriority(Priority.HIGH) .build() .getAsJSONArray(new JSONArrayRequestListener() { @Override public void onResponse(JSONArray response) { Log.e("tgfrdgf", response.toString()); try { orderhistoryArrayList = new ArrayList<>(); for (int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.getJSONObject(i); String id_new=jsonObject.getString("id"); String user_id=jsonObject.getString("user_id"); String order_id=jsonObject.getString("order_id"); String total_amount=jsonObject.getString("total_amount"); String status=jsonObject.getString("status"); String address=jsonObject.getString("address"); String latitude=jsonObject.getString("latitude"); String longitude=jsonObject.getString("longitude"); String order_type=jsonObject.getString("order_type"); String product=jsonObject.getString("product"); JSONArray jsonArray=new JSONArray(product); for (int j=0;j<jsonArray.length();j++){ JSONObject object=jsonArray.getJSONObject(j); String id=object.getString("id"); String shop_id=object.getString("shop_id"); String name=object.getString("name"); String price=object.getString("price"); String stock=object.getString("stock"); String category_id=object.getString("category_id"); String image=object.getString("image"); String description=object.getString("description"); String gst=object.getString("gst"); String total_price=object.getString("total_price"); String status1=object.getString("status"); String category_name=object.getString("category_name"); String cart_quantity=object.getString("cart_quantity"); String cart_price=object.getString("cart_price"); String path=object.getString("path"); String cart_order_date=object.getString("cart_order_date"); String cart_order_id=object.getString("cart_order_id"); String cart_totalprice=object.getString("cart_totalprice"); OrderHistoryModal orderModel = new OrderHistoryModal(); orderModel.setId(jsonObject.getString("id")); orderModel.setName(object.getString("name"));/*Veg*/ orderModel.setPath(object.getString("path")); orderModel.setImage(object.getString("image")); orderModel.setTotalAmount(jsonObject.getString("total_amount")); orderModel.setOrderId(object.getString("cart_order_id")); orderModel.setOrderDate(object.getString("cart_order_date")); orderhistoryArrayList.add(orderModel); } } if (response.length()==0){ } else{ orderHistoryAdapter = new OrderHistoryAdapter(orderhistoryArrayList, OrderHistoryActivity.this); recycler_order_hostory.setAdapter(orderHistoryAdapter); shimmerView.stopShimmerAnimation(); shimmerView.setVisibility(View.GONE); recycler_order_hostory.setVisibility(View.VISIBLE); } } catch (Exception ex) { Log.e("sdfgdg", ex.getMessage()); } } @Override public void onError(ANError anError) { Log.e("dfdgf", anError.getMessage()); } }); } }
7,534
0.541678
0.541147
171
43.064327
33.105034
128
false
false
0
0
0
0
0
0
0.654971
false
false
3
fc73aeb8971a63dda3584609968a7da7a01f087c
6,279,242,205,022
2cb499e4be6ce34054bf854793f0c34716180359
/module2/src/bai12_java_collection_frameword/thuc_hanh/bai4_tim_kiem_cay_nhi_phan/Tree.java
cc0f0865b54e4c254fa90c17ef8d463dff10065b
[]
no_license
nhutam123/C0221G1-le-nhu-tam
https://github.com/nhutam123/C0221G1-le-nhu-tam
3b1398583e778cec1c232ce72a562daf1778398e
549304e82500a5094a91e332dc8a23213ffca80b
refs/heads/main
2023-07-12T01:06:09.316000
2021-08-11T10:35:45
2021-08-11T10:35:45
342,120,462
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bai12_java_collection_frameword.thuc_hanh.bai4_tim_kiem_cay_nhi_phan; public interface Tree<E> { public boolean insert(E e); public void inorder(); public int getSize(); }
UTF-8
Java
195
java
Tree.java
Java
[]
null
[]
package bai12_java_collection_frameword.thuc_hanh.bai4_tim_kiem_cay_nhi_phan; public interface Tree<E> { public boolean insert(E e); public void inorder(); public int getSize(); }
195
0.707692
0.692308
8
23.375
23.848152
77
false
false
0
0
0
0
0
0
0.5
false
false
3