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
c8df1ca5cb6f98d676d1de1fc86235baf5579717
36,996,848,312,936
99161cac529ddf13fc5ff7498bff172c6e7d1380
/src/Servlet/GoodsByClassify.java
832dec6ccbf297bf0605149bd0841da15abfdb1e
[]
no_license
linlianyu/MiShop
https://github.com/linlianyu/MiShop
27230b77b4cef672b9632f8097d600e2feffc990
4937c7c58ef92a35a7aa9a7d26cb2d8864ef118b
refs/heads/master
2018-11-01T15:48:47.905000
2018-08-24T16:38:33
2018-08-24T16:38:33
142,085,041
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Servlet; import Data.GoodsInfo; import Tools.DataBaseOperation; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * 分类中的商品 */ @WebServlet("/goodsByClassify") public class GoodsByClassify extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DataBaseOperation db = new DataBaseOperation(); //分类id int classifyId = Integer.parseInt(request.getParameter("classify_id")); //通过分类id取出分类名 String classifyName = db.searchClassifyNameByClassifyId(classifyId); //通过分类名找出分类中的所有商品的集合 List<GoodsInfo> goodsInfoList = db.searchGoodsByClassify(classifyName); request.setAttribute("classifyName",classifyName); request.setAttribute("goodsInfoList",goodsInfoList); request.getRequestDispatcher("GoodsByClassify.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
UTF-8
Java
1,361
java
GoodsByClassify.java
Java
[]
null
[]
package Servlet; import Data.GoodsInfo; import Tools.DataBaseOperation; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * 分类中的商品 */ @WebServlet("/goodsByClassify") public class GoodsByClassify extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DataBaseOperation db = new DataBaseOperation(); //分类id int classifyId = Integer.parseInt(request.getParameter("classify_id")); //通过分类id取出分类名 String classifyName = db.searchClassifyNameByClassifyId(classifyId); //通过分类名找出分类中的所有商品的集合 List<GoodsInfo> goodsInfoList = db.searchGoodsByClassify(classifyName); request.setAttribute("classifyName",classifyName); request.setAttribute("goodsInfoList",goodsInfoList); request.getRequestDispatcher("GoodsByClassify.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
1,361
0.771495
0.771495
35
35.885715
31.532089
120
false
false
0
0
0
0
0
0
3.485714
false
false
12
9b680f49c51a0c41674257b6a48eb0f73e9a4ada
39,608,188,414,874
c79949f6d110a41ed1d8dca59128c4b017dbd316
/Kakfka-Assignment/src/main/java/com/knoldus/UserPojo/User.java
c3fb77f9c31e7a26ad1bb4f50370ff5bc8100365
[]
no_license
shashankgoyal-sre/sml-dj-vwe
https://github.com/shashankgoyal-sre/sml-dj-vwe
44dbf1337c92c3a45c84e38db14df398576d18ad
c8cc69fc94663842b76a9db27ef8f4ece199035f
refs/heads/main
2023-03-29T11:09:53.327000
2021-03-10T05:10:39
2021-03-10T05:10:39
337,062,901
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.knoldus.UserPojo; public class User { //User class fields private int user_id; private int user_age; private String user_name; private String user_course; //Default Constructor public User() { } //Arg-constructor to initialize fields public User(int user_id, int age, String user_name, String user_course) { this.user_id = user_id; this.user_age = age; this.user_name = user_name; this.user_course = user_course; } //Getters for user class fields public int getUser_id() { return user_id; } public int getUser_age() { return user_age; } public String getUser_name() { return user_name; } public String getUser_course() { return user_course; } //Overriding the default toString() method according the output format we want from our project, @Override public String toString() { return "User Message{"+"\"id\":" + '"'+user_id+'"' + ",\"name\":" + '"'+user_name+'"' + ",\"age\":" + '"'+user_age+'"' + ",\"course\":" + '"'+user_course+'"' + "}"; } }
UTF-8
Java
1,150
java
User.java
Java
[ { "context": " this.user_age = age;\n this.user_name = user_name;\n this.user_course = user_course;\n\n }\n\n", "end": 471, "score": 0.7717493176460266, "start": 462, "tag": "NAME", "value": "user_name" }, { "context": "+\"\\\"id\\\":\" + '\"'+user_id+'\"' + \",\\\"name\\\":\" + '\"'+user_name+'\"' + \",\\\"age\\\":\" + '\"'+user_age+'\"' + \",\\\"c", "end": 1050, "score": 0.795937716960907, "start": 1046, "tag": "NAME", "value": "user" } ]
null
[]
package com.knoldus.UserPojo; public class User { //User class fields private int user_id; private int user_age; private String user_name; private String user_course; //Default Constructor public User() { } //Arg-constructor to initialize fields public User(int user_id, int age, String user_name, String user_course) { this.user_id = user_id; this.user_age = age; this.user_name = user_name; this.user_course = user_course; } //Getters for user class fields public int getUser_id() { return user_id; } public int getUser_age() { return user_age; } public String getUser_name() { return user_name; } public String getUser_course() { return user_course; } //Overriding the default toString() method according the output format we want from our project, @Override public String toString() { return "User Message{"+"\"id\":" + '"'+user_id+'"' + ",\"name\":" + '"'+user_name+'"' + ",\"age\":" + '"'+user_age+'"' + ",\"course\":" + '"'+user_course+'"' + "}"; } }
1,150
0.569565
0.569565
60
18.166666
27.785587
173
false
false
0
0
0
0
0
0
0.35
false
false
12
c95e3bea4cc88461afef314d333651f4f4ad2618
34,866,544,561,565
4db048132ade6f26a079f47900a4f655faf6ef04
/JiraPlugins/atlassian-jira-4.4.3-source/jira-project/jira-func-tests/src/main/java/com/atlassian/jira/webtests/ztests/plugin/reloadable/TestReportModuleReloadability.java
84b4c8714eee0ffce26b4540da678df222a49c58
[]
no_license
JCVI-VIRIFX/SampleTracking
https://github.com/JCVI-VIRIFX/SampleTracking
045f3a690161cd6735dda6cf53964a89910c2d32
8f68cf385a083dcef055605dc040a224576a16fe
refs/heads/master
2018-01-07T23:30:42.211000
2015-12-11T04:23:38
2015-12-11T04:23:38
47,804,829
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atlassian.jira.webtests.ztests.plugin.reloadable; import com.atlassian.jira.functest.framework.suite.Category; import com.atlassian.jira.functest.framework.suite.WebTest; /** * <p> * Test verifying that a report defined within a module can be enabled and disabled any number of times. * * <p> * This scenario assumes that the module has never been enabled and that the plugin is loaded in a disabled state when * JIRA starts up. * * @since v4.3 */ @WebTest ({ Category.FUNC_TEST, Category.RELOADABLE_PLUGINS, Category.REFERENCE_PLUGIN }) public class TestReportModuleReloadability extends AbstractReloadablePluginsTest { private static final String ISSUE_COUNT_BY_PROJECT = "Issue count by Project"; public void testReportModulePluginZeroToOn() throws Exception { shouldNotExistAndBeAccessibleBeforeEnablingThePlugin(); shouldBeAccessibleAfterEnablingTheReferencePlugin(); } private void shouldNotExistAndBeAccessibleBeforeEnablingThePlugin() throws Exception { assertPluginReportNotAccessible(); } private void shouldBeAccessibleAfterEnablingTheReferencePlugin() throws Exception { administration.plugins().referencePlugin().enable(); assertPluginReportAccessible(); } public void testReportModulePlugin() throws Exception { administration.plugins().referencePlugin().enable(); navigation.issue().createIssue("homosapien",ISSUE_TYPE_BUG,"Just a simple bug"); goToProject(); tester.clickLinkWithText(ISSUE_COUNT_BY_PROJECT); text.assertTextPresent(locator.css("td.fieldLabelArea"),"Project Key:"); tester.submit("Next"); text.assertTextPresent(locator.css("div.report"),"HSP has 1 issues"); } public void testReportPluginModuleAccessibilityAfterMultipleReferencePluginEnablingAndDisabling() { assertPluginReportNotAccessible(); administration.plugins().referencePlugin().enable(); assertPluginReportAccessible(); administration.plugins().referencePlugin().disable(); assertPluginReportNotAccessible(); administration.plugins().referencePlugin().enable(); assertPluginReportAccessible(); } public void testAccessibilityAfterReportPluginModuleEnablingAndDisabling() { administration.plugins().referencePlugin().enable(); assertPluginReportAccessible(); for (int i=0; i<3; i++) { disableReportPluginModule(); assertPluginReportNotAccessible(); enableReportPluginModule(); assertPluginReportAccessible(); } } private void assertPluginReportAccessible() { goToProject(); text.assertTextPresent(ISSUE_COUNT_BY_PROJECT); } private void assertPluginReportNotAccessible() { goToProject(); text.assertTextNotPresent(ISSUE_COUNT_BY_PROJECT); } private void goToProject() { navigation.browseProject("HSP"); } private void enableReportPluginModule() { administration.plugins().referencePlugin().enableModule(ReferencePluginConstants.REFERENCE_REPORT_KEY); } private void disableReportPluginModule() { administration.plugins().referencePlugin().disableModule(ReferencePluginConstants.REFERENCE_REPORT_KEY); } }
UTF-8
Java
3,462
java
TestReportModuleReloadability.java
Java
[]
null
[]
package com.atlassian.jira.webtests.ztests.plugin.reloadable; import com.atlassian.jira.functest.framework.suite.Category; import com.atlassian.jira.functest.framework.suite.WebTest; /** * <p> * Test verifying that a report defined within a module can be enabled and disabled any number of times. * * <p> * This scenario assumes that the module has never been enabled and that the plugin is loaded in a disabled state when * JIRA starts up. * * @since v4.3 */ @WebTest ({ Category.FUNC_TEST, Category.RELOADABLE_PLUGINS, Category.REFERENCE_PLUGIN }) public class TestReportModuleReloadability extends AbstractReloadablePluginsTest { private static final String ISSUE_COUNT_BY_PROJECT = "Issue count by Project"; public void testReportModulePluginZeroToOn() throws Exception { shouldNotExistAndBeAccessibleBeforeEnablingThePlugin(); shouldBeAccessibleAfterEnablingTheReferencePlugin(); } private void shouldNotExistAndBeAccessibleBeforeEnablingThePlugin() throws Exception { assertPluginReportNotAccessible(); } private void shouldBeAccessibleAfterEnablingTheReferencePlugin() throws Exception { administration.plugins().referencePlugin().enable(); assertPluginReportAccessible(); } public void testReportModulePlugin() throws Exception { administration.plugins().referencePlugin().enable(); navigation.issue().createIssue("homosapien",ISSUE_TYPE_BUG,"Just a simple bug"); goToProject(); tester.clickLinkWithText(ISSUE_COUNT_BY_PROJECT); text.assertTextPresent(locator.css("td.fieldLabelArea"),"Project Key:"); tester.submit("Next"); text.assertTextPresent(locator.css("div.report"),"HSP has 1 issues"); } public void testReportPluginModuleAccessibilityAfterMultipleReferencePluginEnablingAndDisabling() { assertPluginReportNotAccessible(); administration.plugins().referencePlugin().enable(); assertPluginReportAccessible(); administration.plugins().referencePlugin().disable(); assertPluginReportNotAccessible(); administration.plugins().referencePlugin().enable(); assertPluginReportAccessible(); } public void testAccessibilityAfterReportPluginModuleEnablingAndDisabling() { administration.plugins().referencePlugin().enable(); assertPluginReportAccessible(); for (int i=0; i<3; i++) { disableReportPluginModule(); assertPluginReportNotAccessible(); enableReportPluginModule(); assertPluginReportAccessible(); } } private void assertPluginReportAccessible() { goToProject(); text.assertTextPresent(ISSUE_COUNT_BY_PROJECT); } private void assertPluginReportNotAccessible() { goToProject(); text.assertTextNotPresent(ISSUE_COUNT_BY_PROJECT); } private void goToProject() { navigation.browseProject("HSP"); } private void enableReportPluginModule() { administration.plugins().referencePlugin().enableModule(ReferencePluginConstants.REFERENCE_REPORT_KEY); } private void disableReportPluginModule() { administration.plugins().referencePlugin().disableModule(ReferencePluginConstants.REFERENCE_REPORT_KEY); } }
3,462
0.689775
0.68833
99
32.969696
32.670517
118
false
false
0
0
0
0
83
0.023975
0.444444
false
false
12
dafb9da473fe04fd8dfdcf48cec5f1221707f55d
36,567,351,601,364
8d2cd540a7ac04404bedb0ffe8baf97e674f02da
/src/com/echo/voicewave/VoiceRecorder.java
cd5998a673880870c7b65316f7ff5b83e9da0705
[]
no_license
echohaha/VoiceWave
https://github.com/echohaha/VoiceWave
963c8a1bdf9fb0df5dc43be529d7b589ce43ca1b
4ff2bad1ab36a27e0dad8b6c054c7bad05eb3889
refs/heads/master
2015-09-25T12:51:50.403000
2015-08-08T03:12:47
2015-08-08T03:12:47
40,389,717
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.echo.voicewave; import android.media.MediaRecorder; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class VoiceRecorder { public static final String TAG = "VoiceRecorder:"; public static final String EXTENSION = ".amr"; public static final int VOICE_REFRESH = 0; public static final int VOICE_TIP = 1; public static final int VOICE_LONG = 2; private static final int MAX_VOICE_TIME = 60; public static float voice_position; private static VoiceRecorder mVoiceRecorder; private MediaRecorder mRecorder; private File mRecordFile; private RecordTimer mVoiceTimer; private RecordTimer mRemainTimer; private boolean isRecording = false; private int mVoiceDuration = -1; private SimpleDateFormat mFormat = new SimpleDateFormat("yyyMMddHHmmssSSS"); public static VoiceRecorder getInstance() { if(mVoiceRecorder == null){ synchronized(VoiceRecorder.class){ if(mVoiceRecorder == null){ mVoiceRecorder = new VoiceRecorder(); } } } return mVoiceRecorder; } private abstract class RecordTimer extends Thread { private boolean isCancel = false; @Override public void run() { while (!isCancel) { doTask(); } } public abstract void doTask(); public void cancel() { isCancel = true; } } private VoiceRecorder() { } private void reSetVoiceDefault() { this.isRecording = false; this.mVoiceDuration = -1; this.mRecordFile = null; this.mVoiceTimer = null; this.mRemainTimer = null; } public boolean isRecording() { return isRecording; } public void startRecording() { try { if(isRecording) discardRecording(); isRecording = true; mRecordFile = new File(getVoiceOutPutPath()); mRecorder = new MediaRecorder(); mRecorder.setAudioSource(1); mRecorder.setOutputFormat(3); mRecorder.setAudioEncoder(1); mRecorder.setAudioChannels(1); mRecorder.setAudioSamplingRate(8000); mRecorder.setAudioEncodingBitRate(64); mRecorder.setOutputFile(mRecordFile.getAbsolutePath()); mRecorder.prepare(); mRecorder.start(); } catch (IOException localIOException) { reSetVoiceDefault(); } initTimer(); } //鍙栨秷褰曢煶 public void discardRecording() { if (mRecorder != null) { try { mRecorder.stop(); mRecorder.release(); mRecorder = null; if ((mRecordFile != null) && (mRecordFile.exists()) && (!mRecordFile.isDirectory())) { mRecordFile.delete(); } if(mVoiceTimer != null) { mVoiceTimer.cancel(); } if(mRemainTimer != null) { mRemainTimer.cancel(); } } catch (IllegalStateException localIllegalStateException) { } reSetVoiceDefault(); } } public String stopRecoding() { if (mRecorder != null) { try { mRecorder.stop(); } catch (Exception e) { }finally{ mRecorder.release(); mRecorder = null; if(mVoiceTimer != null) { mVoiceTimer.cancel(); } if(mRemainTimer != null) { mRemainTimer.cancel(); } } String fileName = getVoiceFileNameWithDuration(mVoiceDuration); reSetVoiceDefault(); return fileName; } else { reSetVoiceDefault(); return null; } } private void initTimer() { mVoiceTimer = new RecordTimer() { @Override public void doTask() { try { while (isRecording && mRecorder != null) { double ratio = (double) mRecorder.getMaxAmplitude(); if (ratio > 1) { voice_position = (float) (20 * Math.log10(ratio*ratio)) / 5 - 5; if(voice_position < 15) voice_position = voice_position / 2; } Log.d("bobo", voice_position+""); mVoiceTimer.sleep(200); } } catch (Exception localException) { } } }; mVoiceTimer.start(); } private String getVoiceFileNameWithDuration(int length) { if(mRecordFile != null) { String fileName = mRecordFile.getAbsolutePath().split(EXTENSION)[0] + "_" + length + EXTENSION; mRecordFile.renameTo(new File(fileName)); return fileName; } else return null; } private String getVoiceOutPutPath() { String outPutPath = Environment.getExternalStorageDirectory() + "/" + mFormat.format(new Date()) + EXTENSION; return outPutPath; } }
UTF-8
Java
5,506
java
VoiceRecorder.java
Java
[ { "context": "lt();\n }\n initTimer();\n }\n\n //鍙栨秷褰曢煶\n public void discardRecording() {\n if (", "end": 2717, "score": 0.850275993347168, "start": 2711, "tag": "NAME", "value": "鍙栨秷褰曢煶" } ]
null
[]
package com.echo.voicewave; import android.media.MediaRecorder; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class VoiceRecorder { public static final String TAG = "VoiceRecorder:"; public static final String EXTENSION = ".amr"; public static final int VOICE_REFRESH = 0; public static final int VOICE_TIP = 1; public static final int VOICE_LONG = 2; private static final int MAX_VOICE_TIME = 60; public static float voice_position; private static VoiceRecorder mVoiceRecorder; private MediaRecorder mRecorder; private File mRecordFile; private RecordTimer mVoiceTimer; private RecordTimer mRemainTimer; private boolean isRecording = false; private int mVoiceDuration = -1; private SimpleDateFormat mFormat = new SimpleDateFormat("yyyMMddHHmmssSSS"); public static VoiceRecorder getInstance() { if(mVoiceRecorder == null){ synchronized(VoiceRecorder.class){ if(mVoiceRecorder == null){ mVoiceRecorder = new VoiceRecorder(); } } } return mVoiceRecorder; } private abstract class RecordTimer extends Thread { private boolean isCancel = false; @Override public void run() { while (!isCancel) { doTask(); } } public abstract void doTask(); public void cancel() { isCancel = true; } } private VoiceRecorder() { } private void reSetVoiceDefault() { this.isRecording = false; this.mVoiceDuration = -1; this.mRecordFile = null; this.mVoiceTimer = null; this.mRemainTimer = null; } public boolean isRecording() { return isRecording; } public void startRecording() { try { if(isRecording) discardRecording(); isRecording = true; mRecordFile = new File(getVoiceOutPutPath()); mRecorder = new MediaRecorder(); mRecorder.setAudioSource(1); mRecorder.setOutputFormat(3); mRecorder.setAudioEncoder(1); mRecorder.setAudioChannels(1); mRecorder.setAudioSamplingRate(8000); mRecorder.setAudioEncodingBitRate(64); mRecorder.setOutputFile(mRecordFile.getAbsolutePath()); mRecorder.prepare(); mRecorder.start(); } catch (IOException localIOException) { reSetVoiceDefault(); } initTimer(); } //鍙栨秷褰曢煶 public void discardRecording() { if (mRecorder != null) { try { mRecorder.stop(); mRecorder.release(); mRecorder = null; if ((mRecordFile != null) && (mRecordFile.exists()) && (!mRecordFile.isDirectory())) { mRecordFile.delete(); } if(mVoiceTimer != null) { mVoiceTimer.cancel(); } if(mRemainTimer != null) { mRemainTimer.cancel(); } } catch (IllegalStateException localIllegalStateException) { } reSetVoiceDefault(); } } public String stopRecoding() { if (mRecorder != null) { try { mRecorder.stop(); } catch (Exception e) { }finally{ mRecorder.release(); mRecorder = null; if(mVoiceTimer != null) { mVoiceTimer.cancel(); } if(mRemainTimer != null) { mRemainTimer.cancel(); } } String fileName = getVoiceFileNameWithDuration(mVoiceDuration); reSetVoiceDefault(); return fileName; } else { reSetVoiceDefault(); return null; } } private void initTimer() { mVoiceTimer = new RecordTimer() { @Override public void doTask() { try { while (isRecording && mRecorder != null) { double ratio = (double) mRecorder.getMaxAmplitude(); if (ratio > 1) { voice_position = (float) (20 * Math.log10(ratio*ratio)) / 5 - 5; if(voice_position < 15) voice_position = voice_position / 2; } Log.d("bobo", voice_position+""); mVoiceTimer.sleep(200); } } catch (Exception localException) { } } }; mVoiceTimer.start(); } private String getVoiceFileNameWithDuration(int length) { if(mRecordFile != null) { String fileName = mRecordFile.getAbsolutePath().split(EXTENSION)[0] + "_" + length + EXTENSION; mRecordFile.renameTo(new File(fileName)); return fileName; } else return null; } private String getVoiceOutPutPath() { String outPutPath = Environment.getExternalStorageDirectory() + "/" + mFormat.format(new Date()) + EXTENSION; return outPutPath; } }
5,506
0.527485
0.521842
186
28.537634
21.514715
118
false
false
0
0
0
0
0
0
0.456989
false
false
12
1e4883333a5ede2ae69b61f6c607d1536b413e75
35,381,940,622,944
982354a9df750b8845d1a40ea95e07060b07e992
/servlet_default/src/com/servlet/dao/MemberDAO.java
5c01b13adde7f4ef5d2331962fa8e13f9827d9f0
[]
no_license
Jung-Young-In/javaedu
https://github.com/Jung-Young-In/javaedu
1c5fbef7d1ed2f13449e6900e2dc735562804827
7cf6aaa8f84d41b8d70ec02030ae497ab87d0a6f
refs/heads/main
2023-07-13T01:08:59.383000
2021-08-19T02:23:06
2021-08-19T02:23:06
397,784,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.servlet.dao; import java.sql.SQLException; import com.servlet.dto.MemberVO; public interface MemberDAO { MemberVO selectMemberByID(String id) throws SQLException; }
UTF-8
Java
182
java
MemberDAO.java
Java
[]
null
[]
package com.servlet.dao; import java.sql.SQLException; import com.servlet.dto.MemberVO; public interface MemberDAO { MemberVO selectMemberByID(String id) throws SQLException; }
182
0.802198
0.802198
10
17.200001
19.056757
58
false
false
0
0
0
0
0
0
0.5
false
false
12
77ae7ecbedba06649887f3ecc8994fb5614b417f
34,230,889,403,672
57daa18b8718e0c2a38842ef21bff4bbc2342a47
/src/eu/romainpellerin/remotecontrolviasms/SmsReceiver.java
745d0d2cd28e0293d53ad47531eca358bd1b5b7e
[]
no_license
hvmunlimited/Remote-Control-via-SMS
https://github.com/hvmunlimited/Remote-Control-via-SMS
8aaa09ed330f5e7ec3dd5f2981858a7490498421
381afece418028f4304cdfb5571d415e12ed1d01
refs/heads/master
2021-01-18T11:33:44.087000
2014-07-19T18:23:50
2014-07-19T18:23:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package eu.romainpellerin.remotecontrolviasms; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.telephony.SmsManager; import android.telephony.SmsMessage; /* Google Analytics */ import com.google.analytics.tracking.android.GAServiceManager; import com.google.analytics.tracking.android.GoogleAnalytics; import com.google.analytics.tracking.android.Tracker; /* LOCATION */ import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks; import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener; import com.google.android.gms.location.LocationClient; public class SmsReceiver extends BroadcastReceiver implements ConnectionCallbacks, OnConnectionFailedListener { private Context cont; private String phoneNumber; private static MediaPlayer mp; private static AudioManager audioManager; private static int val_ini; // volume private LocationClient locationClient; @Override public void onReceive(Context context, Intent intent) { cont = context; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); PreferenceManager.setDefaultValues(context, R.xml.prefs_wifi, true); // Met les settings par défaut si l'utilsateur n'a rien personnalisé PreferenceManager.setDefaultValues(context, R.xml.prefs_data, true); PreferenceManager.setDefaultValues(context, R.xml.prefs_beep, true); PreferenceManager.setDefaultValues(context, R.xml.prefs_gps, true); Bundle extras = intent.getExtras(); if (extras != null) { GoogleAnalytics mGaInstance = GoogleAnalytics.getInstance(context); Tracker mGaTracker = mGaInstance.getTracker("UA-39228475-2"); Object[] smsExtra = (Object[]) extras.get("pdus"); SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[0]); phoneNumber = sms.getOriginatingAddress(); String body = sms.getMessageBody().toString(); if (body.equalsIgnoreCase(prefs.getString("wifi_sms", "wifi")) && prefs.getBoolean("wifi_enable", true)) { // WIFI mGaTracker.sendEvent("received_sms", "received_sms", "WIFI", null); WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(true); } if (body.equalsIgnoreCase(prefs.getString("data_sms", "data")) && prefs.getBoolean("data_enable", true)) { // DATA mGaTracker.sendEvent("received_sms", "received_sms", "DATA", null); final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); try { final Class<?> conmanClass = Class.forName(conman.getClass().getName()); final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService"); iConnectivityManagerField.setAccessible(true); final Object iConnectivityManager = iConnectivityManagerField.get(conman); final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName()); final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConnectivityManager, true); } catch (Exception e) { // many e.printStackTrace(); } } if (body.equalsIgnoreCase(prefs.getString("beep_sms", "beep")) && prefs.getBoolean("beep_enable", true)) { // BEEP mGaTracker.sendEvent("received_sms", "received_sms", "BEEP", null); if (mp==null) { // Volume audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); val_ini = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); int volumeToSet = ((prefs.getInt("volume", 100) * audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC))/100); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumeToSet, AudioManager.FLAG_VIBRATE); final boolean loopmode = prefs.getBoolean("beep_play_again", false); mp = MediaPlayer.create(context, R.raw.alarm); mp.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { SmsReceiver.mp.reset(); SmsReceiver.mp.release(); SmsReceiver.mp = null; // Remet le volume tel qu'il était avant audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, val_ini, AudioManager.FLAG_VIBRATE); } }); mp.setLooping(loopmode); mp.start(); Intent inte = new Intent(context, CancelAlarm.class); inte.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (loopmode) context.startActivity(inte); } } if (body.equalsIgnoreCase(prefs.getString("gps_sms", "wifi")) && prefs.getBoolean("gps_enable", false) && GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS) { // GPS mGaTracker.sendEvent("received_sms", "received_sms", "GPS", null); locationClient = new LocationClient(context, this, this); locationClient.connect(); } GAServiceManager.getInstance().dispatch(); // commit les données vers GA } } public static void stopMP() { mp.stop(); mp.reset(); mp.release(); mp = null; // Remet le volume tel qu'il était avant audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, val_ini, AudioManager.FLAG_VIBRATE); } @Override public void onConnectionFailed(ConnectionResult arg0) { SmsManager manager = SmsManager.getDefault(); manager.sendTextMessage(phoneNumber, null, "Connection failed", null, null); } @Override public void onConnected(Bundle arg0) { Thread a = new Thread() { @Override public void run() { Location loc = null; int counter = 0; do { try { Thread.sleep(500); } catch (InterruptedException e) {} loc = locationClient.getLastLocation(); counter++; if (counter>120) return; }while(loc==null); String url = cont.getResources().getString(R.string.location_bug); if (loc != null) { String lat = String.valueOf(loc.getLatitude()); String lon = String.valueOf(loc.getLongitude()); url = "http://maps.google.com/maps?q="+lat+","+lon; } String adress = cont.getResources().getString(R.string.location_no_acuracy); Geocoder geocoder = new Geocoder(cont); try { List<Address> result = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1); adress = addressToText(result.get(0)).toString(); } catch (IOException e) { } SmsManager manager = SmsManager.getDefault(); String msg = adress+" (precision="+loc.getAccuracy()+"m)"; manager.sendTextMessage(phoneNumber, null, msg, null, null); manager.sendTextMessage(phoneNumber, null, url, null, null); if (locationClient.isConnected()) locationClient.disconnect(); } }; a.start(); } @Override public void onDisconnected() {} private StringBuffer addressToText(Address address) { final StringBuffer addressText = new StringBuffer(); for (int i = 0, max = address.getMaxAddressLineIndex(); i < max; ++i) { addressText.append(address.getAddressLine(i)); if ((i+1) < max) { addressText.append(", "); } } addressText.append(", "); addressText.append(address.getCountryName()); return addressText; } }
UTF-8
Java
8,523
java
SmsReceiver.java
Java
[ { "context": "package eu.romainpellerin.remotecontrolviasms;\r\n\r\nimport java.io.IO", "end": 17, "score": 0.611031174659729, "start": 11, "tag": "USERNAME", "value": "romain" } ]
null
[]
package eu.romainpellerin.remotecontrolviasms; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.telephony.SmsManager; import android.telephony.SmsMessage; /* Google Analytics */ import com.google.analytics.tracking.android.GAServiceManager; import com.google.analytics.tracking.android.GoogleAnalytics; import com.google.analytics.tracking.android.Tracker; /* LOCATION */ import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks; import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener; import com.google.android.gms.location.LocationClient; public class SmsReceiver extends BroadcastReceiver implements ConnectionCallbacks, OnConnectionFailedListener { private Context cont; private String phoneNumber; private static MediaPlayer mp; private static AudioManager audioManager; private static int val_ini; // volume private LocationClient locationClient; @Override public void onReceive(Context context, Intent intent) { cont = context; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); PreferenceManager.setDefaultValues(context, R.xml.prefs_wifi, true); // Met les settings par défaut si l'utilsateur n'a rien personnalisé PreferenceManager.setDefaultValues(context, R.xml.prefs_data, true); PreferenceManager.setDefaultValues(context, R.xml.prefs_beep, true); PreferenceManager.setDefaultValues(context, R.xml.prefs_gps, true); Bundle extras = intent.getExtras(); if (extras != null) { GoogleAnalytics mGaInstance = GoogleAnalytics.getInstance(context); Tracker mGaTracker = mGaInstance.getTracker("UA-39228475-2"); Object[] smsExtra = (Object[]) extras.get("pdus"); SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[0]); phoneNumber = sms.getOriginatingAddress(); String body = sms.getMessageBody().toString(); if (body.equalsIgnoreCase(prefs.getString("wifi_sms", "wifi")) && prefs.getBoolean("wifi_enable", true)) { // WIFI mGaTracker.sendEvent("received_sms", "received_sms", "WIFI", null); WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(true); } if (body.equalsIgnoreCase(prefs.getString("data_sms", "data")) && prefs.getBoolean("data_enable", true)) { // DATA mGaTracker.sendEvent("received_sms", "received_sms", "DATA", null); final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); try { final Class<?> conmanClass = Class.forName(conman.getClass().getName()); final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService"); iConnectivityManagerField.setAccessible(true); final Object iConnectivityManager = iConnectivityManagerField.get(conman); final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName()); final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConnectivityManager, true); } catch (Exception e) { // many e.printStackTrace(); } } if (body.equalsIgnoreCase(prefs.getString("beep_sms", "beep")) && prefs.getBoolean("beep_enable", true)) { // BEEP mGaTracker.sendEvent("received_sms", "received_sms", "BEEP", null); if (mp==null) { // Volume audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); val_ini = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); int volumeToSet = ((prefs.getInt("volume", 100) * audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC))/100); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumeToSet, AudioManager.FLAG_VIBRATE); final boolean loopmode = prefs.getBoolean("beep_play_again", false); mp = MediaPlayer.create(context, R.raw.alarm); mp.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { SmsReceiver.mp.reset(); SmsReceiver.mp.release(); SmsReceiver.mp = null; // Remet le volume tel qu'il était avant audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, val_ini, AudioManager.FLAG_VIBRATE); } }); mp.setLooping(loopmode); mp.start(); Intent inte = new Intent(context, CancelAlarm.class); inte.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (loopmode) context.startActivity(inte); } } if (body.equalsIgnoreCase(prefs.getString("gps_sms", "wifi")) && prefs.getBoolean("gps_enable", false) && GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS) { // GPS mGaTracker.sendEvent("received_sms", "received_sms", "GPS", null); locationClient = new LocationClient(context, this, this); locationClient.connect(); } GAServiceManager.getInstance().dispatch(); // commit les données vers GA } } public static void stopMP() { mp.stop(); mp.reset(); mp.release(); mp = null; // Remet le volume tel qu'il était avant audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, val_ini, AudioManager.FLAG_VIBRATE); } @Override public void onConnectionFailed(ConnectionResult arg0) { SmsManager manager = SmsManager.getDefault(); manager.sendTextMessage(phoneNumber, null, "Connection failed", null, null); } @Override public void onConnected(Bundle arg0) { Thread a = new Thread() { @Override public void run() { Location loc = null; int counter = 0; do { try { Thread.sleep(500); } catch (InterruptedException e) {} loc = locationClient.getLastLocation(); counter++; if (counter>120) return; }while(loc==null); String url = cont.getResources().getString(R.string.location_bug); if (loc != null) { String lat = String.valueOf(loc.getLatitude()); String lon = String.valueOf(loc.getLongitude()); url = "http://maps.google.com/maps?q="+lat+","+lon; } String adress = cont.getResources().getString(R.string.location_no_acuracy); Geocoder geocoder = new Geocoder(cont); try { List<Address> result = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1); adress = addressToText(result.get(0)).toString(); } catch (IOException e) { } SmsManager manager = SmsManager.getDefault(); String msg = adress+" (precision="+loc.getAccuracy()+"m)"; manager.sendTextMessage(phoneNumber, null, msg, null, null); manager.sendTextMessage(phoneNumber, null, url, null, null); if (locationClient.isConnected()) locationClient.disconnect(); } }; a.start(); } @Override public void onDisconnected() {} private StringBuffer addressToText(Address address) { final StringBuffer addressText = new StringBuffer(); for (int i = 0, max = address.getMaxAddressLineIndex(); i < max; ++i) { addressText.append(address.getAddressLine(i)); if ((i+1) < max) { addressText.append(", "); } } addressText.append(", "); addressText.append(address.getCountryName()); return addressText; } }
8,523
0.682672
0.679267
200
40.59
33.644344
208
false
false
0
0
0
0
0
0
2.995
false
false
12
b5863ed38dad6622d2df8812c693ad7a6201fda6
39,591,008,561,993
25890e35342c2c51749df035b59e2c9e9bec2f25
/src/main/java/org/academy/pageObjects/android/ProductCatalogue.java
c32b6ec8ee8ea5b469160474f18b43f795f060e0
[]
no_license
KeshavJha0610/AppiumFramework
https://github.com/KeshavJha0610/AppiumFramework
ccc289b8e54ef3887812b6c6b8219003670ffb0b
29e312d25268e6d75523543d033bd759bb0c1c13
refs/heads/main
2023-04-18T20:56:13.301000
2022-07-17T17:44:10
2022-07-17T17:44:10
360,801,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.academy.pageObjects.android; import java.util.List; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.academy.utils.AndroidActions; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.pagefactory.AndroidFindBy; import io.appium.java_client.pagefactory.AppiumFieldDecorator; public class ProductCatalogue extends AndroidActions { AndroidDriver driver; @AndroidFindBy(xpath = "//android.widget.TextView[@text='ADD TO CART']") private List<WebElement> addToCart; //driver.findElements(By.xpath("//android.widget.TextView[@text='ADD TO CART']")) @AndroidFindBy(id = "com.androidsample.generalstore:id/appbar_btn_cart") private WebElement cart; public ProductCatalogue(AndroidDriver driver) { super(driver); this.driver = driver; PageFactory.initElements(new AppiumFieldDecorator(driver), this); // } public void addItemToCartByIndex(int index) { addToCart.get(index).click(); } public CartPage goToCartPage() throws InterruptedException { cart.click(); Thread.sleep(2000); return new CartPage(driver); } }
UTF-8
Java
1,210
java
ProductCatalogue.java
Java
[]
null
[]
package org.academy.pageObjects.android; import java.util.List; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.academy.utils.AndroidActions; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.pagefactory.AndroidFindBy; import io.appium.java_client.pagefactory.AppiumFieldDecorator; public class ProductCatalogue extends AndroidActions { AndroidDriver driver; @AndroidFindBy(xpath = "//android.widget.TextView[@text='ADD TO CART']") private List<WebElement> addToCart; //driver.findElements(By.xpath("//android.widget.TextView[@text='ADD TO CART']")) @AndroidFindBy(id = "com.androidsample.generalstore:id/appbar_btn_cart") private WebElement cart; public ProductCatalogue(AndroidDriver driver) { super(driver); this.driver = driver; PageFactory.initElements(new AppiumFieldDecorator(driver), this); // } public void addItemToCartByIndex(int index) { addToCart.get(index).click(); } public CartPage goToCartPage() throws InterruptedException { cart.click(); Thread.sleep(2000); return new CartPage(driver); } }
1,210
0.726446
0.72314
44
26.5
26.389133
85
false
false
0
0
0
0
0
0
0.431818
false
false
12
78d7411a4602a495c9ee98e76de83fa7bdaa4567
9,156,870,293,655
b06b976e93a57d26dae35e073bc91ffceac290ca
/app/src/main/java/com/diablo/jsonanalysis/MyJsonObj.java
756c4364d54cd34e4cbce007fc8bd7ff66c373ad
[]
no_license
sirencode/JsonAnalysis
https://github.com/sirencode/JsonAnalysis
dafb2fc8126637f1c5b1e61a4011cec526660ca0
f32232d1d9088dad502bd88ea80e56d5acbdbefa
refs/heads/master
2021-07-10T04:55:23.482000
2017-10-09T06:46:53
2017-10-09T06:46:53
106,246,252
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.diablo.jsonanalysis; import com.bluelinelabs.logansquare.annotation.JsonField; import com.bluelinelabs.logansquare.annotation.JsonObject; /** * Created by Diablo on 2017/10/9. */ @JsonObject public class MyJsonObj { @JsonField public String name; @JsonField public String city; @JsonField public int age; @JsonField public long date; @JsonField public String Period; @JsonField public String ListId; @JsonField public String Market; @JsonField public String LongP; @JsonField public String ShortP; @JsonField public String Value; @JsonField public String TradeTime; @JsonField public int LastRegion; @JsonField public int CurrentRegion; @JsonField public int Signals; @JsonField public Son son; @JsonObject public static class Son { @JsonField public int age; @JsonField public String wife; @JsonField public String company; @JsonField public String college; @JsonField public String profession; } @Override public String toString() { return "MyJsonObj{" + "name='" + name + '\'' + ", city='" + city + '\'' + ", age=" + age + ", date=" + date + ", Period='" + Period + '\'' + ", ListId='" + ListId + '\'' + ", Market='" + Market + '\'' + ", LongP='" + LongP + '\'' + ", ShortP='" + ShortP + '\'' + ", Value='" + Value + '\'' + ", TradeTime='" + TradeTime + '\'' + ", LastRegion=" + LastRegion + ", CurrentRegion=" + CurrentRegion + ", Signals=" + Signals + '}'; } }
UTF-8
Java
1,856
java
MyJsonObj.java
Java
[ { "context": "ansquare.annotation.JsonObject;\n\n/**\n * Created by Diablo on 2017/10/9.\n */\n@JsonObject\npublic class MyJson", "end": 176, "score": 0.9912369847297668, "start": 170, "tag": "NAME", "value": "Diablo" } ]
null
[]
package com.diablo.jsonanalysis; import com.bluelinelabs.logansquare.annotation.JsonField; import com.bluelinelabs.logansquare.annotation.JsonObject; /** * Created by Diablo on 2017/10/9. */ @JsonObject public class MyJsonObj { @JsonField public String name; @JsonField public String city; @JsonField public int age; @JsonField public long date; @JsonField public String Period; @JsonField public String ListId; @JsonField public String Market; @JsonField public String LongP; @JsonField public String ShortP; @JsonField public String Value; @JsonField public String TradeTime; @JsonField public int LastRegion; @JsonField public int CurrentRegion; @JsonField public int Signals; @JsonField public Son son; @JsonObject public static class Son { @JsonField public int age; @JsonField public String wife; @JsonField public String company; @JsonField public String college; @JsonField public String profession; } @Override public String toString() { return "MyJsonObj{" + "name='" + name + '\'' + ", city='" + city + '\'' + ", age=" + age + ", date=" + date + ", Period='" + Period + '\'' + ", ListId='" + ListId + '\'' + ", Market='" + Market + '\'' + ", LongP='" + LongP + '\'' + ", ShortP='" + ShortP + '\'' + ", Value='" + Value + '\'' + ", TradeTime='" + TradeTime + '\'' + ", LastRegion=" + LastRegion + ", CurrentRegion=" + CurrentRegion + ", Signals=" + Signals + '}'; } }
1,856
0.515086
0.511315
75
23.746666
14.168597
58
false
false
0
0
0
0
0
0
0.493333
false
false
12
9c6b52c790e2671655e98df46a1f476866d2b062
33,277,406,615,932
8ac0754c47012359b8c98cef70d1e96a7ef3031a
/dddd/src/main/java/com/example/spring/demo/mapper/usermapper.java
e08297aeec92be4845cd22974f9ec5bd05f1bf83
[]
no_license
zzs369/aaaa
https://github.com/zzs369/aaaa
acddb8d80d89127b75fe0952e2ed228b084bc008
f910f45134309e1c8d2cec6079090c8a7aafa1b2
refs/heads/master
2022-12-27T04:46:47.475000
2020-10-13T07:46:42
2020-10-13T07:46:42
303,621,511
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.spring.demo.mapper; import com.example.spring.demo.entity.user; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface usermapper { user getById(int id); public boolean insert(String name); public List<user> getUsers(); public boolean updateUser(user user); public boolean deleteUser(int id); public boolean deleteAllUsers(); }
UTF-8
Java
421
java
usermapper.java
Java
[]
null
[]
package com.example.spring.demo.mapper; import com.example.spring.demo.entity.user; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface usermapper { user getById(int id); public boolean insert(String name); public List<user> getUsers(); public boolean updateUser(user user); public boolean deleteUser(int id); public boolean deleteAllUsers(); }
421
0.75772
0.75772
15
27.066668
16.093338
49
false
false
0
0
0
0
0
0
0.666667
false
false
12
775ab8487bc9ec7390fed3e10c1d7e3880e72ef4
25,598,005,129,714
8c181b0ce3c8fe2ab4389c06ab74f199c7f217e0
/design/src/main/java/com/example/design/struct/bridge/extend/Child.java
960e2410eb88f61a369b940af75be3852daeb845
[]
no_license
apple-tm/design-world
https://github.com/apple-tm/design-world
f1976d268a23ffa54f27ead1d085633bc08cae75
1d8261a8a605870868b091c311391c0406a221ee
refs/heads/main
2023-05-31T23:05:42.851000
2021-06-16T02:47:49
2021-06-16T02:47:49
337,002,995
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.design.struct.bridge.extend; /** * 父类存在非默认构造方法,子类也要有,并且需要调用 super 传递参数 * 也就是初始化子类构造方法最先执行的代码必须是 super(...)先初始化父类构造器 */ public class Child extends Parent { public Child(String name) { super(name); } }
UTF-8
Java
357
java
Child.java
Java
[]
null
[]
package com.example.design.struct.bridge.extend; /** * 父类存在非默认构造方法,子类也要有,并且需要调用 super 传递参数 * 也就是初始化子类构造方法最先执行的代码必须是 super(...)先初始化父类构造器 */ public class Child extends Parent { public Child(String name) { super(name); } }
357
0.692946
0.692946
12
19.083334
18.332386
48
false
false
0
0
0
0
0
0
0.25
false
false
12
6744639f598238113007e8c9c88ac7eba9f2f32a
25,598,005,129,395
c1822ab61406eb42a0d4fe6671f9b1b7285eca56
/hotel-core/src/com/mangocity/hotel/order/service/impl/DebitCardService.java
fad77e1cf4f26677c589fb2bd7e19de3b3ea9e02
[]
no_license
dallaslu/hotel
https://github.com/dallaslu/hotel
a41693769b71fb835686564219adb36b013c698e
15d4291573e4f0000be115d307fbe4ffa790229c
refs/heads/master
2017-12-01T05:00:51.390000
2013-09-18T06:23:33
2013-09-18T06:23:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mangocity.hotel.order.service.impl; import java.util.ArrayList; import java.util.List; import com.mangocity.hotel.order.dao.IDebitCardDao; import com.mangocity.hotel.order.service.IDebitCardService; /** */ public class DebitCardService implements IDebitCardService { private IDebitCardDao debitCardDao; /* * 根据会员cd获取对应的借记卡(银联手机支付)的历史使用信息 */ public List getDebitCardHistoryLis(String memberCd){ List lis = new ArrayList(); lis = debitCardDao.getDebitCardHistotyLis(memberCd); return lis; } public IDebitCardDao getDebitCardDao() { return debitCardDao; } public void setDebitCardDao(IDebitCardDao debitCardDao) { this.debitCardDao = debitCardDao; } }
UTF-8
Java
791
java
DebitCardService.java
Java
[]
null
[]
package com.mangocity.hotel.order.service.impl; import java.util.ArrayList; import java.util.List; import com.mangocity.hotel.order.dao.IDebitCardDao; import com.mangocity.hotel.order.service.IDebitCardService; /** */ public class DebitCardService implements IDebitCardService { private IDebitCardDao debitCardDao; /* * 根据会员cd获取对应的借记卡(银联手机支付)的历史使用信息 */ public List getDebitCardHistoryLis(String memberCd){ List lis = new ArrayList(); lis = debitCardDao.getDebitCardHistotyLis(memberCd); return lis; } public IDebitCardDao getDebitCardDao() { return debitCardDao; } public void setDebitCardDao(IDebitCardDao debitCardDao) { this.debitCardDao = debitCardDao; } }
791
0.731343
0.731343
31
21.774193
22.206814
60
false
false
0
0
0
0
0
0
0.83871
false
false
12
14fe4dfc9a39788d381e43f550ff785b02324c65
21,947,282,894,525
5b9c29a58be66b5514a9e2994ad3e9cbf202d620
/SWAzam/Peer/src/main/java/at/ac/tuwien/swa/SWAzam/Peer/Peer2PeerConnector/Peer2PeerConnectorFactory.java
366a4f31fdfff54596365047a9c27521c918e32a
[]
no_license
grumpo/SWAzam
https://github.com/grumpo/SWAzam
e32c7a9647719531da05ad619c3acfbd7353e235
f800246a5f29cbd2d9f25924fa5d4677f38de208
refs/heads/master
2021-01-01T06:26:42.486000
2014-01-19T11:27:41
2014-01-19T11:27:41
15,003,474
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package at.ac.tuwien.swa.SWAzam.Peer.Peer2PeerConnector; public interface Peer2PeerConnectorFactory { Peer2PeerConnector create(String url); }
UTF-8
Java
148
java
Peer2PeerConnectorFactory.java
Java
[]
null
[]
package at.ac.tuwien.swa.SWAzam.Peer.Peer2PeerConnector; public interface Peer2PeerConnectorFactory { Peer2PeerConnector create(String url); }
148
0.817568
0.797297
5
28.6
23.440136
56
false
false
0
0
0
0
0
0
0.4
false
false
12
7dbae6befc0a3654e3647be63659aac63b635d3a
30,399,778,588,773
36cf6e734b0fd7ef59a0167cd16629919bb8d15d
/src/main/java/iwoplaza/neonshot/graphics/HealthBarRenderer.java
ca40c82a8bc46baf11e8dc9871a2541ed7285ff1
[]
no_license
iwoplaza/neonshot
https://github.com/iwoplaza/neonshot
de8df652cfafc0670e068807d26e598522e34928
f0f5e329a384def7b478bca4b1ee201b1158a058
refs/heads/master
2023-02-12T21:40:26.183000
2021-01-20T18:25:57
2021-01-20T18:25:57
328,789,077
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package iwoplaza.neonshot.graphics; import iwoplaza.meatengine.graphics.Drawable; import iwoplaza.meatengine.graphics.mesh.Mesh; import iwoplaza.meatengine.util.Color; import iwoplaza.meatengine.graphics.GlStack; import iwoplaza.meatengine.graphics.IGameRenderContext; import iwoplaza.meatengine.graphics.mesh.FlatMesh; import iwoplaza.meatengine.graphics.shader.core.FlatShader; import iwoplaza.meatengine.helper.MeshHelper; import iwoplaza.meatengine.util.IColorc; import iwoplaza.neonshot.CommonShaders; import iwoplaza.neonshot.graphics.shader.ProgressBarShader; import iwoplaza.neonshot.world.entity.IDamageable; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class HealthBarRenderer { public static final HealthBarRenderer INSTANCE = new HealthBarRenderer(); private Drawable<FlatShader> background; private Drawable<ProgressBarShader> fill; private Drawable<FlatShader> bigBorder; private ProgressBarShader shader; public static final int SMALL_WIDTH = 20; public static final int SMALL_HEIGHT = 3; public static final int BIG_WIDTH = 80; public static final int BIG_HEIGHT = 12; public static final int THICKNESS = 1; private final Map<IDamageable, HealthMeta> healthMetaMap = new HashMap<>(); public void init() throws IOException { this.shader = new ProgressBarShader(); this.shader.load(); Mesh rectangle = MeshHelper.createFlatRectangle(1, 1); this.background = new Drawable<>(rectangle, CommonShaders.flatShader); this.fill = new Drawable<>(rectangle, this.shader); this.bigBorder = new Drawable<>(MeshHelper.createBorder(BIG_WIDTH, BIG_HEIGHT, THICKNESS), CommonShaders.flatShader); } private void drawBackground(boolean big) { GlStack.push(); if (big) { GlStack.scale(BIG_WIDTH, BIG_HEIGHT, 1); } else { GlStack.scale(SMALL_WIDTH, SMALL_HEIGHT, 1); } this.background.draw(s -> { s.getColor().set(0, 0, 0, 1); }); GlStack.pop(); } private void drawFill(HealthBarSpec spec, HealthMeta meta) { float transition = 1 - meta.getTransitionProgress(); transition *= transition * transition; transition = 1 - transition; final float t = transition; final float lastHealth = meta.getLastHealthPercentage(); final float currHealth = meta.getCurrentHealthPercentage(); GlStack.push(); GlStack.translate(THICKNESS, THICKNESS, 0); if (spec.isBig()) { GlStack.scale(BIG_WIDTH - THICKNESS * 2, BIG_HEIGHT - THICKNESS * 2, 1); } else { GlStack.scale(SMALL_WIDTH - THICKNESS * 2, SMALL_HEIGHT - THICKNESS * 2, 1); } float percentage = lastHealth + (currHealth - lastHealth) * transition; GlStack.scale(percentage, 1, 1); this.fill.draw(s -> { s.getHighlight().set(1 - t); s.getColor().set(spec.baseColor); s.getHighlightColor().set(spec.highlightColor); }); GlStack.pop(); } public void draw(IGameRenderContext context, IDamageable damagable, HealthBarSpec spec) { this.drawBackground(spec.isBig()); if (spec.isBig()) { this.bigBorder.draw(s -> { s.getColor().set(1, 1, 1, 1); }); } HealthMeta meta = healthMetaMap.get(damagable); if (meta == null) { meta = new HealthMeta(0.5f, damagable.getMaxHealth(), damagable.getHealth()); healthMetaMap.put(damagable, meta); } meta.setHealth(damagable.getHealth(), damagable.getMaxHealth()); meta.update(context.getDeltaTime()); this.drawFill(spec, meta); } public static class HealthBarSpec { private final boolean big; private final IColorc baseColor; private final IColorc highlightColor; public HealthBarSpec(boolean big, IColorc baseColor, IColorc highlightColor) { this.big = big; this.baseColor = baseColor; this.highlightColor = highlightColor; } public boolean isBig() { return big; } public IColorc getBaseColor() { return baseColor; } public IColorc getHighlightColor() { return highlightColor; } } private static class HealthMeta { private final float transitionDuration; private float transitionTime; private int lastMaxHealth; private int lastHealth; private int currentMaxHealth; private int currentHealth; public HealthMeta(float transitionDuration, int maxHealth, int currentHealth) { this.transitionDuration = transitionDuration; this.lastMaxHealth = maxHealth; this.currentMaxHealth = maxHealth; this.lastHealth = currentHealth; this.currentHealth = currentHealth; this.transitionTime = 0.0f; } public void update(float deltaTime) { if (this.transitionTime > 0) { this.transitionTime -= deltaTime; if (this.transitionTime < 0) { this.transitionTime = 0; } } } public void setHealth(int health, int maxHealth) { if (this.currentHealth == health && this.currentMaxHealth == maxHealth) { return; } this.lastMaxHealth = this.currentMaxHealth; this.lastHealth = this.currentHealth; this.currentMaxHealth = maxHealth; this.currentHealth = health; this.transitionTime = this.transitionDuration; } public float getTransitionDuration() { return transitionDuration; } public float getCurrentHealthPercentage() { return (float) this.currentHealth / this.currentMaxHealth; } public float getLastHealthPercentage() { return (float) this.lastHealth / this.lastMaxHealth; } public float getTransitionProgress() { return 1 - transitionTime / transitionDuration; } } }
UTF-8
Java
6,491
java
HealthBarRenderer.java
Java
[]
null
[]
package iwoplaza.neonshot.graphics; import iwoplaza.meatengine.graphics.Drawable; import iwoplaza.meatengine.graphics.mesh.Mesh; import iwoplaza.meatengine.util.Color; import iwoplaza.meatengine.graphics.GlStack; import iwoplaza.meatengine.graphics.IGameRenderContext; import iwoplaza.meatengine.graphics.mesh.FlatMesh; import iwoplaza.meatengine.graphics.shader.core.FlatShader; import iwoplaza.meatengine.helper.MeshHelper; import iwoplaza.meatengine.util.IColorc; import iwoplaza.neonshot.CommonShaders; import iwoplaza.neonshot.graphics.shader.ProgressBarShader; import iwoplaza.neonshot.world.entity.IDamageable; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class HealthBarRenderer { public static final HealthBarRenderer INSTANCE = new HealthBarRenderer(); private Drawable<FlatShader> background; private Drawable<ProgressBarShader> fill; private Drawable<FlatShader> bigBorder; private ProgressBarShader shader; public static final int SMALL_WIDTH = 20; public static final int SMALL_HEIGHT = 3; public static final int BIG_WIDTH = 80; public static final int BIG_HEIGHT = 12; public static final int THICKNESS = 1; private final Map<IDamageable, HealthMeta> healthMetaMap = new HashMap<>(); public void init() throws IOException { this.shader = new ProgressBarShader(); this.shader.load(); Mesh rectangle = MeshHelper.createFlatRectangle(1, 1); this.background = new Drawable<>(rectangle, CommonShaders.flatShader); this.fill = new Drawable<>(rectangle, this.shader); this.bigBorder = new Drawable<>(MeshHelper.createBorder(BIG_WIDTH, BIG_HEIGHT, THICKNESS), CommonShaders.flatShader); } private void drawBackground(boolean big) { GlStack.push(); if (big) { GlStack.scale(BIG_WIDTH, BIG_HEIGHT, 1); } else { GlStack.scale(SMALL_WIDTH, SMALL_HEIGHT, 1); } this.background.draw(s -> { s.getColor().set(0, 0, 0, 1); }); GlStack.pop(); } private void drawFill(HealthBarSpec spec, HealthMeta meta) { float transition = 1 - meta.getTransitionProgress(); transition *= transition * transition; transition = 1 - transition; final float t = transition; final float lastHealth = meta.getLastHealthPercentage(); final float currHealth = meta.getCurrentHealthPercentage(); GlStack.push(); GlStack.translate(THICKNESS, THICKNESS, 0); if (spec.isBig()) { GlStack.scale(BIG_WIDTH - THICKNESS * 2, BIG_HEIGHT - THICKNESS * 2, 1); } else { GlStack.scale(SMALL_WIDTH - THICKNESS * 2, SMALL_HEIGHT - THICKNESS * 2, 1); } float percentage = lastHealth + (currHealth - lastHealth) * transition; GlStack.scale(percentage, 1, 1); this.fill.draw(s -> { s.getHighlight().set(1 - t); s.getColor().set(spec.baseColor); s.getHighlightColor().set(spec.highlightColor); }); GlStack.pop(); } public void draw(IGameRenderContext context, IDamageable damagable, HealthBarSpec spec) { this.drawBackground(spec.isBig()); if (spec.isBig()) { this.bigBorder.draw(s -> { s.getColor().set(1, 1, 1, 1); }); } HealthMeta meta = healthMetaMap.get(damagable); if (meta == null) { meta = new HealthMeta(0.5f, damagable.getMaxHealth(), damagable.getHealth()); healthMetaMap.put(damagable, meta); } meta.setHealth(damagable.getHealth(), damagable.getMaxHealth()); meta.update(context.getDeltaTime()); this.drawFill(spec, meta); } public static class HealthBarSpec { private final boolean big; private final IColorc baseColor; private final IColorc highlightColor; public HealthBarSpec(boolean big, IColorc baseColor, IColorc highlightColor) { this.big = big; this.baseColor = baseColor; this.highlightColor = highlightColor; } public boolean isBig() { return big; } public IColorc getBaseColor() { return baseColor; } public IColorc getHighlightColor() { return highlightColor; } } private static class HealthMeta { private final float transitionDuration; private float transitionTime; private int lastMaxHealth; private int lastHealth; private int currentMaxHealth; private int currentHealth; public HealthMeta(float transitionDuration, int maxHealth, int currentHealth) { this.transitionDuration = transitionDuration; this.lastMaxHealth = maxHealth; this.currentMaxHealth = maxHealth; this.lastHealth = currentHealth; this.currentHealth = currentHealth; this.transitionTime = 0.0f; } public void update(float deltaTime) { if (this.transitionTime > 0) { this.transitionTime -= deltaTime; if (this.transitionTime < 0) { this.transitionTime = 0; } } } public void setHealth(int health, int maxHealth) { if (this.currentHealth == health && this.currentMaxHealth == maxHealth) { return; } this.lastMaxHealth = this.currentMaxHealth; this.lastHealth = this.currentHealth; this.currentMaxHealth = maxHealth; this.currentHealth = health; this.transitionTime = this.transitionDuration; } public float getTransitionDuration() { return transitionDuration; } public float getCurrentHealthPercentage() { return (float) this.currentHealth / this.currentMaxHealth; } public float getLastHealthPercentage() { return (float) this.lastHealth / this.lastMaxHealth; } public float getTransitionProgress() { return 1 - transitionTime / transitionDuration; } } }
6,491
0.608689
0.602527
225
27.848888
24.706532
125
false
false
0
0
0
0
0
0
0.604444
false
false
12
663dd8a00fc359c2fbccf1846b8efd4878a597af
21,500,606,306,393
9980bd1bf0aa5072830555cc2c973d0084dc08e0
/AreaShop/src/main/java/me/wiefferink/areashop/events/ask/SellingRegionEvent.java
612a58cf28d6907ec42358d4a0ad26de772adb72
[]
no_license
nifeboy123/AreaShop
https://github.com/nifeboy123/AreaShop
9ffe6b162a5b58ad8bc8a2437a8a179b4ea26726
816d136a62dc20951c56d8d4241bb83134fcdf45
refs/heads/master
2020-12-13T14:42:34.130000
2016-07-24T19:48:39
2016-07-24T19:48:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.wiefferink.areashop.events.ask; import me.wiefferink.areashop.events.CancellableAreaShopEvent; import me.wiefferink.areashop.regions.BuyRegion; /** * Broadcasted when a region is about to get sold */ public class SellingRegionEvent extends CancellableAreaShopEvent { private BuyRegion region; /** * Constructor * @param region The region that is about to get sold */ public SellingRegionEvent(BuyRegion region) { this.region = region; } /** * Get the region that is about to be sold * @return the region that is about to be sold */ public BuyRegion getRegion() { return region; } }
UTF-8
Java
623
java
SellingRegionEvent.java
Java
[]
null
[]
package me.wiefferink.areashop.events.ask; import me.wiefferink.areashop.events.CancellableAreaShopEvent; import me.wiefferink.areashop.regions.BuyRegion; /** * Broadcasted when a region is about to get sold */ public class SellingRegionEvent extends CancellableAreaShopEvent { private BuyRegion region; /** * Constructor * @param region The region that is about to get sold */ public SellingRegionEvent(BuyRegion region) { this.region = region; } /** * Get the region that is about to be sold * @return the region that is about to be sold */ public BuyRegion getRegion() { return region; } }
623
0.739968
0.739968
28
21.25
22.243177
66
false
false
0
0
0
0
0
0
0.821429
false
false
12
9105f286873650199ec07525be8d578765a89245
2,293,512,550,911
f354015167af19918f1ee73cd41ea161fddc8906
/app/src/main/java/com/commutersfamily/commuterfamily/Classes/LatLongClass.java
699acb96a874fd454c8d8461eec7a5db44ea2ba7
[]
no_license
Reyan002/Commuter_Family
https://github.com/Reyan002/Commuter_Family
f13fe815b09e7b7d3b0f4e51aa93a11647a36c45
29b645bf4b3563a2a345d698c29daceab29b77f3
refs/heads/master
2023-04-16T01:50:21.978000
2020-02-24T12:00:26
2020-02-24T12:00:26
216,747,057
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.commutersfamily.commuterfamily.Classes; public class LatLongClass { private double Lat; private double Long; public LatLongClass( ) { } @Override public String toString() { return "LatLongClass{" + "Lat=" + Lat + ", Long=" + Long + '}'; } public void setLat(double lat) { Lat = lat; } public void setLong(double aLong) { Long = aLong; } public double getLat() { return Lat; } public double getLong() { return Long; } }
UTF-8
Java
588
java
LatLongClass.java
Java
[]
null
[]
package com.commutersfamily.commuterfamily.Classes; public class LatLongClass { private double Lat; private double Long; public LatLongClass( ) { } @Override public String toString() { return "LatLongClass{" + "Lat=" + Lat + ", Long=" + Long + '}'; } public void setLat(double lat) { Lat = lat; } public void setLong(double aLong) { Long = aLong; } public double getLat() { return Lat; } public double getLong() { return Long; } }
588
0.517007
0.517007
34
16.294117
14.267465
51
false
false
0
0
0
0
0
0
0.264706
false
false
12
6ae32e2aa351bd385a98f78d4c9771a7c20df6fc
23,699,629,607,512
ec63c4229ce9b966fa834ec36e029e456367dcc2
/Lab5/src/main/java/app/web/laptopsellingweb/lab5/bai42.java
f310f34f8b7a2f21a875a8cbe6e3572663198f87
[]
no_license
VanPhungFD/-Exercise_LTW
https://github.com/VanPhungFD/-Exercise_LTW
715d09f42731fe8d866bdf6ec42767c788f2026d
bafd15200989c83cea13b0be27b9cd7a6b843cbf
refs/heads/main
2023-08-30T11:20:53.359000
2021-11-17T15:58:30
2021-11-17T15:58:30
415,780,548
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.web.laptopsellingweb.lab5; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet(name = "bai4-2", value = "/bai4-2") public class bai42 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public boolean checkMail(String input) { char[] arr = input.toCharArray(); for (char x : arr ) { if (x == 64) return true; } return false; } public boolean checkNumer(String input) { char[] chr = input.toCharArray(); for (int i = 0; i < chr.length; i++) { if (48 <= chr[i] && chr[i] <= 57) { return true; } } return false; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String email = request.getParameter("email"); String pass = request.getParameter("password"); String day = request.getParameter("day"); String month = request.getParameter("month"); String year = request.getParameter("year"); String male = request.getParameter("male"); String female = request.getParameter("female"); String creditCard = request.getHeader("credit-card"); String paypal = request.getParameter("paypal"); String cardNumber = request.getParameter("card-number"); String cardCVC = request.getParameter("card-cvc"); String dayMonth = request.getParameter("day-month"); String yearOption = request.getParameter("year-option"); response.getWriter().println("Full name: " + name); if (!checkMail(email)) { response.getWriter().println("Email error!"); } else { response.getWriter().println("Email: " + email); } response.getWriter().println("Pass: " + pass); if (!checkNumer(day) && !checkNumer(month) && !checkNumer(year)) response.getWriter().println("Date: null/null/null"); else response.getWriter().println("Date: " + day + "/" + month + "/" + year); response.getWriter().println("Sex: " + male + " or " + female); response.getWriter().println("Credit card: " + creditCard); response.getWriter().println("Paypal: " + paypal); response.getWriter().println("Card number: " + cardNumber); response.getWriter().println("Card CVC: " + cardCVC); response.getWriter().println("Date: " + dayMonth + " " + yearOption); } }
UTF-8
Java
2,785
java
bai42.java
Java
[]
null
[]
package app.web.laptopsellingweb.lab5; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet(name = "bai4-2", value = "/bai4-2") public class bai42 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public boolean checkMail(String input) { char[] arr = input.toCharArray(); for (char x : arr ) { if (x == 64) return true; } return false; } public boolean checkNumer(String input) { char[] chr = input.toCharArray(); for (int i = 0; i < chr.length; i++) { if (48 <= chr[i] && chr[i] <= 57) { return true; } } return false; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String email = request.getParameter("email"); String pass = request.getParameter("password"); String day = request.getParameter("day"); String month = request.getParameter("month"); String year = request.getParameter("year"); String male = request.getParameter("male"); String female = request.getParameter("female"); String creditCard = request.getHeader("credit-card"); String paypal = request.getParameter("paypal"); String cardNumber = request.getParameter("card-number"); String cardCVC = request.getParameter("card-cvc"); String dayMonth = request.getParameter("day-month"); String yearOption = request.getParameter("year-option"); response.getWriter().println("Full name: " + name); if (!checkMail(email)) { response.getWriter().println("Email error!"); } else { response.getWriter().println("Email: " + email); } response.getWriter().println("Pass: " + pass); if (!checkNumer(day) && !checkNumer(month) && !checkNumer(year)) response.getWriter().println("Date: null/null/null"); else response.getWriter().println("Date: " + day + "/" + month + "/" + year); response.getWriter().println("Sex: " + male + " or " + female); response.getWriter().println("Credit card: " + creditCard); response.getWriter().println("Paypal: " + paypal); response.getWriter().println("Card number: " + cardNumber); response.getWriter().println("Card CVC: " + cardCVC); response.getWriter().println("Date: " + dayMonth + " " + yearOption); } }
2,785
0.606463
0.601436
70
38.785713
27.266354
122
false
false
0
0
0
0
0
0
0.657143
false
false
12
c09e3c27c1c62bff146f0b45879ce1d23ee24f6a
8,383,776,217,104
b8372c575377ae773311159669fa95a5e4a2de15
/MainMenuGUI.java
c4f7e76ff037687841eb2d5c5a4ac2e18fd6dcf1
[]
no_license
lmtuan/Connect-Four
https://github.com/lmtuan/Connect-Four
a1b7aa17139f16e1f1480034ae9e67cbf73aae54
88e790fdeeea8fede6211993cc90f004963fa7ab
refs/heads/master
2020-03-19T18:59:01.930000
2018-07-16T15:55:20
2018-07-16T15:55:20
136,834,687
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class MainMenuGUI extends GUI { public MainMenuGUI() { boxes = new Box[2]; boxes[0] = new Box(30, 20, 280, 270, 1); boxes[1] = new Box(320, 20, 570, 270, 2); } public void draw() { StdDraw.clear(); StdDraw.setXscale(0,600); StdDraw.setYscale(0,400); StdDraw.picture(300, 200, "image/menu/backgroundW.png", 600, 400); StdDraw.text(300, 350, "Choose Your Game!"); StdDraw.picture(155, 145, "image/menu/TicTacToe.png", 250, 250); StdDraw.picture(445, 145, "image/menu/Connect4.png", 250, 250); StdDraw.show(); } }
UTF-8
Java
570
java
MainMenuGUI.java
Java
[]
null
[]
public class MainMenuGUI extends GUI { public MainMenuGUI() { boxes = new Box[2]; boxes[0] = new Box(30, 20, 280, 270, 1); boxes[1] = new Box(320, 20, 570, 270, 2); } public void draw() { StdDraw.clear(); StdDraw.setXscale(0,600); StdDraw.setYscale(0,400); StdDraw.picture(300, 200, "image/menu/backgroundW.png", 600, 400); StdDraw.text(300, 350, "Choose Your Game!"); StdDraw.picture(155, 145, "image/menu/TicTacToe.png", 250, 250); StdDraw.picture(445, 145, "image/menu/Connect4.png", 250, 250); StdDraw.show(); } }
570
0.62807
0.492982
18
30.722221
22.090233
70
false
false
0
0
0
0
0
0
1.944444
false
false
12
ccb5c85081598dafd34a361b78c4a6916e9b6a09
8,349,416,488,935
2e6a566153aa334ece284d58eb1b2b959bf596d2
/app/src/main/java/dhcc/cn/com/fix_phone/MyApplication.java
902a626f5c330a636ec91476b6384f615daa875d
[]
no_license
fixphone/fix_phone
https://github.com/fixphone/fix_phone
33af79868394237e0c664a05c1f940b0b6615027
88c223561187950e1d1fb21dba110d7e48bd2577
refs/heads/master
2021-07-23T22:46:00.443000
2017-11-04T10:03:07
2017-11-04T13:37:09
103,800,137
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package dhcc.cn.com.fix_phone; import android.app.ActivityManager; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v4.util.ArrayMap; import android.text.TextUtils; import com.raizlabs.android.dbflow.config.FlowManager; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater; import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater; import com.scwang.smartrefresh.layout.api.RefreshFooter; import com.scwang.smartrefresh.layout.api.RefreshHeader; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.footer.ClassicsFooter; import com.scwang.smartrefresh.layout.header.ClassicsHeader; import java.util.Map; import dhcc.cn.com.fix_phone.remote.ApiService; import dhcc.cn.com.fix_phone.rong.SealAppContext; import dhcc.cn.com.fix_phone.rong.SealUserInfoManager; import dhcc.cn.com.fix_phone.rong.message.TestMessage; import dhcc.cn.com.fix_phone.rong.message.provider.ContactNotificationMessageProvider; import dhcc.cn.com.fix_phone.rong.message.provider.TestMessageProvider; import dhcc.cn.com.fix_phone.utils.NLog; import dhcc.cn.com.fix_phone.utils.SharedPreferencesContext; import io.rong.imageloader.core.DisplayImageOptions; import io.rong.imageloader.core.display.FadeInBitmapDisplayer; import io.rong.imkit.RongIM; import io.rong.imkit.widget.provider.RealTimeLocationMessageProvider; import io.rong.imlib.ipc.RongExceptionHandler; import io.rong.push.RongPushClient; /** * 2017/9/16 22 */ public class MyApplication extends Application { private static final String TAG = "MyApplication"; private static Context mContext; private static Handler mHandler; private static long mMainThreadId; private static DisplayImageOptions options; private static String currentTypeId; private static Map<String, String> map = new ArrayMap<>(); public static Context getContext() { return mContext; } public static Handler getHandler() { return mHandler; } public static long getMainThreadId() { return mMainThreadId; } @Override public void onCreate() {//程序的入口方法 //1.上下文 mContext = getApplicationContext(); //2.放置一个主线程的Handler mHandler = new Handler(); //3.得到主线程的Id mMainThreadId = android.os.Process.myTid(); //Tid Thread //Pid Process //Uid User super.onCreate(); FlowManager.init(getApplicationContext()); ApiService.Instance().getService(); setGlobalRefreshStyle(); if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) { // LeakCanary.install(this);//内存泄露检测 RongPushClient.registerHWPush(this); RongPushClient.registerMiPush(this, "2882303761517473625", "5451747338625"); /** * 注意: * * IMKit SDK调用第一步 初始化 * * context上下文 * * 只有两个进程需要初始化,主进程和 push 进程 */ RongIM.setServerInfo("nav.cn.ronghub.com", "up.qbox.me"); RongIM.init(this); NLog.setDebug(true);//Seal Module Log 开关 SealAppContext.init(this); SharedPreferencesContext.init(this); Thread.setDefaultUncaughtExceptionHandler(new RongExceptionHandler(this)); try { RongIM.registerMessageTemplate(new ContactNotificationMessageProvider()); RongIM.registerMessageTemplate(new RealTimeLocationMessageProvider()); RongIM.registerMessageType(TestMessage.class); RongIM.registerMessageTemplate(new TestMessageProvider()); } catch (Exception e) { e.printStackTrace(); } openSealDBIfHasCachedToken(); options = new DisplayImageOptions.Builder() .showImageForEmptyUri(R.drawable.de_default_portrait) .showImageOnFail(R.drawable.de_default_portrait) .showImageOnLoading(R.drawable.de_default_portrait) .displayer(new FadeInBitmapDisplayer(300)) .cacheInMemory(true) .cacheOnDisk(true) .build(); } } public static DisplayImageOptions getOptions() { return options; } public static String getCurProcessName(Context context) { int pid = android.os.Process.myPid(); ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) { if (appProcess.pid == pid) { return appProcess.processName; } } return null; } private void openSealDBIfHasCachedToken() { SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE); String cachedToken = sp.getString("loginToken", ""); if (!TextUtils.isEmpty(cachedToken)) { String current = getCurProcessName(this); String mainProcessName = getPackageName(); if (mainProcessName.equals(current)) { SealUserInfoManager.getInstance().openDB(); } } } private void setGlobalRefreshStyle() { SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() { @NonNull @Override public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) { return new ClassicsHeader(mContext); } }); SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() { @NonNull @Override public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) { return new ClassicsFooter(mContext); } }); } public static String getCurrentTypeId() { return currentTypeId; } public static void setCurrentTypeId(String currentTypeId) { MyApplication.currentTypeId = currentTypeId; } public static void putMessage(String path, String uuid) { map.put(path, uuid); } public static String getMessage(String path) { return map.get(path); } }
UTF-8
Java
6,776
java
MyApplication.java
Java
[]
null
[]
package dhcc.cn.com.fix_phone; import android.app.ActivityManager; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v4.util.ArrayMap; import android.text.TextUtils; import com.raizlabs.android.dbflow.config.FlowManager; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater; import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater; import com.scwang.smartrefresh.layout.api.RefreshFooter; import com.scwang.smartrefresh.layout.api.RefreshHeader; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.footer.ClassicsFooter; import com.scwang.smartrefresh.layout.header.ClassicsHeader; import java.util.Map; import dhcc.cn.com.fix_phone.remote.ApiService; import dhcc.cn.com.fix_phone.rong.SealAppContext; import dhcc.cn.com.fix_phone.rong.SealUserInfoManager; import dhcc.cn.com.fix_phone.rong.message.TestMessage; import dhcc.cn.com.fix_phone.rong.message.provider.ContactNotificationMessageProvider; import dhcc.cn.com.fix_phone.rong.message.provider.TestMessageProvider; import dhcc.cn.com.fix_phone.utils.NLog; import dhcc.cn.com.fix_phone.utils.SharedPreferencesContext; import io.rong.imageloader.core.DisplayImageOptions; import io.rong.imageloader.core.display.FadeInBitmapDisplayer; import io.rong.imkit.RongIM; import io.rong.imkit.widget.provider.RealTimeLocationMessageProvider; import io.rong.imlib.ipc.RongExceptionHandler; import io.rong.push.RongPushClient; /** * 2017/9/16 22 */ public class MyApplication extends Application { private static final String TAG = "MyApplication"; private static Context mContext; private static Handler mHandler; private static long mMainThreadId; private static DisplayImageOptions options; private static String currentTypeId; private static Map<String, String> map = new ArrayMap<>(); public static Context getContext() { return mContext; } public static Handler getHandler() { return mHandler; } public static long getMainThreadId() { return mMainThreadId; } @Override public void onCreate() {//程序的入口方法 //1.上下文 mContext = getApplicationContext(); //2.放置一个主线程的Handler mHandler = new Handler(); //3.得到主线程的Id mMainThreadId = android.os.Process.myTid(); //Tid Thread //Pid Process //Uid User super.onCreate(); FlowManager.init(getApplicationContext()); ApiService.Instance().getService(); setGlobalRefreshStyle(); if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) { // LeakCanary.install(this);//内存泄露检测 RongPushClient.registerHWPush(this); RongPushClient.registerMiPush(this, "2882303761517473625", "5451747338625"); /** * 注意: * * IMKit SDK调用第一步 初始化 * * context上下文 * * 只有两个进程需要初始化,主进程和 push 进程 */ RongIM.setServerInfo("nav.cn.ronghub.com", "up.qbox.me"); RongIM.init(this); NLog.setDebug(true);//Seal Module Log 开关 SealAppContext.init(this); SharedPreferencesContext.init(this); Thread.setDefaultUncaughtExceptionHandler(new RongExceptionHandler(this)); try { RongIM.registerMessageTemplate(new ContactNotificationMessageProvider()); RongIM.registerMessageTemplate(new RealTimeLocationMessageProvider()); RongIM.registerMessageType(TestMessage.class); RongIM.registerMessageTemplate(new TestMessageProvider()); } catch (Exception e) { e.printStackTrace(); } openSealDBIfHasCachedToken(); options = new DisplayImageOptions.Builder() .showImageForEmptyUri(R.drawable.de_default_portrait) .showImageOnFail(R.drawable.de_default_portrait) .showImageOnLoading(R.drawable.de_default_portrait) .displayer(new FadeInBitmapDisplayer(300)) .cacheInMemory(true) .cacheOnDisk(true) .build(); } } public static DisplayImageOptions getOptions() { return options; } public static String getCurProcessName(Context context) { int pid = android.os.Process.myPid(); ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) { if (appProcess.pid == pid) { return appProcess.processName; } } return null; } private void openSealDBIfHasCachedToken() { SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE); String cachedToken = sp.getString("loginToken", ""); if (!TextUtils.isEmpty(cachedToken)) { String current = getCurProcessName(this); String mainProcessName = getPackageName(); if (mainProcessName.equals(current)) { SealUserInfoManager.getInstance().openDB(); } } } private void setGlobalRefreshStyle() { SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() { @NonNull @Override public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) { return new ClassicsHeader(mContext); } }); SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() { @NonNull @Override public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) { return new ClassicsFooter(mContext); } }); } public static String getCurrentTypeId() { return currentTypeId; } public static void setCurrentTypeId(String currentTypeId) { MyApplication.currentTypeId = currentTypeId; } public static void putMessage(String path, String uuid) { map.put(path, uuid); } public static String getMessage(String path) { return map.get(path); } }
6,776
0.663508
0.656288
187
34.5508
26.879436
111
false
false
0
0
0
0
0
0
0.502674
false
false
12
0abd35634e732bbce1f621aa14005d1e5cc4d260
32,667,521,300,456
e618a9125642c6b14e355192b37d3e960f318be3
/java/java-functional-experiment/src/main/java/org/farrukh/examples/java/functional/interfaces/ConsumerExample.java
33ff5666af4d9331f19c72822b855ab440ca9137
[]
no_license
Farrukhjon/experimental-samples
https://github.com/Farrukhjon/experimental-samples
5c062a89ba499ac2223374bcf93b431bb68fae0a
cc20db2dc2c1b28aae54933550c89c13e46040ec
refs/heads/master
2022-07-16T19:23:03.557000
2019-07-27T11:34:56
2019-07-27T11:34:56
61,690,323
6
9
null
false
2022-10-18T18:07:38
2016-06-22T05:03:21
2020-11-01T06:41:18
2022-10-18T18:07:33
7,897
5
7
91
Java
false
false
package org.farrukh.examples.java.functional.interfaces; import java.util.Arrays; import java.util.function.Consumer; /** * Created by Farrukhjon on 18-Sep-15. */ public class ConsumerExample { public static void main(String[] args) { Consumer<Integer> integerConsumer = it -> System.out.println(it * 2); Arrays.asList(1, 2, 3, 4, 5).stream().forEach(integerConsumer); } }
UTF-8
Java
402
java
ConsumerExample.java
Java
[ { "context": "rt java.util.function.Consumer;\n\n/**\n * Created by Farrukhjon on 18-Sep-15.\n */\npublic class ConsumerE", "end": 139, "score": 0.7042234539985657, "start": 138, "tag": "USERNAME", "value": "F" }, { "context": " java.util.function.Consumer;\n\n/**\n * Created by Farrukhjon on 18-Sep-15.\n */\npublic class ConsumerExample", "end": 145, "score": 0.8357186317443848, "start": 139, "tag": "NAME", "value": "arrukh" }, { "context": "util.function.Consumer;\n\n/**\n * Created by Farrukhjon on 18-Sep-15.\n */\npublic class ConsumerExample {\n", "end": 148, "score": 0.5146912932395935, "start": 145, "tag": "USERNAME", "value": "jon" } ]
null
[]
package org.farrukh.examples.java.functional.interfaces; import java.util.Arrays; import java.util.function.Consumer; /** * Created by Farrukhjon on 18-Sep-15. */ public class ConsumerExample { public static void main(String[] args) { Consumer<Integer> integerConsumer = it -> System.out.println(it * 2); Arrays.asList(1, 2, 3, 4, 5).stream().forEach(integerConsumer); } }
402
0.69403
0.669154
15
25.799999
26.136055
77
false
false
0
0
0
0
0
0
0.6
false
false
12
46adfc455095f7060ecc6ad569b085959c0047e0
18,056,042,565,701
ab2283545d8bb92c6fc968337d5c300d7d718a3e
/src/com/placesandplaces/RabbitMQConn.java
4d9dda5e10dee3bd549ff4150ed100654ee466b6
[]
no_license
esantra/androidappforplaces
https://github.com/esantra/androidappforplaces
07978ecabb731e695ca2c36b19f82049b2f1d44a
6646ea85be78c3bb0708a299c78274be51a8f609
refs/heads/master
2021-01-20T07:43:22.128000
2013-12-08T01:14:24
2013-12-08T01:14:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.placesandplaces; import java.io.IOException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; //code inspired and built upon: http://simonwdixon.wordpress.com/2011/06/03/getting-started-with-rabbitmq-on-android-part-1/ public abstract class RabbitMQConn { // declare rabbitmq variables public String mServer; public String mExchange; protected Channel mModel = null; protected Connection mConnection; protected boolean Running; protected String ExchangeType; public RabbitMQConn(String server, String exchange, String exchangeType) { mServer = server; mExchange = exchange; ExchangeType = exchangeType; } public void Dispose() { Running = false; try { if (mConnection != null) { mConnection.close(); }// end if if (mModel != null) { mModel.abort(); }// end if }// end try catch (IOException e) { e.printStackTrace(); } } public boolean connectToRabbitMQ() { if (mModel != null && mModel.isOpen())// already declared return true; try { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost(mServer); mConnection = connectionFactory.newConnection(); mModel = mConnection.createChannel(); mModel.exchangeDeclare(mExchange, ExchangeType, true); return true; } catch (Exception e) { e.printStackTrace(); return false; } } }
UTF-8
Java
1,438
java
RabbitMQConn.java
Java
[]
null
[]
package com.placesandplaces; import java.io.IOException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; //code inspired and built upon: http://simonwdixon.wordpress.com/2011/06/03/getting-started-with-rabbitmq-on-android-part-1/ public abstract class RabbitMQConn { // declare rabbitmq variables public String mServer; public String mExchange; protected Channel mModel = null; protected Connection mConnection; protected boolean Running; protected String ExchangeType; public RabbitMQConn(String server, String exchange, String exchangeType) { mServer = server; mExchange = exchange; ExchangeType = exchangeType; } public void Dispose() { Running = false; try { if (mConnection != null) { mConnection.close(); }// end if if (mModel != null) { mModel.abort(); }// end if }// end try catch (IOException e) { e.printStackTrace(); } } public boolean connectToRabbitMQ() { if (mModel != null && mModel.isOpen())// already declared return true; try { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost(mServer); mConnection = connectionFactory.newConnection(); mModel = mConnection.createChannel(); mModel.exchangeDeclare(mExchange, ExchangeType, true); return true; } catch (Exception e) { e.printStackTrace(); return false; } } }
1,438
0.723227
0.716968
61
22.590164
21.321409
124
false
false
0
0
0
0
0
0
1.983607
false
false
12
25dc46ecaeb050f369522ba3b9955b19469c5fce
21,096,879,420,707
90b82ad81e91b484a57ff28a58984580a9fd4cda
/src/main/java/com/market/entities/BasketEntity.java
1e13dbcd0a08908ef2dbafd974fe3efc0173cbcb
[]
no_license
alexsearchwolf/OnlineMarket
https://github.com/alexsearchwolf/OnlineMarket
e42af7788ad1224921729b155e523e65fc475b36
3f9e436a795aa586525f60f9bd40fb3b9e89d894
refs/heads/master
2020-12-27T21:58:07.900000
2020-02-03T22:54:45
2020-02-03T22:54:45
238,073,248
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.market.entities; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonView; import com.market.security.Views; @Entity @Table(name = "basket") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class BasketEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "basket_id") @JsonView(Views.Admin.class) private Integer id; @JsonView(Views.User.class) @Column(name = "suma",nullable = true) private Double suma; @JsonBackReference @JsonView(Views.User.class) @OneToOne(mappedBy = "basket", cascade = CascadeType.REFRESH,fetch = FetchType.LAZY) protected UserEntity user; @JsonView(Views.User.class) @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH) @JoinTable(name = "product_basket", joinColumns ={@JoinColumn(name = "basket_id", nullable = false, updatable = false) },inverseJoinColumns = { @JoinColumn(name = "product_id",nullable = false, updatable = false) }) protected List<ProductEntity> basket_products = new ArrayList<ProductEntity>(); public BasketEntity(Integer id, UserEntity user, List<ProductEntity> basket_products, Double suma) { super(); this.id = id; this.user = user; this.basket_products = basket_products; this.suma=suma; } public Double getSuma() { return suma; } public void setSuma(Double suma) { this.suma = suma; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public UserEntity getUser() { return user; } public void setUser(UserEntity user) { this.user = user; } public List<ProductEntity> getBasket_products() { return basket_products; } public void setBasket_products(List<ProductEntity> basket_products) { this.basket_products = basket_products; } public BasketEntity() { super(); // TODO Auto-generated constructor stub } }
UTF-8
Java
2,455
java
BasketEntity.java
Java
[]
null
[]
package com.market.entities; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonView; import com.market.security.Views; @Entity @Table(name = "basket") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class BasketEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "basket_id") @JsonView(Views.Admin.class) private Integer id; @JsonView(Views.User.class) @Column(name = "suma",nullable = true) private Double suma; @JsonBackReference @JsonView(Views.User.class) @OneToOne(mappedBy = "basket", cascade = CascadeType.REFRESH,fetch = FetchType.LAZY) protected UserEntity user; @JsonView(Views.User.class) @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH) @JoinTable(name = "product_basket", joinColumns ={@JoinColumn(name = "basket_id", nullable = false, updatable = false) },inverseJoinColumns = { @JoinColumn(name = "product_id",nullable = false, updatable = false) }) protected List<ProductEntity> basket_products = new ArrayList<ProductEntity>(); public BasketEntity(Integer id, UserEntity user, List<ProductEntity> basket_products, Double suma) { super(); this.id = id; this.user = user; this.basket_products = basket_products; this.suma=suma; } public Double getSuma() { return suma; } public void setSuma(Double suma) { this.suma = suma; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public UserEntity getUser() { return user; } public void setUser(UserEntity user) { this.user = user; } public List<ProductEntity> getBasket_products() { return basket_products; } public void setBasket_products(List<ProductEntity> basket_products) { this.basket_products = basket_products; } public BasketEntity() { super(); // TODO Auto-generated constructor stub } }
2,455
0.753157
0.753157
95
24.842106
29.175085
216
false
false
0
0
0
0
0
0
1.347368
false
false
12
2b805dba8e6c7ed866e7d0fd4320430fdbbafc3c
21,096,879,420,825
c0445b0b9e0f6b5fe9b1d13737f4afb25d9ece21
/src/main/java/net/strasnet/kids/ui/components/KIDSUIAbstractComponent.java
f4fe7712f6b0f3d93bbed02b7a51d9a69b7531a4
[]
no_license
jinksunk/KIDSDevelopment
https://github.com/jinksunk/KIDSDevelopment
4b4c191140bea8cb56d5d3a85b2a69d249c36250
39a1e0036125d182746283d001c6e55dd6b887cd
refs/heads/master
2021-05-01T04:21:20.734000
2017-04-21T00:56:47
2017-04-21T00:56:47
12,691,183
0
0
null
false
2017-04-21T00:56:48
2013-09-09T02:07:38
2016-11-03T14:54:03
2017-04-21T00:56:48
798
0
0
36
Web Ontology Language
null
null
/** * */ package net.strasnet.kids.ui.components; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.log4j.LogManager; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLDataFactory; import net.strasnet.kids.ui.KIDSUIInferredProperty; import net.strasnet.kids.ui.KIDSUIRequiredDataProperty; import net.strasnet.kids.ui.KIDSUIRequiredProperty; import net.strasnet.kids.ui.gui.KIDSGUIOracle; import net.strasnet.kids.ui.problems.KIDSMissingDataPropertyUIProblem; import net.strasnet.kids.ui.problems.KIDSMissingRelationUIProblem; import net.strasnet.kids.ui.problems.KIDSSubclassRequiredUIProblem; import net.strasnet.kids.ui.problems.KIDSUIProblem; /** * @author cstras * * Implementation of common methods for implementers of KIDSUIComponent */ public abstract class KIDSUIAbstractComponent implements KIDSUIComponent { public static final org.apache.log4j.Logger logme = LogManager.getLogger(KIDSUIAbstractComponent.class.getName()); public enum KIDSDatatypeClass { STRING, JAVA, FILEPATH }; public enum KIDSComponentDefinition { TBOX, ABOX }; protected IRI myIRI = null; protected Set<KIDSUIInferredProperty> myInfProps; protected Set<KIDSUIRequiredProperty> myReqProps; protected Set<KIDSUIRequiredDataProperty> myDataProps; protected String ABOXIRI; protected IRI TBOXIRI; protected KIDSGUIOracle o; protected OWLDataFactory owldf; protected IRI requiredSubclassOf; protected KIDSComponentDefinition deflocation; public KIDSUIAbstractComponent(IRI myID, KIDSGUIOracle o){ myIRI = myID; TBOXIRI = o.getTBOXIRI(); ABOXIRI = myIRI.getNamespace(); this.o = o; this.owldf = o.getOwlDataFactory(); this.requiredSubclassOf = null; myReqProps = new HashSet<KIDSUIRequiredProperty>(); myInfProps = new HashSet<KIDSUIInferredProperty>(); myDataProps = new HashSet<KIDSUIRequiredDataProperty>(); // By default, set defining component location to the TBOX: this.deflocation = KIDSComponentDefinition.TBOX; } @Override public Set<KIDSUIProblem> getComponentProblems() { HashSet<KIDSUIProblem> toReturn = new HashSet<KIDSUIProblem>(); // Check that each required object property has a target; if not, add to problems. for (KIDSUIRequiredProperty rprop : myReqProps){ Set<IRI> propvals = o.getPropertyIndividualsOfClass(myIRI, rprop.getProperty(), rprop.getObjectClass()); logme.debug(String.format("Evaluating required property (%s, %s, %s)", myIRI, rprop.getProperty(), rprop.getObjectClass())); if (propvals.size() == 0){ // Well, we have a problem: toReturn.add(new KIDSMissingRelationUIProblem( String.format("Required property not satisfied: (%s, %s, %s)", o.getShortIRIString(myIRI), o.getShortIRIString(rprop.getProperty()), o.getShortIRIString(rprop.getObjectClass())), KIDSUIProblem.ProblemType.REQUIRED, rprop.getProperty(), rprop.getObjectClass(), o ) ); } else { logme.debug(String.format("Property requirement satisfied by (%s, %s, %s)", o.getShortIRIString(myIRI), o.getShortIRIString(rprop.getProperty()), o.getShortIRIString(propvals.iterator().next()))); } } // Check that each inferred object property has a target; if not, add to problems. for (KIDSUIInferredProperty rprop : myInfProps){ Set<IRI> propvals = o.getPropertyIndividualsOfClass(myIRI, rprop.getProperty(), rprop.getObjectClass()); if (propvals.size() == 0){ // Well, we have a problem: toReturn.add(new KIDSUIProblem( String.format("Inferred property not defined: (%s, %s, %s)", o.getShortIRIString(myIRI), o.getShortIRIString(rprop.getProperty()), o.getShortIRIString(rprop.getObjectClass())), KIDSUIProblem.ProblemType.REQUIRED ) ); } } // Check that each specified data property has a target; if not, add to problems. for (KIDSUIRequiredDataProperty rprop : myDataProps){ Set<String> values = o.getDataPropertyValues(myIRI, rprop.getProperty()); if (values.size() == 0){ // Well, we have a problem: toReturn.add(new KIDSMissingDataPropertyUIProblem( String.format("Data property not defined: (%s, %s, %s)", o.getShortIRIString(myIRI), o.getShortIRIString(rprop.getProperty()), rprop.getObjectClass()), KIDSUIProblem.ProblemType.REQUIRED, myIRI, rprop.getObjectClass(), rprop.getProperty(), o ) ); } } // If subclass membership is required, ensure that we are a member of a strict subclass: if (requiredSubclassOf != null){ logme.debug(String.format("Checking that individual %s is a member of a subclass of %s...",getIRI().getShortForm(), requiredSubclassOf.getShortForm())); if (!o.isMemberOfStrictSubclass(requiredSubclassOf, myIRI)){ logme.debug(String.format("Individual %s is not a member of a subclass of %s; adding as a problem...",getIRI().getShortForm(), requiredSubclassOf.getShortForm())); toReturn.add(new KIDSSubclassRequiredUIProblem( String.format("%s must be a member of a subclass of %s", o.getShortIRIString(myIRI), o.getShortIRIString(requiredSubclassOf)), KIDSUIProblem.ProblemType.REQUIRED, requiredSubclassOf, myIRI, o ) ); } } logme.debug(String.format("Found %d problems for %s.", toReturn.size(), myIRI.getFragment())); return toReturn; } /** * @return - The IRI as defined for the individual represented by this class. */ @Override public IRI getIRI(){ return this.myIRI; } /** * @return - A short-form version of the IRI for a component. */ @Override public String toString(){ return this.o.getShortIRIString(this.myIRI); } @Override public List<KIDSUIRelation> getRelations(){ List <KIDSUIRelation> toReturn = new LinkedList<KIDSUIRelation>(); // Add object relations for (KIDSUIRequiredProperty p : this.myReqProps){ toReturn.add(new KIDSUIObjectRelationComponent(this.getIRI(), p.getProperty(), p.getObjectClass())); } // Add data relations for (KIDSUIRequiredDataProperty p : this.myDataProps){ toReturn.add(new KIDSUIDataRelationComponent(this.getIRI(), p.getProperty(), p.getObjectClass())); } return toReturn; } @Override public KIDSComponentDefinition getDefiningLocation(){ if (this.deflocation == null){ logme.error(String.format("Component %s does not provide a defining location.", this.getIRI())); } return this.deflocation; } @Override /** * * @param root - The root of the tree to populate with details. * * @return - A tree node hierarchy of values that provide details about the individual. All components will provide at least: * + Object Property Values * + Property IRI: * + individual IRI 1 * ... * + Data Property Values * + Property IRI: * + string value 1 * ... * + Class Memberships: * + Class IRI */ public DefaultMutableTreeNode getComponentDetails(DefaultMutableTreeNode root){ // First, get all of the object properties associated with this individual: DefaultMutableTreeNode objectProperties = new DefaultMutableTreeNode("Object Properties:"); Map<IRI, List<IRI>> objProps = o.getObjectPropertyValues(myIRI); for (IRI oprop : objProps.keySet()){ DefaultMutableTreeNode opropNode = new DefaultMutableTreeNode(oprop.getShortForm()); for (IRI val : objProps.get(oprop)){ DefaultMutableTreeNode opropValNode = new DefaultMutableTreeNode(val.getShortForm()); opropNode.add(opropValNode); } objectProperties.add(opropNode); } root.add(objectProperties); // Next, get all of the data property values: DefaultMutableTreeNode dataProperties = new DefaultMutableTreeNode("Data Properties:"); Map<IRI, List<String>> datProps = o.getDataPropertyValues(myIRI); for (IRI dprop : datProps.keySet()){ DefaultMutableTreeNode dpropNode = new DefaultMutableTreeNode(dprop.getShortForm()); for (String val : datProps.get(dprop)){ DefaultMutableTreeNode dpropValNode = new DefaultMutableTreeNode(val); dpropNode.add(dpropValNode); } dataProperties.add(dpropNode); } root.add(dataProperties); // Next, get all of the subclasses: DefaultMutableTreeNode subclassMemberships = new DefaultMutableTreeNode("Subclass Memberships:"); List<IRI> subclasses = o.getClassMemberships(myIRI); for (IRI sub : subclasses){ DefaultMutableTreeNode subNode = new DefaultMutableTreeNode(sub.getShortForm()); subclassMemberships.add(subNode); } root.add(subclassMemberships); return root; } }
UTF-8
Java
8,953
java
KIDSUIAbstractComponent.java
Java
[ { "context": "et.kids.ui.problems.KIDSUIProblem;\n\n/**\n * @author cstras\n *\n * Implementation of common methods for implem", "end": 869, "score": 0.9996523857116699, "start": 863, "tag": "USERNAME", "value": "cstras" } ]
null
[]
/** * */ package net.strasnet.kids.ui.components; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.log4j.LogManager; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLDataFactory; import net.strasnet.kids.ui.KIDSUIInferredProperty; import net.strasnet.kids.ui.KIDSUIRequiredDataProperty; import net.strasnet.kids.ui.KIDSUIRequiredProperty; import net.strasnet.kids.ui.gui.KIDSGUIOracle; import net.strasnet.kids.ui.problems.KIDSMissingDataPropertyUIProblem; import net.strasnet.kids.ui.problems.KIDSMissingRelationUIProblem; import net.strasnet.kids.ui.problems.KIDSSubclassRequiredUIProblem; import net.strasnet.kids.ui.problems.KIDSUIProblem; /** * @author cstras * * Implementation of common methods for implementers of KIDSUIComponent */ public abstract class KIDSUIAbstractComponent implements KIDSUIComponent { public static final org.apache.log4j.Logger logme = LogManager.getLogger(KIDSUIAbstractComponent.class.getName()); public enum KIDSDatatypeClass { STRING, JAVA, FILEPATH }; public enum KIDSComponentDefinition { TBOX, ABOX }; protected IRI myIRI = null; protected Set<KIDSUIInferredProperty> myInfProps; protected Set<KIDSUIRequiredProperty> myReqProps; protected Set<KIDSUIRequiredDataProperty> myDataProps; protected String ABOXIRI; protected IRI TBOXIRI; protected KIDSGUIOracle o; protected OWLDataFactory owldf; protected IRI requiredSubclassOf; protected KIDSComponentDefinition deflocation; public KIDSUIAbstractComponent(IRI myID, KIDSGUIOracle o){ myIRI = myID; TBOXIRI = o.getTBOXIRI(); ABOXIRI = myIRI.getNamespace(); this.o = o; this.owldf = o.getOwlDataFactory(); this.requiredSubclassOf = null; myReqProps = new HashSet<KIDSUIRequiredProperty>(); myInfProps = new HashSet<KIDSUIInferredProperty>(); myDataProps = new HashSet<KIDSUIRequiredDataProperty>(); // By default, set defining component location to the TBOX: this.deflocation = KIDSComponentDefinition.TBOX; } @Override public Set<KIDSUIProblem> getComponentProblems() { HashSet<KIDSUIProblem> toReturn = new HashSet<KIDSUIProblem>(); // Check that each required object property has a target; if not, add to problems. for (KIDSUIRequiredProperty rprop : myReqProps){ Set<IRI> propvals = o.getPropertyIndividualsOfClass(myIRI, rprop.getProperty(), rprop.getObjectClass()); logme.debug(String.format("Evaluating required property (%s, %s, %s)", myIRI, rprop.getProperty(), rprop.getObjectClass())); if (propvals.size() == 0){ // Well, we have a problem: toReturn.add(new KIDSMissingRelationUIProblem( String.format("Required property not satisfied: (%s, %s, %s)", o.getShortIRIString(myIRI), o.getShortIRIString(rprop.getProperty()), o.getShortIRIString(rprop.getObjectClass())), KIDSUIProblem.ProblemType.REQUIRED, rprop.getProperty(), rprop.getObjectClass(), o ) ); } else { logme.debug(String.format("Property requirement satisfied by (%s, %s, %s)", o.getShortIRIString(myIRI), o.getShortIRIString(rprop.getProperty()), o.getShortIRIString(propvals.iterator().next()))); } } // Check that each inferred object property has a target; if not, add to problems. for (KIDSUIInferredProperty rprop : myInfProps){ Set<IRI> propvals = o.getPropertyIndividualsOfClass(myIRI, rprop.getProperty(), rprop.getObjectClass()); if (propvals.size() == 0){ // Well, we have a problem: toReturn.add(new KIDSUIProblem( String.format("Inferred property not defined: (%s, %s, %s)", o.getShortIRIString(myIRI), o.getShortIRIString(rprop.getProperty()), o.getShortIRIString(rprop.getObjectClass())), KIDSUIProblem.ProblemType.REQUIRED ) ); } } // Check that each specified data property has a target; if not, add to problems. for (KIDSUIRequiredDataProperty rprop : myDataProps){ Set<String> values = o.getDataPropertyValues(myIRI, rprop.getProperty()); if (values.size() == 0){ // Well, we have a problem: toReturn.add(new KIDSMissingDataPropertyUIProblem( String.format("Data property not defined: (%s, %s, %s)", o.getShortIRIString(myIRI), o.getShortIRIString(rprop.getProperty()), rprop.getObjectClass()), KIDSUIProblem.ProblemType.REQUIRED, myIRI, rprop.getObjectClass(), rprop.getProperty(), o ) ); } } // If subclass membership is required, ensure that we are a member of a strict subclass: if (requiredSubclassOf != null){ logme.debug(String.format("Checking that individual %s is a member of a subclass of %s...",getIRI().getShortForm(), requiredSubclassOf.getShortForm())); if (!o.isMemberOfStrictSubclass(requiredSubclassOf, myIRI)){ logme.debug(String.format("Individual %s is not a member of a subclass of %s; adding as a problem...",getIRI().getShortForm(), requiredSubclassOf.getShortForm())); toReturn.add(new KIDSSubclassRequiredUIProblem( String.format("%s must be a member of a subclass of %s", o.getShortIRIString(myIRI), o.getShortIRIString(requiredSubclassOf)), KIDSUIProblem.ProblemType.REQUIRED, requiredSubclassOf, myIRI, o ) ); } } logme.debug(String.format("Found %d problems for %s.", toReturn.size(), myIRI.getFragment())); return toReturn; } /** * @return - The IRI as defined for the individual represented by this class. */ @Override public IRI getIRI(){ return this.myIRI; } /** * @return - A short-form version of the IRI for a component. */ @Override public String toString(){ return this.o.getShortIRIString(this.myIRI); } @Override public List<KIDSUIRelation> getRelations(){ List <KIDSUIRelation> toReturn = new LinkedList<KIDSUIRelation>(); // Add object relations for (KIDSUIRequiredProperty p : this.myReqProps){ toReturn.add(new KIDSUIObjectRelationComponent(this.getIRI(), p.getProperty(), p.getObjectClass())); } // Add data relations for (KIDSUIRequiredDataProperty p : this.myDataProps){ toReturn.add(new KIDSUIDataRelationComponent(this.getIRI(), p.getProperty(), p.getObjectClass())); } return toReturn; } @Override public KIDSComponentDefinition getDefiningLocation(){ if (this.deflocation == null){ logme.error(String.format("Component %s does not provide a defining location.", this.getIRI())); } return this.deflocation; } @Override /** * * @param root - The root of the tree to populate with details. * * @return - A tree node hierarchy of values that provide details about the individual. All components will provide at least: * + Object Property Values * + Property IRI: * + individual IRI 1 * ... * + Data Property Values * + Property IRI: * + string value 1 * ... * + Class Memberships: * + Class IRI */ public DefaultMutableTreeNode getComponentDetails(DefaultMutableTreeNode root){ // First, get all of the object properties associated with this individual: DefaultMutableTreeNode objectProperties = new DefaultMutableTreeNode("Object Properties:"); Map<IRI, List<IRI>> objProps = o.getObjectPropertyValues(myIRI); for (IRI oprop : objProps.keySet()){ DefaultMutableTreeNode opropNode = new DefaultMutableTreeNode(oprop.getShortForm()); for (IRI val : objProps.get(oprop)){ DefaultMutableTreeNode opropValNode = new DefaultMutableTreeNode(val.getShortForm()); opropNode.add(opropValNode); } objectProperties.add(opropNode); } root.add(objectProperties); // Next, get all of the data property values: DefaultMutableTreeNode dataProperties = new DefaultMutableTreeNode("Data Properties:"); Map<IRI, List<String>> datProps = o.getDataPropertyValues(myIRI); for (IRI dprop : datProps.keySet()){ DefaultMutableTreeNode dpropNode = new DefaultMutableTreeNode(dprop.getShortForm()); for (String val : datProps.get(dprop)){ DefaultMutableTreeNode dpropValNode = new DefaultMutableTreeNode(val); dpropNode.add(dpropValNode); } dataProperties.add(dpropNode); } root.add(dataProperties); // Next, get all of the subclasses: DefaultMutableTreeNode subclassMemberships = new DefaultMutableTreeNode("Subclass Memberships:"); List<IRI> subclasses = o.getClassMemberships(myIRI); for (IRI sub : subclasses){ DefaultMutableTreeNode subNode = new DefaultMutableTreeNode(sub.getShortForm()); subclassMemberships.add(subNode); } root.add(subclassMemberships); return root; } }
8,953
0.707361
0.706579
279
31.089605
29.51828
167
false
false
0
0
0
0
0
0
2.913979
false
false
12
e8b421874435153994a34de4c8d1c0b15115d526
15,728,170,290,032
fcb03efe322daae6d12a326e2e2b4937c2a6dd11
/Data Intensive Computing/hw4/hbase/src/Phase1.java
5c3d7f3d8ce757f9f8085ec2726da7ff04c1dc49
[]
no_license
Naveen1789/myHub
https://github.com/Naveen1789/myHub
f2aaff92ae0a5418da2d656bd1e8945513bbc429
02ee8269b9cb86848918a12f300e02c11bb91808
refs/heads/master
2020-12-24T12:04:21.825000
2015-09-27T08:32:41
2015-09-27T08:32:41
31,687,182
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.mapreduce.TableReducer; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Text; public class Phase1 { public static class MyMapper extends TableMapper<Text, Text> { public static final byte[] STOCK = "stock".getBytes(); public static final byte[] STOCK_ATTR1 = "name".getBytes(); public static final byte[] TIME = "time".getBytes(); public static final byte[] TIME_ATTR1 = "yr".getBytes(); public static final byte[] TIME_ATTR2 = "mm".getBytes(); public static final byte[] TIME_ATTR3 = "dd".getBytes(); public static final byte[] PRICE = "price".getBytes(); public static final byte[] PRICE_ATTR1 = "price".getBytes(); private Text keyTemp = new Text(); private Text valTemp = new Text(); public void map(ImmutableBytesWritable row, Result value, Context context) throws IOException, InterruptedException { String key = new String(value.getValue(STOCK, STOCK_ATTR1)); String val = new String(value.getValue(TIME, TIME_ATTR1)) + "-" + new String(value.getValue(TIME, TIME_ATTR2)) + "-" + new String(value.getValue(TIME, TIME_ATTR3)) + "," + new String(value.getValue(PRICE, PRICE_ATTR1)); keyTemp.set(key); valTemp.set(val); try{ context.write(keyTemp, valTemp); } catch(Exception e){ e.printStackTrace(); } } } public static class MyTableReducer extends TableReducer<Text, Text, ImmutableBytesWritable> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { String tempDate; String tempMonth; String tempYear; String tempAdjCP; String temp; String date; String mapKey; String mapValue; String arr[]; String dateArr[]; HashMap<String,String> map = new HashMap<String,String>(); int count = 0; for (Text val : values) { // System.out.println("Inside while loop"); count++; temp = (val.toString()); arr = temp.split(","); date = arr[0]; // System.out.println("date : " + date); dateArr = date.split("-"); if((dateArr != null) && (dateArr.length == 3)){ tempYear = dateArr[0]; tempMonth = dateArr[1]; tempDate = dateArr[2]; tempAdjCP = arr[1]; // System.out.println("tempAdjCP : " + tempAdjCP); mapKey = key.toString() + "#"+ tempYear + "#" + tempMonth; // System.out.println("mapKey : " + mapKey); if(map.containsKey(mapKey)){ // System.out.println("Map contains mapkey"); // System.out.println("Map contains key"); temp = map.get(mapKey); // System.out.println("temp : " + temp); dateArr = temp.split("#"); if(Integer.parseInt(tempDate) < Integer.parseInt(dateArr[0])){ mapValue = tempDate + "#" + tempAdjCP + "#" + dateArr[2] + "#" + dateArr[3]; map.remove(mapKey); map.put(mapKey, mapValue); } else if(Integer.parseInt(tempDate) > Integer.parseInt(dateArr[2])){ mapValue = dateArr[0] + "#" + dateArr[1] + "#" + tempDate + "#" + tempAdjCP; map.remove(mapKey); map.put(mapKey, mapValue); } } else{ // System.out.println("Map does not contain key"); mapValue = tempDate + "#" + tempAdjCP + "#" + tempDate + "#" + tempAdjCP; map.put(mapKey, mapValue); } } } // System.out.println("count : " + count); // System.out.println("map.size() : " + map.size()); // [ // Calculate xBar, n String min; String max; String acp; String tempAcpArr[]; Double xi = 0.0; Double xBar = 0.0; Double sum = 0.0; int n = 0; LinkedList<Double> x = new LinkedList<Double>(); for(String k : map.keySet()){ acp = map.get(k); tempAcpArr = acp.split("#"); min = tempAcpArr[1]; max = tempAcpArr[3]; xi = ( Double.parseDouble(max) - Double.parseDouble(min) ) / (Double.parseDouble(min)); sum = sum + xi; n = n + 1; x.add(xi); } // System.out.println("sum : " + sum); // System.out.println("n : " + n); xBar = (sum) / n ; // System.out.println("xBar : " + xBar); // ] // [ // Calculate volatility Double sumOfSqDiff = 0.0 ; for (Double d : x){ sumOfSqDiff = sumOfSqDiff + ((d-xBar) * (d-xBar)); } // System.out.println("sumOfSqDiff : " + sumOfSqDiff); Double volatility = 0.0; if(n > 1){ volatility = sumOfSqDiff / (n-1); volatility = Math.sqrt(volatility); // System.out.println("volatility : " + volatility); Put put = new Put(Bytes.toBytes(key.toString())); put.add(Bytes.toBytes("StockName"), Bytes.toBytes("name"), Bytes.toBytes(key.toString())); put.add(Bytes.toBytes("Volatility"), Bytes.toBytes("vol"), Bytes.toBytes(volatility.toString())); context.write(null, put); } } } }
UTF-8
Java
5,332
java
Phase1.java
Java
[]
null
[]
import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.mapreduce.TableReducer; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Text; public class Phase1 { public static class MyMapper extends TableMapper<Text, Text> { public static final byte[] STOCK = "stock".getBytes(); public static final byte[] STOCK_ATTR1 = "name".getBytes(); public static final byte[] TIME = "time".getBytes(); public static final byte[] TIME_ATTR1 = "yr".getBytes(); public static final byte[] TIME_ATTR2 = "mm".getBytes(); public static final byte[] TIME_ATTR3 = "dd".getBytes(); public static final byte[] PRICE = "price".getBytes(); public static final byte[] PRICE_ATTR1 = "price".getBytes(); private Text keyTemp = new Text(); private Text valTemp = new Text(); public void map(ImmutableBytesWritable row, Result value, Context context) throws IOException, InterruptedException { String key = new String(value.getValue(STOCK, STOCK_ATTR1)); String val = new String(value.getValue(TIME, TIME_ATTR1)) + "-" + new String(value.getValue(TIME, TIME_ATTR2)) + "-" + new String(value.getValue(TIME, TIME_ATTR3)) + "," + new String(value.getValue(PRICE, PRICE_ATTR1)); keyTemp.set(key); valTemp.set(val); try{ context.write(keyTemp, valTemp); } catch(Exception e){ e.printStackTrace(); } } } public static class MyTableReducer extends TableReducer<Text, Text, ImmutableBytesWritable> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { String tempDate; String tempMonth; String tempYear; String tempAdjCP; String temp; String date; String mapKey; String mapValue; String arr[]; String dateArr[]; HashMap<String,String> map = new HashMap<String,String>(); int count = 0; for (Text val : values) { // System.out.println("Inside while loop"); count++; temp = (val.toString()); arr = temp.split(","); date = arr[0]; // System.out.println("date : " + date); dateArr = date.split("-"); if((dateArr != null) && (dateArr.length == 3)){ tempYear = dateArr[0]; tempMonth = dateArr[1]; tempDate = dateArr[2]; tempAdjCP = arr[1]; // System.out.println("tempAdjCP : " + tempAdjCP); mapKey = key.toString() + "#"+ tempYear + "#" + tempMonth; // System.out.println("mapKey : " + mapKey); if(map.containsKey(mapKey)){ // System.out.println("Map contains mapkey"); // System.out.println("Map contains key"); temp = map.get(mapKey); // System.out.println("temp : " + temp); dateArr = temp.split("#"); if(Integer.parseInt(tempDate) < Integer.parseInt(dateArr[0])){ mapValue = tempDate + "#" + tempAdjCP + "#" + dateArr[2] + "#" + dateArr[3]; map.remove(mapKey); map.put(mapKey, mapValue); } else if(Integer.parseInt(tempDate) > Integer.parseInt(dateArr[2])){ mapValue = dateArr[0] + "#" + dateArr[1] + "#" + tempDate + "#" + tempAdjCP; map.remove(mapKey); map.put(mapKey, mapValue); } } else{ // System.out.println("Map does not contain key"); mapValue = tempDate + "#" + tempAdjCP + "#" + tempDate + "#" + tempAdjCP; map.put(mapKey, mapValue); } } } // System.out.println("count : " + count); // System.out.println("map.size() : " + map.size()); // [ // Calculate xBar, n String min; String max; String acp; String tempAcpArr[]; Double xi = 0.0; Double xBar = 0.0; Double sum = 0.0; int n = 0; LinkedList<Double> x = new LinkedList<Double>(); for(String k : map.keySet()){ acp = map.get(k); tempAcpArr = acp.split("#"); min = tempAcpArr[1]; max = tempAcpArr[3]; xi = ( Double.parseDouble(max) - Double.parseDouble(min) ) / (Double.parseDouble(min)); sum = sum + xi; n = n + 1; x.add(xi); } // System.out.println("sum : " + sum); // System.out.println("n : " + n); xBar = (sum) / n ; // System.out.println("xBar : " + xBar); // ] // [ // Calculate volatility Double sumOfSqDiff = 0.0 ; for (Double d : x){ sumOfSqDiff = sumOfSqDiff + ((d-xBar) * (d-xBar)); } // System.out.println("sumOfSqDiff : " + sumOfSqDiff); Double volatility = 0.0; if(n > 1){ volatility = sumOfSqDiff / (n-1); volatility = Math.sqrt(volatility); // System.out.println("volatility : " + volatility); Put put = new Put(Bytes.toBytes(key.toString())); put.add(Bytes.toBytes("StockName"), Bytes.toBytes("name"), Bytes.toBytes(key.toString())); put.add(Bytes.toBytes("Volatility"), Bytes.toBytes("vol"), Bytes.toBytes(volatility.toString())); context.write(null, put); } } } }
5,332
0.592836
0.585334
196
26.204082
28.654507
225
false
false
0
0
0
0
0
0
3.678571
false
false
12
043194844dff569669c0ae5183f0719de6f841a2
8,564,164,825,214
03541926ffda46547e71fd4125c12bb831b8c214
/src/practice/CodeInstance11.java
6089e5f9f1484ef1314f1218473c97aaf1a893d8
[]
no_license
zhenjingbiao/Letcode
https://github.com/zhenjingbiao/Letcode
537875adc3be155d8074e922d5787add87235979
59abefccbb61e18cd80d7824f9c67b53b49b5bfe
refs/heads/master
2020-04-23T20:23:20.968000
2019-05-05T08:50:01
2019-05-05T08:50:01
171,438,366
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package practice;//题目: //我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠 // 地覆盖一个2*n的大矩形,总共有多少种方法? public class CodeInstance11 { public static void main(String[] args) { System.out.println(numberOf1(5)); System.out.println(numberOf12(5)); System.out.println(numberOf13(5)); } //方法一 public static int numberOf1(int n) { int count=0; int flag=1; while(flag!=0){ if((flag&n)!=0){ count++; } flag=flag<<1; } return count; } public static int numberOf12(int n){ int count=0; while (n!=0){ n=n&(n-1); count++; } return count; } public static int numberOf13(int n) { int a = 0; for(int i = 0;i<32;i++){ if((n&(1<<i))==(1<<i)){ a++; } } return a; } //相关题目:判断一个数是不是二的整数次方 ? //两个整数m,n,需要改变m的二进制表示中的多少位才能得到n }
UTF-8
Java
1,192
java
CodeInstance11.java
Java
[]
null
[]
package practice;//题目: //我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠 // 地覆盖一个2*n的大矩形,总共有多少种方法? public class CodeInstance11 { public static void main(String[] args) { System.out.println(numberOf1(5)); System.out.println(numberOf12(5)); System.out.println(numberOf13(5)); } //方法一 public static int numberOf1(int n) { int count=0; int flag=1; while(flag!=0){ if((flag&n)!=0){ count++; } flag=flag<<1; } return count; } public static int numberOf12(int n){ int count=0; while (n!=0){ n=n&(n-1); count++; } return count; } public static int numberOf13(int n) { int a = 0; for(int i = 0;i<32;i++){ if((n&(1<<i))==(1<<i)){ a++; } } return a; } //相关题目:判断一个数是不是二的整数次方 ? //两个整数m,n,需要改变m的二进制表示中的多少位才能得到n }
1,192
0.479675
0.445122
47
19.936171
13.866237
44
false
false
0
0
0
0
0
0
0.404255
false
false
12
030da11c61203dca06ccadea8d534f0495fa296a
8,564,164,825,188
ab3b72de30ea81bc1d41cd4cd3fb80ba35ad879f
/starfish-mall/starfish-mall-bean/src/main/java/priv/starfish/mall/comn/entity/BankProvinceCode.java
0717b426dc2f1f8ec3ca3c9e75804eea37a36809
[]
no_license
Jstarfish/starfish
https://github.com/Jstarfish/starfish
f81f147d7a93432c6aa77e5d34eb7d12b4312b89
2c15e33c5d158d333d21f68b98cc161d2afa7cd3
refs/heads/master
2022-12-21T12:05:08.900000
2019-09-04T06:52:07
2019-09-04T06:52:07
126,459,466
0
1
null
false
2022-12-16T04:52:51
2018-03-23T09:01:56
2019-09-04T06:52:16
2022-12-16T04:52:48
90,097
0
1
19
Java
false
false
package priv.starfish.mall.comn.entity; import java.io.Serializable; import java.sql.Types; import priv.starfish.common.annotation.Column; import priv.starfish.common.annotation.ForeignKey; import priv.starfish.common.annotation.Id; import priv.starfish.common.annotation.Table; /** * 银行省份代码 * * @author "WJJ" * @date 2016年1月26日 上午11:08:32 * */ @Table(name = "bank_province_code") public class BankProvinceCode implements Serializable { private static final long serialVersionUID = 1L; @Id(type = Types.INTEGER) private Integer id; @Column(nullable = false, type = Types.VARCHAR) @ForeignKey(refEntityClass = Bank.class, refFieldName = "code") private String bankCode; @Column(nullable = false, type = Types.VARCHAR) private String province; @Column(type = Types.VARCHAR, length = 30, desc = "代码") private String code; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBankCode() { return bankCode; } public void setBankCode(String bankCode) { this.bankCode = bankCode; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public String toString() { return "BankProvinceCode [id=" + id + ", bankCode=" + bankCode + ", province=" + province + ", code=" + code + "]"; } }
UTF-8
Java
1,496
java
BankProvinceCode.java
Java
[ { "context": ".annotation.Table;\n\n/**\n * 银行省份代码\n * \n * @author \"WJJ\"\n * @date 2016年1月26日 上午11:08:32\n *\n */\n@Table(nam", "end": 315, "score": 0.9996906518936157, "start": 312, "tag": "USERNAME", "value": "WJJ" } ]
null
[]
package priv.starfish.mall.comn.entity; import java.io.Serializable; import java.sql.Types; import priv.starfish.common.annotation.Column; import priv.starfish.common.annotation.ForeignKey; import priv.starfish.common.annotation.Id; import priv.starfish.common.annotation.Table; /** * 银行省份代码 * * @author "WJJ" * @date 2016年1月26日 上午11:08:32 * */ @Table(name = "bank_province_code") public class BankProvinceCode implements Serializable { private static final long serialVersionUID = 1L; @Id(type = Types.INTEGER) private Integer id; @Column(nullable = false, type = Types.VARCHAR) @ForeignKey(refEntityClass = Bank.class, refFieldName = "code") private String bankCode; @Column(nullable = false, type = Types.VARCHAR) private String province; @Column(type = Types.VARCHAR, length = 30, desc = "代码") private String code; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBankCode() { return bankCode; } public void setBankCode(String bankCode) { this.bankCode = bankCode; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public String toString() { return "BankProvinceCode [id=" + id + ", bankCode=" + bankCode + ", province=" + province + ", code=" + code + "]"; } }
1,496
0.705442
0.694558
73
19.136986
21.460583
117
false
false
0
0
0
0
0
0
1.041096
false
false
12
6dc6d70ad7b459753255c4e09c2b50120cd70a79
1,529,008,399,003
08461cb5fd062b264e6589c536c76bb5b9e186b5
/src/main/java/com/stream/consumer/receive/DiyReceiveService.java
59dc7049e795dc861124abef4295be5868f65363
[]
no_license
mxfdsy/consumer
https://github.com/mxfdsy/consumer
e0ce6fb4b7b5e46a0c842855f04636d4169ee145
007b022ac46bd04ebd5003448ac929030a74c5ec
refs/heads/master
2020-04-28T04:50:52.249000
2019-03-11T12:34:45
2019-03-11T12:34:45
174,996,424
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stream.consumer.receive; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.StreamListener; /** */ @EnableBinding(MyDiyReceiveService.class) public class DiyReceiveService { @StreamListener(MyDiyReceiveService.INPUT) public void receive(Object payload){ System.out.println(payload); } }
UTF-8
Java
391
java
DiyReceiveService.java
Java
[]
null
[]
package com.stream.consumer.receive; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.StreamListener; /** */ @EnableBinding(MyDiyReceiveService.class) public class DiyReceiveService { @StreamListener(MyDiyReceiveService.INPUT) public void receive(Object payload){ System.out.println(payload); } }
391
0.777494
0.777494
17
22
23.527206
66
false
false
0
0
0
0
0
0
0.235294
false
false
12
ce151035cf5187f8a629fb97b9d041481373a33d
24,361,054,553,620
a94b5106c315debb2072eb3786bf45fadd1c4d02
/src/main/java/duke/task/ToDoTask.java
26bb3f33c8645080977b78001a85cf9b34223718
[]
no_license
seanlowjk/duke
https://github.com/seanlowjk/duke
856ada426af2ef1e2f14d7120aa7b4963756fc18
95553ff84e335425ec8585388b47ca6b18093777
refs/heads/master
2020-07-05T16:04:49.853000
2019-10-06T02:50:12
2019-10-06T02:50:12
202,540,584
3
0
null
true
2019-08-15T12:51:38
2019-08-15T12:51:38
2019-08-15T07:33:18
2019-08-15T07:33:16
1,383
0
0
0
null
false
false
package duke.task; /** * A Class that represents a Task in which the user wishes to do. */ public class ToDoTask extends Task { /** * Constructs a ToDo Task which sets the default of isCompleted value to false. * @param todo The name of the task. */ public ToDoTask(String todo) { super(todo); } /** * Constructs the name of the todo task. * @param todo the array containing the data for the task name. * @return the task name as a String. */ public static String getName(String[] todo) { String taskName = ""; for (int i = 1; i < todo.length; i++) { if (i > 1) { taskName += " "; } taskName += todo[i]; } return taskName; } /** * Constructs a ToDo Task based on the name and the isComplated value given. * @param todo The name of the task. * @param isCompleted Whether the task is Completed or not. */ public ToDoTask(String todo, boolean isCompleted) { super(todo, isCompleted); } /** * Returns a string representation of the Task. * @return A string representation of the Task. */ public String toString() { if (isCompleted) { return String.format("[T][Y] %s", this.todo); } else { return String.format("[T][N] %s", this.todo); } } }
UTF-8
Java
1,413
java
ToDoTask.java
Java
[]
null
[]
package duke.task; /** * A Class that represents a Task in which the user wishes to do. */ public class ToDoTask extends Task { /** * Constructs a ToDo Task which sets the default of isCompleted value to false. * @param todo The name of the task. */ public ToDoTask(String todo) { super(todo); } /** * Constructs the name of the todo task. * @param todo the array containing the data for the task name. * @return the task name as a String. */ public static String getName(String[] todo) { String taskName = ""; for (int i = 1; i < todo.length; i++) { if (i > 1) { taskName += " "; } taskName += todo[i]; } return taskName; } /** * Constructs a ToDo Task based on the name and the isComplated value given. * @param todo The name of the task. * @param isCompleted Whether the task is Completed or not. */ public ToDoTask(String todo, boolean isCompleted) { super(todo, isCompleted); } /** * Returns a string representation of the Task. * @return A string representation of the Task. */ public String toString() { if (isCompleted) { return String.format("[T][Y] %s", this.todo); } else { return String.format("[T][N] %s", this.todo); } } }
1,413
0.557679
0.556263
53
25.660378
23.163034
83
false
false
0
0
0
0
0
0
0.283019
false
false
12
c0a5e94d42f9fe8813049b6600488463c3e787e8
10,831,907,590,201
b1ef9fd677e620f67efbfd878dcb30e9da117c92
/self_org_control/src/main/java/com/watchtogether/autonomic/selforg/red5/manager/group/GroupReceiverAdapter.java
2a0be0cb97c23422e1f3f5629c084b3a8b5c40e0
[ "MIT" ]
permissive
bogsolomon/self-org-scala
https://github.com/bogsolomon/self-org-scala
93705425c36a98cefe1b2f687b6006b8806efada
09225bd9f84ca6663cb0da8b4db5ccb3c772eb46
refs/heads/master
2020-04-06T06:04:20.703000
2016-11-11T16:37:43
2016-11-11T16:37:43
52,645,625
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.watchtogether.autonomic.selforg.red5.manager.group; import org.jgroups.Message; import org.jgroups.Receiver; import org.jgroups.ReceiverAdapter; import com.watchtogether.common.StringMessages; public class GroupReceiverAdapter extends ReceiverAdapter { private GroupManager groupManager; @Override public void receive(Message msg) { Object message = msg.getObject(); if (message instanceof String && message.equals(StringMessages.JOIN_MESSAGE)) { } //pass messages to other receivers for (Receiver rec:groupManager.getReceivers()) { rec.receive(msg); } } public void setGroupManager(GroupManager groupManager) { this.groupManager = groupManager; } }
UTF-8
Java
702
java
GroupReceiverAdapter.java
Java
[]
null
[]
package com.watchtogether.autonomic.selforg.red5.manager.group; import org.jgroups.Message; import org.jgroups.Receiver; import org.jgroups.ReceiverAdapter; import com.watchtogether.common.StringMessages; public class GroupReceiverAdapter extends ReceiverAdapter { private GroupManager groupManager; @Override public void receive(Message msg) { Object message = msg.getObject(); if (message instanceof String && message.equals(StringMessages.JOIN_MESSAGE)) { } //pass messages to other receivers for (Receiver rec:groupManager.getReceivers()) { rec.receive(msg); } } public void setGroupManager(GroupManager groupManager) { this.groupManager = groupManager; } }
702
0.766382
0.764957
31
21.645161
23.364639
81
false
false
0
0
0
0
0
0
1.258065
false
false
12
1861ceb27044b3876b858e9889089ada3d93dad3
7,447,473,352,983
9d255746aca5cb8216bc8a531583025657343d53
/src/main/java/beamline/core/web/miner/controllers/InstanceController.java
1ce14ab8e34f8ab969796818e67a40cb28a1cfd4
[]
no_license
l-esa/core
https://github.com/l-esa/core
15102fdf15f5d09fb7effc52c6dcbfe817e5021c
06eb871587b47a86d54466380f238c828ce26554
refs/heads/master
2023-07-13T05:04:31.255000
2021-08-27T08:31:01
2021-08-27T08:31:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package beamline.core.web.miner.controllers; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import beamline.core.logger.Logger; import beamline.core.miner.AbstractMiner; import beamline.core.miner.exceptions.MinerException; import beamline.core.web.miner.models.Miner; import beamline.core.web.miner.models.MinerInstance; import beamline.core.web.miner.models.MinerInstanceConfiguration; import beamline.core.web.miner.models.MinerInstanceStatus; import beamline.core.web.miner.models.MinerParameter; import beamline.core.web.miner.models.MinerParameterValue; import beamline.core.web.miner.models.MinerView; import beamline.core.web.miner.models.MinerViewSummary; import beamline.core.web.miner.models.MinerParameter.Type; @RestController @RequestMapping("/api/v1/") @CrossOrigin public class InstanceController { @Autowired private MinerController minerController; @Autowired private UploadController uploadController; @Autowired private NotificationController notificationController; private Map<String, MinerInstance> instances = new HashMap<String, MinerInstance>(); private Map<String, MinerInstanceStatus> instancesStatus = new HashMap<String, MinerInstanceStatus>(); @GetMapping( value = "/instances", produces = { "application/json" }) public ResponseEntity<Collection<MinerInstance>> getInstances() { return new ResponseEntity<Collection<MinerInstance>>(instances.values(), HttpStatus.OK); } @PostMapping("/instances/{minerId}") public ResponseEntity<MinerInstance> createInstance(@PathVariable("minerId") String minerId, @RequestBody MinerInstanceConfiguration configuration) { if (!minerController.minerExists(minerId)) { return ResponseEntity.notFound().build(); } // create an instance of the miner MinerInstance mi = null; try { Miner miner = minerController.getById(minerId); Class<AbstractMiner> clazz = miner.getMinerClass(); Collection<MinerParameterValue> parameterValues = configuration.getParameterValues(); Collection<MinerParameterValue> parameterValuesTyped = new ArrayList<MinerParameterValue>(parameterValues.size()); for (MinerParameterValue v : parameterValues) { MinerParameterValue vNew = new MinerParameterValue(v.getName(), v.getValue()); for (MinerParameter p : minerController.getById(minerId).getConfigurationParameters()) { if (p.getName().equals(vNew.getName())) { vNew.setType(p.getType()); if (p.getType().equals(Type.FILE)) { vNew.setValue(uploadController.get((String) vNew.getValue())); } } } parameterValuesTyped.add(vNew); } AbstractMiner minerObject = clazz.getDeclaredConstructor().newInstance(); minerObject.setNotificationController(notificationController); minerObject.setStream(configuration.getStream()); mi = new MinerInstance(miner, configuration); mi.setMinerObject(minerObject); minerObject.setInstance(mi); instances.put(mi.getId(), mi); instancesStatus.put(mi.getId(), MinerInstanceStatus.CONFIGURING); configureInstance(mi.getId(), minerObject, parameterValuesTyped); } catch (Exception e) { Logger.instance().error(e); } return new ResponseEntity<MinerInstance>(mi, HttpStatus.OK); } @GetMapping("/instances/{instanceId}/start") public ResponseEntity<Boolean> instanceStart(@PathVariable("instanceId") String instanceId) { if (!instances.containsKey(instanceId)) { return ResponseEntity.notFound().build(); } try { instances.get(instanceId).getMinerObject().start(); instancesStatus.put(instanceId, MinerInstanceStatus.MINING); } catch (MinerException e) { Logger.instance().error(e); return new ResponseEntity<Boolean>(false, HttpStatus.OK); } return new ResponseEntity<Boolean>(true, HttpStatus.OK); } @DeleteMapping("/instances/{instanceId}/delete") public ResponseEntity<Void> instanceDelete(@PathVariable("instanceId") String instanceId) { if (!instances.containsKey(instanceId)) { return ResponseEntity.notFound().build(); } try{ instances.remove(instanceId); instancesStatus.remove(instanceId); }catch (Exception e) { Logger.instance().error(e); } return ResponseEntity.ok().build(); } @GetMapping("/instances/{instanceId}/stop") public ResponseEntity<Boolean> instanceStop(@PathVariable("instanceId") String instanceId) { if (!instances.containsKey(instanceId)) { return ResponseEntity.notFound().build(); } try { instances.get(instanceId).getMinerObject().stop(); instancesStatus.put(instanceId, MinerInstanceStatus.NOT_MINING); } catch (MinerException e) { Logger.instance().error(e); return new ResponseEntity<Boolean>(false, HttpStatus.OK); } return new ResponseEntity<Boolean>(true, HttpStatus.OK); } @GetMapping("/instances/{instanceId}/status") public ResponseEntity<MinerInstanceStatus> instanceStatus(@PathVariable("instanceId") String instanceId) { if (!instances.containsKey(instanceId)) { return ResponseEntity.notFound().build(); } return new ResponseEntity<MinerInstanceStatus>(instancesStatus.get(instanceId), HttpStatus.OK); } @PostMapping( value = "/instances/{instanceId}/views", produces = { "application/json" }) public ResponseEntity<Collection<MinerView>> instanceView(@PathVariable("instanceId") String instanceId, @RequestBody List<MinerParameterValue> configuration) { if (!instances.containsKey(instanceId)) { return ResponseEntity.notFound().build(); } MinerInstance mi = instances.get(instanceId); List<MinerView> views = mi.getMinerObject().getViews(configuration); views.add(0, new MinerViewSummary(mi)); return new ResponseEntity<Collection<MinerView>>(views, HttpStatus.OK); } private void configureInstance(String instanceId, AbstractMiner minerObject, Collection<MinerParameterValue> parameterValuesTyped) { new Thread() { @Override public void run() { minerObject.configure(parameterValuesTyped); instancesStatus.put(instanceId, MinerInstanceStatus.NOT_MINING); } }.start(); } }
UTF-8
Java
6,927
java
InstanceController.java
Java
[]
null
[]
package beamline.core.web.miner.controllers; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import beamline.core.logger.Logger; import beamline.core.miner.AbstractMiner; import beamline.core.miner.exceptions.MinerException; import beamline.core.web.miner.models.Miner; import beamline.core.web.miner.models.MinerInstance; import beamline.core.web.miner.models.MinerInstanceConfiguration; import beamline.core.web.miner.models.MinerInstanceStatus; import beamline.core.web.miner.models.MinerParameter; import beamline.core.web.miner.models.MinerParameterValue; import beamline.core.web.miner.models.MinerView; import beamline.core.web.miner.models.MinerViewSummary; import beamline.core.web.miner.models.MinerParameter.Type; @RestController @RequestMapping("/api/v1/") @CrossOrigin public class InstanceController { @Autowired private MinerController minerController; @Autowired private UploadController uploadController; @Autowired private NotificationController notificationController; private Map<String, MinerInstance> instances = new HashMap<String, MinerInstance>(); private Map<String, MinerInstanceStatus> instancesStatus = new HashMap<String, MinerInstanceStatus>(); @GetMapping( value = "/instances", produces = { "application/json" }) public ResponseEntity<Collection<MinerInstance>> getInstances() { return new ResponseEntity<Collection<MinerInstance>>(instances.values(), HttpStatus.OK); } @PostMapping("/instances/{minerId}") public ResponseEntity<MinerInstance> createInstance(@PathVariable("minerId") String minerId, @RequestBody MinerInstanceConfiguration configuration) { if (!minerController.minerExists(minerId)) { return ResponseEntity.notFound().build(); } // create an instance of the miner MinerInstance mi = null; try { Miner miner = minerController.getById(minerId); Class<AbstractMiner> clazz = miner.getMinerClass(); Collection<MinerParameterValue> parameterValues = configuration.getParameterValues(); Collection<MinerParameterValue> parameterValuesTyped = new ArrayList<MinerParameterValue>(parameterValues.size()); for (MinerParameterValue v : parameterValues) { MinerParameterValue vNew = new MinerParameterValue(v.getName(), v.getValue()); for (MinerParameter p : minerController.getById(minerId).getConfigurationParameters()) { if (p.getName().equals(vNew.getName())) { vNew.setType(p.getType()); if (p.getType().equals(Type.FILE)) { vNew.setValue(uploadController.get((String) vNew.getValue())); } } } parameterValuesTyped.add(vNew); } AbstractMiner minerObject = clazz.getDeclaredConstructor().newInstance(); minerObject.setNotificationController(notificationController); minerObject.setStream(configuration.getStream()); mi = new MinerInstance(miner, configuration); mi.setMinerObject(minerObject); minerObject.setInstance(mi); instances.put(mi.getId(), mi); instancesStatus.put(mi.getId(), MinerInstanceStatus.CONFIGURING); configureInstance(mi.getId(), minerObject, parameterValuesTyped); } catch (Exception e) { Logger.instance().error(e); } return new ResponseEntity<MinerInstance>(mi, HttpStatus.OK); } @GetMapping("/instances/{instanceId}/start") public ResponseEntity<Boolean> instanceStart(@PathVariable("instanceId") String instanceId) { if (!instances.containsKey(instanceId)) { return ResponseEntity.notFound().build(); } try { instances.get(instanceId).getMinerObject().start(); instancesStatus.put(instanceId, MinerInstanceStatus.MINING); } catch (MinerException e) { Logger.instance().error(e); return new ResponseEntity<Boolean>(false, HttpStatus.OK); } return new ResponseEntity<Boolean>(true, HttpStatus.OK); } @DeleteMapping("/instances/{instanceId}/delete") public ResponseEntity<Void> instanceDelete(@PathVariable("instanceId") String instanceId) { if (!instances.containsKey(instanceId)) { return ResponseEntity.notFound().build(); } try{ instances.remove(instanceId); instancesStatus.remove(instanceId); }catch (Exception e) { Logger.instance().error(e); } return ResponseEntity.ok().build(); } @GetMapping("/instances/{instanceId}/stop") public ResponseEntity<Boolean> instanceStop(@PathVariable("instanceId") String instanceId) { if (!instances.containsKey(instanceId)) { return ResponseEntity.notFound().build(); } try { instances.get(instanceId).getMinerObject().stop(); instancesStatus.put(instanceId, MinerInstanceStatus.NOT_MINING); } catch (MinerException e) { Logger.instance().error(e); return new ResponseEntity<Boolean>(false, HttpStatus.OK); } return new ResponseEntity<Boolean>(true, HttpStatus.OK); } @GetMapping("/instances/{instanceId}/status") public ResponseEntity<MinerInstanceStatus> instanceStatus(@PathVariable("instanceId") String instanceId) { if (!instances.containsKey(instanceId)) { return ResponseEntity.notFound().build(); } return new ResponseEntity<MinerInstanceStatus>(instancesStatus.get(instanceId), HttpStatus.OK); } @PostMapping( value = "/instances/{instanceId}/views", produces = { "application/json" }) public ResponseEntity<Collection<MinerView>> instanceView(@PathVariable("instanceId") String instanceId, @RequestBody List<MinerParameterValue> configuration) { if (!instances.containsKey(instanceId)) { return ResponseEntity.notFound().build(); } MinerInstance mi = instances.get(instanceId); List<MinerView> views = mi.getMinerObject().getViews(configuration); views.add(0, new MinerViewSummary(mi)); return new ResponseEntity<Collection<MinerView>>(views, HttpStatus.OK); } private void configureInstance(String instanceId, AbstractMiner minerObject, Collection<MinerParameterValue> parameterValuesTyped) { new Thread() { @Override public void run() { minerObject.configure(parameterValuesTyped); instancesStatus.put(instanceId, MinerInstanceStatus.NOT_MINING); } }.start(); } }
6,927
0.748376
0.748087
179
36.698322
31.151613
161
false
false
0
0
0
0
0
0
2.396648
false
false
12
0f44a64fec97474df4868b00ca160d3a26ced8d7
2,456,721,321,094
adcab187cc55aa4010ed353cc10e02b8a29d6e16
/src/main/java/com/lhjz/portal/entity/security/GroupMember.java
3c388689ff0f1ea1260459bcd7f3497c75e4c190
[ "Apache-2.0" ]
permissive
czs/lhjz.portal
https://github.com/czs/lhjz.portal
431ceb27e25616fc36022e6e26fb565acdb22e78
edc8c15051e1cfc6ed7a2a72d69fcf5ae8ec9db1
refs/heads/develop
2020-04-28T12:41:55.044000
2015-07-05T14:06:17
2015-07-05T14:06:17
33,015,756
0
1
null
false
2015-06-03T12:39:12
2015-03-28T00:43:41
2015-05-15T15:03:01
2015-06-03T12:39:12
14,568
0
0
4
JavaScript
null
null
package com.lhjz.portal.entity.security; // default package // Generated May 6, 2015 11:39:38 AM by Hibernate Tools 4.3.1 import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * GroupMember generated by hbm2java */ @Entity @Table(name = "group_members") public class GroupMember implements java.io.Serializable { /** serialVersionUID long */ private static final long serialVersionUID = -3808056203741340408L; private Long id; private Group group; private String username; public GroupMember() { } public GroupMember(Group group, String username) { this.group = group; this.username = username; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "group_id", nullable = false) public Group getGroup() { return this.group; } public void setGroup(Group group) { this.group = group; } @Column(name = "username", nullable = false, length = 50) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } }
UTF-8
Java
1,493
java
GroupMember.java
Java
[ { "context": "sername) {\n\t\tthis.group = group;\n\t\tthis.username = username;\n\t}\n\n\t@Id\n\t@GeneratedValue(strategy = IDENTITY)\n\t", "end": 897, "score": 0.6709847450256348, "start": 889, "tag": "USERNAME", "value": "username" }, { "context": "d setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n}\n", "end": 1485, "score": 0.7700762152671814, "start": 1477, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.lhjz.portal.entity.security; // default package // Generated May 6, 2015 11:39:38 AM by Hibernate Tools 4.3.1 import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * GroupMember generated by hbm2java */ @Entity @Table(name = "group_members") public class GroupMember implements java.io.Serializable { /** serialVersionUID long */ private static final long serialVersionUID = -3808056203741340408L; private Long id; private Group group; private String username; public GroupMember() { } public GroupMember(Group group, String username) { this.group = group; this.username = username; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "group_id", nullable = false) public Group getGroup() { return this.group; } public void setGroup(Group group) { this.group = group; } @Column(name = "username", nullable = false, length = 50) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } }
1,493
0.738111
0.713999
67
21.283583
19.04418
68
false
false
0
0
0
0
0
0
1.074627
false
false
12
204bc82fd48124fa6288c00ee3f44cc1024fb708
30,983,894,111,896
fc97069a0b4701fd7ee5d489e94abbfdba273066
/src/main/java/f/r2/o.java
b07c8c833a6adb5b7b3eb50b0965559a9f9596ee
[]
no_license
bellmit/zycami-ded
https://github.com/bellmit/zycami-ded
8604f1eb24fb767e4cf499e019d6e4568451bb4b
27686ca846de6d164692c81bac2ae7f85710361f
refs/heads/main
2023-06-17T20:36:29.589000
2021-07-19T18:58:18
2021-07-19T18:58:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Decompiled with CFR 0.151. */ package f.r2; import f.r2.c; import f.r2.d; public abstract class o { public abstract double a(); public final boolean b() { return d.F(this.a()); } public final boolean c() { return d.F(this.a()) ^ true; } public o d(double d10) { d10 = d.a0(d10); return this.e(d10); } public o e(double d10) { c c10 = new c(this, d10, null); return c10; } }
UTF-8
Java
472
java
o.java
Java
[]
null
[]
/* * Decompiled with CFR 0.151. */ package f.r2; import f.r2.c; import f.r2.d; public abstract class o { public abstract double a(); public final boolean b() { return d.F(this.a()); } public final boolean c() { return d.F(this.a()) ^ true; } public o d(double d10) { d10 = d.a0(d10); return this.e(d10); } public o e(double d10) { c c10 = new c(this, d10, null); return c10; } }
472
0.519068
0.46822
29
15.24138
13.205681
39
false
false
0
0
0
0
0
0
0.413793
false
false
12
6877df3431b9bcdc885604ad22f3ae53169bc7b5
30,983,894,113,231
f68b6547472acd4b0700f32b73d128a08f54f693
/src/main/java/org/launchcode/controllers/LevelController.java
acc525ce4d6d2d36d122d1d3a9dccb4c1e4dc53d
[]
no_license
hiroko-lc101/mathercise
https://github.com/hiroko-lc101/mathercise
51642a91c0cf2519af3557bc41d85bead008bd67
d8fa7900d7b8363474517d2a8a6f1fda7b3654a8
refs/heads/master
2020-03-24T12:41:45.078000
2018-09-29T17:09:39
2018-09-29T17:09:39
142,531,569
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.launchcode.controllers; import org.launchcode.models.Level; import org.launchcode.models.data.LevelDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @Controller @RequestMapping("level") public class LevelController { @Autowired private LevelDao levelDao; // Request path: level @RequestMapping(value = "") public String index(Model model) { model.addAttribute("levels", levelDao.findAll()); model.addAttribute("title", "Levels"); return "level/index"; } // Request path: level/add @RequestMapping(value = "add", method = RequestMethod.GET) public String displayAddLevelForm(Model model) { model.addAttribute("title", "Add Level"); model.addAttribute(new Level()); return "level/add"; } // Request path: level/add @RequestMapping(value = "add", method = RequestMethod.POST) public String processAddLevelForm(@ModelAttribute @Valid Level newLevel, Errors errors, Model model) { if (errors.hasErrors()) { model.addAttribute("title", "Add Level"); return "level/add"; } levelDao.save(newLevel); return "redirect:"; } // Request path: level/remove @RequestMapping(value = "remove", method = RequestMethod.GET) public String displayRemoveLevelForm(Model model){ model.addAttribute("levels", levelDao.findAll()); model.addAttribute("title", "Remove Levels"); return "level/remove"; } // Request path: level/remove @RequestMapping(value = "remove", method = RequestMethod.POST) public String processRemoveLevelForm(@RequestParam int[] levelIds) { for (int levelId : levelIds) { levelDao.delete(levelId); } return "redirect:"; } // Request path: level/edit @RequestMapping(value = "edit/{levelId}", method = RequestMethod.GET) public String displayEditLevelForm(Model model, @PathVariable int levelId) { model.addAttribute("level", levelDao.findOne(levelId)); model.addAttribute("title", "Edit Level"); return "level/edit"; } // Request path: level/edit @RequestMapping(value = "edit", method = RequestMethod.POST) public String processEditLevelForm(int levelId, String name) { Level editLevel = levelDao.findOne(levelId); editLevel.setName(name); levelDao.save(editLevel); return "redirect:"; } }
UTF-8
Java
2,725
java
LevelController.java
Java
[]
null
[]
package org.launchcode.controllers; import org.launchcode.models.Level; import org.launchcode.models.data.LevelDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @Controller @RequestMapping("level") public class LevelController { @Autowired private LevelDao levelDao; // Request path: level @RequestMapping(value = "") public String index(Model model) { model.addAttribute("levels", levelDao.findAll()); model.addAttribute("title", "Levels"); return "level/index"; } // Request path: level/add @RequestMapping(value = "add", method = RequestMethod.GET) public String displayAddLevelForm(Model model) { model.addAttribute("title", "Add Level"); model.addAttribute(new Level()); return "level/add"; } // Request path: level/add @RequestMapping(value = "add", method = RequestMethod.POST) public String processAddLevelForm(@ModelAttribute @Valid Level newLevel, Errors errors, Model model) { if (errors.hasErrors()) { model.addAttribute("title", "Add Level"); return "level/add"; } levelDao.save(newLevel); return "redirect:"; } // Request path: level/remove @RequestMapping(value = "remove", method = RequestMethod.GET) public String displayRemoveLevelForm(Model model){ model.addAttribute("levels", levelDao.findAll()); model.addAttribute("title", "Remove Levels"); return "level/remove"; } // Request path: level/remove @RequestMapping(value = "remove", method = RequestMethod.POST) public String processRemoveLevelForm(@RequestParam int[] levelIds) { for (int levelId : levelIds) { levelDao.delete(levelId); } return "redirect:"; } // Request path: level/edit @RequestMapping(value = "edit/{levelId}", method = RequestMethod.GET) public String displayEditLevelForm(Model model, @PathVariable int levelId) { model.addAttribute("level", levelDao.findOne(levelId)); model.addAttribute("title", "Edit Level"); return "level/edit"; } // Request path: level/edit @RequestMapping(value = "edit", method = RequestMethod.POST) public String processEditLevelForm(int levelId, String name) { Level editLevel = levelDao.findOne(levelId); editLevel.setName(name); levelDao.save(editLevel); return "redirect:"; } }
2,725
0.661651
0.661651
81
32.65432
22.730391
80
false
false
0
0
0
0
0
0
0.617284
false
false
12
b8f3463b43e3ff805bad325c041d1f1a7dbd7d89
24,481,313,613,187
b0f7e380c49406cc2b7cd32f77fff87776d1ef0a
/src/leetcode_array/M_34.java
649f2db17b53265dc513f1784f1ee5ec5238ffee
[]
no_license
Jackjoily/leetcode
https://github.com/Jackjoily/leetcode
478bdfdafb1f50bd505b31c900ee9bd7cde02267
74a153123b27d4725885bd7704c054334aa5ba6d
refs/heads/main
2023-07-12T12:17:53.889000
2021-08-07T12:17:10
2021-08-07T12:17:10
307,641,661
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode_array; import java.util.Arrays; /** * 给定一个按照升序排列的整数数组 nums,和一个目标值 target。 找出给定目标值在数组中的开始位置和结束位置。 * * @author jackjoily * */ public class M_34 { public static void main(String[] args) { M_34 m = new M_34(); int a[] = { 5, 7, 7, 8, 8, 10 }; System.out.println(Arrays.toString(m.searchRange1(a, 8))); } public int[] searchRange(int[] nums, int target) { if (nums.length == 0) { return new int[] { -1, -1 }; } if (nums[0] > target) { return new int[] { -1, -1 }; } if (nums[nums.length - 1] < target) { return new int[] { -1, -1 }; } int start = 0, end = nums.length - 1; boolean flag = true; while (start <= end && flag) { while (start < nums.length && nums[start] != target) start++; while (end >= 0 && nums[end] != target) end--; if (start < nums.length && end >= 0 && nums[start] == nums[end] && nums[end] == target) { flag = false; } } if (!flag) { return new int[] { start, end }; } else { return new int[] { -1, -1 }; } } public int[] searchRange1(int[] nums, int target) { if (nums.length == 0) { return new int[] { -1, -1 }; } if (nums[0] > target) { return new int[] { -1, -1 }; } if (nums[nums.length - 1] < target) { return new int[] { -1, -1 }; } int i = 0, j = nums.length - 1, mid = 0; int start = 0, end = 0; while (i >= 0 && j < nums.length && i <= j) { mid = (i + j) / 2; if (nums[mid] == target) { start = mid-1; end = mid + 1; while (start>= 0 && nums[start] == target) start--; while (end < nums.length && nums[end] == target) end++; if (start >= 0 && end < nums.length) { if (nums[start] == nums[end] && nums[start] == target) { return new int[] { start, end }; } else if (nums[start] != target && nums[end] != target) { return new int[] { mid, mid }; } else if (nums[start] == target) { return new int[] { start, mid }; } else if (nums[end] == target) { return new int[] { mid, end }; } } } else if (nums[mid] > target) { j = mid - 1; } else { i = mid + 1; } } return new int[] { -1, -1 }; } }
UTF-8
Java
2,338
java
M_34.java
Java
[ { "context": "标值 target。 找出给定目标值在数组中的开始位置和结束位置。\r\n * \r\n * @author jackjoily\r\n *\r\n */\r\npublic class M_34 {\r\n\r\n\tpublic static v", "end": 148, "score": 0.9992693662643433, "start": 139, "tag": "USERNAME", "value": "jackjoily" } ]
null
[]
package leetcode_array; import java.util.Arrays; /** * 给定一个按照升序排列的整数数组 nums,和一个目标值 target。 找出给定目标值在数组中的开始位置和结束位置。 * * @author jackjoily * */ public class M_34 { public static void main(String[] args) { M_34 m = new M_34(); int a[] = { 5, 7, 7, 8, 8, 10 }; System.out.println(Arrays.toString(m.searchRange1(a, 8))); } public int[] searchRange(int[] nums, int target) { if (nums.length == 0) { return new int[] { -1, -1 }; } if (nums[0] > target) { return new int[] { -1, -1 }; } if (nums[nums.length - 1] < target) { return new int[] { -1, -1 }; } int start = 0, end = nums.length - 1; boolean flag = true; while (start <= end && flag) { while (start < nums.length && nums[start] != target) start++; while (end >= 0 && nums[end] != target) end--; if (start < nums.length && end >= 0 && nums[start] == nums[end] && nums[end] == target) { flag = false; } } if (!flag) { return new int[] { start, end }; } else { return new int[] { -1, -1 }; } } public int[] searchRange1(int[] nums, int target) { if (nums.length == 0) { return new int[] { -1, -1 }; } if (nums[0] > target) { return new int[] { -1, -1 }; } if (nums[nums.length - 1] < target) { return new int[] { -1, -1 }; } int i = 0, j = nums.length - 1, mid = 0; int start = 0, end = 0; while (i >= 0 && j < nums.length && i <= j) { mid = (i + j) / 2; if (nums[mid] == target) { start = mid-1; end = mid + 1; while (start>= 0 && nums[start] == target) start--; while (end < nums.length && nums[end] == target) end++; if (start >= 0 && end < nums.length) { if (nums[start] == nums[end] && nums[start] == target) { return new int[] { start, end }; } else if (nums[start] != target && nums[end] != target) { return new int[] { mid, mid }; } else if (nums[start] == target) { return new int[] { start, mid }; } else if (nums[end] == target) { return new int[] { mid, end }; } } } else if (nums[mid] > target) { j = mid - 1; } else { i = mid + 1; } } return new int[] { -1, -1 }; } }
2,338
0.490214
0.465747
90
22.977777
19.290745
92
false
false
0
0
0
0
0
0
3.011111
false
false
12
e5874de11810cf3de0d6c9ae3e5c3e58b811f48b
24,945,170,094,608
9791e47816597c2bd56781d1006552d6020c2184
/Main.java
2a783b062d0e8bfe1ac10878af8a35fe8fb3563f
[]
no_license
korias24/ChocAn
https://github.com/korias24/ChocAn
f8f46a1ac70d1dc9816462832b2397778974bdd2
c1b3afd9b71043691991ce9ef8c4fa9f230127c8
refs/heads/master
2021-06-06T11:17:20.739000
2016-09-17T09:07:49
2016-09-17T09:07:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.IOException; /** * * @author Enis * The main class of the program. */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { System.out.println("File loc: "+FileUtilities.FILE_LOC+"\n"); ChocAnDPS dataCenter = new ChocAnDPS(); GlobalTerminal terminal = new GlobalTerminal(dataCenter); terminal.UseTerminal(); dataCenter.Exit(); } }
UTF-8
Java
522
java
Main.java
Java
[ { "context": "import java.io.IOException;\r\n/**\r\n *\r\n * @author Enis\r\n * The main class of the program.\r\n */\r\npublic c", "end": 53, "score": 0.958980917930603, "start": 49, "tag": "NAME", "value": "Enis" } ]
null
[]
import java.io.IOException; /** * * @author Enis * The main class of the program. */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { System.out.println("File loc: "+FileUtilities.FILE_LOC+"\n"); ChocAnDPS dataCenter = new ChocAnDPS(); GlobalTerminal terminal = new GlobalTerminal(dataCenter); terminal.UseTerminal(); dataCenter.Exit(); } }
522
0.590038
0.590038
22
21.727272
23.159883
73
false
false
0
0
0
0
0
0
0.272727
false
false
12
23dab5c95975478e1ec4347473e90e101fe60a1a
29,420,525,979,426
c2ef7c48e236c3d1780fdcac75abce25c672c652
/src/main/java/com/job/designpattern/flyweight/WebsiteFactory.java
42742cbdc800986b9cf564182f2588852bdecf42
[]
no_license
ToryZhou/design-pattern
https://github.com/ToryZhou/design-pattern
8d63b720ef54c9633eb10122c4cbeae45ae7ea1c
c9bcd6ae5cfb398e86d3af9a6a704e70a604b5cd
refs/heads/master
2022-09-10T09:57:10.616000
2022-08-22T02:48:42
2022-08-22T02:48:42
132,232,311
62
31
null
false
2022-08-22T02:48:43
2018-05-05T09:11:57
2022-07-19T08:52:02
2022-08-22T02:48:43
65,903
52
28
0
Java
false
false
package com.job.designpattern.flyweight; import java.util.Hashtable; public class WebsiteFactory { private Hashtable<String, Website> hashtable = new Hashtable<>(); public Website getWebsiteCategory(String key) { if (!hashtable.contains(key)) { hashtable.put(key, new ConcreteWebsite(key)); } return hashtable.get(key); } public int getWebsiteCount(){ return this.hashtable.size(); } }
UTF-8
Java
455
java
WebsiteFactory.java
Java
[]
null
[]
package com.job.designpattern.flyweight; import java.util.Hashtable; public class WebsiteFactory { private Hashtable<String, Website> hashtable = new Hashtable<>(); public Website getWebsiteCategory(String key) { if (!hashtable.contains(key)) { hashtable.put(key, new ConcreteWebsite(key)); } return hashtable.get(key); } public int getWebsiteCount(){ return this.hashtable.size(); } }
455
0.657143
0.657143
19
22.947369
21.816154
69
false
false
0
0
0
0
0
0
0.421053
false
false
12
5adbfb3fdb249509d9738ee90395733d976dbd5d
29,420,525,980,475
99360a7b51c1674c0352b9c073a2aceea749b564
/valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/table/glazedlists/GlazedListsSupport.java
c1c2c4635024a0ba012339984362a3795f66424e
[ "Apache-2.0" ]
permissive
lievendoclo/Valkyrie-RCP
https://github.com/lievendoclo/Valkyrie-RCP
c8e782a659c1c52d8e5cd19bb8ccbbe5fffe798b
eef9cbd2957524378b84fbf6446a3754ae6b7343
refs/heads/master
2021-07-04T17:50:18.891000
2021-03-23T20:31:08
2021-03-23T20:31:08
3,993,169
7
3
Apache-2.0
false
2021-06-07T18:20:19
2012-04-11T12:23:15
2021-03-23T20:33:51
2021-06-07T18:20:18
8,371
23
10
6
Java
false
false
/** * Copyright (C) 2015 Valkyrie RCP * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.valkyriercp.widget.table.glazedlists; import ca.odell.glazedlists.GlazedLists; import ca.odell.glazedlists.gui.AdvancedTableFormat; import ca.odell.glazedlists.gui.TableFormat; import ca.odell.glazedlists.gui.WritableTableFormat; import org.valkyriercp.widget.table.TableDescription; import java.util.Comparator; /** * GlazedListsSupport */ public class GlazedListsSupport { interface AdvancedWritableTableFormat extends AdvancedTableFormat, WritableTableFormat { } private static Comparator lowerCaseStringComparator = null; public static String[] makeFilterProperties(TableDescription desc) { return desc.getPropertiesInTextFilter(); } /** * Conversion of RCP TableDescription to GlazedLists TableFormat * * @param desc * @return AdvancedWritableTableFormat */ public static TableFormat makeTableFormat(final TableDescription desc) { return new AdvancedWritableTableFormat() { public Class getColumnClass(int i) { return desc.getType(i); } public Comparator getColumnComparator(int i) { Comparator comp = desc.getColumnComparator(i); if (comp != null) return comp; Class type = getColumnClass(i); if (Boolean.class.isAssignableFrom(type) || Boolean.TYPE.isAssignableFrom(type)) return GlazedLists.booleanComparator(); else if (String.class.isAssignableFrom(type)) return getLowerCaseStringComparator(); else if(Comparable.class.isAssignableFrom(type)) return GlazedLists.comparableComparator(); else return null; } public int getColumnCount() { return desc.getColumnCount(); } public String getColumnName(int i) { return desc.getHeader(i); } public Object getColumnValue(Object obj, int i) { return desc.getValue(obj, i); } public boolean isEditable(Object baseObject, int column) { return desc.getColumnEditor(column) != null; } public Object setColumnValue(Object baseObject, Object editedValue, int column) { desc.setValue(baseObject, column, editedValue); return baseObject; } }; } public static Comparator getLowerCaseStringComparator() { if (lowerCaseStringComparator == null) lowerCaseStringComparator = createLowerCaseStringComparator(); return lowerCaseStringComparator; } private static Comparator createLowerCaseStringComparator() { return new Comparator() { public int compare(Object o1, Object o2) { String str1 = (String) o1; String str2 = (String) o2; if (str1 == null) { if (str2 == null) return 0; return -1; } else if (str2 == null) { return 1; } return str1.toLowerCase().compareTo(str2.toLowerCase()); } }; } }
UTF-8
Java
4,078
java
GlazedListsSupport.java
Java
[ { "context": "/**\n * Copyright (C) 2015 Valkyrie RCP\n *\n * Licensed under the Apache License, Vers", "end": 34, "score": 0.8394527435302734, "start": 26, "tag": "NAME", "value": "Valkyrie" } ]
null
[]
/** * Copyright (C) 2015 Valkyrie RCP * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.valkyriercp.widget.table.glazedlists; import ca.odell.glazedlists.GlazedLists; import ca.odell.glazedlists.gui.AdvancedTableFormat; import ca.odell.glazedlists.gui.TableFormat; import ca.odell.glazedlists.gui.WritableTableFormat; import org.valkyriercp.widget.table.TableDescription; import java.util.Comparator; /** * GlazedListsSupport */ public class GlazedListsSupport { interface AdvancedWritableTableFormat extends AdvancedTableFormat, WritableTableFormat { } private static Comparator lowerCaseStringComparator = null; public static String[] makeFilterProperties(TableDescription desc) { return desc.getPropertiesInTextFilter(); } /** * Conversion of RCP TableDescription to GlazedLists TableFormat * * @param desc * @return AdvancedWritableTableFormat */ public static TableFormat makeTableFormat(final TableDescription desc) { return new AdvancedWritableTableFormat() { public Class getColumnClass(int i) { return desc.getType(i); } public Comparator getColumnComparator(int i) { Comparator comp = desc.getColumnComparator(i); if (comp != null) return comp; Class type = getColumnClass(i); if (Boolean.class.isAssignableFrom(type) || Boolean.TYPE.isAssignableFrom(type)) return GlazedLists.booleanComparator(); else if (String.class.isAssignableFrom(type)) return getLowerCaseStringComparator(); else if(Comparable.class.isAssignableFrom(type)) return GlazedLists.comparableComparator(); else return null; } public int getColumnCount() { return desc.getColumnCount(); } public String getColumnName(int i) { return desc.getHeader(i); } public Object getColumnValue(Object obj, int i) { return desc.getValue(obj, i); } public boolean isEditable(Object baseObject, int column) { return desc.getColumnEditor(column) != null; } public Object setColumnValue(Object baseObject, Object editedValue, int column) { desc.setValue(baseObject, column, editedValue); return baseObject; } }; } public static Comparator getLowerCaseStringComparator() { if (lowerCaseStringComparator == null) lowerCaseStringComparator = createLowerCaseStringComparator(); return lowerCaseStringComparator; } private static Comparator createLowerCaseStringComparator() { return new Comparator() { public int compare(Object o1, Object o2) { String str1 = (String) o1; String str2 = (String) o2; if (str1 == null) { if (str2 == null) return 0; return -1; } else if (str2 == null) { return 1; } return str1.toLowerCase().compareTo(str2.toLowerCase()); } }; } }
4,078
0.586317
0.580922
132
29.886364
25.551981
96
false
false
0
0
0
0
0
0
0.371212
false
false
12
d7d16206e755c822b845001bacd5660c603a456a
23,768,349,034,959
041535defb1fa30280915245dac5f3a24b60a935
/RendirProyectos/src/java/com/ozdev/mail/utils/MailTransporter.java
8b7b12f430b326b28dced34a5ce0a6649dc81996
[]
no_license
google-code/actividadesproyectos
https://github.com/google-code/actividadesproyectos
fbb66a93b6b61d7e635c2fcb785cf5628b50cd36
708d8cb80224e3f10d6c1b65b161df2256220834
refs/heads/master
2016-09-06T19:25:25.781000
2015-03-13T18:31:24
2015-03-13T18:31:24
32,173,705
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ozdev.mail.utils; import com.ozdev.comun.alltest.App; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.MimeMessage; /** * * @author rberrezueta */ public class MailTransporter { private String host; private String user; private String password; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public MailTransporter(String host, String user, String password) { this.setHost(host); this.setPassword(password); this.setUser(user); } public void SendMail(MimeMessage msg, Session session){ Transport t = null; try { t = session.getTransport("smtps"); } catch (NoSuchProviderException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } try { t.connect(this.getHost(), this.getUser(), this.getPassword()); t.sendMessage(msg, msg.getAllRecipients()); } catch (MessagingException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } finally { try { t.close(); } catch (MessagingException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } } }
UTF-8
Java
2,048
java
MailTransporter.java
Java
[ { "context": ".mail.internet.MimeMessage;\r\n\r\n/**\r\n *\r\n * @author rberrezueta\r\n */\r\npublic class MailTransporter {\r\n \r\n p", "end": 486, "score": 0.9995610117912292, "start": 475, "tag": "USERNAME", "value": "rberrezueta" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ozdev.mail.utils; import com.ozdev.comun.alltest.App; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.MimeMessage; /** * * @author rberrezueta */ public class MailTransporter { private String host; private String user; private String password; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public MailTransporter(String host, String user, String password) { this.setHost(host); this.setPassword(password); this.setUser(user); } public void SendMail(MimeMessage msg, Session session){ Transport t = null; try { t = session.getTransport("smtps"); } catch (NoSuchProviderException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } try { t.connect(this.getHost(), this.getUser(), this.getPassword()); t.sendMessage(msg, msg.getAllRecipients()); } catch (MessagingException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } finally { try { t.close(); } catch (MessagingException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } } }
2,048
0.585938
0.585938
81
23.283951
20.973372
82
false
false
0
0
0
0
0
0
0.54321
false
false
12
eb25635db192d7f3f6d2b59b3c2b90ec0b88eca9
17,540,646,468,042
ab0f79892c8bdb34cf9b192295248dd65342a4e1
/com/shamchat/models/FriendGroup.java
edd7b5d261f9c2cb5282efeb0f9e1d9870f1399d
[]
no_license
jozn/Salam
https://github.com/jozn/Salam
0dac7ce3fd8f8473a7124b5a0a23dd7c13b5798a
322282e55bff78094745f787d1463b1ec5f6248c
refs/heads/master
2021-01-20T03:22:24.212000
2016-02-04T11:23:27
2016-02-04T11:23:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shamchat.models; import android.content.Context; import android.database.Cursor; import com.shamchat.androidclient.data.UserProvider; public final class FriendGroup { public static String CHAT_ROOM_NAME; public static String DB_ID; public static String DB_NAME; public static String DB_RECORD_OWNER; public static String DID_JOIN_ROOM; public static String DID_LEAVE; public String chatRoomName; public String dbRecordId; public String id; public String name; public String recordOwnerId; static { DB_ID = "friend_group_id"; DB_NAME = "friend_group_name"; DB_RECORD_OWNER = "record_owner_id"; CHAT_ROOM_NAME = "chat_room_name"; DID_JOIN_ROOM = "did_join_room"; DID_LEAVE = "did_leave"; } public FriendGroup(String name, String ownerId) { this.name = name; this.recordOwnerId = ownerId; } public final String toString() { return "Id:" + this.id + " Name:" + this.name + " Owner:" + this.recordOwnerId; } public static String getNextAvailableGroupName(Context context) { Cursor cursor = context.getContentResolver().query(UserProvider.CONTENT_URI_GROUP, new String[]{DB_ID}, null, null, null); int i = cursor.getCount() + 1; cursor.close(); return "Group " + i; } }
UTF-8
Java
1,362
java
FriendGroup.java
Java
[]
null
[]
package com.shamchat.models; import android.content.Context; import android.database.Cursor; import com.shamchat.androidclient.data.UserProvider; public final class FriendGroup { public static String CHAT_ROOM_NAME; public static String DB_ID; public static String DB_NAME; public static String DB_RECORD_OWNER; public static String DID_JOIN_ROOM; public static String DID_LEAVE; public String chatRoomName; public String dbRecordId; public String id; public String name; public String recordOwnerId; static { DB_ID = "friend_group_id"; DB_NAME = "friend_group_name"; DB_RECORD_OWNER = "record_owner_id"; CHAT_ROOM_NAME = "chat_room_name"; DID_JOIN_ROOM = "did_join_room"; DID_LEAVE = "did_leave"; } public FriendGroup(String name, String ownerId) { this.name = name; this.recordOwnerId = ownerId; } public final String toString() { return "Id:" + this.id + " Name:" + this.name + " Owner:" + this.recordOwnerId; } public static String getNextAvailableGroupName(Context context) { Cursor cursor = context.getContentResolver().query(UserProvider.CONTENT_URI_GROUP, new String[]{DB_ID}, null, null, null); int i = cursor.getCount() + 1; cursor.close(); return "Group " + i; } }
1,362
0.651982
0.651248
44
29.954546
24.346882
130
false
false
0
0
0
0
0
0
0.75
false
false
12
9af21fe86781aecad0a7fb94b9c9b5f8aa6e45cd
33,088,428,099,688
5bdf8d52abad074fe428a430f359aad07763679d
/app/src/main/java/com/example/acer/bakingapp/ItemDetailActivity.java
bac644aac57c3b5bbf283f8edf2be1d5e3789f0d
[]
no_license
PujithaKurakula/BakingApp
https://github.com/PujithaKurakula/BakingApp
1b36fe8ab6befd1144d60895c7223c1b08f7cc77
6d5dc104b00504ff60b5a7511ad01631e41fac2f
refs/heads/master
2022-11-21T13:27:46.722000
2020-07-08T13:25:31
2020-07-08T13:25:31
278,090,675
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.acer.bakingapp; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.widget.Toolbar; import android.view.View; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.NavUtils; import android.view.MenuItem; /** * An activity representing a single Item detail screen. This * activity is only used on narrow width devices. On tablet-size devices, * item details are presented side-by-side with a list of items * in a {@link ItemListActivity}. */ public class ItemDetailActivity extends AppCompatActivity { static int posi; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_detail); Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar); setSupportActionBar(toolbar); Intent intent=getIntent(); String shortde=intent.getStringExtra("shortdesc"); setTitle(shortde); String desc=intent.getStringExtra("description"); String vediourl=intent.getStringExtra("videourl"); String thumb=intent.getStringExtra("thumbnail"); posi=intent.getIntExtra(ItemDetailFragment.ARG_ITEM_ID,-1); // Show the Up button in the action bar. ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. Bundle arguments = new Bundle(); String position= String.valueOf(posi); arguments.putString("description",desc); arguments.putString("shortdesc",shortde); arguments.putString("videourl",vediourl); arguments.putString("thumbnail",thumb); arguments.putString(ItemDetailFragment.ARG_ITEM_ID, getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID)); ItemDetailFragment fragment = new ItemDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.item_detail_container, fragment) .commit(); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { navigateUpTo(new Intent(this, ItemListActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
UTF-8
Java
2,909
java
ItemDetailActivity.java
Java
[]
null
[]
package com.example.acer.bakingapp; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.widget.Toolbar; import android.view.View; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.NavUtils; import android.view.MenuItem; /** * An activity representing a single Item detail screen. This * activity is only used on narrow width devices. On tablet-size devices, * item details are presented side-by-side with a list of items * in a {@link ItemListActivity}. */ public class ItemDetailActivity extends AppCompatActivity { static int posi; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_detail); Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar); setSupportActionBar(toolbar); Intent intent=getIntent(); String shortde=intent.getStringExtra("shortdesc"); setTitle(shortde); String desc=intent.getStringExtra("description"); String vediourl=intent.getStringExtra("videourl"); String thumb=intent.getStringExtra("thumbnail"); posi=intent.getIntExtra(ItemDetailFragment.ARG_ITEM_ID,-1); // Show the Up button in the action bar. ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. Bundle arguments = new Bundle(); String position= String.valueOf(posi); arguments.putString("description",desc); arguments.putString("shortdesc",shortde); arguments.putString("videourl",vediourl); arguments.putString("thumbnail",thumb); arguments.putString(ItemDetailFragment.ARG_ITEM_ID, getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID)); ItemDetailFragment fragment = new ItemDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.item_detail_container, fragment) .commit(); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { navigateUpTo(new Intent(this, ItemListActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
2,909
0.673771
0.672052
80
35.375
23.302561
80
false
false
0
0
0
0
0
0
0.6125
false
false
12
4c3fc855aeb1df52eed02e6d7543f43f52f0b47d
2,516,850,851,279
a1dc7ab48766dbc3600fdc37ad5a443657589ec2
/src/main/java/net/floodlightcontroller/devicemanager/internal/DeviceIndex.java
dd3702cc9ebbef8fe603e39209ee3d8a6ea27a3b
[ "Apache-2.0" ]
permissive
medic0803/Ginkgo-RnD-Project-Floodlight
https://github.com/medic0803/Ginkgo-RnD-Project-Floodlight
ebb5418d4615d6242da5a32a0c45a14cf85d9c5a
784cbd1808d9b6e24d60bc2c875d2c5461b3cdc9
refs/heads/dev
2023-04-29T14:43:51.469000
2021-05-17T13:00:29
2021-05-17T13:00:29
324,116,410
3
0
Apache-2.0
false
2021-05-13T11:00:03
2020-12-24T09:20:01
2021-05-13T10:52:27
2021-05-13T11:00:02
5,517
3
0
1
Java
false
false
/** * Copyright 2012 Big Switch Networks, Inc. * Originally created by David Erickson, Stanford University * * 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 net.floodlightcontroller.devicemanager.internal; import java.util.Collection; import java.util.EnumSet; import java.util.Iterator; import net.floodlightcontroller.devicemanager.IDeviceService.DeviceField; /** * An index that maps key fields of an entity to device keys */ public abstract class DeviceIndex { /** * The key fields for this index */ protected EnumSet<DeviceField> keyFields; /** * Construct a new device index using the provided key fields * @param keyFields the key fields to use */ public DeviceIndex(EnumSet<DeviceField> keyFields) { super(); this.keyFields = keyFields; } /** * Find all device keys in the index that match the given entity * on all the key fields for this index * @param e the entity to search for * @return an iterator over device keys */ public abstract Iterator<Long> queryByEntity(Entity entity); /** * Get all device keys in the index. If certain devices exist * multiple times, then these devices may be returned multiple times * @return an iterator over device keys */ public abstract Iterator<Long> getAll(); /** * Attempt to update an index with the entities in the provided * {@link Device}. If the update fails because of a concurrent update, * will return false. * @param device the device to update * @param deviceKey the device key for the device * @return true if the update succeeded, false otherwise. */ public abstract boolean updateIndex(Device device, Long deviceKey); /** * Add a mapping from the given entity to the given device key. This * update will not fail because of a concurrent update * @param device the device to update * @param deviceKey the device key for the device * @return */ public abstract boolean updateIndex(Entity entity, Long deviceKey); /** * Remove the entry for the given entity * @param entity the entity to remove */ public abstract void removeEntity(Entity entity); /** * Remove the given device key from the index for the given entity * @param entity the entity to search for * @param deviceKey the key to remove */ public abstract void removeEntity(Entity entity, Long deviceKey); /** * Remove the give device from the index only if this the collection * of others does not contain an entity that is identical on all the key * fields for this index. * @param entity the entity to search for * @param deviceKey the key to remove * @param others the others against which to check */ public void removeEntityIfNeeded(Entity entity, Long deviceKey, Collection<Entity> others) { IndexedEntity ie = new IndexedEntity(keyFields, entity); for (Entity o : others) { IndexedEntity oio = new IndexedEntity(keyFields, o); if (oio.equals(ie)) return; } Iterator<Long> keyiter = this.queryByEntity(entity); while (keyiter.hasNext()) { Long key = keyiter.next(); if (key.equals(deviceKey)) { removeEntity(entity, deviceKey); break; } } } }
UTF-8
Java
4,039
java
DeviceIndex.java
Java
[ { "context": " Switch Networks, Inc. \n* Originally created by David Erickson, Stanford University\n* \n* Licensed under the A", "end": 92, "score": 0.9997621774673462, "start": 78, "tag": "NAME", "value": "David Erickson" } ]
null
[]
/** * Copyright 2012 Big Switch Networks, Inc. * Originally created by <NAME>, Stanford University * * 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 net.floodlightcontroller.devicemanager.internal; import java.util.Collection; import java.util.EnumSet; import java.util.Iterator; import net.floodlightcontroller.devicemanager.IDeviceService.DeviceField; /** * An index that maps key fields of an entity to device keys */ public abstract class DeviceIndex { /** * The key fields for this index */ protected EnumSet<DeviceField> keyFields; /** * Construct a new device index using the provided key fields * @param keyFields the key fields to use */ public DeviceIndex(EnumSet<DeviceField> keyFields) { super(); this.keyFields = keyFields; } /** * Find all device keys in the index that match the given entity * on all the key fields for this index * @param e the entity to search for * @return an iterator over device keys */ public abstract Iterator<Long> queryByEntity(Entity entity); /** * Get all device keys in the index. If certain devices exist * multiple times, then these devices may be returned multiple times * @return an iterator over device keys */ public abstract Iterator<Long> getAll(); /** * Attempt to update an index with the entities in the provided * {@link Device}. If the update fails because of a concurrent update, * will return false. * @param device the device to update * @param deviceKey the device key for the device * @return true if the update succeeded, false otherwise. */ public abstract boolean updateIndex(Device device, Long deviceKey); /** * Add a mapping from the given entity to the given device key. This * update will not fail because of a concurrent update * @param device the device to update * @param deviceKey the device key for the device * @return */ public abstract boolean updateIndex(Entity entity, Long deviceKey); /** * Remove the entry for the given entity * @param entity the entity to remove */ public abstract void removeEntity(Entity entity); /** * Remove the given device key from the index for the given entity * @param entity the entity to search for * @param deviceKey the key to remove */ public abstract void removeEntity(Entity entity, Long deviceKey); /** * Remove the give device from the index only if this the collection * of others does not contain an entity that is identical on all the key * fields for this index. * @param entity the entity to search for * @param deviceKey the key to remove * @param others the others against which to check */ public void removeEntityIfNeeded(Entity entity, Long deviceKey, Collection<Entity> others) { IndexedEntity ie = new IndexedEntity(keyFields, entity); for (Entity o : others) { IndexedEntity oio = new IndexedEntity(keyFields, o); if (oio.equals(ie)) return; } Iterator<Long> keyiter = this.queryByEntity(entity); while (keyiter.hasNext()) { Long key = keyiter.next(); if (key.equals(deviceKey)) { removeEntity(entity, deviceKey); break; } } } }
4,031
0.656846
0.654865
117
33.529915
26.727358
78
false
false
0
0
0
0
0
0
0.333333
false
false
12
9352756a3508f16c005c9a0f65b0fdb7c440c11a
23,828,478,574,297
788ce09298c45e323920ac5f3d84ad6cd4f5f613
/src/main/java/com/java_test/App.java
2df135d4921d323faf5b6cd6029da9101f27ca4d
[]
no_license
amitpl/java-test
https://github.com/amitpl/java-test
d3877167b39cd115a8d0e661689191c183fcfd53
61f95e38171f97862066141b2050c750d5653a4c
refs/heads/master
2020-05-15T13:36:28.696000
2014-08-20T13:36:22
2014-08-20T13:36:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.java_test; import java.io.IOException; import org.apache.commons.lang3.exception.ExceptionUtils; import com.google.gson.Gson; import com.java_test.csv.CSVFileWriter; import com.java_test.http.HttpSender; import com.java_test.http.HttpSender.TransportException; import com.java_test.json.GetSuggestionResponse; /** * Hello world! */ public class App { public static void main(String[] args) { String csvFilename = "javaTest.csv"; String baseServiceUrl = "http://api.goeuro.com/api/v2/position/suggest/en/"; if (args.length < 1) { return; } String restApi = baseServiceUrl + args[0]; HttpSender sender = new HttpSender(); String json; try { json = sender.executeGETRequest(restApi); } catch (TransportException e) { System.out.println("Transport Exception, " + e.getMessage()); return; } GetSuggestionResponse[] array = new Gson().fromJson(json, GetSuggestionResponse[].class); try (CSVFileWriter w = new CSVFileWriter(csvFilename)) { for (GetSuggestionResponse gsr : array) { w.writeLine(new String[] { gsr.getType1(), gsr.getId(), gsr.getName(), gsr.getType(), gsr.getGeoPosition().getLatitude(), gsr.getGeoPosition().getLongitude() }); } } catch (IOException e) { System.out.println("IOException in writing to csv file, " + ExceptionUtils.getStackTrace(e)); } } }
UTF-8
Java
1,509
java
App.java
Java
[]
null
[]
package com.java_test; import java.io.IOException; import org.apache.commons.lang3.exception.ExceptionUtils; import com.google.gson.Gson; import com.java_test.csv.CSVFileWriter; import com.java_test.http.HttpSender; import com.java_test.http.HttpSender.TransportException; import com.java_test.json.GetSuggestionResponse; /** * Hello world! */ public class App { public static void main(String[] args) { String csvFilename = "javaTest.csv"; String baseServiceUrl = "http://api.goeuro.com/api/v2/position/suggest/en/"; if (args.length < 1) { return; } String restApi = baseServiceUrl + args[0]; HttpSender sender = new HttpSender(); String json; try { json = sender.executeGETRequest(restApi); } catch (TransportException e) { System.out.println("Transport Exception, " + e.getMessage()); return; } GetSuggestionResponse[] array = new Gson().fromJson(json, GetSuggestionResponse[].class); try (CSVFileWriter w = new CSVFileWriter(csvFilename)) { for (GetSuggestionResponse gsr : array) { w.writeLine(new String[] { gsr.getType1(), gsr.getId(), gsr.getName(), gsr.getType(), gsr.getGeoPosition().getLatitude(), gsr.getGeoPosition().getLongitude() }); } } catch (IOException e) { System.out.println("IOException in writing to csv file, " + ExceptionUtils.getStackTrace(e)); } } }
1,509
0.638171
0.634858
47
31.106382
34.592606
177
false
false
0
0
0
0
0
0
0.595745
false
false
12
c3b564e70739bc12f6af05bda75907c9c4640a83
34,016,140,997,437
cd95e7264db90f5566c93e0a5a3690c773d0f4cc
/app/src/main/java/com/anikrajc/remote/ui/fragments/SeasonFragment.java
a005c9314f669a88e2576e65ee5da40e1daecd52
[ "Apache-2.0" ]
permissive
anikraj1994/Remote
https://github.com/anikraj1994/Remote
50cfec4ef2e439896300791e91cf83e9dd17f941
fd9a87a9d4c3c8586809a817f4ce12f11cf80001
refs/heads/master
2020-02-22T08:14:58.614000
2017-08-11T22:51:42
2017-08-11T22:51:42
100,073,878
7
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.anikrajc.remote.ui.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.anikrajc.remote.R; import com.anikrajc.remote.RemoteApplication; import com.anikrajc.remote.globals.DataShared; import com.anikrajc.remote.jobs.SelectEpisodeJob; import com.anikrajc.remote.models.Episode; import com.birbit.android.jobqueue.JobManager; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by anik on 08/08/17. */ public class SeasonFragment extends Fragment { private JobManager jobManager; private List<Episode> currentList; public SeasonFragment() { } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_season, container, false); Bundle bundle = getArguments(); int position = bundle.getInt("position"); ListView listView = (ListView) rootView.findViewById(R.id.list); currentList = new ArrayList<>(); jobManager = RemoteApplication.getInstance().getJobManager(); for (Episode episode : DataShared.episodeList) { if (episode.getSeason() == position) currentList.add(episode); } Collections.sort(currentList, new Comparator<Episode>() { @Override public int compare(Episode episode, Episode t1) { return episode.getEpisode() - t1.getEpisode(); } }); List<String> asd = new ArrayList<>(); for (Episode e : currentList) { asd.add(e.getEpisode() + ". " + e.getTitle()); } listView.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, asd)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { jobManager.addJobInBackground(new SelectEpisodeJob(currentList.get(i).getSeason(), currentList.get(i).getEpisode())); } }); return rootView; } // public class ListAdapter extends ArrayAdapter<Episode> { // // public ListAdapter(Context context, int textViewResourceId) { // super(context, textViewResourceId); // } // // public ListAdapter(Context context, int resource, List<Episode> items) { // super(context, resource, items); // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // // View v = convertView; // // if (v == null) { // LayoutInflater vi; // vi = LayoutInflater.from(getContext()); // v = vi.inflate(R.layout.episode_item, null); // } // // Episode p = getItem(position); // // if (p != null) { // Log.e("anik",p.getEpisode()+""); // Log.e("anik",p.getTitle()+""); // TextView tt1 = (TextView) v.findViewById(R.id.srno); // TextView tt2 = (TextView) v.findViewById(R.id.title); // tt1.setText(p.getEpisode()); // tt2.setText(p.getTitle()); // // } // // return v; // } // // } }
UTF-8
Java
3,671
java
SeasonFragment.java
Java
[ { "context": "parator;\nimport java.util.List;\n\n/**\n * Created by anik on 08/08/17.\n */\n\npublic class SeasonFragment ext", "end": 747, "score": 0.9931378364562988, "start": 743, "tag": "USERNAME", "value": "anik" } ]
null
[]
package com.anikrajc.remote.ui.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.anikrajc.remote.R; import com.anikrajc.remote.RemoteApplication; import com.anikrajc.remote.globals.DataShared; import com.anikrajc.remote.jobs.SelectEpisodeJob; import com.anikrajc.remote.models.Episode; import com.birbit.android.jobqueue.JobManager; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by anik on 08/08/17. */ public class SeasonFragment extends Fragment { private JobManager jobManager; private List<Episode> currentList; public SeasonFragment() { } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_season, container, false); Bundle bundle = getArguments(); int position = bundle.getInt("position"); ListView listView = (ListView) rootView.findViewById(R.id.list); currentList = new ArrayList<>(); jobManager = RemoteApplication.getInstance().getJobManager(); for (Episode episode : DataShared.episodeList) { if (episode.getSeason() == position) currentList.add(episode); } Collections.sort(currentList, new Comparator<Episode>() { @Override public int compare(Episode episode, Episode t1) { return episode.getEpisode() - t1.getEpisode(); } }); List<String> asd = new ArrayList<>(); for (Episode e : currentList) { asd.add(e.getEpisode() + ". " + e.getTitle()); } listView.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, asd)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { jobManager.addJobInBackground(new SelectEpisodeJob(currentList.get(i).getSeason(), currentList.get(i).getEpisode())); } }); return rootView; } // public class ListAdapter extends ArrayAdapter<Episode> { // // public ListAdapter(Context context, int textViewResourceId) { // super(context, textViewResourceId); // } // // public ListAdapter(Context context, int resource, List<Episode> items) { // super(context, resource, items); // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // // View v = convertView; // // if (v == null) { // LayoutInflater vi; // vi = LayoutInflater.from(getContext()); // v = vi.inflate(R.layout.episode_item, null); // } // // Episode p = getItem(position); // // if (p != null) { // Log.e("anik",p.getEpisode()+""); // Log.e("anik",p.getTitle()+""); // TextView tt1 = (TextView) v.findViewById(R.id.srno); // TextView tt2 = (TextView) v.findViewById(R.id.title); // tt1.setText(p.getEpisode()); // tt2.setText(p.getTitle()); // // } // // return v; // } // // } }
3,671
0.623263
0.61945
113
31.486725
28.89196
133
false
false
0
0
0
0
0
0
0.654867
false
false
12
7dfb519cc39b7cfe4ff36486b072f00faa7c58b0
19,825,569,088,195
caeb322fcb641de334ee05f87467cb42a6571830
/src/main/java/pages/environment/InsideEnvironmentPage.java
19f55a599c9901de812984a313b25766d6bdffad
[]
no_license
catalin-parvana/nirmataPE
https://github.com/catalin-parvana/nirmataPE
292700698fe697855c2575c3879508f4fa5c66e2
10f7ef3be010d1b69f4b37fc430acc25dd13c966
refs/heads/master
2022-10-23T18:37:12.828000
2020-05-20T19:28:52
2020-05-20T19:28:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pages.environment; import com.codeborne.selenide.SelenideElement; import org.openqa.selenium.WebDriver; import pages.catalog.catalog.InsideApplicationPage; import utils.LibraryUtils; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Selenide.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; public class InsideEnvironmentPage extends LibraryUtils { private final SelenideElement runAnApplicationButton= $x("//*[@id='launchApplication']"); private final SelenideElement modelContentPanelTitle= $x("//h1[@id='model-content-panel-title']"); private final SelenideElement actionButton= $x("//*[contains(@class,'btn-lg dropdown-toggle')]"); private final SelenideElement nameInputField=$x("//input[@id='run']"); private final SelenideElement runApplicationButton=$x("//button[text()='Run Application']"); private final SelenideElement upstreamTypeDropdown=$x("//select[@id='upstreamType']"); private final SelenideElement catalogApplicationDropdown=$x("//select[@id='application']"); private final SelenideElement deleteEnvironmentButton=$x("//a[@id='deleteEnvironment']"); private final SelenideElement deleteAllApplicationsCheckbox=$x("//input[@id='deleteAllApplications']"); private final SelenideElement deleteFromClusterCheckbox=$x("//input[@id='deleteOnCluster']"); private final SelenideElement deleteButton=$x("//button[text()='Delete']"); private final SelenideElement pendingDeleteState=$x("//span[@id='state-popover'][contains(.,'Pending Delete')]"); private final SelenideElement applicationRunningState=$x("//span[@id='state-popover'][contains(.,'Running')]"); private final SelenideElement applicationExecutingState=$x("//span[@id='state-popover'][contains(.,'Executing')]"); private final SelenideElement clusterConnectedState=$x("//span[@id='state-popover'][contains(.,'Cluster Connected')]"); private final SelenideElement toggleTableView=$x("//img[@id='toggleTableView']"); private final SelenideElement toggleCardView=$x("//img[@id='toggleCardView']"); private final SelenideElement nextButtonEnabled=$x("//button[contains(text(),'Next')][not(@disabled)]"); private final SelenideElement nextButton = $x("//button[contains(text(),'Next')]"); private final SelenideElement modalDialog=$x("//div[@class='modal-dialog']"); private final SelenideElement applicationButton=$x("//li[@id='applications']"); private final SelenideElement environmentLabel=$x("//div[@class='pull-left model-index-name'][contains(.,'Environment')]"); private SelenideElement deployment, runningApplicationLink; private boolean found=false; private final WebDriver driver; public InsideEnvironmentPage(WebDriver driver){ this.driver=driver; environmentLabel.shouldBe(visible); actionButton.shouldBe(visible); modelContentPanelTitle.shouldBe(visible); applicationButton.shouldBe(visible) .shouldHave(text("Applications")); } public InsideEnvironmentPage verifyPanelTitle(String environmentName){ assertEquals(modelContentPanelTitle.text(),environmentName, "Incorrect environment name"); return this; } public InsideEnvironmentPage clickRunAnApplicationButton(){ click("Run Application Button",runAnApplicationButton); return this; } public InsideEnvironmentPage setNameInputField(String runName){ type("Name Input Field",nameInputField,runName); return this; } public InsideEnvironmentPage selectUpstreamTypeFromDropdown(String upstreamType){ selectOptionByText("Upstream Type Dropdown ",upstreamTypeDropdown,upstreamType); return this; } public InsideEnvironmentPage selectCatalogApplicationFromDropdown(String applicationName) { selectOptionByText("Catalog Application Dropdown ", catalogApplicationDropdown, applicationName); return this; } public InsideRunningApplicationPage clickRunApplicationButton(){ click("Run Application Button",runApplicationButton); runAnApplicationButton.should(disappear); return new InsideRunningApplicationPage(driver); } public InsideEnvironmentPage clickActionButton(){ click("Action Button",actionButton); return this; } public InsideEnvironmentPage clickDeleteEnvironmentButton(){ click("Delete Environment Button",deleteEnvironmentButton); return this; } public InsideEnvironmentPage checkDeleteApplicationsCheckboxIfNecessary(){ modalDialog.shouldBe(visible); if(deleteAllApplicationsCheckbox.exists()){ click("Delete Application Checkbox",deleteAllApplicationsCheckbox); } return this; } public InsideEnvironmentPage checkDeleteFromClusterCheckboxIfNecessary(){ modalDialog.shouldBe(visible); if(deleteFromClusterCheckbox.exists()){ click("Delete From Cluster Checkbox",deleteFromClusterCheckbox); } return this; } public InsideEnvironmentPage setEnvironmentNameIfNecessary(String environmentName){ modalDialog.shouldBe(visible); if(nameInputField.isDisplayed()){ type("Name Input Field",nameInputField,environmentName); } return this; } public EnvironmentsPage clickDeleteButton(){ click("Delete Button",deleteButton); deleteButton.should(disappear); return new EnvironmentsPage(driver); } public InsideEnvironmentPage isDeletedDeploymentDisplayed(String appDeployName){ assertFalse(isDeploymentDisplayed(appDeployName),"Deployment was not deleted"); return this; } public boolean isDeploymentDisplayed(String deploymentName){ actionButton.shouldBe(visible); if(toggleTableView.exists()){ deployment=$x("//div[@class='card-title']//*[text()='"+deploymentName+"']"); }else if(toggleCardView.exists()){ deployment=$x("//div[@class='runningAppName']//*[text()='"+deploymentName+"']"); } if (deployment!=null && deployment.exists()) { found = true; } else if(nextButton.exists()){ if (nextButtonEnabled.exists()) { do { nextButton.click(); if (deployment.exists()){ found = true; break; } } while (nextButtonEnabled.exists()); } } return found; } public InsideRunningApplicationPage clickRunningApplicationWithName(String runningApplicationName){ actionButton.shouldBe(visible); if(toggleTableView.exists()){ runningApplicationLink=$x("//div[@class='card-title']//*[text()='"+runningApplicationName+"']"); }else if(toggleCardView.exists()){ runningApplicationLink=$x("//div[@class='application-name']//*[text()='"+runningApplicationName+"']"); } click("Running Application Link: "+runningApplicationName,runningApplicationLink); return new InsideRunningApplicationPage(driver); } public InsideEnvironmentPage waitForClusterConnectedStatus(){ waitFor("Cluster Connected Status",clusterConnectedState,120); return this; } }
UTF-8
Java
7,549
java
InsideEnvironmentPage.java
Java
[]
null
[]
package pages.environment; import com.codeborne.selenide.SelenideElement; import org.openqa.selenium.WebDriver; import pages.catalog.catalog.InsideApplicationPage; import utils.LibraryUtils; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Selenide.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; public class InsideEnvironmentPage extends LibraryUtils { private final SelenideElement runAnApplicationButton= $x("//*[@id='launchApplication']"); private final SelenideElement modelContentPanelTitle= $x("//h1[@id='model-content-panel-title']"); private final SelenideElement actionButton= $x("//*[contains(@class,'btn-lg dropdown-toggle')]"); private final SelenideElement nameInputField=$x("//input[@id='run']"); private final SelenideElement runApplicationButton=$x("//button[text()='Run Application']"); private final SelenideElement upstreamTypeDropdown=$x("//select[@id='upstreamType']"); private final SelenideElement catalogApplicationDropdown=$x("//select[@id='application']"); private final SelenideElement deleteEnvironmentButton=$x("//a[@id='deleteEnvironment']"); private final SelenideElement deleteAllApplicationsCheckbox=$x("//input[@id='deleteAllApplications']"); private final SelenideElement deleteFromClusterCheckbox=$x("//input[@id='deleteOnCluster']"); private final SelenideElement deleteButton=$x("//button[text()='Delete']"); private final SelenideElement pendingDeleteState=$x("//span[@id='state-popover'][contains(.,'Pending Delete')]"); private final SelenideElement applicationRunningState=$x("//span[@id='state-popover'][contains(.,'Running')]"); private final SelenideElement applicationExecutingState=$x("//span[@id='state-popover'][contains(.,'Executing')]"); private final SelenideElement clusterConnectedState=$x("//span[@id='state-popover'][contains(.,'Cluster Connected')]"); private final SelenideElement toggleTableView=$x("//img[@id='toggleTableView']"); private final SelenideElement toggleCardView=$x("//img[@id='toggleCardView']"); private final SelenideElement nextButtonEnabled=$x("//button[contains(text(),'Next')][not(@disabled)]"); private final SelenideElement nextButton = $x("//button[contains(text(),'Next')]"); private final SelenideElement modalDialog=$x("//div[@class='modal-dialog']"); private final SelenideElement applicationButton=$x("//li[@id='applications']"); private final SelenideElement environmentLabel=$x("//div[@class='pull-left model-index-name'][contains(.,'Environment')]"); private SelenideElement deployment, runningApplicationLink; private boolean found=false; private final WebDriver driver; public InsideEnvironmentPage(WebDriver driver){ this.driver=driver; environmentLabel.shouldBe(visible); actionButton.shouldBe(visible); modelContentPanelTitle.shouldBe(visible); applicationButton.shouldBe(visible) .shouldHave(text("Applications")); } public InsideEnvironmentPage verifyPanelTitle(String environmentName){ assertEquals(modelContentPanelTitle.text(),environmentName, "Incorrect environment name"); return this; } public InsideEnvironmentPage clickRunAnApplicationButton(){ click("Run Application Button",runAnApplicationButton); return this; } public InsideEnvironmentPage setNameInputField(String runName){ type("Name Input Field",nameInputField,runName); return this; } public InsideEnvironmentPage selectUpstreamTypeFromDropdown(String upstreamType){ selectOptionByText("Upstream Type Dropdown ",upstreamTypeDropdown,upstreamType); return this; } public InsideEnvironmentPage selectCatalogApplicationFromDropdown(String applicationName) { selectOptionByText("Catalog Application Dropdown ", catalogApplicationDropdown, applicationName); return this; } public InsideRunningApplicationPage clickRunApplicationButton(){ click("Run Application Button",runApplicationButton); runAnApplicationButton.should(disappear); return new InsideRunningApplicationPage(driver); } public InsideEnvironmentPage clickActionButton(){ click("Action Button",actionButton); return this; } public InsideEnvironmentPage clickDeleteEnvironmentButton(){ click("Delete Environment Button",deleteEnvironmentButton); return this; } public InsideEnvironmentPage checkDeleteApplicationsCheckboxIfNecessary(){ modalDialog.shouldBe(visible); if(deleteAllApplicationsCheckbox.exists()){ click("Delete Application Checkbox",deleteAllApplicationsCheckbox); } return this; } public InsideEnvironmentPage checkDeleteFromClusterCheckboxIfNecessary(){ modalDialog.shouldBe(visible); if(deleteFromClusterCheckbox.exists()){ click("Delete From Cluster Checkbox",deleteFromClusterCheckbox); } return this; } public InsideEnvironmentPage setEnvironmentNameIfNecessary(String environmentName){ modalDialog.shouldBe(visible); if(nameInputField.isDisplayed()){ type("Name Input Field",nameInputField,environmentName); } return this; } public EnvironmentsPage clickDeleteButton(){ click("Delete Button",deleteButton); deleteButton.should(disappear); return new EnvironmentsPage(driver); } public InsideEnvironmentPage isDeletedDeploymentDisplayed(String appDeployName){ assertFalse(isDeploymentDisplayed(appDeployName),"Deployment was not deleted"); return this; } public boolean isDeploymentDisplayed(String deploymentName){ actionButton.shouldBe(visible); if(toggleTableView.exists()){ deployment=$x("//div[@class='card-title']//*[text()='"+deploymentName+"']"); }else if(toggleCardView.exists()){ deployment=$x("//div[@class='runningAppName']//*[text()='"+deploymentName+"']"); } if (deployment!=null && deployment.exists()) { found = true; } else if(nextButton.exists()){ if (nextButtonEnabled.exists()) { do { nextButton.click(); if (deployment.exists()){ found = true; break; } } while (nextButtonEnabled.exists()); } } return found; } public InsideRunningApplicationPage clickRunningApplicationWithName(String runningApplicationName){ actionButton.shouldBe(visible); if(toggleTableView.exists()){ runningApplicationLink=$x("//div[@class='card-title']//*[text()='"+runningApplicationName+"']"); }else if(toggleCardView.exists()){ runningApplicationLink=$x("//div[@class='application-name']//*[text()='"+runningApplicationName+"']"); } click("Running Application Link: "+runningApplicationName,runningApplicationLink); return new InsideRunningApplicationPage(driver); } public InsideEnvironmentPage waitForClusterConnectedStatus(){ waitFor("Cluster Connected Status",clusterConnectedState,120); return this; } }
7,549
0.684462
0.683932
177
41.649719
35.67004
127
false
false
0
0
0
0
0
0
0.655367
false
false
12
62e8085d3154bf044c6f717e7547901fc55d7447
36,352,603,216,895
6d3cf1d1f521ff5694da04037049b8dfb95700a3
/src/com/cathalnoonan/query/Sort.java
8e4014240cd37d496ca5460a81992868f2e9145f
[]
no_license
cathalnoonan/JavaSorting
https://github.com/cathalnoonan/JavaSorting
7718e76b840afd21a68b12128118f24025a1d19c
97bca1f9349ddd2aa0f04675d5b0cd41ab5f8c01
refs/heads/master
2018-09-20T09:49:05.487000
2018-06-19T16:03:57
2018-06-19T16:03:57
135,006,138
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cathalnoonan.query; import java.util.List; public class Sort { /** * Sorts a generic collection by a given key. * * Uses the Quick Sort algorithm to sort the collection. * * @param collection Collection to be sorted. * @param predicate Return the field intended to compare. * @param <TItem> The type of item held in the collection. * @param <TComparison> The type being used in the comparison while sorting the elements. */ public static <TItem, TComparison extends Comparable<TComparison>> void quickSort(TItem[] collection, final Predicate<TItem, TComparison> predicate){ quickSort(collection, 0, collection.length-1, predicate); } /** * Sorts a generic collection. * * Uses the "Quick Sort" algorithm. * * @param collection Collection to be sorted. * @param <TItem> The type of item held in the collection. */ public static <TItem extends Comparable<TItem>> void quickSort(TItem[] collection){ quickSort(collection, 0, collection.length-1, x -> x); } private static <TItem, TComparison extends Comparable<TComparison>> void quickSort(TItem[] collection, int start, int end, final Predicate<TItem, TComparison> predicate) { /* * Extends on the following Stack-Overflow thread using Generics in place of String: * https://stackoverflow.com/questions/29294982/using-quicksort-on-a-string-array */ // index for the "left-to-right scan" int i = start; // index for the "right-to-left scan" int j = end; // only examine arrays of 2 or more elements. if (j - i >= 1) { // The pivot point of the sort method is arbitrarily set to the first element int the array. TItem pivot = collection[i]; // only scan between the two indexes, until they meet. while (j > i) { // from the left, if the current element is lexicographically less than the (original) // first element in the String array, move on. Stop advancing the counter when we reach // the right or an element that is lexicographically greater than the pivot String. while ((predicate.get(collection[i]).compareTo(predicate.get(pivot)) <= 0 && i < end && j > i)){ i++; } // from the right, if the current element is lexicographically greater than the (original) // first element in the String array, move on. Stop advancing the counter when we reach // the left or an element that is lexicographically less than the pivot String. while ((predicate.get(collection[j]).compareTo(predicate.get(pivot)) >= 0 && j > start && j >= i)) { j--; } // check the two elements in the center, the last comparison before the scans cross. if (j > i) { swap(collection, i, j); } } // At this point, the two scans have crossed each other in the center of the array and stop. // The left partition and right partition contain the right groups of numbers but are not // sorted themselves. The following recursive code sorts the left and right partitions. // Swap the pivot point with the last element of the left partition. swap(collection, start, j); // sort left partition quickSort(collection, start, j-1, predicate); // sort right partition quickSort(collection, j+1, end, predicate); } } /** * Sorts a generic collection by a given key. * * Uses the Quick Sort algorithm. * * @param collection Collection to be sorted. * @param predicate Return the field intended to compare. * @param <TItem> The type of item held in the collection. * @param <TComparison> The type being used in the comparison while sorting the elements. */ public static <TItem, TComparison extends Comparable<TComparison>> void quickSort(List<TItem> collection, final Predicate<TItem, TComparison> predicate) { quickSort(collection, 0, collection.size() -1, predicate); } /** * Sorts a generic collection. * * Uses the Quick Sort algorithm. * * @param collection Collection to be sorted. * @param <TItem> The type of item held in the collection. */ public static <TItem extends Comparable<TItem>> void quickSort(List<TItem> collection){ quickSort(collection, 0, collection.size()-1, x -> x); } private static <TItem, TComparison extends Comparable<TComparison>> void quickSort(List<TItem> collection, int start, int end, final Predicate<TItem, TComparison> predicate) { // See the method with an ARRAY as the first argument for comments. int i = start; int j = end; if (j - i >= 1) { TItem pivot = collection.get(i); while (j > i) { while ((predicate.get(collection.get(i)).compareTo(predicate.get(pivot)) <= 0 && i < end && j > i)){ i++; } while ((predicate.get(collection.get(j)).compareTo(predicate.get(pivot)) >= 0 && j > start && j >= i)) { j--; } if (j > i) { swap(collection, i, j); } } swap(collection, start, j); quickSort(collection, start, j-1, predicate); quickSort(collection, j+1, end, predicate); } } /** * Swaps two elements in an collection. * * @param collection Collection containing the elements to be swapped. * @param i1 First element to be swapped. * @param i2 Second element to be swapped. * @param <TItem> Generic type used in the collection. */ private static <TItem> void swap(TItem[] collection, int i1, int i2) { TItem swap = collection[i1]; collection[i1] = collection[i2]; collection[i2] = swap; } /** * Swaps two elements in an collection. * * @param collection Collection containing the elements to be swapped. * @param i1 First element to be swapped. * @param i2 Second element to be swapped. * @param <TItem> Generic type used in the collection. */ private static <TItem> void swap(List<TItem> collection, int i1, int i2) { TItem swap = collection.get(i1); collection.set(i1, collection.get(i2)); collection.set(i2, swap); } }
UTF-8
Java
7,119
java
Sort.java
Java
[]
null
[]
package com.cathalnoonan.query; import java.util.List; public class Sort { /** * Sorts a generic collection by a given key. * * Uses the Quick Sort algorithm to sort the collection. * * @param collection Collection to be sorted. * @param predicate Return the field intended to compare. * @param <TItem> The type of item held in the collection. * @param <TComparison> The type being used in the comparison while sorting the elements. */ public static <TItem, TComparison extends Comparable<TComparison>> void quickSort(TItem[] collection, final Predicate<TItem, TComparison> predicate){ quickSort(collection, 0, collection.length-1, predicate); } /** * Sorts a generic collection. * * Uses the "Quick Sort" algorithm. * * @param collection Collection to be sorted. * @param <TItem> The type of item held in the collection. */ public static <TItem extends Comparable<TItem>> void quickSort(TItem[] collection){ quickSort(collection, 0, collection.length-1, x -> x); } private static <TItem, TComparison extends Comparable<TComparison>> void quickSort(TItem[] collection, int start, int end, final Predicate<TItem, TComparison> predicate) { /* * Extends on the following Stack-Overflow thread using Generics in place of String: * https://stackoverflow.com/questions/29294982/using-quicksort-on-a-string-array */ // index for the "left-to-right scan" int i = start; // index for the "right-to-left scan" int j = end; // only examine arrays of 2 or more elements. if (j - i >= 1) { // The pivot point of the sort method is arbitrarily set to the first element int the array. TItem pivot = collection[i]; // only scan between the two indexes, until they meet. while (j > i) { // from the left, if the current element is lexicographically less than the (original) // first element in the String array, move on. Stop advancing the counter when we reach // the right or an element that is lexicographically greater than the pivot String. while ((predicate.get(collection[i]).compareTo(predicate.get(pivot)) <= 0 && i < end && j > i)){ i++; } // from the right, if the current element is lexicographically greater than the (original) // first element in the String array, move on. Stop advancing the counter when we reach // the left or an element that is lexicographically less than the pivot String. while ((predicate.get(collection[j]).compareTo(predicate.get(pivot)) >= 0 && j > start && j >= i)) { j--; } // check the two elements in the center, the last comparison before the scans cross. if (j > i) { swap(collection, i, j); } } // At this point, the two scans have crossed each other in the center of the array and stop. // The left partition and right partition contain the right groups of numbers but are not // sorted themselves. The following recursive code sorts the left and right partitions. // Swap the pivot point with the last element of the left partition. swap(collection, start, j); // sort left partition quickSort(collection, start, j-1, predicate); // sort right partition quickSort(collection, j+1, end, predicate); } } /** * Sorts a generic collection by a given key. * * Uses the Quick Sort algorithm. * * @param collection Collection to be sorted. * @param predicate Return the field intended to compare. * @param <TItem> The type of item held in the collection. * @param <TComparison> The type being used in the comparison while sorting the elements. */ public static <TItem, TComparison extends Comparable<TComparison>> void quickSort(List<TItem> collection, final Predicate<TItem, TComparison> predicate) { quickSort(collection, 0, collection.size() -1, predicate); } /** * Sorts a generic collection. * * Uses the Quick Sort algorithm. * * @param collection Collection to be sorted. * @param <TItem> The type of item held in the collection. */ public static <TItem extends Comparable<TItem>> void quickSort(List<TItem> collection){ quickSort(collection, 0, collection.size()-1, x -> x); } private static <TItem, TComparison extends Comparable<TComparison>> void quickSort(List<TItem> collection, int start, int end, final Predicate<TItem, TComparison> predicate) { // See the method with an ARRAY as the first argument for comments. int i = start; int j = end; if (j - i >= 1) { TItem pivot = collection.get(i); while (j > i) { while ((predicate.get(collection.get(i)).compareTo(predicate.get(pivot)) <= 0 && i < end && j > i)){ i++; } while ((predicate.get(collection.get(j)).compareTo(predicate.get(pivot)) >= 0 && j > start && j >= i)) { j--; } if (j > i) { swap(collection, i, j); } } swap(collection, start, j); quickSort(collection, start, j-1, predicate); quickSort(collection, j+1, end, predicate); } } /** * Swaps two elements in an collection. * * @param collection Collection containing the elements to be swapped. * @param i1 First element to be swapped. * @param i2 Second element to be swapped. * @param <TItem> Generic type used in the collection. */ private static <TItem> void swap(TItem[] collection, int i1, int i2) { TItem swap = collection[i1]; collection[i1] = collection[i2]; collection[i2] = swap; } /** * Swaps two elements in an collection. * * @param collection Collection containing the elements to be swapped. * @param i1 First element to be swapped. * @param i2 Second element to be swapped. * @param <TItem> Generic type used in the collection. */ private static <TItem> void swap(List<TItem> collection, int i1, int i2) { TItem swap = collection.get(i1); collection.set(i1, collection.get(i2)); collection.set(i2, swap); } }
7,119
0.563843
0.557803
177
39.220341
38.042084
135
false
false
0
0
0
0
0
0
0.514124
false
false
12
b4ac98d3d8188accbdd2bf816c45405880774bcb
31,756,988,252,420
d5072fbeaa5bf7e4f09830b8f0fc837226468248
/src/더블릿/threeeight.java
a3e3e8ad0d0c544674961e2b8681bed50a7727e8
[]
no_license
anseohyun/javadouble
https://github.com/anseohyun/javadouble
058ef779e7ab7207d8ae008358c42834727cf331
7a3d4115990dfb42cd6652a3a07883d9d10d31c3
refs/heads/master
2021-01-02T02:13:50.649000
2020-03-22T02:33:46
2020-03-22T02:33:46
239,449,472
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// 프로그램 명: 1ton1 // 제한시간: 1 초 // // 자연수 n 을 입력으로 받아 1 부터 n 까지의 보기의 예와 같이 출력하는 프로그램을 작성하시오. // // 입력 // 1000 이하의 자연수가 입력으로 주어진다. // 출력 // 보기에 제시된 형식으로 출력 한다. 출력되는 문자사이에 공백은 없다. // // 입출력 예 // 입력 // 5 // 출력 // 1+2+3+4+5=15 package 더블릿; import java.util.Scanner; public class threeeight { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int sum = 0; for(int i = 1; i < num ; i++) { System.out.print(i+"+"); sum = sum + i; } sum = sum + num; System.out.println(num+"="+sum); } }
UHC
Java
819
java
threeeight.java
Java
[]
null
[]
// 프로그램 명: 1ton1 // 제한시간: 1 초 // // 자연수 n 을 입력으로 받아 1 부터 n 까지의 보기의 예와 같이 출력하는 프로그램을 작성하시오. // // 입력 // 1000 이하의 자연수가 입력으로 주어진다. // 출력 // 보기에 제시된 형식으로 출력 한다. 출력되는 문자사이에 공백은 없다. // // 입출력 예 // 입력 // 5 // 출력 // 1+2+3+4+5=15 package 더블릿; import java.util.Scanner; public class threeeight { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int sum = 0; for(int i = 1; i < num ; i++) { System.out.print(i+"+"); sum = sum + i; } sum = sum + num; System.out.println(num+"="+sum); } }
819
0.522095
0.492635
40
13.275
14.383997
57
false
false
0
0
0
0
0
0
1.4
false
false
12
48dcac77c99ff7f4618d513f6a9cdc7f8bc91b56
38,706,245,284,224
449afe56d7be449eaca68c1d9b0a5a65a67f8bcb
/TP BIG-DATA/Projet/Projet/P1/mapreduce_maven/src/main/java/mapreduce_maven/KMeans.java
ab6901c0b0fbcc7cfeca5a45e985b04154602d61
[]
no_license
lassouani/BigDataProject
https://github.com/lassouani/BigDataProject
192abb56f4c9f5415e25e20fdbb90c10a10bac88
6855b2197e54fab4396a7bae281d3c841c7ee802
refs/heads/master
2020-06-14T06:11:34.323000
2017-02-14T22:26:43
2017-02-14T22:26:43
75,223,289
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mapreduce_maven; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; public class KMeans { static long startTime = System.nanoTime(); static String basePath = "/centroids/"; public static MultiDemPoint[] getCentroids(Configuration conf, String input, String separator, int dimension, Integer[] columnPoint, int k) throws IOException { // Création des premiers centroids MultiDemPoint[] centroids = new MultiDemPoint[k]; FileSystem fs = FileSystem.get(conf); BufferedReader lines = new BufferedReader(new InputStreamReader(fs.open(new Path(input)), "UTF-8")); String line; String data[]; Boolean lineIsCorrect; int i = 0; do { line = lines.readLine(); if(line == null) { break; } data = line.toString().split("\\" + separator, -1); List<Double> coordCentroid = new ArrayList<Double>(); lineIsCorrect = true; for (int j = 0; (j < dimension && lineIsCorrect); j++) { try { coordCentroid.add(Double.parseDouble(data[columnPoint[j]])); } catch (NumberFormatException ignore) { lineIsCorrect = false; } } if (lineIsCorrect) { Boolean add = true; for(int j=0;j<i;j++) { if(centroids[j].getCoords().equals(coordCentroid)){ add = false; break; } } if(add) { centroids[i] = new MultiDemPoint(coordCentroid); i++; } } } while (i < k); fs.close(); return centroids; } public static MultiDemPoint[] getNewCentroids(Configuration conf, String input, int dimension, int k) throws IOException { // Création des premiers centroids MultiDemPoint[] centroids = new MultiDemPoint[k]; FileSystem fs = FileSystem.get(conf); BufferedReader lines = new BufferedReader(new InputStreamReader(fs.open(new Path(input)), "UTF-8")); String line; String data[]; int i = 0; do { line = lines.readLine(); if(line == null) { break; } data = line.toString().split("\\;", -1); List<Double> coordCentroid = new ArrayList<Double>(); for (int j = 0;j < dimension; j++) { coordCentroid.add(Double.parseDouble(data[j])); } centroids[i] = new MultiDemPoint(coordCentroid); i++; } while (i < k); fs.close(); return centroids; } public static void saveCentroids(MultiDemPoint[] centroids, long startTime, int numIteration) { String file = startTime + "_centroids_" + numIteration+".dat"; try { Path pt = new Path(basePath + file); FileSystem fs = FileSystem.get(new Configuration()); BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fs.create(pt, true))); // TO append data to a file, use fs.append(Path f) for(MultiDemPoint point : centroids){ br.write(point.toString()); br.write("\r\n"); } br.close(); } catch (Exception e) { System.out.println("File not found"); } } public static void main(String[] args) throws Exception { // Vérification qu'il y ait assez de paramètres if (args.length < 5) { System.out.println("Nombre de paramètres incorrects"); System.exit(0); } /* * PARAMETERS IN OUT K SEPARATOR COLUMNS ... [HEADER] */ // Définition des paramètres du job String input = args[0]; String output = args[1]; Integer k = Integer.parseInt(args[2]); String separator = args[3]; Integer dimension = (args.length - 4); Boolean header = false; if (args[args.length-1].equals("true")) { dimension--; header = true; } if (dimension < 1) { System.out.println("Nombre de paramètres insuffisants"); System.exit(0); } Configuration conf = new Configuration(); conf.setInt("K", k); conf.set("SEPARATOR", separator); conf.setInt("DIM", dimension); conf.setBoolean("HEADER", header); Integer columnPoint[] = new Integer[dimension]; for (int i = 4; i < dimension+4; i++) { columnPoint[i - 4] = Integer.parseInt(args[i]); conf.setInt("PARAM"+(i-4), Integer.parseInt(args[i])); } int numIteration = 0; boolean converged = false; String inputCentroids = input; MultiDemPoint[] centroids = new MultiDemPoint[k]; centroids = getCentroids(conf, inputCentroids, separator, dimension, columnPoint, k); saveCentroids(centroids, startTime, numIteration); while (!converged) { String nextCentroids = basePath+ startTime + "_centroids_" + (numIteration+1); Job job = Job.getInstance(conf, "KMeans"); job.addCacheFile(new Path(basePath+startTime + "_centroids_" + numIteration+".dat").toUri()); job.setNumReduceTasks(1); job.setJarByClass(KMeans.class); job.setMapperClass(KMeansMapper.class); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(CentroidWritable.class); job.setReducerClass(KMeansReducer.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(Text.class); job.setOutputFormatClass(TextOutputFormat.class); job.setInputFormatClass(TextInputFormat.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(nextCentroids+"_folder")); job.waitForCompletion(true); FileSystem fs = FileSystem.get(conf); Path source = new Path(nextCentroids+"_folder"); Path target = new Path(nextCentroids+".dat"); FileUtil.copyMerge(fs, source, fs, target, true, conf, null); System.out.println("\n"); System.out.println("-------------------------------"); System.out.println(">> Nouveaux centroids calculés"); System.out.println("-------------------------------\n"); MultiDemPoint[] newCentroids = new MultiDemPoint[k]; newCentroids = getNewCentroids(conf, nextCentroids+".dat", dimension, k); for(MultiDemPoint p : newCentroids){ System.out.println(p.toString()); } System.out.println("\n"); converged = converge(centroids, newCentroids); numIteration++; centroids = newCentroids; } // On créer le fichier final avec le numéro du cluster Job job = Job.getInstance(conf, "KMeans"); System.out.println("\n"); System.out.println("------------------------------------------------------"); System.out.println(">> Concaténation du fichier avec le numéro du cluster"); System.out.println("------------------------------------------------------\n"); job.addCacheFile(new Path(basePath+startTime + "_centroids_" + numIteration+".dat").toUri()); job.setNumReduceTasks(1); job.setJarByClass(KMeans.class); job.setMapperClass(KMeansResultMapper.class); job.setMapOutputKeyClass(NullWritable.class); job.setMapOutputValueClass(Text.class); job.setOutputFormatClass(TextOutputFormat.class); job.setInputFormatClass(TextInputFormat.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(output)); System.exit(job.waitForCompletion(true)? 0 : 1); } private static boolean converge(MultiDemPoint[] centroids, MultiDemPoint[] newCentroids) { for(int i=0;i<centroids.length;i++){ if(!centroids[i].converge(newCentroids[i])) { return false; } } return true; } }
UTF-8
Java
7,774
java
KMeans.java
Java
[]
null
[]
package mapreduce_maven; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; public class KMeans { static long startTime = System.nanoTime(); static String basePath = "/centroids/"; public static MultiDemPoint[] getCentroids(Configuration conf, String input, String separator, int dimension, Integer[] columnPoint, int k) throws IOException { // Création des premiers centroids MultiDemPoint[] centroids = new MultiDemPoint[k]; FileSystem fs = FileSystem.get(conf); BufferedReader lines = new BufferedReader(new InputStreamReader(fs.open(new Path(input)), "UTF-8")); String line; String data[]; Boolean lineIsCorrect; int i = 0; do { line = lines.readLine(); if(line == null) { break; } data = line.toString().split("\\" + separator, -1); List<Double> coordCentroid = new ArrayList<Double>(); lineIsCorrect = true; for (int j = 0; (j < dimension && lineIsCorrect); j++) { try { coordCentroid.add(Double.parseDouble(data[columnPoint[j]])); } catch (NumberFormatException ignore) { lineIsCorrect = false; } } if (lineIsCorrect) { Boolean add = true; for(int j=0;j<i;j++) { if(centroids[j].getCoords().equals(coordCentroid)){ add = false; break; } } if(add) { centroids[i] = new MultiDemPoint(coordCentroid); i++; } } } while (i < k); fs.close(); return centroids; } public static MultiDemPoint[] getNewCentroids(Configuration conf, String input, int dimension, int k) throws IOException { // Création des premiers centroids MultiDemPoint[] centroids = new MultiDemPoint[k]; FileSystem fs = FileSystem.get(conf); BufferedReader lines = new BufferedReader(new InputStreamReader(fs.open(new Path(input)), "UTF-8")); String line; String data[]; int i = 0; do { line = lines.readLine(); if(line == null) { break; } data = line.toString().split("\\;", -1); List<Double> coordCentroid = new ArrayList<Double>(); for (int j = 0;j < dimension; j++) { coordCentroid.add(Double.parseDouble(data[j])); } centroids[i] = new MultiDemPoint(coordCentroid); i++; } while (i < k); fs.close(); return centroids; } public static void saveCentroids(MultiDemPoint[] centroids, long startTime, int numIteration) { String file = startTime + "_centroids_" + numIteration+".dat"; try { Path pt = new Path(basePath + file); FileSystem fs = FileSystem.get(new Configuration()); BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fs.create(pt, true))); // TO append data to a file, use fs.append(Path f) for(MultiDemPoint point : centroids){ br.write(point.toString()); br.write("\r\n"); } br.close(); } catch (Exception e) { System.out.println("File not found"); } } public static void main(String[] args) throws Exception { // Vérification qu'il y ait assez de paramètres if (args.length < 5) { System.out.println("Nombre de paramètres incorrects"); System.exit(0); } /* * PARAMETERS IN OUT K SEPARATOR COLUMNS ... [HEADER] */ // Définition des paramètres du job String input = args[0]; String output = args[1]; Integer k = Integer.parseInt(args[2]); String separator = args[3]; Integer dimension = (args.length - 4); Boolean header = false; if (args[args.length-1].equals("true")) { dimension--; header = true; } if (dimension < 1) { System.out.println("Nombre de paramètres insuffisants"); System.exit(0); } Configuration conf = new Configuration(); conf.setInt("K", k); conf.set("SEPARATOR", separator); conf.setInt("DIM", dimension); conf.setBoolean("HEADER", header); Integer columnPoint[] = new Integer[dimension]; for (int i = 4; i < dimension+4; i++) { columnPoint[i - 4] = Integer.parseInt(args[i]); conf.setInt("PARAM"+(i-4), Integer.parseInt(args[i])); } int numIteration = 0; boolean converged = false; String inputCentroids = input; MultiDemPoint[] centroids = new MultiDemPoint[k]; centroids = getCentroids(conf, inputCentroids, separator, dimension, columnPoint, k); saveCentroids(centroids, startTime, numIteration); while (!converged) { String nextCentroids = basePath+ startTime + "_centroids_" + (numIteration+1); Job job = Job.getInstance(conf, "KMeans"); job.addCacheFile(new Path(basePath+startTime + "_centroids_" + numIteration+".dat").toUri()); job.setNumReduceTasks(1); job.setJarByClass(KMeans.class); job.setMapperClass(KMeansMapper.class); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(CentroidWritable.class); job.setReducerClass(KMeansReducer.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(Text.class); job.setOutputFormatClass(TextOutputFormat.class); job.setInputFormatClass(TextInputFormat.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(nextCentroids+"_folder")); job.waitForCompletion(true); FileSystem fs = FileSystem.get(conf); Path source = new Path(nextCentroids+"_folder"); Path target = new Path(nextCentroids+".dat"); FileUtil.copyMerge(fs, source, fs, target, true, conf, null); System.out.println("\n"); System.out.println("-------------------------------"); System.out.println(">> Nouveaux centroids calculés"); System.out.println("-------------------------------\n"); MultiDemPoint[] newCentroids = new MultiDemPoint[k]; newCentroids = getNewCentroids(conf, nextCentroids+".dat", dimension, k); for(MultiDemPoint p : newCentroids){ System.out.println(p.toString()); } System.out.println("\n"); converged = converge(centroids, newCentroids); numIteration++; centroids = newCentroids; } // On créer le fichier final avec le numéro du cluster Job job = Job.getInstance(conf, "KMeans"); System.out.println("\n"); System.out.println("------------------------------------------------------"); System.out.println(">> Concaténation du fichier avec le numéro du cluster"); System.out.println("------------------------------------------------------\n"); job.addCacheFile(new Path(basePath+startTime + "_centroids_" + numIteration+".dat").toUri()); job.setNumReduceTasks(1); job.setJarByClass(KMeans.class); job.setMapperClass(KMeansResultMapper.class); job.setMapOutputKeyClass(NullWritable.class); job.setMapOutputValueClass(Text.class); job.setOutputFormatClass(TextOutputFormat.class); job.setInputFormatClass(TextInputFormat.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(output)); System.exit(job.waitForCompletion(true)? 0 : 1); } private static boolean converge(MultiDemPoint[] centroids, MultiDemPoint[] newCentroids) { for(int i=0;i<centroids.length;i++){ if(!centroids[i].converge(newCentroids[i])) { return false; } } return true; } }
7,774
0.678263
0.67414
263
28.513308
25.743374
123
false
false
0
0
0
0
0
0
2.809886
false
false
5
46bd1bbc664b329ba8fd362860decc46d5dda80d
35,381,940,614,274
d9a3d8299c93bb88e274290893ed8f95c9dd9762
/OpenGL8/app/src/main/java/jp/ohwada/android/opengl8/SampleGLSurfaceViewRenderer.java
43b552fbe491bdfb4017422beec7df8155102368
[]
no_license
lzzkdxc/Android_Samples
https://github.com/lzzkdxc/Android_Samples
67d11ca20b06ee7edeea3e4480049693f3795aad
2c6649fef782f926a1a187d4500805c70b8c316d
refs/heads/master
2020-12-14T00:19:21.916000
2020-01-16T04:24:37
2020-01-16T04:24:37
234,574,842
1
0
null
true
2020-01-17T15:17:49
2020-01-17T15:17:49
2020-01-16T14:23:57
2020-01-16T04:24:47
921,630
0
0
0
null
false
false
/** * OpenGL ES2.0 Sample * draw Square and scaling Triangle * 2019-10-01 K.OHWADA * original : https://github.com/JimSeker/opengl/tree/master/HelloOpenGLES20 */ package jp.ohwada.android.opengl8; /* * Copyright (C) 2011 The Android Open Source Project * * 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. */ import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.Matrix; import android.os.SystemClock; import android.util.Log; /** * class SampleGLSurfaceViewRenderer * Provides drawing instructions for a GLSurfaceView object. This class * must override the OpenGL ES drawing lifecycle methods: * <ul> * <li>{@link android.opengl.GLSurfaceView.Renderer#onSurfaceCreated}</li> * <li>{@link android.opengl.GLSurfaceView.Renderer#onDrawFrame}</li> * <li>{@link android.opengl.GLSurfaceView.Renderer#onSurfaceChanged}</li> * </ul> */ public class SampleGLSurfaceViewRenderer implements GLSurfaceView.Renderer { // debug private static final String TAG = "SampleGLSurfaceViewRenderer"; // Bckground Color(Blue) private static final float[] BG_COLOR = { 0.4f, 0.4f, 0.4f, 1.0f }; // Square Color(Blue) private static final float[] SQUARE_COLOR = { 0.0f, 0.0f, 1.0f, 1.0f }; // Triangle Color(Red) private static final float[] TRIANGLE_COLOR = { 1.0f, 0.0f, 0.0f, 1.0f }; // Triangle Scale private static final float FACTOR_ZOOM_X = 1.001f; private static final float FACTOR_ZOOM_Y = 1.001f; private Triangle mTriangle; private Square mSquare; // mMVPMatrix is an abbreviation for "Model View Projection Matrix" private final float[] mMVPMatrix = new float[16]; private final float[] mProjectionMatrix = new float[16]; private final float[] mViewMatrix = new float[16]; private float[] mScaleMatrix = new float[16]; // Triangle Scale // little smaller at the start private float mScaleX = 0.8f; private float mScaleY = 0.8f; private float mFactorX = FACTOR_ZOOM_X; private float mFactorY = FACTOR_ZOOM_Y; /** * onSurfaceCreated */ @Override public void onSurfaceCreated(GL10 unused, EGLConfig config) { // set Background Frame Color GLES20.glClearColor(BG_COLOR[0], BG_COLOR[1], BG_COLOR[2], BG_COLOR[3]); mTriangle = new Triangle(); mTriangle.setColor(TRIANGLE_COLOR); mSquare = new Square(); mSquare.setColor(SQUARE_COLOR); } /** * onDrawFrame */ @Override public void onDrawFrame(GL10 unused) { // Draw background color GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); createViewMatrix(); // Draw square mSquare.draw(mMVPMatrix); createScaleMatrix(); // Draw triangle mTriangle.draw(mScaleMatrix); } /** * createViewMatrix */ private void createViewMatrix() { // Set the camera position (View matrix) Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f); // Calculate the projection and view transformation Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0); } /** * createScaleMatrix */ private void createScaleMatrix() { mScaleMatrix = mMVPMatrix.clone(); float SZ = 1.0f; int OFFSET = 0; float SHRINK_X = 0.999f; float SHRINK_Y = 0.999f; float MAX_X = 2.1f; float MIN_X = 0.6f; float MAX_Y = 2.2f; float MIN_Y = 0.6f; mScaleX = mFactorX * mScaleX; if(mScaleX > MAX_X) { mScaleX = MAX_X; mFactorX = SHRINK_X; } if(mScaleX < MIN_X) { mScaleX = MIN_X; mFactorX = FACTOR_ZOOM_X; } mScaleY = mFactorY * mScaleY; if(mScaleY > MAX_Y) { mScaleY = MAX_Y; mFactorY = SHRINK_Y; } if(mScaleY < MIN_Y) { mScaleY = MIN_Y; mFactorY = FACTOR_ZOOM_Y; } Matrix.scaleM(mScaleMatrix, OFFSET, mScaleX, mScaleY, SZ); } /** * onSurfaceChanged */ @Override public void onSurfaceChanged(GL10 unused, int width, int height) { // Adjust the viewport based on geometry changes, // such as screen rotation GLES20.glViewport(0, 0, width, height); float ratio = (float) width / height; // this projection matrix is applied to object coordinates // in the onDrawFrame() method Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7); } /** * loadShader * Utility method for compiling a OpenGL shader. * * <p><strong>Note:</strong> When developing shaders, use the checkGlError() * method to debug shader coding errors.</p> * * @param type - Vertex or fragment shader type. * @param shaderCode - String containing the shader code. * @return - Returns an id for the shader. */ public static int loadShader(int type, String shaderCode){ // create a vertex shader type (GLES20.GL_VERTEX_SHADER) // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER) int shader = GLES20.glCreateShader(type); // add the source code to the shader and compile it GLES20.glShaderSource(shader, shaderCode); GLES20.glCompileShader(shader); return shader; } /** * checkGlError * Utility method for debugging OpenGL calls. Provide the name of the call * just after making it: * * <pre> * mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor"); * SampleGLSurfaceViewRenderer.checkGlError("glGetUniformLocation");</pre> * * If the operation is not successful, the check throws an error. * * @param glOperation - Name of the OpenGL call to check. */ public static void checkGlError(String glOperation) { int error; while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { log_d(glOperation + ": glError " + error); throw new RuntimeException(glOperation + ": glError " + error); } } /** * write into logcat */ private static void log_d( String msg ) { Log.d( TAG, msg ); } } // class SampleGLSurfaceViewRenderer
UTF-8
Java
6,805
java
SampleGLSurfaceViewRenderer.java
Java
[ { "context": "* draw Square and scaling Triangle\n * 2019-10-01 K.OHWADA\n * original : https://github.com/JimSeker/opengl/", "end": 89, "score": 0.9998270869255066, "start": 81, "tag": "NAME", "value": "K.OHWADA" }, { "context": "9-10-01 K.OHWADA\n * original : https://github.com/JimSeker/opengl/tree/master/HelloOpenGLES20\n */\npackage jp", "end": 131, "score": 0.9997217059135437, "start": 123, "tag": "USERNAME", "value": "JimSeker" } ]
null
[]
/** * OpenGL ES2.0 Sample * draw Square and scaling Triangle * 2019-10-01 K.OHWADA * original : https://github.com/JimSeker/opengl/tree/master/HelloOpenGLES20 */ package jp.ohwada.android.opengl8; /* * Copyright (C) 2011 The Android Open Source Project * * 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. */ import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.Matrix; import android.os.SystemClock; import android.util.Log; /** * class SampleGLSurfaceViewRenderer * Provides drawing instructions for a GLSurfaceView object. This class * must override the OpenGL ES drawing lifecycle methods: * <ul> * <li>{@link android.opengl.GLSurfaceView.Renderer#onSurfaceCreated}</li> * <li>{@link android.opengl.GLSurfaceView.Renderer#onDrawFrame}</li> * <li>{@link android.opengl.GLSurfaceView.Renderer#onSurfaceChanged}</li> * </ul> */ public class SampleGLSurfaceViewRenderer implements GLSurfaceView.Renderer { // debug private static final String TAG = "SampleGLSurfaceViewRenderer"; // Bckground Color(Blue) private static final float[] BG_COLOR = { 0.4f, 0.4f, 0.4f, 1.0f }; // Square Color(Blue) private static final float[] SQUARE_COLOR = { 0.0f, 0.0f, 1.0f, 1.0f }; // Triangle Color(Red) private static final float[] TRIANGLE_COLOR = { 1.0f, 0.0f, 0.0f, 1.0f }; // Triangle Scale private static final float FACTOR_ZOOM_X = 1.001f; private static final float FACTOR_ZOOM_Y = 1.001f; private Triangle mTriangle; private Square mSquare; // mMVPMatrix is an abbreviation for "Model View Projection Matrix" private final float[] mMVPMatrix = new float[16]; private final float[] mProjectionMatrix = new float[16]; private final float[] mViewMatrix = new float[16]; private float[] mScaleMatrix = new float[16]; // Triangle Scale // little smaller at the start private float mScaleX = 0.8f; private float mScaleY = 0.8f; private float mFactorX = FACTOR_ZOOM_X; private float mFactorY = FACTOR_ZOOM_Y; /** * onSurfaceCreated */ @Override public void onSurfaceCreated(GL10 unused, EGLConfig config) { // set Background Frame Color GLES20.glClearColor(BG_COLOR[0], BG_COLOR[1], BG_COLOR[2], BG_COLOR[3]); mTriangle = new Triangle(); mTriangle.setColor(TRIANGLE_COLOR); mSquare = new Square(); mSquare.setColor(SQUARE_COLOR); } /** * onDrawFrame */ @Override public void onDrawFrame(GL10 unused) { // Draw background color GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); createViewMatrix(); // Draw square mSquare.draw(mMVPMatrix); createScaleMatrix(); // Draw triangle mTriangle.draw(mScaleMatrix); } /** * createViewMatrix */ private void createViewMatrix() { // Set the camera position (View matrix) Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f); // Calculate the projection and view transformation Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0); } /** * createScaleMatrix */ private void createScaleMatrix() { mScaleMatrix = mMVPMatrix.clone(); float SZ = 1.0f; int OFFSET = 0; float SHRINK_X = 0.999f; float SHRINK_Y = 0.999f; float MAX_X = 2.1f; float MIN_X = 0.6f; float MAX_Y = 2.2f; float MIN_Y = 0.6f; mScaleX = mFactorX * mScaleX; if(mScaleX > MAX_X) { mScaleX = MAX_X; mFactorX = SHRINK_X; } if(mScaleX < MIN_X) { mScaleX = MIN_X; mFactorX = FACTOR_ZOOM_X; } mScaleY = mFactorY * mScaleY; if(mScaleY > MAX_Y) { mScaleY = MAX_Y; mFactorY = SHRINK_Y; } if(mScaleY < MIN_Y) { mScaleY = MIN_Y; mFactorY = FACTOR_ZOOM_Y; } Matrix.scaleM(mScaleMatrix, OFFSET, mScaleX, mScaleY, SZ); } /** * onSurfaceChanged */ @Override public void onSurfaceChanged(GL10 unused, int width, int height) { // Adjust the viewport based on geometry changes, // such as screen rotation GLES20.glViewport(0, 0, width, height); float ratio = (float) width / height; // this projection matrix is applied to object coordinates // in the onDrawFrame() method Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7); } /** * loadShader * Utility method for compiling a OpenGL shader. * * <p><strong>Note:</strong> When developing shaders, use the checkGlError() * method to debug shader coding errors.</p> * * @param type - Vertex or fragment shader type. * @param shaderCode - String containing the shader code. * @return - Returns an id for the shader. */ public static int loadShader(int type, String shaderCode){ // create a vertex shader type (GLES20.GL_VERTEX_SHADER) // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER) int shader = GLES20.glCreateShader(type); // add the source code to the shader and compile it GLES20.glShaderSource(shader, shaderCode); GLES20.glCompileShader(shader); return shader; } /** * checkGlError * Utility method for debugging OpenGL calls. Provide the name of the call * just after making it: * * <pre> * mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor"); * SampleGLSurfaceViewRenderer.checkGlError("glGetUniformLocation");</pre> * * If the operation is not successful, the check throws an error. * * @param glOperation - Name of the OpenGL call to check. */ public static void checkGlError(String glOperation) { int error; while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { log_d(glOperation + ": glError " + error); throw new RuntimeException(glOperation + ": glError " + error); } } /** * write into logcat */ private static void log_d( String msg ) { Log.d( TAG, msg ); } } // class SampleGLSurfaceViewRenderer
6,805
0.649816
0.628362
259
25.277992
25.541849
80
false
false
0
0
0
0
0
0
0.490348
false
false
5
21c0a8b5cc316413bb59d9c983e89f17e1ac48a6
38,208,029,080,676
cc2bffa7b1ffb4f6d3728a3e2ef8c9d74695c1ec
/app/src/main/java/com/faceng/jetpackdemo/entity/User.java
d25a02009f880540b4af6c07920b8d3cbc9a4273
[]
no_license
zengfa/jetpackdemo
https://github.com/zengfa/jetpackdemo
626648abc183a773a8a3219878a19daefd11655a
2da140b5fc731fa2c9e556c241a216af92db50aa
refs/heads/main
2023-01-28T22:41:38.299000
2020-12-07T14:54:37
2020-12-07T14:54:37
319,345,643
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.faceng.jetpackdemo.entity; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "user_table") public class User { @PrimaryKey @NonNull @ColumnInfo(name = "user") private String mUser; public User(String user) {this.mUser = user;} public String getUser(){return this.mUser;} }
UTF-8
Java
408
java
User.java
Java
[]
null
[]
package com.faceng.jetpackdemo.entity; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "user_table") public class User { @PrimaryKey @NonNull @ColumnInfo(name = "user") private String mUser; public User(String user) {this.mUser = user;} public String getUser(){return this.mUser;} }
408
0.742647
0.742647
19
20.526316
16.384745
48
false
false
0
0
0
0
0
0
0.421053
false
false
5
968b058dce61477bec3ed18e39b32a6dc2efa426
21,998,822,538,255
cfe621e8c36e6ac5053a2c4f7129a13ea9f9f66b
/AndroidApplications/com.zeptolab.ctr.ads-912244/src/a/a/w.java
61beef48485a3bdab216a17f117bfe8dc6f0eeb3
[]
no_license
linux86/AndoirdSecurity
https://github.com/linux86/AndoirdSecurity
3165de73b37f53070cd6b435e180a2cb58d6f672
1e72a3c1f7a72ea9cd12048d9874a8651e0aede7
refs/heads/master
2021-01-11T01:20:58.986000
2016-04-05T17:14:26
2016-04-05T17:14:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package a.a; public abstract class w { public abstract void a(); public abstract void a(l lVar); }
UTF-8
Java
108
java
w.java
Java
[]
null
[]
package a.a; public abstract class w { public abstract void a(); public abstract void a(l lVar); }
108
0.666667
0.666667
7
14.571428
13.885832
35
false
false
0
0
0
0
0
0
0.428571
false
false
5
852b48c3bdcecd0faaa1913481517888d6ac5385
37,520,834,324,394
49795f863037438be70eec7882301c50e369e92e
/coding/src/TwoStrings.java
cec27d05129c5f054e945e5e3268a7ebbddd0b85
[]
no_license
anshu1106/Algo-Practice-Problems
https://github.com/anshu1106/Algo-Practice-Problems
32aaaa202ad4e915498669b578d3dc21af264224
ea13cad09cbd784c2f2223dacae845fef87a2e05
refs/heads/master
2021-01-19T02:43:29.920000
2016-07-28T16:45:19
2016-07-28T16:45:19
28,168,184
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; class TwoStrings { public static void main(String args[]) { Scanner in = new Scanner(System.in); int count = in.nextInt(); boolean flag; for (int i=0;i<count;i++) { flag = false; int lettersArray[] = new int[26]; String a=in.next(); String b = in.next(); for ( int index = 0; index < a.length(); index++){ lettersArray[a.charAt(index)-'a']=1; } for(int index=0;index<b.length();index++) { char c = b.charAt(index); int arrayIndex= c-'a'; if (lettersArray[arrayIndex]!=0) { flag = true; break; } } if(flag) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
UTF-8
Java
724
java
TwoStrings.java
Java
[]
null
[]
import java.util.Scanner; class TwoStrings { public static void main(String args[]) { Scanner in = new Scanner(System.in); int count = in.nextInt(); boolean flag; for (int i=0;i<count;i++) { flag = false; int lettersArray[] = new int[26]; String a=in.next(); String b = in.next(); for ( int index = 0; index < a.length(); index++){ lettersArray[a.charAt(index)-'a']=1; } for(int index=0;index<b.length();index++) { char c = b.charAt(index); int arrayIndex= c-'a'; if (lettersArray[arrayIndex]!=0) { flag = true; break; } } if(flag) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
724
0.54558
0.535912
43
15.83721
14.764713
53
false
false
0
0
0
0
0
0
3.046512
false
false
5
31792b9775ccc71143f5fcfcb9ceca53c6ef54ae
37,984,690,787,674
ab2432c3898a953d5a12ca3f1091b41de33570a3
/GaragemModel/src/main/java/com/academico/garagem/model/entity/Garage.java
13e6945f0eb64ca9892fcd7ad9ce3185e5b0ed07
[]
no_license
JenniferBorges/GaragemVirtual-TCC-Faitec2018
https://github.com/JenniferBorges/GaragemVirtual-TCC-Faitec2018
3cabbfd18093218e779aa337313efc8e99265ada
27a1c75f7eb22f5de318d2879888cb7d268a2725
refs/heads/master
2020-04-19T23:55:23.049000
2019-01-31T10:49:38
2019-01-31T10:49:38
168,509,308
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.academico.garagem.model.entity; import com.academico.garagem.model.base.BaseEntity; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonManagedReference; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author mathe */ @Entity @Table(name = "garage") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Garage.findAll", query = "SELECT g FROM Garage g"), @NamedQuery(name = "Garage.findById", query = "SELECT g FROM Garage g WHERE g.id = :id"), @NamedQuery(name = "Garage.findByHeight", query = "SELECT g FROM Garage g WHERE g.height = :height"), @NamedQuery(name = "Garage.findByWidth", query = "SELECT g FROM Garage g WHERE g.width = :width"), @NamedQuery(name = "Garage.findByLength", query = "SELECT g FROM Garage g WHERE g.length = :length"), @NamedQuery(name = "Garage.findByAccess", query = "SELECT g FROM Garage g WHERE g.access = :access"), @NamedQuery(name = "Garage.findByHasRoof", query = "SELECT g FROM Garage g WHERE g.hasRoof = :hasRoof"), @NamedQuery(name = "Garage.findByHasCam", query = "SELECT g FROM Garage g WHERE g.hasCam = :hasCam"), @NamedQuery(name = "Garage.findByHasIndemnity", query = "SELECT g FROM Garage g WHERE g.hasIndemnity = :hasIndemnity"), @NamedQuery(name = "Garage.findByHasElectronicGate", query = "SELECT g FROM Garage g WHERE g.hasElectronicGate = :hasElectronicGate")}) public class Garage extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; @Basic(optional = false) @NotNull @Column(name = "height") private double height; @Basic(optional = false) @NotNull @Column(name = "width") private double width; @Basic(optional = false) @NotNull @Column(name = "length") private double length; @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) @Column(name = "access") private String access; @Basic(optional = false) @NotNull @Column(name = "has_roof") private boolean hasRoof; @Basic(optional = false) @NotNull @Column(name = "has_cam") private boolean hasCam; @Basic(optional = false) @NotNull @Column(name = "has_indemnity") private boolean hasIndemnity; @Basic(optional = false) @NotNull @Column(name = "has_electronic_gate") private boolean hasElectronicGate; @OneToMany(mappedBy = "garageId") private List<Image> imageList; @JsonBackReference @JoinColumn(name = "user_id", referencedColumnName = "id") @ManyToOne(optional = false) private User userId; @JoinColumn(name = "address_id", referencedColumnName = "id") @ManyToOne(optional = false) private Address addressId; @JsonManagedReference @OneToMany(cascade = CascadeType.ALL, mappedBy = "garageId") private List<Advertisement> advertisementList; public Garage() { } public Garage(Integer id) { this.id = id; } public Garage(Integer id, double height, double width, double length, String access, boolean hasRoof, boolean hasCam, boolean hasIndemnity, boolean hasElectronicGate) { this.id = id; this.height = height; this.width = width; this.length = length; this.access = access; this.hasRoof = hasRoof; this.hasCam = hasCam; this.hasIndemnity = hasIndemnity; this.hasElectronicGate = hasElectronicGate; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getLength() { return length; } public void setLength(double length) { this.length = length; } public String getAccess() { return access; } public void setAccess(String access) { this.access = access; } public boolean getHasRoof() { return hasRoof; } public void setHasRoof(boolean hasRoof) { this.hasRoof = hasRoof; } public boolean getHasCam() { return hasCam; } public void setHasCam(boolean hasCam) { this.hasCam = hasCam; } public boolean getHasIndemnity() { return hasIndemnity; } public void setHasIndemnity(boolean hasIndemnity) { this.hasIndemnity = hasIndemnity; } public boolean getHasElectronicGate() { return hasElectronicGate; } public void setHasElectronicGate(boolean hasElectronicGate) { this.hasElectronicGate = hasElectronicGate; } @XmlTransient public List<Image> getImageList() { return imageList; } public void setImageList(List<Image> imageList) { this.imageList = imageList; } public User getUserId() { return userId; } public void setUserId(User userId) { this.userId = userId; } public Address getAddressId() { return addressId; } public void setAddressId(Address addressId) { this.addressId = addressId; } @XmlTransient public List<Advertisement> getAdvertisementList() { return advertisementList; } public void setAdvertisementList(List<Advertisement> advertisementList) { this.advertisementList = advertisementList; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Garage)) { return false; } Garage other = (Garage) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.academico.garagem.model.entity.Garage[ id=" + id + " ]"; } }
UTF-8
Java
7,120
java
Garage.java
Java
[ { "context": "nd.annotation.XmlTransient;\r\n\r\n/**\r\n *\r\n * @author mathe\r\n */\r\n@Entity\r\n@Table(name = \"garage\")\r\n@XmlRootE", "end": 1044, "score": 0.8460075259208679, "start": 1039, "tag": "USERNAME", "value": "mathe" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.academico.garagem.model.entity; import com.academico.garagem.model.base.BaseEntity; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonManagedReference; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author mathe */ @Entity @Table(name = "garage") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Garage.findAll", query = "SELECT g FROM Garage g"), @NamedQuery(name = "Garage.findById", query = "SELECT g FROM Garage g WHERE g.id = :id"), @NamedQuery(name = "Garage.findByHeight", query = "SELECT g FROM Garage g WHERE g.height = :height"), @NamedQuery(name = "Garage.findByWidth", query = "SELECT g FROM Garage g WHERE g.width = :width"), @NamedQuery(name = "Garage.findByLength", query = "SELECT g FROM Garage g WHERE g.length = :length"), @NamedQuery(name = "Garage.findByAccess", query = "SELECT g FROM Garage g WHERE g.access = :access"), @NamedQuery(name = "Garage.findByHasRoof", query = "SELECT g FROM Garage g WHERE g.hasRoof = :hasRoof"), @NamedQuery(name = "Garage.findByHasCam", query = "SELECT g FROM Garage g WHERE g.hasCam = :hasCam"), @NamedQuery(name = "Garage.findByHasIndemnity", query = "SELECT g FROM Garage g WHERE g.hasIndemnity = :hasIndemnity"), @NamedQuery(name = "Garage.findByHasElectronicGate", query = "SELECT g FROM Garage g WHERE g.hasElectronicGate = :hasElectronicGate")}) public class Garage extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; @Basic(optional = false) @NotNull @Column(name = "height") private double height; @Basic(optional = false) @NotNull @Column(name = "width") private double width; @Basic(optional = false) @NotNull @Column(name = "length") private double length; @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) @Column(name = "access") private String access; @Basic(optional = false) @NotNull @Column(name = "has_roof") private boolean hasRoof; @Basic(optional = false) @NotNull @Column(name = "has_cam") private boolean hasCam; @Basic(optional = false) @NotNull @Column(name = "has_indemnity") private boolean hasIndemnity; @Basic(optional = false) @NotNull @Column(name = "has_electronic_gate") private boolean hasElectronicGate; @OneToMany(mappedBy = "garageId") private List<Image> imageList; @JsonBackReference @JoinColumn(name = "user_id", referencedColumnName = "id") @ManyToOne(optional = false) private User userId; @JoinColumn(name = "address_id", referencedColumnName = "id") @ManyToOne(optional = false) private Address addressId; @JsonManagedReference @OneToMany(cascade = CascadeType.ALL, mappedBy = "garageId") private List<Advertisement> advertisementList; public Garage() { } public Garage(Integer id) { this.id = id; } public Garage(Integer id, double height, double width, double length, String access, boolean hasRoof, boolean hasCam, boolean hasIndemnity, boolean hasElectronicGate) { this.id = id; this.height = height; this.width = width; this.length = length; this.access = access; this.hasRoof = hasRoof; this.hasCam = hasCam; this.hasIndemnity = hasIndemnity; this.hasElectronicGate = hasElectronicGate; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getLength() { return length; } public void setLength(double length) { this.length = length; } public String getAccess() { return access; } public void setAccess(String access) { this.access = access; } public boolean getHasRoof() { return hasRoof; } public void setHasRoof(boolean hasRoof) { this.hasRoof = hasRoof; } public boolean getHasCam() { return hasCam; } public void setHasCam(boolean hasCam) { this.hasCam = hasCam; } public boolean getHasIndemnity() { return hasIndemnity; } public void setHasIndemnity(boolean hasIndemnity) { this.hasIndemnity = hasIndemnity; } public boolean getHasElectronicGate() { return hasElectronicGate; } public void setHasElectronicGate(boolean hasElectronicGate) { this.hasElectronicGate = hasElectronicGate; } @XmlTransient public List<Image> getImageList() { return imageList; } public void setImageList(List<Image> imageList) { this.imageList = imageList; } public User getUserId() { return userId; } public void setUserId(User userId) { this.userId = userId; } public Address getAddressId() { return addressId; } public void setAddressId(Address addressId) { this.addressId = addressId; } @XmlTransient public List<Advertisement> getAdvertisementList() { return advertisementList; } public void setAdvertisementList(List<Advertisement> advertisementList) { this.advertisementList = advertisementList; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Garage)) { return false; } Garage other = (Garage) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.academico.garagem.model.entity.Garage[ id=" + id + " ]"; } }
7,120
0.638764
0.636798
237
28.042194
27.032999
172
false
false
0
0
0
0
0
0
0.468354
false
false
5
20a16fdd5c7f5b13d218347d04981f8cdf335530
34,419,867,963,041
1bb92e8d2b2d221cb6b6f66fd17348355a9a17a2
/app/src/main/java/com/clientBase/util/URLDrawable.java
190d57f4182d5f85d166fa6eb5644cb9ef5067df
[]
no_license
xujunhua555/shopclient1
https://github.com/xujunhua555/shopclient1
5177a6553b25c2f6608560bbc94f1c5420a697cb
4a44ec7864922cd60b8d245aeed34374ddc26ec6
refs/heads/master
2022-06-14T17:34:27.080000
2020-05-04T17:19:51
2020-05-04T17:19:51
261,188,145
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.clientBase.util; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; public class URLDrawable extends BitmapDrawable { protected Drawable drawable; public Bitmap bitmap; @Override public void draw(Canvas canvas) { if (drawable != null) { drawable.draw(canvas); } if (bitmap != null) { canvas.drawBitmap(bitmap, 0, 0, getPaint()); } } }
UTF-8
Java
501
java
URLDrawable.java
Java
[]
null
[]
package com.clientBase.util; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; public class URLDrawable extends BitmapDrawable { protected Drawable drawable; public Bitmap bitmap; @Override public void draw(Canvas canvas) { if (drawable != null) { drawable.draw(canvas); } if (bitmap != null) { canvas.drawBitmap(bitmap, 0, 0, getPaint()); } } }
501
0.706587
0.702595
24
18.875
17.340494
49
false
false
0
0
0
0
0
0
1.291667
false
false
5
ecbccb24df31b90e6552f377bfc698083820431d
27,204,322,915,350
1ce5be8183cd7cdf72551df788f8b67b0b4c4d3f
/parent/rest/src/main/java/br/com/pojo/Menu.java
71c4ad9f054cf570df68eae12a5827db9a6841f1
[ "Apache-2.0" ]
permissive
DaviCastro/FrameWork
https://github.com/DaviCastro/FrameWork
381393cac42779ddefdbd822873a015dd57fed48
b93fac2dc9d1f3a472f8be0745f18986cb7f0ed1
refs/heads/master
2021-01-23T11:48:11.465000
2015-01-06T19:16:37
2015-01-06T19:16:37
24,986,213
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.pojo; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import br.com.annotation.AAutoComplete; import br.com.annotation.AHbnDao; import br.com.annotation.AService; import br.com.dao.Identifiable; import br.com.dao.hbn.HbnMenuDao; import br.com.service.MenuServiceImpl; @Entity @Table(name = "menu") @AService(service=MenuServiceImpl.class) @AHbnDao(hbnDao = HbnMenuDao.class) public class Menu implements Serializable, Identifiable { /** * */ private static final long serialVersionUID = -642312115827482492L; @Id @GeneratedValue() @Column(name = "id") private Integer id; @AAutoComplete @Column(name = "nome") private String nome; @ManyToOne(targetEntity=Menu.class) @JoinColumn(name = "idMenuPai") private Menu menuPai; @Column(name = "url") private String url; @ElementCollection(targetClass = String.class) @JoinTable(name = "menu_permissao", uniqueConstraints = { @UniqueConstraint(columnNames = { "menu", "permissao" }) }, joinColumns = @JoinColumn(name="menu")) @Column(name = "permissao", length = 50) private Set<String> permissao = new HashSet<String>(); public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Menu getMenuPai() { return menuPai; } public void setMenuPai(Menu menuPai) { this.menuPai = menuPai; } public boolean possuiFilho() { return this.menuPai != null && this.menuPai.getId() != 0 && this.url != null; } public boolean isPai() { return this.menuPai == null || this.menuPai.getId() == 0; } @Override public String toString() { return nome; } public Set<String> getPermissao() { return permissao; } public void setPermissao(Set<String> permissao) { this.permissao = permissao; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((menuPai == null) ? 0 : menuPai.hashCode()); result = prime * result + ((nome == null) ? 0 : nome.hashCode()); result = prime * result + ((permissao == null) ? 0 : permissao.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Menu other = (Menu) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (menuPai == null) { if (other.menuPai != null) return false; } else if (!menuPai.equals(other.menuPai)) return false; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; if (permissao == null) { if (other.permissao != null) return false; } else if (!permissao.equals(other.permissao)) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; return true; } }
UTF-8
Java
3,653
java
Menu.java
Java
[]
null
[]
package br.com.pojo; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import br.com.annotation.AAutoComplete; import br.com.annotation.AHbnDao; import br.com.annotation.AService; import br.com.dao.Identifiable; import br.com.dao.hbn.HbnMenuDao; import br.com.service.MenuServiceImpl; @Entity @Table(name = "menu") @AService(service=MenuServiceImpl.class) @AHbnDao(hbnDao = HbnMenuDao.class) public class Menu implements Serializable, Identifiable { /** * */ private static final long serialVersionUID = -642312115827482492L; @Id @GeneratedValue() @Column(name = "id") private Integer id; @AAutoComplete @Column(name = "nome") private String nome; @ManyToOne(targetEntity=Menu.class) @JoinColumn(name = "idMenuPai") private Menu menuPai; @Column(name = "url") private String url; @ElementCollection(targetClass = String.class) @JoinTable(name = "menu_permissao", uniqueConstraints = { @UniqueConstraint(columnNames = { "menu", "permissao" }) }, joinColumns = @JoinColumn(name="menu")) @Column(name = "permissao", length = 50) private Set<String> permissao = new HashSet<String>(); public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Menu getMenuPai() { return menuPai; } public void setMenuPai(Menu menuPai) { this.menuPai = menuPai; } public boolean possuiFilho() { return this.menuPai != null && this.menuPai.getId() != 0 && this.url != null; } public boolean isPai() { return this.menuPai == null || this.menuPai.getId() == 0; } @Override public String toString() { return nome; } public Set<String> getPermissao() { return permissao; } public void setPermissao(Set<String> permissao) { this.permissao = permissao; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((menuPai == null) ? 0 : menuPai.hashCode()); result = prime * result + ((nome == null) ? 0 : nome.hashCode()); result = prime * result + ((permissao == null) ? 0 : permissao.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Menu other = (Menu) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (menuPai == null) { if (other.menuPai != null) return false; } else if (!menuPai.equals(other.menuPai)) return false; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; if (permissao == null) { if (other.permissao != null) return false; } else if (!permissao.equals(other.permissao)) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; return true; } }
3,653
0.678894
0.670682
164
21.274391
19.127724
92
false
false
0
0
0
0
0
0
1.579268
false
false
5
1fd665a673308613d33da16d3ce05c8cfb4101f1
31,817,117,780,976
57b61a73ff4cc75d8dbb79b5e511208c1ea9f4db
/BayesNetDFSGraph.java
b45fbe22387a8f3b3d73dd7792365c07332ddc3a
[]
no_license
caseycode/ProbabilityBaySample
https://github.com/caseycode/ProbabilityBaySample
03ab5830ac016e885111ec679b39d39dba559419
e824e8a828dfb7a32be45ae53fb73813a04629a7
refs/heads/master
2021-01-21T12:40:40.078000
2012-12-14T04:37:43
2012-12-14T04:37:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bnp; import java.util.ArrayList; /* * class BayesNetDFSGraph: * * Using a Depth First Search (DFS) algorithm, * this class finds an elimination sequence that * has a small total table size. * * * A BayesNetDFSGraph object is constructed with a BayesNetGraph object. * * BayesNetDFSGraph makes its own hard copies of nodes and connections * so that BayesNetGraph won't be affected. * */ import java.util.Random; public class BayesNetDFSGraph { private ArrayList<BayesNetDFSNode> nodeList; private ArrayList<BayesNetDFSNode> remainingNodeList; private BayesNetDFSCliqueSet cliqueSet; private ArrayList<BayesNetDFSNode> eliminatedNodeSequence; private BayesNetDFSLineSet addedLineSetSinceLastCliqueUpdate; private boolean isInitialCliqueSetIdentified; // private constructor: used for initialization private BayesNetDFSGraph() { nodeList = new ArrayList<BayesNetDFSNode>(); remainingNodeList = new ArrayList<BayesNetDFSNode>(); isInitialCliqueSetIdentified = false; cliqueSet = new BayesNetDFSCliqueSet(); addedLineSetSinceLastCliqueUpdate = new BayesNetDFSLineSet(); eliminatedNodeSequence = new ArrayList<BayesNetDFSNode>(); } // constructor // this constructor makes its own hard copies of the BayesNetGraph object. BayesNetDFSGraph(BayesNetGraph graph) { this(); // add nodes for(int i=0; i<graph.getNodeList().size(); i++) { BayesNetNode eachNode = graph.getNodeList().get(i); String name = eachNode.getName(); int size = eachNode.getSize(); nodeList.add(new BayesNetDFSNode(name, size)); } // add connections for(int i=0; i<graph.getNodeList().size(); i++) { BayesNetNode eachNode = graph.getNodeList().get(i); for(BayesNetNode eachNeighbor : eachNode.getNonDirectionalLineList()) { // add connections to both // allConnections and remainingConnections int index = graph.getNodeList().indexOf(eachNeighbor); BayesNetDFSNode dfsNodeToConnect = nodeList.get(index); nodeList.get(i).addNeighborToBothConnections(dfsNodeToConnect); } } remainingNodeList.addAll(nodeList); } // make a hard copy of this BayesNetDFSGraph BayesNetDFSGraph copy() { BayesNetDFSGraph copiedGraph = new BayesNetDFSGraph(); // copy each node, connections of each node in nodeList, for(BayesNetDFSNode eachNode : nodeList) { copiedGraph.nodeList.add(eachNode.copyExcludingConnections()); } // add connections for(int i=0; i<this.nodeList.size(); i++) { BayesNetDFSNode eachNode = this.nodeList.get(i); // copy allConnectedNodelist for(BayesNetDFSNode eachNeighbor : eachNode.getAllNeighborNodeSet().getNodelist()) { int index = this.nodeList.indexOf(eachNeighbor); BayesNetDFSNode dfsNodeToConnect = copiedGraph.nodeList.get(index); copiedGraph.nodeList.get(i).addFillinNeighbor(dfsNodeToConnect); } } // copy remainingNodeList for(int i=0; i<this.remainingNodeList.size(); i++) { BayesNetDFSNode eachNode = this.remainingNodeList.get(i); int index = this.nodeList.indexOf(eachNode); copiedGraph.remainingNodeList.add(copiedGraph.nodeList.get(index)); // copy remainingConnectedNodelist for(BayesNetDFSNode eachNeighbor : eachNode.getRemainingNeighborNodeSet().getNodelist()) { int index1 = this.nodeList.indexOf(eachNeighbor); BayesNetDFSNode dfsNodeToConnect = copiedGraph.nodeList.get(index1); copiedGraph.remainingNodeList.get(i). addRemainingNeighbor(dfsNodeToConnect); } } // cliqueSet if(this.isInitialCliqueSetIdentified()) { copiedGraph.cliqueSet = new BayesNetDFSCliqueSet(); for(int i=0; i<this.cliqueSet.getCliqueList().size(); i++) { BayesNetDFSClique eachOldClique = this.cliqueSet.getCliqueList().get(i); ArrayList<BayesNetDFSNode> oldCliqueNodelist = eachOldClique.getNodelist(); ArrayList<BayesNetDFSNode> newCliqueNodelist = new ArrayList<BayesNetDFSNode>(); for(BayesNetDFSNode eachOldNode : oldCliqueNodelist) { int index = this.nodeList.indexOf(eachOldNode); BayesNetDFSNode eachNewNode = copiedGraph.nodeList.get(index); newCliqueNodelist.add(eachNewNode); } BayesNetDFSNodeSet newNodeSet = new BayesNetDFSNodeSet(newCliqueNodelist); copiedGraph.cliqueSet.add(new BayesNetDFSClique(newNodeSet)); } } // eliminationNodeSequence for(BayesNetDFSNode eachOldNode : this.eliminatedNodeSequence) { int index = this.nodeList.indexOf(eachOldNode); if(index==-1) { System.out.println(eachOldNode.getName()+" "+eachOldNode); for(BayesNetDFSNode eachNode : this.nodeList) { System.out.print(eachNode.getName()+" "+eachNode+ " "); } } copiedGraph.eliminatedNodeSequence.add( copiedGraph.nodeList.get(index)); } // eliminatedLineSetSinceLastCliqueUpdate for(BayesNetDFSLine eachLine : this.addedLineSetSinceLastCliqueUpdate.getLineList()) { BayesNetDFSNode oldNodeA = eachLine.nodeA; int indexA = this.nodeList.indexOf(oldNodeA); BayesNetDFSNode newNodeA = copiedGraph.nodeList.get(indexA); BayesNetDFSNode oldNodeB = eachLine.nodeB; int indexB = this.nodeList.indexOf(oldNodeB); BayesNetDFSNode newNodeB = copiedGraph.nodeList.get(indexB); copiedGraph.addedLineSetSinceLastCliqueUpdate.addLine( new BayesNetDFSLine(newNodeA, newNodeB)); } // isInitialCliqueSetIdentified copiedGraph.isInitialCliqueSetIdentified = this.isInitialCliqueSetIdentified; if(!checkCopy(copiedGraph)) throw new RuntimeException("--"); return copiedGraph; } // assert whether properly copied or not private boolean checkCopy(BayesNetDFSGraph copiedGraph) { // copy each node, connections of each node in nodeList, for(int i=0; i<nodeList.size(); i++) { nodeList.get(i).hasSameNodeFxiedInfo(copiedGraph.nodeList.get(i)); if(nodeList.get(i)==copiedGraph.nodeList.get(i)) { throw new RuntimeException(); } } // cliqueSet, if(this.isInitialCliqueSetIdentified()) { if(this.cliqueSet.getCliqueList()==copiedGraph.cliqueSet.cliqueList) { throw new RuntimeException(); } if(this.cliqueSet.getCliqueList().size()!=copiedGraph.cliqueSet.getCliqueList().size()) { throw new RuntimeException(); } for(int i=0; i<this.cliqueSet.getCliqueList().size(); i++) { BayesNetDFSClique eachOldClique = this.cliqueSet.getCliqueList().get(i); BayesNetDFSClique eachNewClique = copiedGraph.cliqueSet.getCliqueList().get(i); ArrayList<BayesNetDFSNode> newCliqueNodelist = eachNewClique.getNodelist(); for(int j=0; j<eachOldClique.getNodelist().size(); j++) { BayesNetDFSNode eachOldNode = eachOldClique.getNodelist().get(j); BayesNetDFSNode eachNewNode = eachNewClique.getNodelist().get(j); if(!eachOldNode.hasSameNodeFxiedInfo(eachNewNode)) return false; if(eachOldNode==eachNewNode) return false; } if(eachOldClique.getNodelist().size()!=newCliqueNodelist.size()) { throw new RuntimeException(eachOldClique.getNodelist().size()+" vs "+newCliqueNodelist.size()); } } } if(this.eliminatedNodeSequence.size()!=copiedGraph.eliminatedNodeSequence.size()) return false; for(int i=0; i<this.eliminatedNodeSequence.size(); i++) { if(this.eliminatedNodeSequence.get(i)==copiedGraph.eliminatedNodeSequence.get(i)) return false; if(!this.eliminatedNodeSequence.get(i).hasSameNodeFxiedInfo(copiedGraph.eliminatedNodeSequence.get(i))) return false; } // isInitialCliqueSetIdentified if(copiedGraph.isInitialCliqueSetIdentified!= this.isInitialCliqueSetIdentified) return false; return true; } private void setIsInitialCliqueSetIdentified(boolean value) { isInitialCliqueSetIdentified = value; } private boolean isInitialCliqueSetIdentified() { return isInitialCliqueSetIdentified; } void eliminateAllSimplicials() { boolean isSimplicialFound; do { isSimplicialFound = false; for(int i=remainingNodeList.size()-1; 0<=i; i--) { BayesNetDFSNode eachNode = remainingNodeList.get(i); if(eachNode.isRemainingSimplicial()) { eliminateNode(eachNode); isSimplicialFound = true; } } } while(isSimplicialFound && remainingNodeList.size()!=0); } // eliminate the node if it still exists void eliminateNode(BayesNetDFSNode node) { if(remainingNodeList.contains(node)) { BayesNetDFSLineSet fillinSet = node.addAllFillins(); node.removeAllRemainingConnections(); eliminatedNodeSequence.add(node); addedLineSetSinceLastCliqueUpdate.add(fillinSet); remainingNodeList.remove(node); } } int totalTableSize() { if(!isInitialCliqueSetIdentified()) { findAllCliques(); setIsInitialCliqueSetIdentified(true); } if(0<=addedLineSetSinceLastCliqueUpdate.size()) { this.updateCliques(cliqueSet, addedLineSetSinceLastCliqueUpdate); } int totalTableSize = 1; for(BayesNetDFSClique eachClique : cliqueSet.getCliqueList()) { totalTableSize += eachClique.tableSize(); } return totalTableSize; } private void findAllCliques() { BayesNetDFSNodeSet copiedDFSNodeSet = new BayesNetDFSNodeSet(this.nodeList).copy(); BayesNetDFSCliqueSet maximalCliqueSet = BronKerbosch(new BayesNetDFSNodeSet(), copiedDFSNodeSet, new BayesNetDFSNodeSet()); this.cliqueSet = maximalCliqueSet; } void updateCliques(BayesNetDFSCliqueSet C, BayesNetDFSLineSet F) { BayesNetDFSNodeSet U = F.nodeSet(); //G' = (V, E U F) //addLines(F); BayesNetDFSCliqueSet Cnew = BronKerbosch(new BayesNetDFSNodeSet(), U.allFamilyNodeSet(), new BayesNetDFSNodeSet()); for(int i=C.getCliqueList().size()-1; 0<=i; i--) { BayesNetDFSClique c = C.getCliqueList().get(i); // if(c intersection U !=empty) C = C \ { c } if(0 < c.sizeOfIntersectionWith(U)) C.remove(c); } /* for(BayesNetDFSClique c :C.getCliqueList()) { // if(c intersection U !=empty) C = C \ { c } if(c.sizeOfIntersectionWith(U) != 0) C.remove(c); } */ for(BayesNetDFSClique c : Cnew.getCliqueList()) { // if(c intersection U !=empty) C = C U { c } if(0 < c.sizeOfIntersectionWith(U)) { C.addIfDoesNotExist(c); } } this.cliqueSet = C; } // Original Bron-Kerbosch algorithm private ArrayList<BayesNetDFSClique> BronKerboschOriginal(BayesNetDFSNodeSet R, BayesNetDFSNodeSet P, BayesNetDFSNodeSet X) { System.out.print("KB: "); System.out.print("R "); R.print(); System.out.print("P "); P.print(); System.out.print("X "); X.print(); System.out.println(); // C = empty ArrayList<BayesNetDFSClique> C = new ArrayList<BayesNetDFSClique>(); if(P.size()==0 && X.size()==0) { C.add(new BayesNetDFSClique(R)); return C; } else { //C = empty, is used above instead; while(0<P.size()) { System.out.print("R "); R.print(); System.out.print("P "); P.print(); System.out.print("X "); X.print(); System.out.println(); BayesNetDFSNode v = P.get(0); System.out.println(v.getName()+" has been selected"); //P = P\{v} P.subtract(v); //Rnew = R U {v} BayesNetDFSNodeSet Rnew = R.copy(); Rnew.add(v); //Pnew = P intersect nb(v) BayesNetDFSNodeSet Pnew = P.intersection(v.getAllNeighborNodeSet()); //Xnew = X intersect nb(v) BayesNetDFSNodeSet Xnew = X.intersection(v.getAllNeighborNodeSet()); //K = BronKerbosch(Rnew, Pnew, Xnew); ArrayList<BayesNetDFSClique> K = BronKerboschOriginal(Rnew, Pnew, Xnew); //X = X U {v} X.add(v); //C = C U K for(BayesNetDFSClique eachClique : K) { //if(!C.contains(eachClique)) C.add(eachClique); } } return C; } } //Bron-Kerbosch algorithm with pivot private BayesNetDFSCliqueSet BronKerbosch(BayesNetDFSNodeSet R, BayesNetDFSNodeSet P, BayesNetDFSNodeSet X) { // C = empty if(P.size()==0 && X.size()==0) { BayesNetDFSCliqueSet C = new BayesNetDFSCliqueSet(R); return C; } else { //C = empty; BayesNetDFSCliqueSet C = new BayesNetDFSCliqueSet(); BayesNetDFSNode u = selectPivot(P, X); BayesNetDFSNodeSet PWithoutNeighborU = P.copy(); PWithoutNeighborU.subtract(u.getAllNeighborNodeSet()); while(0<PWithoutNeighborU.size()) { BayesNetDFSNode v = PWithoutNeighborU.get(0); PWithoutNeighborU.subtract(v); //P = P\{v} P.subtract(v); //Rnew = R U {v} BayesNetDFSNodeSet Rnew = R.copy(); Rnew.add(v); //Pnew = P intersect nb(v) BayesNetDFSNodeSet Pnew = P.intersection(v.getAllNeighborNodeSet()); //Xnew = X intersect nb(v) BayesNetDFSNodeSet Xnew = X.intersection(v.getAllNeighborNodeSet()); //K = BronKerbosch(Rnew, Pnew, Xnew); BayesNetDFSCliqueSet K = BronKerbosch(Rnew, Pnew, Xnew); //X = X U {v} X.add(v); //C = C U K for(BayesNetDFSClique eachClique : K.getCliqueList()) { C.add(eachClique); } } return C; } } void println() { System.out.println("Graph:"); System.out.println("nodeList"); for(BayesNetDFSNode eachNode : nodeList) { eachNode.print(); System.out.println(); } System.out.println("remainingNodeList"); for(BayesNetDFSNode eachNode : remainingNodeList) { eachNode.print(); System.out.println(); } if(isInitialCliqueSetIdentified()) { System.out.println("CliqueList"); for(BayesNetDFSClique eachClique : cliqueSet.getCliqueList()) { eachClique.print(); System.out.println();//(" "); } } System.out.print("Eliminated nodeList:"); for(BayesNetDFSNode eachNode : eliminatedNodeSequence) { System.out.print(eachNode.getName()+ " "); } System.out.println(); } // for test purpose void addLineAndUpdateCliques(String nodeNameA, String nodeNameB) { BayesNetDFSNode nodeA = null, nodeB = null; for(BayesNetDFSNode eachNode : remainingNodeList) { if(eachNode.getName().equals(nodeNameA)) { nodeA = eachNode; break; } } for(BayesNetDFSNode eachNode : remainingNodeList) { if(eachNode.getName().equals(nodeNameB)) { nodeB = eachNode; break; } } if(nodeA==null || nodeB==null) throw new RuntimeException("Node A or Node B not fonud"); BayesNetDFSLine newLine = new BayesNetDFSLine(nodeA, nodeB); BayesNetDFSLineSet lineset = new BayesNetDFSLineSet(); lineset.addLine(newLine); updateCliques(cliqueSet, lineset); } int numOfRemainingNodes() { return remainingNodeList.size(); } void minFill() { System.out.println("min fill"); while(0<remainingNodeList.size()) { int minFillinSize = Integer.MAX_VALUE; BayesNetDFSNode minFillinNode = null; for(BayesNetDFSNode eachNode : remainingNodeList) { int fillinSize = eachNode.fillinSize(); System.out.print(eachNode.getName()+" " + fillinSize+" "); if(fillinSize < minFillinSize) { minFillinSize = fillinSize; minFillinNode = eachNode; } } System.out.println(); // find each minFill System.out.println("min: "+minFillinNode.getName()); eliminateNode(minFillinNode); } System.out.println("min fill finished"); } int remainingNodeListSize() { return remainingNodeList.size(); } ArrayList<BayesNetDFSNode> getRemainingNodeList() { return remainingNodeList; } boolean hasSameRemainingNodeList(BayesNetDFSGraph graph) { if(remainingNodeList.size()!=graph.remainingNodeList.size()) return false; for(int i=0; i<remainingNodeList.size(); i++) { if(!remainingNodeList.get(i).hasSameNodeFxiedInfo( graph.remainingNodeList.get(i)) ) { return false; } } return true; } BayesNetDFSNode selectPivot(BayesNetDFSNodeSet P, BayesNetDFSNodeSet X) { // do not consider P intersection X // to save computation time // thus, it does not pick totally random, but somewhat random. int size = P.size() + X.size(); Random random = new Random(); int randomNumber = random.nextInt(size); if(randomNumber<P.size()) return P.get(randomNumber); else return X.get(randomNumber-P.size()); } BayesNetDFSNode equivalentNodeitselfExceptConnections(BayesNetDFSNode node) { for(BayesNetDFSNode eachNode : nodeList) { if(eachNode.hasSameNodeFxiedInfo(node)) { return eachNode; } } throw new RuntimeException("No such node found in " + "equivalentNodeitselfExceptConnections: "+node.getName()); } ArrayList<String> eliminationOrder() { ArrayList<String> eliminationOrder = new ArrayList<String>(); for(BayesNetDFSNode eachNode : eliminatedNodeSequence) { eliminationOrder.add(eachNode.getName()); } return eliminationOrder; } ArrayList<BayesNetDFSNode> getEliminatedNodeSequence() { return eliminatedNodeSequence; } private class BayesNetDFSClique { private ArrayList<BayesNetDFSNode> nodelist; BayesNetDFSClique(BayesNetDFSNodeSet nodeSet) { this.nodelist = nodeSet.getNodelist(); } int sizeOfIntersectionWith(BayesNetDFSNodeSet nodeSet) { int size = 0; for(BayesNetDFSNode eachNode : nodelist) { if(nodeSet.contains(eachNode)) size++; } return size; } boolean equals(BayesNetDFSClique clique) { if(this==clique) return true; else if(this.nodelist.size()==clique.nodelist.size() && nodelist.containsAll(clique.nodelist)) return true; return false; } void print() { System.out.print("Clique("); System.out.print("["+tableSize()+"] "); for(BayesNetDFSNode eachNode : nodelist) { System.out.print(eachNode.getName()+ " "); //+ eachNode + " "); } System.out.print(")"); } int tableSize() { int size = 1; for(BayesNetDFSNode eachNode : nodelist) { size *= eachNode.tableSize(); } return size; } ArrayList<BayesNetDFSNode> getNodelist() { return nodelist; } } private class BayesNetDFSCliqueSet { private ArrayList<BayesNetDFSClique> cliqueList; BayesNetDFSCliqueSet() { cliqueList = new ArrayList<BayesNetDFSClique>(); } BayesNetDFSCliqueSet(BayesNetDFSNodeSet nodeSet) { this(); cliqueList.add(new BayesNetDFSClique(nodeSet)); } ArrayList<BayesNetDFSClique> getCliqueList() { return cliqueList; } // check if the contents of clique exists in this cliqueList void addIfDoesNotExist(BayesNetDFSClique clique) { for(BayesNetDFSClique eachClique : cliqueList) { if(eachClique.equals(clique)) { return; } } add(clique); } // do not check whether the clique exists or not void add(BayesNetDFSClique clique) { cliqueList.add(clique); } // remove the instance of clique from the list // does not remove, if they are different objects, but they have the // same contents void remove(BayesNetDFSClique clique) { cliqueList.remove(clique); } } }
UTF-8
Java
18,648
java
BayesNetDFSGraph.java
Java
[]
null
[]
package bnp; import java.util.ArrayList; /* * class BayesNetDFSGraph: * * Using a Depth First Search (DFS) algorithm, * this class finds an elimination sequence that * has a small total table size. * * * A BayesNetDFSGraph object is constructed with a BayesNetGraph object. * * BayesNetDFSGraph makes its own hard copies of nodes and connections * so that BayesNetGraph won't be affected. * */ import java.util.Random; public class BayesNetDFSGraph { private ArrayList<BayesNetDFSNode> nodeList; private ArrayList<BayesNetDFSNode> remainingNodeList; private BayesNetDFSCliqueSet cliqueSet; private ArrayList<BayesNetDFSNode> eliminatedNodeSequence; private BayesNetDFSLineSet addedLineSetSinceLastCliqueUpdate; private boolean isInitialCliqueSetIdentified; // private constructor: used for initialization private BayesNetDFSGraph() { nodeList = new ArrayList<BayesNetDFSNode>(); remainingNodeList = new ArrayList<BayesNetDFSNode>(); isInitialCliqueSetIdentified = false; cliqueSet = new BayesNetDFSCliqueSet(); addedLineSetSinceLastCliqueUpdate = new BayesNetDFSLineSet(); eliminatedNodeSequence = new ArrayList<BayesNetDFSNode>(); } // constructor // this constructor makes its own hard copies of the BayesNetGraph object. BayesNetDFSGraph(BayesNetGraph graph) { this(); // add nodes for(int i=0; i<graph.getNodeList().size(); i++) { BayesNetNode eachNode = graph.getNodeList().get(i); String name = eachNode.getName(); int size = eachNode.getSize(); nodeList.add(new BayesNetDFSNode(name, size)); } // add connections for(int i=0; i<graph.getNodeList().size(); i++) { BayesNetNode eachNode = graph.getNodeList().get(i); for(BayesNetNode eachNeighbor : eachNode.getNonDirectionalLineList()) { // add connections to both // allConnections and remainingConnections int index = graph.getNodeList().indexOf(eachNeighbor); BayesNetDFSNode dfsNodeToConnect = nodeList.get(index); nodeList.get(i).addNeighborToBothConnections(dfsNodeToConnect); } } remainingNodeList.addAll(nodeList); } // make a hard copy of this BayesNetDFSGraph BayesNetDFSGraph copy() { BayesNetDFSGraph copiedGraph = new BayesNetDFSGraph(); // copy each node, connections of each node in nodeList, for(BayesNetDFSNode eachNode : nodeList) { copiedGraph.nodeList.add(eachNode.copyExcludingConnections()); } // add connections for(int i=0; i<this.nodeList.size(); i++) { BayesNetDFSNode eachNode = this.nodeList.get(i); // copy allConnectedNodelist for(BayesNetDFSNode eachNeighbor : eachNode.getAllNeighborNodeSet().getNodelist()) { int index = this.nodeList.indexOf(eachNeighbor); BayesNetDFSNode dfsNodeToConnect = copiedGraph.nodeList.get(index); copiedGraph.nodeList.get(i).addFillinNeighbor(dfsNodeToConnect); } } // copy remainingNodeList for(int i=0; i<this.remainingNodeList.size(); i++) { BayesNetDFSNode eachNode = this.remainingNodeList.get(i); int index = this.nodeList.indexOf(eachNode); copiedGraph.remainingNodeList.add(copiedGraph.nodeList.get(index)); // copy remainingConnectedNodelist for(BayesNetDFSNode eachNeighbor : eachNode.getRemainingNeighborNodeSet().getNodelist()) { int index1 = this.nodeList.indexOf(eachNeighbor); BayesNetDFSNode dfsNodeToConnect = copiedGraph.nodeList.get(index1); copiedGraph.remainingNodeList.get(i). addRemainingNeighbor(dfsNodeToConnect); } } // cliqueSet if(this.isInitialCliqueSetIdentified()) { copiedGraph.cliqueSet = new BayesNetDFSCliqueSet(); for(int i=0; i<this.cliqueSet.getCliqueList().size(); i++) { BayesNetDFSClique eachOldClique = this.cliqueSet.getCliqueList().get(i); ArrayList<BayesNetDFSNode> oldCliqueNodelist = eachOldClique.getNodelist(); ArrayList<BayesNetDFSNode> newCliqueNodelist = new ArrayList<BayesNetDFSNode>(); for(BayesNetDFSNode eachOldNode : oldCliqueNodelist) { int index = this.nodeList.indexOf(eachOldNode); BayesNetDFSNode eachNewNode = copiedGraph.nodeList.get(index); newCliqueNodelist.add(eachNewNode); } BayesNetDFSNodeSet newNodeSet = new BayesNetDFSNodeSet(newCliqueNodelist); copiedGraph.cliqueSet.add(new BayesNetDFSClique(newNodeSet)); } } // eliminationNodeSequence for(BayesNetDFSNode eachOldNode : this.eliminatedNodeSequence) { int index = this.nodeList.indexOf(eachOldNode); if(index==-1) { System.out.println(eachOldNode.getName()+" "+eachOldNode); for(BayesNetDFSNode eachNode : this.nodeList) { System.out.print(eachNode.getName()+" "+eachNode+ " "); } } copiedGraph.eliminatedNodeSequence.add( copiedGraph.nodeList.get(index)); } // eliminatedLineSetSinceLastCliqueUpdate for(BayesNetDFSLine eachLine : this.addedLineSetSinceLastCliqueUpdate.getLineList()) { BayesNetDFSNode oldNodeA = eachLine.nodeA; int indexA = this.nodeList.indexOf(oldNodeA); BayesNetDFSNode newNodeA = copiedGraph.nodeList.get(indexA); BayesNetDFSNode oldNodeB = eachLine.nodeB; int indexB = this.nodeList.indexOf(oldNodeB); BayesNetDFSNode newNodeB = copiedGraph.nodeList.get(indexB); copiedGraph.addedLineSetSinceLastCliqueUpdate.addLine( new BayesNetDFSLine(newNodeA, newNodeB)); } // isInitialCliqueSetIdentified copiedGraph.isInitialCliqueSetIdentified = this.isInitialCliqueSetIdentified; if(!checkCopy(copiedGraph)) throw new RuntimeException("--"); return copiedGraph; } // assert whether properly copied or not private boolean checkCopy(BayesNetDFSGraph copiedGraph) { // copy each node, connections of each node in nodeList, for(int i=0; i<nodeList.size(); i++) { nodeList.get(i).hasSameNodeFxiedInfo(copiedGraph.nodeList.get(i)); if(nodeList.get(i)==copiedGraph.nodeList.get(i)) { throw new RuntimeException(); } } // cliqueSet, if(this.isInitialCliqueSetIdentified()) { if(this.cliqueSet.getCliqueList()==copiedGraph.cliqueSet.cliqueList) { throw new RuntimeException(); } if(this.cliqueSet.getCliqueList().size()!=copiedGraph.cliqueSet.getCliqueList().size()) { throw new RuntimeException(); } for(int i=0; i<this.cliqueSet.getCliqueList().size(); i++) { BayesNetDFSClique eachOldClique = this.cliqueSet.getCliqueList().get(i); BayesNetDFSClique eachNewClique = copiedGraph.cliqueSet.getCliqueList().get(i); ArrayList<BayesNetDFSNode> newCliqueNodelist = eachNewClique.getNodelist(); for(int j=0; j<eachOldClique.getNodelist().size(); j++) { BayesNetDFSNode eachOldNode = eachOldClique.getNodelist().get(j); BayesNetDFSNode eachNewNode = eachNewClique.getNodelist().get(j); if(!eachOldNode.hasSameNodeFxiedInfo(eachNewNode)) return false; if(eachOldNode==eachNewNode) return false; } if(eachOldClique.getNodelist().size()!=newCliqueNodelist.size()) { throw new RuntimeException(eachOldClique.getNodelist().size()+" vs "+newCliqueNodelist.size()); } } } if(this.eliminatedNodeSequence.size()!=copiedGraph.eliminatedNodeSequence.size()) return false; for(int i=0; i<this.eliminatedNodeSequence.size(); i++) { if(this.eliminatedNodeSequence.get(i)==copiedGraph.eliminatedNodeSequence.get(i)) return false; if(!this.eliminatedNodeSequence.get(i).hasSameNodeFxiedInfo(copiedGraph.eliminatedNodeSequence.get(i))) return false; } // isInitialCliqueSetIdentified if(copiedGraph.isInitialCliqueSetIdentified!= this.isInitialCliqueSetIdentified) return false; return true; } private void setIsInitialCliqueSetIdentified(boolean value) { isInitialCliqueSetIdentified = value; } private boolean isInitialCliqueSetIdentified() { return isInitialCliqueSetIdentified; } void eliminateAllSimplicials() { boolean isSimplicialFound; do { isSimplicialFound = false; for(int i=remainingNodeList.size()-1; 0<=i; i--) { BayesNetDFSNode eachNode = remainingNodeList.get(i); if(eachNode.isRemainingSimplicial()) { eliminateNode(eachNode); isSimplicialFound = true; } } } while(isSimplicialFound && remainingNodeList.size()!=0); } // eliminate the node if it still exists void eliminateNode(BayesNetDFSNode node) { if(remainingNodeList.contains(node)) { BayesNetDFSLineSet fillinSet = node.addAllFillins(); node.removeAllRemainingConnections(); eliminatedNodeSequence.add(node); addedLineSetSinceLastCliqueUpdate.add(fillinSet); remainingNodeList.remove(node); } } int totalTableSize() { if(!isInitialCliqueSetIdentified()) { findAllCliques(); setIsInitialCliqueSetIdentified(true); } if(0<=addedLineSetSinceLastCliqueUpdate.size()) { this.updateCliques(cliqueSet, addedLineSetSinceLastCliqueUpdate); } int totalTableSize = 1; for(BayesNetDFSClique eachClique : cliqueSet.getCliqueList()) { totalTableSize += eachClique.tableSize(); } return totalTableSize; } private void findAllCliques() { BayesNetDFSNodeSet copiedDFSNodeSet = new BayesNetDFSNodeSet(this.nodeList).copy(); BayesNetDFSCliqueSet maximalCliqueSet = BronKerbosch(new BayesNetDFSNodeSet(), copiedDFSNodeSet, new BayesNetDFSNodeSet()); this.cliqueSet = maximalCliqueSet; } void updateCliques(BayesNetDFSCliqueSet C, BayesNetDFSLineSet F) { BayesNetDFSNodeSet U = F.nodeSet(); //G' = (V, E U F) //addLines(F); BayesNetDFSCliqueSet Cnew = BronKerbosch(new BayesNetDFSNodeSet(), U.allFamilyNodeSet(), new BayesNetDFSNodeSet()); for(int i=C.getCliqueList().size()-1; 0<=i; i--) { BayesNetDFSClique c = C.getCliqueList().get(i); // if(c intersection U !=empty) C = C \ { c } if(0 < c.sizeOfIntersectionWith(U)) C.remove(c); } /* for(BayesNetDFSClique c :C.getCliqueList()) { // if(c intersection U !=empty) C = C \ { c } if(c.sizeOfIntersectionWith(U) != 0) C.remove(c); } */ for(BayesNetDFSClique c : Cnew.getCliqueList()) { // if(c intersection U !=empty) C = C U { c } if(0 < c.sizeOfIntersectionWith(U)) { C.addIfDoesNotExist(c); } } this.cliqueSet = C; } // Original Bron-Kerbosch algorithm private ArrayList<BayesNetDFSClique> BronKerboschOriginal(BayesNetDFSNodeSet R, BayesNetDFSNodeSet P, BayesNetDFSNodeSet X) { System.out.print("KB: "); System.out.print("R "); R.print(); System.out.print("P "); P.print(); System.out.print("X "); X.print(); System.out.println(); // C = empty ArrayList<BayesNetDFSClique> C = new ArrayList<BayesNetDFSClique>(); if(P.size()==0 && X.size()==0) { C.add(new BayesNetDFSClique(R)); return C; } else { //C = empty, is used above instead; while(0<P.size()) { System.out.print("R "); R.print(); System.out.print("P "); P.print(); System.out.print("X "); X.print(); System.out.println(); BayesNetDFSNode v = P.get(0); System.out.println(v.getName()+" has been selected"); //P = P\{v} P.subtract(v); //Rnew = R U {v} BayesNetDFSNodeSet Rnew = R.copy(); Rnew.add(v); //Pnew = P intersect nb(v) BayesNetDFSNodeSet Pnew = P.intersection(v.getAllNeighborNodeSet()); //Xnew = X intersect nb(v) BayesNetDFSNodeSet Xnew = X.intersection(v.getAllNeighborNodeSet()); //K = BronKerbosch(Rnew, Pnew, Xnew); ArrayList<BayesNetDFSClique> K = BronKerboschOriginal(Rnew, Pnew, Xnew); //X = X U {v} X.add(v); //C = C U K for(BayesNetDFSClique eachClique : K) { //if(!C.contains(eachClique)) C.add(eachClique); } } return C; } } //Bron-Kerbosch algorithm with pivot private BayesNetDFSCliqueSet BronKerbosch(BayesNetDFSNodeSet R, BayesNetDFSNodeSet P, BayesNetDFSNodeSet X) { // C = empty if(P.size()==0 && X.size()==0) { BayesNetDFSCliqueSet C = new BayesNetDFSCliqueSet(R); return C; } else { //C = empty; BayesNetDFSCliqueSet C = new BayesNetDFSCliqueSet(); BayesNetDFSNode u = selectPivot(P, X); BayesNetDFSNodeSet PWithoutNeighborU = P.copy(); PWithoutNeighborU.subtract(u.getAllNeighborNodeSet()); while(0<PWithoutNeighborU.size()) { BayesNetDFSNode v = PWithoutNeighborU.get(0); PWithoutNeighborU.subtract(v); //P = P\{v} P.subtract(v); //Rnew = R U {v} BayesNetDFSNodeSet Rnew = R.copy(); Rnew.add(v); //Pnew = P intersect nb(v) BayesNetDFSNodeSet Pnew = P.intersection(v.getAllNeighborNodeSet()); //Xnew = X intersect nb(v) BayesNetDFSNodeSet Xnew = X.intersection(v.getAllNeighborNodeSet()); //K = BronKerbosch(Rnew, Pnew, Xnew); BayesNetDFSCliqueSet K = BronKerbosch(Rnew, Pnew, Xnew); //X = X U {v} X.add(v); //C = C U K for(BayesNetDFSClique eachClique : K.getCliqueList()) { C.add(eachClique); } } return C; } } void println() { System.out.println("Graph:"); System.out.println("nodeList"); for(BayesNetDFSNode eachNode : nodeList) { eachNode.print(); System.out.println(); } System.out.println("remainingNodeList"); for(BayesNetDFSNode eachNode : remainingNodeList) { eachNode.print(); System.out.println(); } if(isInitialCliqueSetIdentified()) { System.out.println("CliqueList"); for(BayesNetDFSClique eachClique : cliqueSet.getCliqueList()) { eachClique.print(); System.out.println();//(" "); } } System.out.print("Eliminated nodeList:"); for(BayesNetDFSNode eachNode : eliminatedNodeSequence) { System.out.print(eachNode.getName()+ " "); } System.out.println(); } // for test purpose void addLineAndUpdateCliques(String nodeNameA, String nodeNameB) { BayesNetDFSNode nodeA = null, nodeB = null; for(BayesNetDFSNode eachNode : remainingNodeList) { if(eachNode.getName().equals(nodeNameA)) { nodeA = eachNode; break; } } for(BayesNetDFSNode eachNode : remainingNodeList) { if(eachNode.getName().equals(nodeNameB)) { nodeB = eachNode; break; } } if(nodeA==null || nodeB==null) throw new RuntimeException("Node A or Node B not fonud"); BayesNetDFSLine newLine = new BayesNetDFSLine(nodeA, nodeB); BayesNetDFSLineSet lineset = new BayesNetDFSLineSet(); lineset.addLine(newLine); updateCliques(cliqueSet, lineset); } int numOfRemainingNodes() { return remainingNodeList.size(); } void minFill() { System.out.println("min fill"); while(0<remainingNodeList.size()) { int minFillinSize = Integer.MAX_VALUE; BayesNetDFSNode minFillinNode = null; for(BayesNetDFSNode eachNode : remainingNodeList) { int fillinSize = eachNode.fillinSize(); System.out.print(eachNode.getName()+" " + fillinSize+" "); if(fillinSize < minFillinSize) { minFillinSize = fillinSize; minFillinNode = eachNode; } } System.out.println(); // find each minFill System.out.println("min: "+minFillinNode.getName()); eliminateNode(minFillinNode); } System.out.println("min fill finished"); } int remainingNodeListSize() { return remainingNodeList.size(); } ArrayList<BayesNetDFSNode> getRemainingNodeList() { return remainingNodeList; } boolean hasSameRemainingNodeList(BayesNetDFSGraph graph) { if(remainingNodeList.size()!=graph.remainingNodeList.size()) return false; for(int i=0; i<remainingNodeList.size(); i++) { if(!remainingNodeList.get(i).hasSameNodeFxiedInfo( graph.remainingNodeList.get(i)) ) { return false; } } return true; } BayesNetDFSNode selectPivot(BayesNetDFSNodeSet P, BayesNetDFSNodeSet X) { // do not consider P intersection X // to save computation time // thus, it does not pick totally random, but somewhat random. int size = P.size() + X.size(); Random random = new Random(); int randomNumber = random.nextInt(size); if(randomNumber<P.size()) return P.get(randomNumber); else return X.get(randomNumber-P.size()); } BayesNetDFSNode equivalentNodeitselfExceptConnections(BayesNetDFSNode node) { for(BayesNetDFSNode eachNode : nodeList) { if(eachNode.hasSameNodeFxiedInfo(node)) { return eachNode; } } throw new RuntimeException("No such node found in " + "equivalentNodeitselfExceptConnections: "+node.getName()); } ArrayList<String> eliminationOrder() { ArrayList<String> eliminationOrder = new ArrayList<String>(); for(BayesNetDFSNode eachNode : eliminatedNodeSequence) { eliminationOrder.add(eachNode.getName()); } return eliminationOrder; } ArrayList<BayesNetDFSNode> getEliminatedNodeSequence() { return eliminatedNodeSequence; } private class BayesNetDFSClique { private ArrayList<BayesNetDFSNode> nodelist; BayesNetDFSClique(BayesNetDFSNodeSet nodeSet) { this.nodelist = nodeSet.getNodelist(); } int sizeOfIntersectionWith(BayesNetDFSNodeSet nodeSet) { int size = 0; for(BayesNetDFSNode eachNode : nodelist) { if(nodeSet.contains(eachNode)) size++; } return size; } boolean equals(BayesNetDFSClique clique) { if(this==clique) return true; else if(this.nodelist.size()==clique.nodelist.size() && nodelist.containsAll(clique.nodelist)) return true; return false; } void print() { System.out.print("Clique("); System.out.print("["+tableSize()+"] "); for(BayesNetDFSNode eachNode : nodelist) { System.out.print(eachNode.getName()+ " "); //+ eachNode + " "); } System.out.print(")"); } int tableSize() { int size = 1; for(BayesNetDFSNode eachNode : nodelist) { size *= eachNode.tableSize(); } return size; } ArrayList<BayesNetDFSNode> getNodelist() { return nodelist; } } private class BayesNetDFSCliqueSet { private ArrayList<BayesNetDFSClique> cliqueList; BayesNetDFSCliqueSet() { cliqueList = new ArrayList<BayesNetDFSClique>(); } BayesNetDFSCliqueSet(BayesNetDFSNodeSet nodeSet) { this(); cliqueList.add(new BayesNetDFSClique(nodeSet)); } ArrayList<BayesNetDFSClique> getCliqueList() { return cliqueList; } // check if the contents of clique exists in this cliqueList void addIfDoesNotExist(BayesNetDFSClique clique) { for(BayesNetDFSClique eachClique : cliqueList) { if(eachClique.equals(clique)) { return; } } add(clique); } // do not check whether the clique exists or not void add(BayesNetDFSClique clique) { cliqueList.add(clique); } // remove the instance of clique from the list // does not remove, if they are different objects, but they have the // same contents void remove(BayesNetDFSClique clique) { cliqueList.remove(clique); } } }
18,648
0.703882
0.702059
597
30.236181
21.982622
106
false
false
0
0
0
0
0
0
3.159129
false
false
5
22dba112eaf6baafb3f9196aeac719fc0e37880d
29,420,525,984,071
9f2e5bee437ec9542995eab6bb2a3e4b0c186231
/wicket/src/main/java/org/apache/wicket/session/DefaultPageFactory.java
0b3c40b5cf1221be77830a0350b41ccbfb2bb133
[ "LicenseRef-scancode-generic-export-compliance", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "CDDL-1.0", "MIT", "LicenseRef-scancode-public-domain", "X11", "Apache-1.1", "LicenseRef-scancode-oswego-concurrent", "BSD-3-Clause" ]
permissive
astubbs/wicket.get-portals2
https://github.com/astubbs/wicket.get-portals2
5498dbf711788933303040f61bda7b2979472c18
6ceca0773ab057880643ba2bd87eb18855e04082
refs/heads/portal-javadoc
2023-07-09T12:48:38.796000
2008-10-09T16:54:16
2008-10-09T16:54:16
61,109
2
0
Apache-2.0
false
2022-06-10T22:44:44
2008-10-09T10:13:28
2019-08-13T13:37:34
2022-06-10T22:44:42
49,636
2
0
4
null
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.session; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map; import org.apache.wicket.AbortException; import org.apache.wicket.IPageFactory; import org.apache.wicket.Page; import org.apache.wicket.PageParameters; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.authorization.AuthorizationException; import org.apache.wicket.markup.MarkupException; import org.apache.wicket.util.lang.Generics; /** * A factory that constructs Pages. * * @see org.apache.wicket.settings.ISessionSettings#setPageFactory(IPageFactory) * @see IPageFactory * * @author Juergen Donnerstag * @author Jonathan Locke */ public final class DefaultPageFactory implements IPageFactory { /** Map of Constructors for Page subclasses */ private final Map<Class<?>, Constructor<?>> constructorForClass = Generics.newConcurrentHashMap(); /** * @see IPageFactory#newPage(Class) */ public final <C extends Page> Page newPage(final Class<C> pageClass) { try { // throw an exception in case default constructor is missing // => improved error message final Constructor<? extends Page> constructor = pageClass.getConstructor((Class[])null); return newPage(constructor, null); } catch (NoSuchMethodException e) { // a bit of a hack here.. Constructor<?> constructor = constructor(pageClass, PageParameters.class); if (constructor != null) { return newPage(constructor, new PageParameters()); } else { throw new WicketRuntimeException("Unable to create page from " + pageClass + ". Class does not have a default contructor", e); } } } /** * @see IPageFactory#newPage(Class, PageParameters) */ public final <C extends Page> Page newPage(final Class<C> pageClass, final PageParameters parameters) { // Try to get constructor that takes PageParameters Constructor<?> constructor = constructor(pageClass, PageParameters.class); // If we got a PageParameters constructor if (constructor != null) { // return new Page(parameters) return newPage(constructor, parameters); } // Always try default constructor if one exists return newPage(pageClass); } /** * Looks up a one-arg Page constructor by class and argument type. * * @param <C> * * @param pageClass * The class of page * @param argumentType * The argument type * @return The page constructor, or null if no one-arg constructor can be found taking the given * argument type. */ private final <C extends Page> Constructor<?> constructor(final Class<C> pageClass, final Class<PageParameters> argumentType) { // Get constructor for page class from cache Constructor<?> constructor = constructorForClass.get(pageClass); // Need to look up? if (constructor == null) { try { // Try to find the constructor constructor = pageClass.getConstructor(new Class[] { argumentType }); // Store it in the cache constructorForClass.put(pageClass, constructor); } catch (NoSuchMethodException e) { return null; } } return constructor; } /** * Creates a new Page using the given constructor and argument. * * @param constructor * The constructor to invoke * @param argument * The argument to pass to the constructor or null to pass no arguments * @return The new page * @throws WicketRuntimeException * Thrown if the Page cannot be instantiated using the given constructor and * argument. */ private final Page newPage(final Constructor<?> constructor, final Object argument) { try { if (argument != null) return (Page)constructor.newInstance(new Object[] { argument }); else return (Page)constructor.newInstance(new Object[] {}); } catch (InstantiationException e) { throw new WicketRuntimeException(createDescription(constructor, argument), e); } catch (IllegalAccessException e) { throw new WicketRuntimeException(createDescription(constructor, argument), e); } catch (InvocationTargetException e) { // honor redirect exception contract defined in IPageFactory if (e.getTargetException() instanceof AbortException || e.getTargetException() instanceof AuthorizationException || e.getTargetException() instanceof MarkupException) { throw (RuntimeException)e.getTargetException(); } throw new WicketRuntimeException(createDescription(constructor, argument), e); } } private String createDescription(Constructor<?> constructor, Object argument) { if (argument != null) return "Can't instantiate page using constructor " + constructor + " and argument " + argument; else return "Can't instantiate page using constructor " + constructor; } }
UTF-8
Java
5,643
java
DefaultPageFactory.java
Java
[ { "context": "(IPageFactory)\n * @see IPageFactory\n * \n * @author Juergen Donnerstag\n * @author Jonathan Locke\n */\npublic final class ", "end": 1491, "score": 0.9998669028282166, "start": 1473, "tag": "NAME", "value": "Juergen Donnerstag" }, { "context": "ctory\n * \n * @author Juergen Donnerstag\n * @author Jonathan Locke\n */\npublic final class DefaultPageFactory impleme", "end": 1517, "score": 0.9998620748519897, "start": 1503, "tag": "NAME", "value": "Jonathan Locke" } ]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.session; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map; import org.apache.wicket.AbortException; import org.apache.wicket.IPageFactory; import org.apache.wicket.Page; import org.apache.wicket.PageParameters; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.authorization.AuthorizationException; import org.apache.wicket.markup.MarkupException; import org.apache.wicket.util.lang.Generics; /** * A factory that constructs Pages. * * @see org.apache.wicket.settings.ISessionSettings#setPageFactory(IPageFactory) * @see IPageFactory * * @author <NAME> * @author <NAME> */ public final class DefaultPageFactory implements IPageFactory { /** Map of Constructors for Page subclasses */ private final Map<Class<?>, Constructor<?>> constructorForClass = Generics.newConcurrentHashMap(); /** * @see IPageFactory#newPage(Class) */ public final <C extends Page> Page newPage(final Class<C> pageClass) { try { // throw an exception in case default constructor is missing // => improved error message final Constructor<? extends Page> constructor = pageClass.getConstructor((Class[])null); return newPage(constructor, null); } catch (NoSuchMethodException e) { // a bit of a hack here.. Constructor<?> constructor = constructor(pageClass, PageParameters.class); if (constructor != null) { return newPage(constructor, new PageParameters()); } else { throw new WicketRuntimeException("Unable to create page from " + pageClass + ". Class does not have a default contructor", e); } } } /** * @see IPageFactory#newPage(Class, PageParameters) */ public final <C extends Page> Page newPage(final Class<C> pageClass, final PageParameters parameters) { // Try to get constructor that takes PageParameters Constructor<?> constructor = constructor(pageClass, PageParameters.class); // If we got a PageParameters constructor if (constructor != null) { // return new Page(parameters) return newPage(constructor, parameters); } // Always try default constructor if one exists return newPage(pageClass); } /** * Looks up a one-arg Page constructor by class and argument type. * * @param <C> * * @param pageClass * The class of page * @param argumentType * The argument type * @return The page constructor, or null if no one-arg constructor can be found taking the given * argument type. */ private final <C extends Page> Constructor<?> constructor(final Class<C> pageClass, final Class<PageParameters> argumentType) { // Get constructor for page class from cache Constructor<?> constructor = constructorForClass.get(pageClass); // Need to look up? if (constructor == null) { try { // Try to find the constructor constructor = pageClass.getConstructor(new Class[] { argumentType }); // Store it in the cache constructorForClass.put(pageClass, constructor); } catch (NoSuchMethodException e) { return null; } } return constructor; } /** * Creates a new Page using the given constructor and argument. * * @param constructor * The constructor to invoke * @param argument * The argument to pass to the constructor or null to pass no arguments * @return The new page * @throws WicketRuntimeException * Thrown if the Page cannot be instantiated using the given constructor and * argument. */ private final Page newPage(final Constructor<?> constructor, final Object argument) { try { if (argument != null) return (Page)constructor.newInstance(new Object[] { argument }); else return (Page)constructor.newInstance(new Object[] {}); } catch (InstantiationException e) { throw new WicketRuntimeException(createDescription(constructor, argument), e); } catch (IllegalAccessException e) { throw new WicketRuntimeException(createDescription(constructor, argument), e); } catch (InvocationTargetException e) { // honor redirect exception contract defined in IPageFactory if (e.getTargetException() instanceof AbortException || e.getTargetException() instanceof AuthorizationException || e.getTargetException() instanceof MarkupException) { throw (RuntimeException)e.getTargetException(); } throw new WicketRuntimeException(createDescription(constructor, argument), e); } } private String createDescription(Constructor<?> constructor, Object argument) { if (argument != null) return "Can't instantiate page using constructor " + constructor + " and argument " + argument; else return "Can't instantiate page using constructor " + constructor; } }
5,623
0.718767
0.718058
184
29.673914
28.515675
99
false
false
0
0
0
0
0
0
1.815217
false
false
5
31883b49bb5ee5d7797dbe940f28bc15c68597b2
8,718,783,649,601
3a26a2426c24fe630994832d76d62da8f0978d1c
/app/src/main/java/com/example/study/fourth_pass_animation/DrawableAnimActivity.java
ac18a5b0f03a71c085a570c32d94408b631d1a89
[]
no_license
swallowwen/Android_Element_Study
https://github.com/swallowwen/Android_Element_Study
46d6be8aae936bbb548dec330688b8dedfbb31db
d2cf566c2b25c1aaf57deccfc02c387642ba6a52
refs/heads/master
2020-04-10T21:54:37.104000
2019-04-04T09:19:49
2019-04-04T09:19:49
161,310,057
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.study.fourth_pass_animation; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.widget.ImageView; import com.example.study.R; /** * 帧动画 * Created by swallow on 2018/12/20. */ public class DrawableAnimActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drawable_anim); ImageView imageView = findViewById(R.id.iv_drawable_anim); // imageView.setImageResource(R.drawable.drawable_anim); // AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable(); // animationDrawable.start(); AnimationDrawable animationDrawable1=new AnimationDrawable(); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao1),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao2),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao3),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao4),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao5),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao6),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao7),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao8),50); animationDrawable1.setOneShot(false); imageView.setImageDrawable(animationDrawable1); animationDrawable1.start(); } }
UTF-8
Java
1,739
java
DrawableAnimActivity.java
Java
[ { "context": "ort com.example.study.R;\n\n/**\n * 帧动画\n * Created by swallow on 2018/12/20.\n */\n\npublic class DrawableAnimActi", "end": 309, "score": 0.9996806383132935, "start": 302, "tag": "USERNAME", "value": "swallow" } ]
null
[]
package com.example.study.fourth_pass_animation; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.widget.ImageView; import com.example.study.R; /** * 帧动画 * Created by swallow on 2018/12/20. */ public class DrawableAnimActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drawable_anim); ImageView imageView = findViewById(R.id.iv_drawable_anim); // imageView.setImageResource(R.drawable.drawable_anim); // AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable(); // animationDrawable.start(); AnimationDrawable animationDrawable1=new AnimationDrawable(); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao1),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao2),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao3),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao4),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao5),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao6),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao7),50); animationDrawable1.addFrame(getResources().getDrawable(R.drawable.bao8),50); animationDrawable1.setOneShot(false); imageView.setImageDrawable(animationDrawable1); animationDrawable1.start(); } }
1,739
0.751298
0.725909
40
42.325001
31.385815
92
false
false
0
0
0
0
0
0
0.825
false
false
5
14264a2767c83bc5b2606603433037bbff788193
14,431,090,124,402
6cdf277f6e322f20adf147713f1ef8366a854192
/src/view/IPlayerInterface.java
d68070f4d836d6172f09342d58a449890a95f280
[ "MIT" ]
permissive
andrewbharrisiv/NineManMorris
https://github.com/andrewbharrisiv/NineManMorris
898ce66bb0f9b895fff2e7bd33516196c9cdeea2
969973aa4e49984c4a6d01b25ad8e260e79cb68d
refs/heads/master
2015-08-13T06:01:39
2014-12-12T22:24:49
2014-12-12T22:24:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package view; import controller.IController; import model.MoveInfo; public interface IPlayerInterface { /** * Update the IPlayerInterface with game information from game board and * game state. * @param currentState * Model of the game that keeps track of following states: * boardState * startingPiecesRemainingWhite * startingPiecesRemainingBlack * currentPlayerTurn * playerAction */ public abstract void updateGameInfo(MoveInfo currentState); public abstract void addController(IController controller); }
UTF-8
Java
562
java
IPlayerInterface.java
Java
[]
null
[]
package view; import controller.IController; import model.MoveInfo; public interface IPlayerInterface { /** * Update the IPlayerInterface with game information from game board and * game state. * @param currentState * Model of the game that keeps track of following states: * boardState * startingPiecesRemainingWhite * startingPiecesRemainingBlack * currentPlayerTurn * playerAction */ public abstract void updateGameInfo(MoveInfo currentState); public abstract void addController(IController controller); }
562
0.743772
0.743772
23
23.434782
22.115952
73
false
false
0
0
0
0
0
0
1.869565
false
false
5
40dbf0db95b7f555f92596352d75db7bf1a2559d
14,431,090,125,244
4a44e30c1132b5e84423f2befc431a1d0088ca30
/src/com/paulinefeytel/tests/AllListsTest.java
c549052b7267282ee04d1f22833f43b30f06df22
[]
no_license
pauline-f/MyVocabulary
https://github.com/pauline-f/MyVocabulary
ccaa452a1e41361db47d401536672d418347dd0c
4127df31a11bdeb14e506b8738b12d9af789a9b9
refs/heads/master
2021-05-07T08:33:17.823000
2017-11-20T21:13:06
2017-11-20T21:13:06
109,308,832
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.paulinefeytel.tests; import com.paulinefeytel.model.AllLists; import com.paulinefeytel.model.ListWord; import org.junit.Test; import static org.junit.Assert.*; public class AllListsTest { @Test public void findAList() { AllLists allLists = new AllLists(); ListWord list1 = new ListWord("colors"); ListWord list2 = new ListWord("animals"); ListWord list3 = new ListWord("food"); allLists.addList(list1); allLists.addList(list2); allLists.addList(list3); assertEquals(list2, allLists.findAList("animals")); } }
UTF-8
Java
601
java
AllListsTest.java
Java
[]
null
[]
package com.paulinefeytel.tests; import com.paulinefeytel.model.AllLists; import com.paulinefeytel.model.ListWord; import org.junit.Test; import static org.junit.Assert.*; public class AllListsTest { @Test public void findAList() { AllLists allLists = new AllLists(); ListWord list1 = new ListWord("colors"); ListWord list2 = new ListWord("animals"); ListWord list3 = new ListWord("food"); allLists.addList(list1); allLists.addList(list2); allLists.addList(list3); assertEquals(list2, allLists.findAList("animals")); } }
601
0.673877
0.66223
23
25.173914
18.79096
59
false
false
0
0
0
0
0
0
0.608696
false
false
5
19c6261a7ef35f651118e0c93e510568c7a53e95
14,431,090,124,510
1a16ffe491fd7c1d66dbe29c36b0cc421f1a13ff
/mybatis/mybatis04design/src/main/java/cn/dave/mybatis/cfg/Mapper.java
58977978b89d3da7e676a3e098af49217521ea5b
[]
no_license
dave0824/ssm
https://github.com/dave0824/ssm
d8c00e8dc8016c0f42eb5b0a1df71075153c7e89
0a72c934bea28add2d3bedd9730e17631f4d35fc
refs/heads/master
2022-12-23T13:48:11.133000
2019-08-29T13:42:48
2019-08-29T13:42:48
205,171,046
0
0
null
false
2022-12-15T23:57:51
2019-08-29T13:32:21
2019-08-29T13:47:47
2022-12-15T23:57:48
73,420
0
0
46
JavaScript
false
false
package cn.dave.mybatis.cfg; /** * @program: mybatis04design * @description:用于封装执行SQL语句和结果类型的全限定类名 * @author: dave * @create: 2019-06-24 11:23 **/ public class Mapper { private String queryString; private String resultType; public String getQueryString() { return queryString; } public void setQueryString(String queryString) { this.queryString = queryString; } public String getResultType() { return resultType; } public void setResultType(String resultType) { this.resultType = resultType; } }
UTF-8
Java
617
java
Mapper.java
Java
[ { "context": " * @description:用于封装执行SQL语句和结果类型的全限定类名\n * @author: dave\n * @create: 2019-06-24 11:23\n **/\n\npublic class M", "end": 118, "score": 0.9747213125228882, "start": 114, "tag": "USERNAME", "value": "dave" } ]
null
[]
package cn.dave.mybatis.cfg; /** * @program: mybatis04design * @description:用于封装执行SQL语句和结果类型的全限定类名 * @author: dave * @create: 2019-06-24 11:23 **/ public class Mapper { private String queryString; private String resultType; public String getQueryString() { return queryString; } public void setQueryString(String queryString) { this.queryString = queryString; } public String getResultType() { return resultType; } public void setResultType(String resultType) { this.resultType = resultType; } }
617
0.663212
0.639033
29
18.965517
16.680532
52
false
false
0
0
0
0
0
0
0.241379
false
false
5
a18d7ed3f5c76f456de3d595ee4e00c092bf2cef
12,773,232,782,998
22a0dd0bc9e45f28d65ae4cac3978917ceb696ac
/app/src/main/java/com/example/administrator/logindemo/fragment/TeamFragment.java
303697784e26f2960c310769e0b0d8f39e7d6068
[]
no_license
he1995/basketball
https://github.com/he1995/basketball
767201a4e42f548a71907f40588e9a28755c4be3
f33a6e7118f1144e0ceb3a31b66059c8aadd98b6
refs/heads/master
2017-01-01T20:40:12.301000
2016-09-02T14:05:00
2016-09-02T14:05:00
65,717,967
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.administrator.logindemo.fragment; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.example.administrator.logindemo.ListviewItem.Member; import com.example.administrator.logindemo.ListviewItem.MemberAdapter; import com.example.administrator.logindemo.R; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/8/18. */ public class TeamFragment extends Fragment { private ListView memberListView; private List<Member> memberList = new ArrayList<Member>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.team_fragment, container, false); //初始化team member数据 initMembers(); MemberAdapter memberAdapter = new MemberAdapter(this.getActivity().getApplicationContext(), R.layout.member_item, memberList); memberListView = (ListView) view.findViewById(R.id.list_view_team); memberListView.setAdapter(memberAdapter); return view; } /** * 加载team_member_listview中的数据,此处为暂时性的测试数据 */ private void initMembers() { Member kobe = new Member(R.drawable.head_kobe, "Kobe", "得分后卫", "198cm", "96kg"); memberList.add(kobe); Member james = new Member(R.drawable.head_james, "James", "小前锋", "203cm", "110kg"); memberList.add(james); Member wade = new Member(R.drawable.head_wade, "Wade", "得分后卫", "193cm", "95kg"); memberList.add(wade); Member curry = new Member(R.drawable.head_curry, "Curry", "控球后卫", "190cm", "80kg"); memberList.add(curry); Member irving = new Member(R.drawable.head_irving, "Irving", "控球后卫", "187cm", "83kg"); memberList.add(irving); Member gasol = new Member(R.drawable.head_gasol, "Gasol", "中锋", "216cm", "120kg"); memberList.add(gasol); Member howard = new Member(R.drawable.head_howard, "Howard", "中锋", "211cm", "125kg"); memberList.add(howard); Member tompson = new Member(R.drawable.head_tompson, "Tompson", "得分后卫", "201cm", "96kg"); memberList.add(tompson); Member hardon = new Member(R.drawable.head_hardon, "Hardon", "得分后卫", "196cm", "96kg"); memberList.add(hardon); } }
UTF-8
Java
2,549
java
TeamFragment.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Administrator on 2016/8/18.\n */\npublic class TeamFragment exten", "end": 501, "score": 0.5680508613586426, "start": 488, "tag": "NAME", "value": "Administrator" }, { "context": " Member kobe = new Member(R.drawable.head_kobe, \"Kobe\", \"得分后卫\", \"198cm\", \"96kg\");\n memberList.ad", "end": 1376, "score": 0.999561071395874, "start": 1372, "tag": "NAME", "value": "Kobe" }, { "context": "Member james = new Member(R.drawable.head_james, \"James\", \"小前锋\", \"203cm\", \"110kg\");\n memberList.ad", "end": 1498, "score": 0.9990485310554504, "start": 1493, "tag": "NAME", "value": "James" }, { "context": " Member wade = new Member(R.drawable.head_wade, \"Wade\", \"得分后卫\", \"193cm\", \"95kg\");\n memberList.ad", "end": 1618, "score": 0.9995325803756714, "start": 1614, "tag": "NAME", "value": "Wade" }, { "context": "Member curry = new Member(R.drawable.head_curry, \"Curry\", \"控球后卫\", \"190cm\", \"80kg\");\n memberList.ad", "end": 1740, "score": 0.9992504715919495, "start": 1735, "tag": "NAME", "value": "Curry" }, { "context": "mber irving = new Member(R.drawable.head_irving, \"Irving\", \"控球后卫\", \"187cm\", \"83kg\");\n memberList.ad", "end": 1866, "score": 0.9996939301490784, "start": 1860, "tag": "NAME", "value": "Irving" }, { "context": "Member gasol = new Member(R.drawable.head_gasol, \"Gasol\", \"中锋\", \"216cm\", \"120kg\");\n memberList.add", "end": 1990, "score": 0.9997036457061768, "start": 1985, "tag": "NAME", "value": "Gasol" }, { "context": "mber howard = new Member(R.drawable.head_howard, \"Howard\", \"中锋\", \"211cm\", \"125kg\");\n memberList.add", "end": 2115, "score": 0.9996101260185242, "start": 2109, "tag": "NAME", "value": "Howard" }, { "context": "er tompson = new Member(R.drawable.head_tompson, \"Tompson\", \"得分后卫\", \"201cm\", \"96kg\");\n memberList.ad", "end": 2244, "score": 0.9996950030326843, "start": 2237, "tag": "NAME", "value": "Tompson" }, { "context": "mber hardon = new Member(R.drawable.head_hardon, \"Hardon\", \"得分后卫\", \"196cm\", \"96kg\");\n memberList.ad", "end": 2372, "score": 0.9996140003204346, "start": 2366, "tag": "NAME", "value": "Hardon" } ]
null
[]
package com.example.administrator.logindemo.fragment; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.example.administrator.logindemo.ListviewItem.Member; import com.example.administrator.logindemo.ListviewItem.MemberAdapter; import com.example.administrator.logindemo.R; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/8/18. */ public class TeamFragment extends Fragment { private ListView memberListView; private List<Member> memberList = new ArrayList<Member>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.team_fragment, container, false); //初始化team member数据 initMembers(); MemberAdapter memberAdapter = new MemberAdapter(this.getActivity().getApplicationContext(), R.layout.member_item, memberList); memberListView = (ListView) view.findViewById(R.id.list_view_team); memberListView.setAdapter(memberAdapter); return view; } /** * 加载team_member_listview中的数据,此处为暂时性的测试数据 */ private void initMembers() { Member kobe = new Member(R.drawable.head_kobe, "Kobe", "得分后卫", "198cm", "96kg"); memberList.add(kobe); Member james = new Member(R.drawable.head_james, "James", "小前锋", "203cm", "110kg"); memberList.add(james); Member wade = new Member(R.drawable.head_wade, "Wade", "得分后卫", "193cm", "95kg"); memberList.add(wade); Member curry = new Member(R.drawable.head_curry, "Curry", "控球后卫", "190cm", "80kg"); memberList.add(curry); Member irving = new Member(R.drawable.head_irving, "Irving", "控球后卫", "187cm", "83kg"); memberList.add(irving); Member gasol = new Member(R.drawable.head_gasol, "Gasol", "中锋", "216cm", "120kg"); memberList.add(gasol); Member howard = new Member(R.drawable.head_howard, "Howard", "中锋", "211cm", "125kg"); memberList.add(howard); Member tompson = new Member(R.drawable.head_tompson, "Tompson", "得分后卫", "201cm", "96kg"); memberList.add(tompson); Member hardon = new Member(R.drawable.head_hardon, "Hardon", "得分后卫", "196cm", "96kg"); memberList.add(hardon); } }
2,549
0.677181
0.65465
61
39.016392
31.938719
103
false
false
0
0
0
0
0
0
1.311475
false
false
5
054bbe15099a3d15a314732314a157171f45f58d
12,369,505,840,451
77454dc9ab42abe999c4fb9bba945303469308be
/WebSifa/src/main/java/upacifico/ec/core/entity/Campus.java
a78b8e4b28bbdc74301a0ede4796c8be5a0e9681
[ "Apache-2.0" ]
permissive
edecisions/sifa
https://github.com/edecisions/sifa
69078f49bc6a1a342286d0085d612b1671ef263a
7516ea68788be6a03791c91845388533bebd5940
refs/heads/master
2017-12-16T17:32:40.513000
2017-02-24T18:39:33
2017-02-24T18:39:33
77,486,986
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package upacifico.ec.core.entity; import javax.persistence.*; import java.util.List; /** * Represent the different campus of the university * * Pacific University http://upacifico.edu.ec * * @author Msc. Ing. Eduardo Alfonso Sanchez eddie.alfonso@gmail.com * Date & Time: 23/1/2017 12:25 */ @Entity @Table(name = Module.CORE_PREFIX + "_campus") public class Campus { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(nullable = false, unique = true, length = 20) private long id; @Column(length = 60, nullable = false, unique = true) private String name; @OneToMany(cascade = CascadeType.ALL, mappedBy = "campus", orphanRemoval = true) private List<Place> placeList; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Place> getPlaceList() { return placeList; } public void setPlaceList(List<Place> placeList) { this.placeList = placeList; } }
UTF-8
Java
1,150
java
Campus.java
Java
[ { "context": "ty http://upacifico.edu.ec\n *\n * @author Msc. Ing. Eduardo Alfonso Sanchez eddie.alfonso@gmail.com\n * Date & Time: 2", "end": 239, "score": 0.9998810887336731, "start": 216, "tag": "NAME", "value": "Eduardo Alfonso Sanchez" }, { "context": "ec\n *\n * @author Msc. Ing. Eduardo Alfonso Sanchez eddie.alfonso@gmail.com\n * Date & Time: 23/1/2017 12:25\n */\n@Ent", "end": 263, "score": 0.9999305009841919, "start": 240, "tag": "EMAIL", "value": "eddie.alfonso@gmail.com" } ]
null
[]
package upacifico.ec.core.entity; import javax.persistence.*; import java.util.List; /** * Represent the different campus of the university * * Pacific University http://upacifico.edu.ec * * @author Msc. Ing. <NAME> <EMAIL> * Date & Time: 23/1/2017 12:25 */ @Entity @Table(name = Module.CORE_PREFIX + "_campus") public class Campus { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(nullable = false, unique = true, length = 20) private long id; @Column(length = 60, nullable = false, unique = true) private String name; @OneToMany(cascade = CascadeType.ALL, mappedBy = "campus", orphanRemoval = true) private List<Place> placeList; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Place> getPlaceList() { return placeList; } public void setPlaceList(List<Place> placeList) { this.placeList = placeList; } }
1,117
0.635652
0.622609
52
21.115385
21.178411
84
false
false
0
0
0
0
0
0
0.346154
false
false
5
7cb86f2dac23bdfd564eeb7bcf432d29eb13a033
21,706,764,725,575
d3a91b8aa81aaaa52a534f6bfa6bb0b9b4dc19ea
/src/main/java/me/search/concept/util/ApplicationUtil.java
8b05521961cbd9f69343221de02a10250d3af52a
[]
no_license
jecky100000/SearchConcept
https://github.com/jecky100000/SearchConcept
7a9a5288700aacbdb952d2c4a18f8787bed77379
0d544694a980c04a48ba209912c06ddd08733007
refs/heads/master
2022-04-20T12:12:10.824000
2019-05-18T16:20:45
2019-05-18T16:20:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.search.concept.util; public final class ApplicationUtil { public static void exit() { LogUtil.info("退出程序"); System.exit(0); } }
UTF-8
Java
174
java
ApplicationUtil.java
Java
[]
null
[]
package me.search.concept.util; public final class ApplicationUtil { public static void exit() { LogUtil.info("退出程序"); System.exit(0); } }
174
0.620482
0.614458
10
15.6
14.766177
36
false
false
0
0
0
0
0
0
0.3
false
false
5
167095ce3afca4a20265e09d13594cc063e91f1f
20,684,562,514,850
bdb39a2e2b3273b267dbc75e1cabe4849b7f7503
/src/main/java/com/shanxijuzhi/juzhi/tsak/ExcelManage.java
2f02e3cd3e6b9468ff0b8a4db051072cf9d8266a
[]
no_license
Zhazhahui8954/test
https://github.com/Zhazhahui8954/test
69a6efb6636ca06e978e64b33316c3bb66ffb3c0
e6ccba24468deb333e295a4b8a83c3adfc412c74
refs/heads/master
2023-02-17T23:41:27.919000
2021-01-21T07:56:40
2021-01-21T07:56:40
330,573,780
0
0
null
false
2021-01-21T07:56:41
2021-01-18T06:21:20
2021-01-21T07:14:15
2021-01-21T07:56:40
1,229
0
0
0
JavaScript
false
false
/* package com.shanxijuzhi.juzhi.tsak;*/ /* package com.shanxijuzhi.juzhi.tsak; import com.microsoft.schemas.office.visio.x2012.main.CellType; import com.shanxijuzhi.juzhi.model.TestDataInfo; import com.sun.rowset.internal.Row; import javafx.scene.control.Cell; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import javax.annotation.Resource; import java.io.*; import java.util.ArrayList; import java.util.List; @Configuration @EnableScheduling//开启定时任务的支持 public class Test { @Resource private TestDataInfo testDataInfo; @Value("${file.url}")//获取文件的存储路径 private String url; @Scheduled(cron="0/10 * * * * *") public List<TestDataInfo> test1() throws Exception { String saveUrl = url; System.out.println("存储文件的地址为"+ saveUrl); File file = new File(saveUrl); //遍历saveURl文件下的目录和文件 File[] files = file.listFiles(); for (File fs : files){ //获取文件名 String fileName = fs.getName(); System.out.println(fileName); //获取文件的后缀名 String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); //非目录(即文件是为excel文件.xls)则处理文件,数据插入到库中 String path = url +"/"+fileName; System.out.println(fs); System.out.println(path); if (!fs.isDirectory() && suffix.equals("xls")) { ImportExcel<TestDataInfo> importExcel = new ImportExcel<>(); List<TestDataInfo> testDataInfos = ReadExcel.readExcelInfo(path,TestDataInfo.class); for (TestDataInfo tt:testDataInfos){ System.out.println(tt); } }else if (!fs.isDirectory() && suffix.equals("xlsx")){ ImportExcel<TestDataInfo> importExcel = new ImportExcel<>(); List<TestDataInfo> testDataInfos = ReadExcel.readExcelInfo(path,TestDataInfo.class); for (TestDataInfo tt:testDataInfos){ System.out.println("00000000000000000000000000000000000000000000000000000000000000000000000"+tt); } } } return null; } } *//* import com.shanxijuzhi.juzhi.model.TestDataInfo; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import javax.annotation.Resource; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @Configuration @EnableScheduling//开启定时任务的支持 public class ExcelManage { private HSSFWorkbook workbook; @Resource private TestDataInfo testDataInfo; @Value("${file.url}")//获取文件的存储路径 private String url; @Scheduled(cron="0/10 * * * * *") public boolean ExcelManage() { String saveUrl = url; File file = new File(url); //遍历saveURl文件下的目录和文件 File[] files = file.listFiles(); for (File fs : files) { //获取文件名 String fileName = fs.getName(); System.out.println(fileName); //获取文件的后缀名 String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); //非目录(即文件是为excel文件.xls)则处理文件,数据插入到库中 String path = url + "/" + fileName; if (!fs.isDirectory() && suffix.equals("xls")) { ExcelManage excelManage = new ExcelManage(); List<TestDataInfo> testDataInfos = excelManage.readFromExcel(fileName,TestDataInfo.class); // List<TestDataInfo> testDataInfos = ExcelManage.ExcelManage(path,TestDataInfo.class); for (TestDataInfo tt:testDataInfos){ System.out.println(tt.getId()); System.out.println(tt.getNo()); System.out.println(tt); } }else if (!fs.isDirectory() && suffix.equals("xlsx")){ ExcelManage excelManage = new ExcelManage(); List<TestDataInfo> testDataInfos = excelManage.readFromExcel(path,TestDataInfo.class); for (TestDataInfo tt:testDataInfos){ System.out.println("00000000000000000000000000000000000000000000000000000000000000000000000"+tt); } } } return true; } public List readFromExcel(String sheetName, Object object) { List result = new ArrayList(); // 获取该对象的class对象 Class class_ = object.getClass(); // 获得该类的所有属性 Field[] fields = class_.getDeclaredFields(); // 读取excel数据 // 获得指定的excel表 HSSFSheet sheet = workbook.getSheet(sheetName); // 获取表格的总行数 int rowCount = sheet.getLastRowNum() + 1; // 需要加一 if (rowCount < 1) { return result; } // 获取表头的列数 int columnCount = sheet.getRow(0).getLastCellNum(); // 读取表头信息,确定需要用的方法名---set方法 // 用于存储方法名 String[] methodNames = new String[columnCount]; // 表头列数即为需要的set方法个数 // 用于存储属性类型 String[] fieldTypes = new String[columnCount]; // 获得表头行对象 HSSFRow titleRow = sheet.getRow(0); // 遍历 for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { // 遍历表头列 String data = titleRow.getCell(columnIndex).toString(); // 某一列的内容 String Udata = Character.toUpperCase(data.charAt(0)) + data.substring(1, data.length()); // 使其首字母大写 methodNames[columnIndex] = "set" + Udata; for (int i = 0; i < fields.length; i++) { // 遍历属性数组 if (data.equals(fields[i].getName())) { // 属性与表头相等 fieldTypes[columnIndex] = fields[i].getType().getName(); // 将属性类型放到数组中 } } } // 逐行读取数据 从1开始 忽略表头 for (int rowIndex = 1; rowIndex < rowCount; rowIndex++) { // 获得行对象 HSSFRow row = sheet.getRow(rowIndex); if (row != null) { Object obj = null; // 实例化该泛型类的对象一个对象 try { obj = class_.newInstance(); } catch (Exception e1) { e1.printStackTrace(); } // 获得本行中各单元格中的数据 for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { String data = row.getCell(columnIndex).toString(); // 获取要调用方法的方法名 String methodName = methodNames[columnIndex]; Method method = null; try { // 这部分可自己扩展 if (fieldTypes[columnIndex].equals("java.lang.String")) { method = class_.getDeclaredMethod(methodName, String.class); // 设置要执行的方法--set方法参数为String method.invoke(obj, data); // 执行该方法 } else if (fieldTypes[columnIndex].equals("int")) { method = class_.getDeclaredMethod(methodName, int.class); // 设置要执行的方法--set方法参数为int double data_double = Double.parseDouble(data); int data_int = (int) data_double; method.invoke(obj, data_int); // 执行该方法 } } catch (Exception e) { e.printStackTrace(); } } result.add(obj); } } return result; } */ /*public static void main(String[] args) { String url = "E:/file/001.xlsx"; TestDataInfo testDataInfo = new TestDataInfo(); ExcelManage em = new ExcelManage(url); List list = em.readFromExcel("sheet1", testDataInfo); for (int i = 0; i < list.size(); i++) { TestDataInfo newUser = (TestDataInfo) list.get(i); System.out.println(newUser.getNo() + " " + newUser.getStoreTime() + " " + newUser.getCheckData()); } }*//* } */
UTF-8
Java
9,579
java
ExcelManage.java
Java
[]
null
[]
/* package com.shanxijuzhi.juzhi.tsak;*/ /* package com.shanxijuzhi.juzhi.tsak; import com.microsoft.schemas.office.visio.x2012.main.CellType; import com.shanxijuzhi.juzhi.model.TestDataInfo; import com.sun.rowset.internal.Row; import javafx.scene.control.Cell; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import javax.annotation.Resource; import java.io.*; import java.util.ArrayList; import java.util.List; @Configuration @EnableScheduling//开启定时任务的支持 public class Test { @Resource private TestDataInfo testDataInfo; @Value("${file.url}")//获取文件的存储路径 private String url; @Scheduled(cron="0/10 * * * * *") public List<TestDataInfo> test1() throws Exception { String saveUrl = url; System.out.println("存储文件的地址为"+ saveUrl); File file = new File(saveUrl); //遍历saveURl文件下的目录和文件 File[] files = file.listFiles(); for (File fs : files){ //获取文件名 String fileName = fs.getName(); System.out.println(fileName); //获取文件的后缀名 String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); //非目录(即文件是为excel文件.xls)则处理文件,数据插入到库中 String path = url +"/"+fileName; System.out.println(fs); System.out.println(path); if (!fs.isDirectory() && suffix.equals("xls")) { ImportExcel<TestDataInfo> importExcel = new ImportExcel<>(); List<TestDataInfo> testDataInfos = ReadExcel.readExcelInfo(path,TestDataInfo.class); for (TestDataInfo tt:testDataInfos){ System.out.println(tt); } }else if (!fs.isDirectory() && suffix.equals("xlsx")){ ImportExcel<TestDataInfo> importExcel = new ImportExcel<>(); List<TestDataInfo> testDataInfos = ReadExcel.readExcelInfo(path,TestDataInfo.class); for (TestDataInfo tt:testDataInfos){ System.out.println("00000000000000000000000000000000000000000000000000000000000000000000000"+tt); } } } return null; } } *//* import com.shanxijuzhi.juzhi.model.TestDataInfo; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import javax.annotation.Resource; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @Configuration @EnableScheduling//开启定时任务的支持 public class ExcelManage { private HSSFWorkbook workbook; @Resource private TestDataInfo testDataInfo; @Value("${file.url}")//获取文件的存储路径 private String url; @Scheduled(cron="0/10 * * * * *") public boolean ExcelManage() { String saveUrl = url; File file = new File(url); //遍历saveURl文件下的目录和文件 File[] files = file.listFiles(); for (File fs : files) { //获取文件名 String fileName = fs.getName(); System.out.println(fileName); //获取文件的后缀名 String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); //非目录(即文件是为excel文件.xls)则处理文件,数据插入到库中 String path = url + "/" + fileName; if (!fs.isDirectory() && suffix.equals("xls")) { ExcelManage excelManage = new ExcelManage(); List<TestDataInfo> testDataInfos = excelManage.readFromExcel(fileName,TestDataInfo.class); // List<TestDataInfo> testDataInfos = ExcelManage.ExcelManage(path,TestDataInfo.class); for (TestDataInfo tt:testDataInfos){ System.out.println(tt.getId()); System.out.println(tt.getNo()); System.out.println(tt); } }else if (!fs.isDirectory() && suffix.equals("xlsx")){ ExcelManage excelManage = new ExcelManage(); List<TestDataInfo> testDataInfos = excelManage.readFromExcel(path,TestDataInfo.class); for (TestDataInfo tt:testDataInfos){ System.out.println("00000000000000000000000000000000000000000000000000000000000000000000000"+tt); } } } return true; } public List readFromExcel(String sheetName, Object object) { List result = new ArrayList(); // 获取该对象的class对象 Class class_ = object.getClass(); // 获得该类的所有属性 Field[] fields = class_.getDeclaredFields(); // 读取excel数据 // 获得指定的excel表 HSSFSheet sheet = workbook.getSheet(sheetName); // 获取表格的总行数 int rowCount = sheet.getLastRowNum() + 1; // 需要加一 if (rowCount < 1) { return result; } // 获取表头的列数 int columnCount = sheet.getRow(0).getLastCellNum(); // 读取表头信息,确定需要用的方法名---set方法 // 用于存储方法名 String[] methodNames = new String[columnCount]; // 表头列数即为需要的set方法个数 // 用于存储属性类型 String[] fieldTypes = new String[columnCount]; // 获得表头行对象 HSSFRow titleRow = sheet.getRow(0); // 遍历 for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { // 遍历表头列 String data = titleRow.getCell(columnIndex).toString(); // 某一列的内容 String Udata = Character.toUpperCase(data.charAt(0)) + data.substring(1, data.length()); // 使其首字母大写 methodNames[columnIndex] = "set" + Udata; for (int i = 0; i < fields.length; i++) { // 遍历属性数组 if (data.equals(fields[i].getName())) { // 属性与表头相等 fieldTypes[columnIndex] = fields[i].getType().getName(); // 将属性类型放到数组中 } } } // 逐行读取数据 从1开始 忽略表头 for (int rowIndex = 1; rowIndex < rowCount; rowIndex++) { // 获得行对象 HSSFRow row = sheet.getRow(rowIndex); if (row != null) { Object obj = null; // 实例化该泛型类的对象一个对象 try { obj = class_.newInstance(); } catch (Exception e1) { e1.printStackTrace(); } // 获得本行中各单元格中的数据 for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { String data = row.getCell(columnIndex).toString(); // 获取要调用方法的方法名 String methodName = methodNames[columnIndex]; Method method = null; try { // 这部分可自己扩展 if (fieldTypes[columnIndex].equals("java.lang.String")) { method = class_.getDeclaredMethod(methodName, String.class); // 设置要执行的方法--set方法参数为String method.invoke(obj, data); // 执行该方法 } else if (fieldTypes[columnIndex].equals("int")) { method = class_.getDeclaredMethod(methodName, int.class); // 设置要执行的方法--set方法参数为int double data_double = Double.parseDouble(data); int data_int = (int) data_double; method.invoke(obj, data_int); // 执行该方法 } } catch (Exception e) { e.printStackTrace(); } } result.add(obj); } } return result; } */ /*public static void main(String[] args) { String url = "E:/file/001.xlsx"; TestDataInfo testDataInfo = new TestDataInfo(); ExcelManage em = new ExcelManage(url); List list = em.readFromExcel("sheet1", testDataInfo); for (int i = 0; i < list.size(); i++) { TestDataInfo newUser = (TestDataInfo) list.get(i); System.out.println(newUser.getNo() + " " + newUser.getStoreTime() + " " + newUser.getCheckData()); } }*//* } */
9,579
0.576771
0.55694
286
29.856644
27.404068
117
false
false
0
0
0
0
71
0.016091
0.468531
false
false
5
67da5b671a9f51237619e7e7f3e13dc0b1113913
4,226,247,883,098
7edbafb8008438177675f20ee8eb19060eef7776
/src/test/java/ch02/TestEx06.java
9c222068ed904804bf3f2db053feca1d4fa9816a
[]
no_license
t-kensuke/Java8
https://github.com/t-kensuke/Java8
2f93f51e2cbdc02c9bd737f168d4cb69b85fd7ca
5525db015756f61748b1be449e442a7cdb0aec5a
refs/heads/master
2021-01-22T07:39:01.487000
2015-05-14T10:43:14
2015-05-14T10:43:14
23,376,859
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch02; import java.util.stream.Stream; import junit.framework.TestCase; public class TestEx06 extends TestCase{ public void testRand() throws Exception { Stream<Character> charStream = Ex06.characterStream("abc"); charStream.forEach(c -> System.out.println(c)); } }
UTF-8
Java
302
java
TestEx06.java
Java
[]
null
[]
package ch02; import java.util.stream.Stream; import junit.framework.TestCase; public class TestEx06 extends TestCase{ public void testRand() throws Exception { Stream<Character> charStream = Ex06.characterStream("abc"); charStream.forEach(c -> System.out.println(c)); } }
302
0.708609
0.688742
16
16.875
20.931063
61
false
false
0
0
0
0
0
0
0.6875
false
false
5
dfe894bbcc06cc3dc508b3601f201e09834cced5
5,978,594,543,014
0f7d57c0023968eaa698441a1394ce11b03689fd
/src/main/java/com/gagror/data/AbstractEditableNamedEntity.java
4f8144d144150b544a4cd71a8e5f6cc89cab2723
[]
no_license
spacejens/GaGrOr
https://github.com/spacejens/GaGrOr
2ab9a71b10db664881723e1e0373a83d692017f3
5ac2d4039e677704e3af717db00f2f3ff72efd52
refs/heads/master
2020-05-31T23:11:41.153000
2015-02-22T13:58:03
2015-02-22T13:58:03
1,086,105
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gagror.data; import javax.persistence.Column; import javax.persistence.MappedSuperclass; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @MappedSuperclass public class AbstractEditableNamedEntity extends AbstractEditableEntity implements Named { @Column(nullable = false) @Getter @Setter private String name; public AbstractEditableNamedEntity(final String name) { setName(name); } @Override public String toString() { return String.format("%s, name='%s'", super.toString(), getName()); } }
UTF-8
Java
570
java
AbstractEditableNamedEntity.java
Java
[]
null
[]
package com.gagror.data; import javax.persistence.Column; import javax.persistence.MappedSuperclass; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @MappedSuperclass public class AbstractEditableNamedEntity extends AbstractEditableEntity implements Named { @Column(nullable = false) @Getter @Setter private String name; public AbstractEditableNamedEntity(final String name) { setName(name); } @Override public String toString() { return String.format("%s, name='%s'", super.toString(), getName()); } }
570
0.780702
0.780702
27
20.111111
22.193314
90
false
false
0
0
0
0
0
0
0.925926
false
false
5
25545bd9fb694c7b60952b85e2f8378f23f3168b
17,669,495,456,748
98244b292987bb6016e1e15e2bd14185c09388a5
/etc/marytts/java/de/dfki/lt/mary/modules/synthesis/FestivalUttSectioner.java
e6dcc8017a977692346a3ea644b5cd54aa09749d
[]
no_license
sal1023/speechapi
https://github.com/sal1023/speechapi
d2a7314a9a0a57149107864b2f5ed3899344a681
79e9fc81af0b8d6cfaa5f434af6bbd79203f4449
refs/heads/master
2021-01-10T03:58:44.963000
2012-06-29T19:42:28
2012-06-29T19:42:28
48,013,799
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright 2000-2006 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * * Permission is hereby granted, free of charge, to use and distribute * this software and its documentation without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of this work, and to * permit persons to whom this work is furnished to do so, subject to * the following conditions: * * 1. The code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Any modifications must be clearly marked as such. * 3. Original authors' names are not deleted. * 4. The authors' names are not used to endorse or promote products * derived from this software without specific prior written * permission. * * DFKI GMBH AND THE CONTRIBUTORS TO THIS WORK DISCLAIM ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DFKI GMBH NOR THE * CONTRIBUTORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ package de.dfki.lt.mary.modules.synthesis; import de.dfki.lt.mary.modules.FreeTTS2FestivalUtt; public class FestivalUttSectioner extends VoiceSectioner { public FestivalUttSectioner(String s, Voice defaultVoice) { super(s, defaultVoice); } public VoiceSection nextSection() { if (pos >= s.length()) return null; if (s.startsWith(FreeTTS2FestivalUtt.UTTMARKER, pos)) { pos += FreeTTS2FestivalUtt.UTTMARKER.length(); } int n = s.indexOf(FreeTTS2FestivalUtt.UTTMARKER, pos); if (n == -1) n = s.length(); String section = s.substring(pos, n).trim(); int endline = section.indexOf(System.getProperty("line.separator")); if (endline > -1 && section.startsWith(FreeTTS2FestivalUtt.VOICEMARKER)) { String voiceName = section.substring(FreeTTS2FestivalUtt.VOICEMARKER.length(), endline); Voice newVoice = Voice.getVoice(voiceName); if (newVoice == null) { logger.warn("Could not find voice named " + voiceName + ". Using " + currentVoice.getName() + "instead."); } else { currentVoice = newVoice; } } pos = n; logger.debug("Next voice section: voice = "+ currentVoice.getName() + "\n" + section); return new VoiceSection(currentVoice, section); } }
UTF-8
Java
2,835
java
FestivalUttSectioner.java
Java
[]
null
[]
/** * Copyright 2000-2006 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * * Permission is hereby granted, free of charge, to use and distribute * this software and its documentation without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of this work, and to * permit persons to whom this work is furnished to do so, subject to * the following conditions: * * 1. The code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Any modifications must be clearly marked as such. * 3. Original authors' names are not deleted. * 4. The authors' names are not used to endorse or promote products * derived from this software without specific prior written * permission. * * DFKI GMBH AND THE CONTRIBUTORS TO THIS WORK DISCLAIM ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DFKI GMBH NOR THE * CONTRIBUTORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ package de.dfki.lt.mary.modules.synthesis; import de.dfki.lt.mary.modules.FreeTTS2FestivalUtt; public class FestivalUttSectioner extends VoiceSectioner { public FestivalUttSectioner(String s, Voice defaultVoice) { super(s, defaultVoice); } public VoiceSection nextSection() { if (pos >= s.length()) return null; if (s.startsWith(FreeTTS2FestivalUtt.UTTMARKER, pos)) { pos += FreeTTS2FestivalUtt.UTTMARKER.length(); } int n = s.indexOf(FreeTTS2FestivalUtt.UTTMARKER, pos); if (n == -1) n = s.length(); String section = s.substring(pos, n).trim(); int endline = section.indexOf(System.getProperty("line.separator")); if (endline > -1 && section.startsWith(FreeTTS2FestivalUtt.VOICEMARKER)) { String voiceName = section.substring(FreeTTS2FestivalUtt.VOICEMARKER.length(), endline); Voice newVoice = Voice.getVoice(voiceName); if (newVoice == null) { logger.warn("Could not find voice named " + voiceName + ". Using " + currentVoice.getName() + "instead."); } else { currentVoice = newVoice; } } pos = n; logger.debug("Next voice section: voice = "+ currentVoice.getName() + "\n" + section); return new VoiceSection(currentVoice, section); } }
2,835
0.666314
0.659259
64
42.296875
28.481726
100
false
false
0
0
0
0
0
0
0.671875
false
false
5
ff3546989970ece6075f4d14601bc61963a4a7e2
17,669,495,460,891
2496007c4aa21c7d2c1af99c21565b8f52ae717f
/BridgeLab/src/com/utility/Utility.java
4545c2aa63dc96ba2069535cd210b248ce6d0932
[]
no_license
pankaj739/BridgeLabz
https://github.com/pankaj739/BridgeLabz
7bb2d7ba0a97cea7a1a33df142703e5dbad91801
ace1d0ef0b37fdc4c88f99329742dee48704ba85
refs/heads/master
2020-07-05T16:48:37.611000
2019-08-16T10:01:53
2019-08-16T10:01:53
202,703,382
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.utility; import java.util.Arrays; import com.bridgelab.datastruture.com.MyDeque; import com.bridgelab.datastruture.com.Node; public class Utility { public static void bubbleString(String[] arr) { String temp; System.out.println("Strings in sorted order: "); for(int i=0;i<arr.length;i++) { for(int j=i+1;j<arr.length;j++) { if(arr[j].compareTo(arr[i])<0) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } System.out.println(arr[i]); } } ///////////////////////////////////////////////////////////////////////////////////// public static void sort(int arr[]) { int n=arr.length; for(int i=1;i<n;i++) { int k=arr[i]; int j=i-1; while(j>=0 &&arr[j]>k) { arr[j+1]=arr[j]; j=j-1; } arr[j+1]=k; } } public static void printArray(int arr[]) { int n=arr.length; for(int i =0;i<n;++i) { System.out.print(arr[i]); System.out.println(); } } /////////////////////////////////////////////////////////// public static String[] sortSub(String array[],int f) { String temp=" "; for(int i=0; i<f;i++) { for(int j=i+1;j<f;j++) { if(array[i].compareTo(array[j])>0) { temp=array[i]; array[i]=array[j]; array[j]=temp; } } } return array; } //////////////////////////////////////////////////////// public static void tempConversionFtoC(double f) { double c=(f-32)*5/9; System.out.println("c="+(f-32)*9/5); } public static void tempConversionCtoF(double c) { double f=((9*c)/5)+32; System.out.println("f="+((c*9)/5)+32); } ///////////////////////////////////////////////////////////////////////////// public static void paymentMonthly(double p,double R,double y) { double n=12*y; double r=R/(12*100); double payment=p*r/(1-(Math.pow((1+r), -n))); System.out.println("monthly payment is :"+payment); } //////////////////////////// public static void dayofweek(int m,int d,int y) { int y0=y-(14-m)/12; int x=y0+y0/4-y0/100+y0/400; int m0=m+12*((14-m)/12)-2; int d0=(d+x+(31*m0)/12)%7; if(d==0) { System.out.println("Sunday"); } if(d==1) { System.out.println("Monday"); } if(d==2) { System.out.println("tuesday"); } if(d==3) { System.out.println(" wednesday "); } if(d==4) { System.out.println(" thursday "); } if(d==5) { System.out.println(" friday "); } if(d==6) { System.out.println(" saturday "); } if(m==1 && m<=12) { System.out.println(" valid month"); } if(y==0 && y>=1000000) { System.out.println("valid year"); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void sqrt(double c) { double t=c; double epsilon=1e-15; while(Math.abs(t-c/t)>epsilon*t) { t=(c/t+t)/2; } System.out.println(t); } /////////////////////////////////////////////////////////////////////////////////////////////////// public static void countcurrency(int amount) { int[] notes = new int[]{2000,500,200,100,50,20,10,5,2,1}; int[] countnotes=new int[10]; for(int i=0;i<10;i++) { if(amount>=notes[i]) { countnotes[i]=amount/notes[i]; amount=amount-countnotes[i]*notes[i]; } if(countnotes[i]!=0) { System.out.println(notes[i]+":"+countnotes[i]); } } } ///////////////////////////////////////////////////////////////////////////////////////////// public static void toBinary(int d) { String bin=" "; while(d!=0) { bin=(d%2)+bin; d/=2; } while(bin.length()%4==0) { bin=0+bin; } System.out.println("binary number is:" +bin); } ////////////////////////////////////////////////////////////////////////////// public static int[] stringToIntArray(String bin) { int[] binary=new int[bin.length()]; for(int i=0;i<binary.length;i++) { binary[i]=bin.charAt(i)-48; } return binary; } public static void showArr(int[] arr){ for(int i=0;i<arr.length;i++) { System.out.print(arr[i]); } System.out.println(); } public static boolean powerOf2(int n) { int i=0; int temp=0; temp=(int)Math.pow(2, i); while(temp<n) { return true; } i++; return false; } public static int[] swapNibbles(int[] arr) { int temp,j=arr.length-4; for(int i=0;i<4;i++) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; j++; } return arr; } public static int toDecimal(int[] binary) { // TODO Auto-generated method stub return 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void bubbleSort(int[] arr) { for(int i=0;i<arr.length-1;i++) { int temp; for(int j=0;j<arr.length-1-i;j++) { if(arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); System.out.println(); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void binarySearch(int[] arr,int first,int last,int k) { int mid=(first+last)/2; while(first<=last) { if(arr[mid]<k) { first=mid+1; } else if(arr[mid]==k) { System.out.println(" Element is found at index :"+mid); break; } else { last=mid-1; } mid=(first+last)/2; } if(first>last) { System.out.println(" Element is not found "); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static int stringBinarySearch(String[] arr,int min,int max,String k) { min=0; max=arr.length-1; int mid; while(min<=max) { mid=(min+max)/2; if(arr[mid].compareTo(k)<0) { min=mid+1; } else if(arr[mid].compareTo(k)>0) { max=mid-1; }else { return mid; }} return-1; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean anagramChk(String s1, String s2) { char[] charArray1=s1.toCharArray(); char[] charArray2=s2.toCharArray(); Arrays.sort(charArray1); Arrays.sort(charArray2); return Arrays.equals(charArray1,charArray2); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void prime() { int i,j; System.out.print("Prime nos from 0 to 100 are 1,2,"); for(i=3;i<=1000;i++) { for(j=2;j<i;j++) { if(i%j==0) break; } if(i==j) { System.out.print(i+","); } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* public static void primeAnagrams() { ArrayList<Integer> ar = new ArrayList<Integer>(); System.out.println(); boolean b; for (int j = 2; j <= 1000; j++) { b = true; for (int i = 2; i < j / 2; i++) { if (j % i == 0) { b = false; break; } } if (b) ar.add(j); } for (int i = 0; i < ar.size(); i++) { for (int j = i + 1; j < ar.size(); j++) { if (anagram(ar.get(i), ar.get(j))) { System.out.println(ar.get(i) + " " + ar.get(j)); } */ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void insertionString(String[] arr) { String temp; for (int i =0; i < arr.length; i++) { for (int j =1; j<arr.length; j++) { if(arr[j].compareTo(arr[j-1])<0) { temp=arr[j-1]; arr[j-1]=arr[j]; arr[j]=temp; } } } for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean palindromCheaker(String word) { MyDeque<Character> dq=new MyDeque<Character>(); char[] c=word.toCharArray(); for(int i=0;i<c.length;i++) { dq.addFront(c[i]); } String s=""; for(int i=0;i<c.length;i++) { Node<Character> ch=dq.removeFront(); s=s+ch.data; } System.out.println(s); if(s.equals(word)) { return true; }else { return false; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean isPrime(int number) { int count = 0; for (int i = 2; i <= number / 2; i++) { if (number % i == 0) { count++; } } if (count == 0) { return true;} else { return false;}} public static void prime2DArray() { int[][] array = new int[10][100]; int[][] prime = new int[10][100]; int z=1; for(int i=0;i<10;i++) { for(int j=0;j<100;j++) { array[i][j]=z; z++; } } for(int i=0;i<10;i++) { for(int j=0;j<100;j++) { if(isPrime(array[i][j])) { prime[i][j]=array[i][j]; }else { prime[i][j]=-1; } } } for(int i=0;i<10;i++) { for(int j=0;j<100;j++) { if(prime[i][j]!=-1) { System.out.println(prime[i][j] +" "); } } } }}
UTF-8
Java
9,515
java
Utility.java
Java
[]
null
[]
package com.utility; import java.util.Arrays; import com.bridgelab.datastruture.com.MyDeque; import com.bridgelab.datastruture.com.Node; public class Utility { public static void bubbleString(String[] arr) { String temp; System.out.println("Strings in sorted order: "); for(int i=0;i<arr.length;i++) { for(int j=i+1;j<arr.length;j++) { if(arr[j].compareTo(arr[i])<0) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } System.out.println(arr[i]); } } ///////////////////////////////////////////////////////////////////////////////////// public static void sort(int arr[]) { int n=arr.length; for(int i=1;i<n;i++) { int k=arr[i]; int j=i-1; while(j>=0 &&arr[j]>k) { arr[j+1]=arr[j]; j=j-1; } arr[j+1]=k; } } public static void printArray(int arr[]) { int n=arr.length; for(int i =0;i<n;++i) { System.out.print(arr[i]); System.out.println(); } } /////////////////////////////////////////////////////////// public static String[] sortSub(String array[],int f) { String temp=" "; for(int i=0; i<f;i++) { for(int j=i+1;j<f;j++) { if(array[i].compareTo(array[j])>0) { temp=array[i]; array[i]=array[j]; array[j]=temp; } } } return array; } //////////////////////////////////////////////////////// public static void tempConversionFtoC(double f) { double c=(f-32)*5/9; System.out.println("c="+(f-32)*9/5); } public static void tempConversionCtoF(double c) { double f=((9*c)/5)+32; System.out.println("f="+((c*9)/5)+32); } ///////////////////////////////////////////////////////////////////////////// public static void paymentMonthly(double p,double R,double y) { double n=12*y; double r=R/(12*100); double payment=p*r/(1-(Math.pow((1+r), -n))); System.out.println("monthly payment is :"+payment); } //////////////////////////// public static void dayofweek(int m,int d,int y) { int y0=y-(14-m)/12; int x=y0+y0/4-y0/100+y0/400; int m0=m+12*((14-m)/12)-2; int d0=(d+x+(31*m0)/12)%7; if(d==0) { System.out.println("Sunday"); } if(d==1) { System.out.println("Monday"); } if(d==2) { System.out.println("tuesday"); } if(d==3) { System.out.println(" wednesday "); } if(d==4) { System.out.println(" thursday "); } if(d==5) { System.out.println(" friday "); } if(d==6) { System.out.println(" saturday "); } if(m==1 && m<=12) { System.out.println(" valid month"); } if(y==0 && y>=1000000) { System.out.println("valid year"); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void sqrt(double c) { double t=c; double epsilon=1e-15; while(Math.abs(t-c/t)>epsilon*t) { t=(c/t+t)/2; } System.out.println(t); } /////////////////////////////////////////////////////////////////////////////////////////////////// public static void countcurrency(int amount) { int[] notes = new int[]{2000,500,200,100,50,20,10,5,2,1}; int[] countnotes=new int[10]; for(int i=0;i<10;i++) { if(amount>=notes[i]) { countnotes[i]=amount/notes[i]; amount=amount-countnotes[i]*notes[i]; } if(countnotes[i]!=0) { System.out.println(notes[i]+":"+countnotes[i]); } } } ///////////////////////////////////////////////////////////////////////////////////////////// public static void toBinary(int d) { String bin=" "; while(d!=0) { bin=(d%2)+bin; d/=2; } while(bin.length()%4==0) { bin=0+bin; } System.out.println("binary number is:" +bin); } ////////////////////////////////////////////////////////////////////////////// public static int[] stringToIntArray(String bin) { int[] binary=new int[bin.length()]; for(int i=0;i<binary.length;i++) { binary[i]=bin.charAt(i)-48; } return binary; } public static void showArr(int[] arr){ for(int i=0;i<arr.length;i++) { System.out.print(arr[i]); } System.out.println(); } public static boolean powerOf2(int n) { int i=0; int temp=0; temp=(int)Math.pow(2, i); while(temp<n) { return true; } i++; return false; } public static int[] swapNibbles(int[] arr) { int temp,j=arr.length-4; for(int i=0;i<4;i++) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; j++; } return arr; } public static int toDecimal(int[] binary) { // TODO Auto-generated method stub return 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void bubbleSort(int[] arr) { for(int i=0;i<arr.length-1;i++) { int temp; for(int j=0;j<arr.length-1-i;j++) { if(arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); System.out.println(); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void binarySearch(int[] arr,int first,int last,int k) { int mid=(first+last)/2; while(first<=last) { if(arr[mid]<k) { first=mid+1; } else if(arr[mid]==k) { System.out.println(" Element is found at index :"+mid); break; } else { last=mid-1; } mid=(first+last)/2; } if(first>last) { System.out.println(" Element is not found "); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static int stringBinarySearch(String[] arr,int min,int max,String k) { min=0; max=arr.length-1; int mid; while(min<=max) { mid=(min+max)/2; if(arr[mid].compareTo(k)<0) { min=mid+1; } else if(arr[mid].compareTo(k)>0) { max=mid-1; }else { return mid; }} return-1; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean anagramChk(String s1, String s2) { char[] charArray1=s1.toCharArray(); char[] charArray2=s2.toCharArray(); Arrays.sort(charArray1); Arrays.sort(charArray2); return Arrays.equals(charArray1,charArray2); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void prime() { int i,j; System.out.print("Prime nos from 0 to 100 are 1,2,"); for(i=3;i<=1000;i++) { for(j=2;j<i;j++) { if(i%j==0) break; } if(i==j) { System.out.print(i+","); } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* public static void primeAnagrams() { ArrayList<Integer> ar = new ArrayList<Integer>(); System.out.println(); boolean b; for (int j = 2; j <= 1000; j++) { b = true; for (int i = 2; i < j / 2; i++) { if (j % i == 0) { b = false; break; } } if (b) ar.add(j); } for (int i = 0; i < ar.size(); i++) { for (int j = i + 1; j < ar.size(); j++) { if (anagram(ar.get(i), ar.get(j))) { System.out.println(ar.get(i) + " " + ar.get(j)); } */ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void insertionString(String[] arr) { String temp; for (int i =0; i < arr.length; i++) { for (int j =1; j<arr.length; j++) { if(arr[j].compareTo(arr[j-1])<0) { temp=arr[j-1]; arr[j-1]=arr[j]; arr[j]=temp; } } } for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean palindromCheaker(String word) { MyDeque<Character> dq=new MyDeque<Character>(); char[] c=word.toCharArray(); for(int i=0;i<c.length;i++) { dq.addFront(c[i]); } String s=""; for(int i=0;i<c.length;i++) { Node<Character> ch=dq.removeFront(); s=s+ch.data; } System.out.println(s); if(s.equals(word)) { return true; }else { return false; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean isPrime(int number) { int count = 0; for (int i = 2; i <= number / 2; i++) { if (number % i == 0) { count++; } } if (count == 0) { return true;} else { return false;}} public static void prime2DArray() { int[][] array = new int[10][100]; int[][] prime = new int[10][100]; int z=1; for(int i=0;i<10;i++) { for(int j=0;j<100;j++) { array[i][j]=z; z++; } } for(int i=0;i<10;i++) { for(int j=0;j<100;j++) { if(isPrime(array[i][j])) { prime[i][j]=array[i][j]; }else { prime[i][j]=-1; } } } for(int i=0;i<10;i++) { for(int j=0;j<100;j++) { if(prime[i][j]!=-1) { System.out.println(prime[i][j] +" "); } } } }}
9,515
0.422701
0.397583
508
17.236221
23.212543
130
false
false
0
0
0
0
140
0.203363
1.679134
false
false
5
7f32e144a23fb2ec8a2cf0bd2314d3ea8fbd0aca
21,328,807,594,779
75a19778f0920cc612b9cf359dffcb446e39e7ac
/src/main/java/pl/coderslab/charity/validation/validators/SamePassword.java
f25979a3c11f029960337139fc83b84e51e3eb84
[]
no_license
Marcin-Bojanowski/charity
https://github.com/Marcin-Bojanowski/charity
faf997c457dac467c0764186a3d98958c6082d43
958bc1f659777ef159ee04bf03a5fc2e614b496e
refs/heads/master
2023-02-23T10:52:21.806000
2021-01-28T22:16:24
2021-01-28T22:16:24
305,449,474
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.coderslab.charity.validation.validators; import pl.coderslab.charity.validation.validatorsClasses.PasswordValidator; import pl.coderslab.charity.validation.validatorsClasses.SameNewPasswordValidator; import pl.coderslab.charity.validation.validatorsClasses.SamePasswordUpdateValidator; import pl.coderslab.charity.validation.validatorsClasses.SamePasswordValidator; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Constraint(validatedBy = {SamePasswordValidator.class, SamePasswordUpdateValidator.class, SameNewPasswordValidator.class}) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface SamePassword { String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
UTF-8
Java
994
java
SamePassword.java
Java
[]
null
[]
package pl.coderslab.charity.validation.validators; import pl.coderslab.charity.validation.validatorsClasses.PasswordValidator; import pl.coderslab.charity.validation.validatorsClasses.SameNewPasswordValidator; import pl.coderslab.charity.validation.validatorsClasses.SamePasswordUpdateValidator; import pl.coderslab.charity.validation.validatorsClasses.SamePasswordValidator; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Constraint(validatedBy = {SamePasswordValidator.class, SamePasswordUpdateValidator.class, SameNewPasswordValidator.class}) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface SamePassword { String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
994
0.82998
0.82998
22
44.18182
30.609917
123
false
false
0
0
0
0
0
0
0.818182
false
false
5
e5b00a45c1146a53acf23cad5dcc3bae9fe56bb7
28,217,935,148,299
a008d1d624624bef2846de3b6265498aeccc527a
/src/main/java/com/sharad/interview/coding/AtoI.java
772b27530dfec4448c36d43a18a87ffdcee32001
[]
no_license
gargsharad/coding
https://github.com/gargsharad/coding
cbd92fd2e7a2994276283207802493a59d8fe23a
1f9679ce2b20e41f73c5334444487b896bdb2b0d
refs/heads/master
2016-09-06T12:17:37.104000
2014-10-24T23:28:03
2014-10-24T23:28:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sharad.interview.coding; import java.util.Scanner; public class AtoI { public static int atoi(String input) { long result = 0l; char flag = '+'; char[] inputDigitArray = input.toCharArray(); int idx = 0; if (inputDigitArray[idx] == '-') { flag = '-'; idx++; } else if (inputDigitArray[idx] == '+') { flag = '+'; idx++; } while (inputDigitArray.length > idx) { result = (result * 10) + (inputDigitArray[idx++] - '0'); } if (flag == '-') result = -result; if (result < Integer.MIN_VALUE) { result = Integer.MIN_VALUE; } if (result > Integer.MAX_VALUE) { result = Integer.MAX_VALUE; } return (int) result; } public static String getInput() { System.out .print("Please enter a string you want to convert in to integer :: "); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); scanner.close(); return input.trim(); } public static boolean validateInput(String input) { boolean returnValue = false; if (input.matches("^[+,-]?\\d*$") && !(input.length() < 1)) { returnValue = true; } return returnValue; } public static void main(String[] args) { System.out.println("~~~~~~~~~~~~~~~Start~~~~~~~~~~~~~~~~~~~\n"); String input = AtoI.getInput(); if (!AtoI.validateInput(input)) { System.out.println("\nNot a valid input exiting"); } else { System.out.println("\n The number coverted to integer is :: " + AtoI.atoi(input)); } System.out.println("\n~~~~~~~~~~~~~~~End~~~~~~~~~~~~~~~~~~~~~"); } }
UTF-8
Java
1,599
java
AtoI.java
Java
[]
null
[]
package com.sharad.interview.coding; import java.util.Scanner; public class AtoI { public static int atoi(String input) { long result = 0l; char flag = '+'; char[] inputDigitArray = input.toCharArray(); int idx = 0; if (inputDigitArray[idx] == '-') { flag = '-'; idx++; } else if (inputDigitArray[idx] == '+') { flag = '+'; idx++; } while (inputDigitArray.length > idx) { result = (result * 10) + (inputDigitArray[idx++] - '0'); } if (flag == '-') result = -result; if (result < Integer.MIN_VALUE) { result = Integer.MIN_VALUE; } if (result > Integer.MAX_VALUE) { result = Integer.MAX_VALUE; } return (int) result; } public static String getInput() { System.out .print("Please enter a string you want to convert in to integer :: "); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); scanner.close(); return input.trim(); } public static boolean validateInput(String input) { boolean returnValue = false; if (input.matches("^[+,-]?\\d*$") && !(input.length() < 1)) { returnValue = true; } return returnValue; } public static void main(String[] args) { System.out.println("~~~~~~~~~~~~~~~Start~~~~~~~~~~~~~~~~~~~\n"); String input = AtoI.getInput(); if (!AtoI.validateInput(input)) { System.out.println("\nNot a valid input exiting"); } else { System.out.println("\n The number coverted to integer is :: " + AtoI.atoi(input)); } System.out.println("\n~~~~~~~~~~~~~~~End~~~~~~~~~~~~~~~~~~~~~"); } }
1,599
0.571607
0.567855
61
24.245901
20.209278
74
false
false
0
0
0
0
0
0
2.278688
false
false
5
f45b7ce0d8b1b80659bc5ef85f6d7226b543542e
9,990,093,949,183
8191277f7b3e4b0baaaaf0079a0e29c3a95d8a0f
/Day01/ex01/Program.java
e8085d410999510cd5ff0fe7a7fe5ded425b17b2
[]
no_license
EnthusiasticOrange/JavaPiscine
https://github.com/EnthusiasticOrange/JavaPiscine
4f1aee1bc4a1bb94addb5a8e052c89f5b44ed594
e7405725130ddff45f6166136349591f79dd63fa
refs/heads/master
2023-07-17T19:52:48.965000
2021-09-04T17:23:23
2021-09-04T17:23:23
398,918,721
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Program { public static void printUser(User user) { System.out.println("User:"); System.out.printf("\tID: %d\n", user.getId()); System.out.printf("\tName: %s\n", user.getName()); System.out.printf("\tBalance: %d\n", user.getBalance()); System.out.println(); } public static void main(String[] args) { User bob = new User("Bob", 200); User mike = new User("Mike", 300); printUser(bob); printUser(mike); System.out.println("===== Generate Users in a loop ====="); for (int i = 0; i < 3; ++i) { User u = new User("Name " + i, i * 1000); printUser(u); } } }
UTF-8
Java
714
java
Program.java
Java
[ { "context": "ain(String[] args) {\n User bob = new User(\"Bob\", 200);\n\n User mike = new User(\"Mike\", 300", "end": 407, "score": 0.9984999299049377, "start": 404, "tag": "NAME", "value": "Bob" }, { "context": " User(\"Bob\", 200);\n\n User mike = new User(\"Mike\", 300);\n\n printUser(bob);\n printUse", "end": 451, "score": 0.9994117617607117, "start": 447, "tag": "NAME", "value": "Mike" } ]
null
[]
public class Program { public static void printUser(User user) { System.out.println("User:"); System.out.printf("\tID: %d\n", user.getId()); System.out.printf("\tName: %s\n", user.getName()); System.out.printf("\tBalance: %d\n", user.getBalance()); System.out.println(); } public static void main(String[] args) { User bob = new User("Bob", 200); User mike = new User("Mike", 300); printUser(bob); printUser(mike); System.out.println("===== Generate Users in a loop ====="); for (int i = 0; i < 3; ++i) { User u = new User("Name " + i, i * 1000); printUser(u); } } }
714
0.509804
0.492997
24
28.791666
22.246683
67
false
false
0
0
0
0
0
0
0.833333
false
false
5
c4ebfac5636af6ee3c480cf04e8d99d3ce3a43bf
12,352,325,961,232
f83e1d1e8a9ef81c4622a66e1136ee31892aa3be
/ExeAbst/trianguloEquilatero.java
a18078196d86cf40529edaf7ce7f1ae1b32dc704
[]
no_license
MarcioJrios/Programacao-1
https://github.com/MarcioJrios/Programacao-1
c2a6f9a955b3e34a7834c9f2e6187f6542535098
13ca82563b87021cdaa54654533fc0962e8ac484
refs/heads/master
2021-01-21T12:15:20.714000
2018-05-24T17:38:34
2018-05-24T17:38:34
102,053,768
0
2
null
false
2017-09-28T23:45:39
2017-08-31T23:23:04
2017-08-31T23:25:24
2017-09-28T23:45:22
4
0
1
1
Java
null
null
public class TEquilatero extends Triangulo{ @override public double area(){ this.area = (area*altura)/2; } }
UTF-8
Java
119
java
trianguloEquilatero.java
Java
[]
null
[]
public class TEquilatero extends Triangulo{ @override public double area(){ this.area = (area*altura)/2; } }
119
0.680672
0.672269
6
18.833334
15.301598
43
false
false
0
0
0
0
0
0
0.166667
false
false
5
5e39a2fa1264801176e7be4651307e7b2a4590c5
19,550,691,147,292
8570e5fe4dfa5999830d1f03d3bb2423fbb3d204
/src/main/java/dev/juho/ffmpegrender/events/events/RenderProgressEvent.java
08873d2cb298fdee100fe6c5bafa904d8ad53f7f
[]
no_license
juhodev/multiple-computer-ffmpeg-render
https://github.com/juhodev/multiple-computer-ffmpeg-render
04063bce1b254c7a2c5fde0772837b447081ac11
eef384f02426b736e127c90d7e90989b6af92770
refs/heads/master
2020-08-07T01:36:13.408000
2020-02-16T20:23:33
2020-02-16T20:23:33
213,244,021
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dev.juho.ffmpegrender.events.events; import dev.juho.ffmpegrender.events.Event; import dev.juho.ffmpegrender.events.EventType; public class RenderProgressEvent implements Event<EventType, Double> { private double progress; private boolean cancelled; public RenderProgressEvent(double progress) { this.progress = progress; this.cancelled = false; } @Override public EventType getType() { return EventType.RENDER_PROGRESS; } @Override public Double getData() { return progress; } @Override public boolean isCancelled() { return cancelled; } @Override public void cancel() { cancelled = true; } }
UTF-8
Java
638
java
RenderProgressEvent.java
Java
[]
null
[]
package dev.juho.ffmpegrender.events.events; import dev.juho.ffmpegrender.events.Event; import dev.juho.ffmpegrender.events.EventType; public class RenderProgressEvent implements Event<EventType, Double> { private double progress; private boolean cancelled; public RenderProgressEvent(double progress) { this.progress = progress; this.cancelled = false; } @Override public EventType getType() { return EventType.RENDER_PROGRESS; } @Override public Double getData() { return progress; } @Override public boolean isCancelled() { return cancelled; } @Override public void cancel() { cancelled = true; } }
638
0.750784
0.750784
35
17.228571
17.606956
70
false
false
0
0
0
0
0
0
1.142857
false
false
5
90908f67291f83bc76e40677de6393e41a4a4dc5
24,215,025,631,763
8be409348510fc4e07c0346d1153c1e4e1897e31
/ETS_Review/src/test2/inheritance/q63/q63.java
bb20cbba6345bb83805059609db392fb9afec6a5
[]
no_license
BuffaloBorn/OCA
https://github.com/BuffaloBorn/OCA
73317064fe4c3f84a0df5ff1e1ec3044602f635b
8840bcfcbfea4bcfe108a6b2b1b41adbc2c3c44d
refs/heads/master
2020-07-29T11:28:06.186000
2017-04-03T21:59:34
2017-04-03T21:59:34
73,670,414
0
0
null
true
2016-11-14T05:37:55
2016-11-14T05:37:54
2015-08-09T15:57:32
2015-08-25T15:59:29
176
0
0
0
null
null
null
package test2.inheritance.q63; //Given the following definitions and reference declarations: interface I1 { } interface I2 { } class C1 implements I1 { } class C2 implements I2 { } class C3 extends C1 implements I2 { } // Which of these statements are legal? class C4 extends C3 implements I1, I2 { } /* * Although, the implements I1, I2 is redundant here because C3 already * implements I1 and I2, it is not invalid. */ public class q63 { public static void main(String[] args) { C1 o1; C2 o2; C3 o3 = null; // o3 = o1; // superclass reference cannot be assigned to subclass reference without explicit cast. // notice that o1->c1 can not be assigned to o3->c3 // o3 = o2; // There is no way a reference of class C2 (which is o2) can point to an object of // class C3 because C2 and C3 have no inheritance relationship. // So this assignment is rejected at compile time itself. I1 i1 = o3; I2 i2 = (I2) i1; // This is valid because at run time i1 actually refers to an object that implements I2. I1 b = o3; // Because C3 extends C1 which implements I1. } }
UTF-8
Java
1,146
java
q63.java
Java
[]
null
[]
package test2.inheritance.q63; //Given the following definitions and reference declarations: interface I1 { } interface I2 { } class C1 implements I1 { } class C2 implements I2 { } class C3 extends C1 implements I2 { } // Which of these statements are legal? class C4 extends C3 implements I1, I2 { } /* * Although, the implements I1, I2 is redundant here because C3 already * implements I1 and I2, it is not invalid. */ public class q63 { public static void main(String[] args) { C1 o1; C2 o2; C3 o3 = null; // o3 = o1; // superclass reference cannot be assigned to subclass reference without explicit cast. // notice that o1->c1 can not be assigned to o3->c3 // o3 = o2; // There is no way a reference of class C2 (which is o2) can point to an object of // class C3 because C2 and C3 have no inheritance relationship. // So this assignment is rejected at compile time itself. I1 i1 = o3; I2 i2 = (I2) i1; // This is valid because at run time i1 actually refers to an object that implements I2. I1 b = o3; // Because C3 extends C1 which implements I1. } }
1,146
0.670157
0.621291
44
24.045454
26.80142
89
false
false
0
0
0
0
0
0
0.886364
false
false
5
90a4166d4a4844b7be74a915d52c375bce0925c6
7,593,502,200,914
4cdfe6eafbbb539c756a4adfb5fc4d2b40a852bc
/src/main/java/com/n/stu/Employee.java
0953af65e8e26e2f406327cadc485205a7167c42
[]
no_license
tyuya7411/20210309java
https://github.com/tyuya7411/20210309java
e99a904e58ddd283f32f1b0297db0358a78fd336
5e9e72b69874f93e2caa13e0a7b3ec1a37d55a31
refs/heads/master
2023-05-11T09:14:14.764000
2021-06-01T13:57:17
2021-06-01T13:57:17
352,932,636
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.n.stu; public class Employee { }
UTF-8
Java
46
java
Employee.java
Java
[]
null
[]
package com.n.stu; public class Employee { }
46
0.717391
0.717391
4
10.5
10.161201
23
false
false
0
0
0
0
0
0
0.25
false
false
5
74a4432a8c019f3e2e75d5d5793cae343264e080
9,534,827,418,011
ad2c32be89712d598dfcd9ac3d3bffe718da697d
/Module_5/Hometask_5_3_Marine_Yegoryan_ATM2017Q2/BDD_5.3/src/test/java/builder/User.java
68bf3473c257d4e5c80fc8a43c1c71fcbb452c22
[]
no_license
Marine84/AutomationTrainings
https://github.com/Marine84/AutomationTrainings
446c602c5e82efef608de4443b0c3480d5c65ee9
004e59434786e575751620876bbfc72f78232bea
refs/heads/master
2021-01-25T05:10:15.701000
2017-09-08T13:55:52
2017-09-08T13:55:52
93,509,499
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package builder; public class User { private final String userName; private final String pass; //Constructor for Decorator pattern usage public User(String user, String pass) { this.userName = user; this.pass = pass; } //Constructor for Builder pattern usage public User(UserBuilder builder) { this.userName = builder.userName; this.pass = builder.pass; } public String getUsername() { return userName; } public String getPassword() { return pass; } // Nested class has created to perform Builder pattern method public static class UserBuilder { private final String userName; private final String pass; public UserBuilder(String userName, String pass) { this.userName = userName; this.pass = pass; } public User build() { return new User(this); } } }
UTF-8
Java
953
java
User.java
Java
[ { "context": "tring user, String pass) {\n this.userName = user;\n this.pass = pass;\n }\n\n //Construct", "end": 223, "score": 0.9936313629150391, "start": 219, "tag": "USERNAME", "value": "user" }, { "context": "uilder builder) {\n this.userName = builder.userName;\n this.pass = builder.pass;\n }\n\n pub", "end": 381, "score": 0.9270583391189575, "start": 373, "tag": "USERNAME", "value": "userName" }, { "context": "\n\n public String getUsername() {\n return userName;\n }\n\n public String getPassword() {\n ", "end": 481, "score": 0.9928820133209229, "start": 473, "tag": "USERNAME", "value": "userName" }, { "context": "erName, String pass) {\n this.userName = userName;\n this.pass = pass;\n }\n\n ", "end": 826, "score": 0.997524082660675, "start": 818, "tag": "USERNAME", "value": "userName" }, { "context": " this.userName = userName;\n this.pass = pass;\n }\n\n public User build() {\n ", "end": 856, "score": 0.6735835075378418, "start": 852, "tag": "PASSWORD", "value": "pass" } ]
null
[]
package builder; public class User { private final String userName; private final String pass; //Constructor for Decorator pattern usage public User(String user, String pass) { this.userName = user; this.pass = pass; } //Constructor for Builder pattern usage public User(UserBuilder builder) { this.userName = builder.userName; this.pass = builder.pass; } public String getUsername() { return userName; } public String getPassword() { return pass; } // Nested class has created to perform Builder pattern method public static class UserBuilder { private final String userName; private final String pass; public UserBuilder(String userName, String pass) { this.userName = userName; this.pass = <PASSWORD>; } public User build() { return new User(this); } } }
959
0.606506
0.606506
42
21.690475
17.94368
65
false
false
0
0
0
0
0
0
0.380952
false
false
5
09b329d3184e504dcea7a678899a1ad74cd0983f
12,635,793,836,668
3e1b42cf5657b0f807cb5495c217574448cd660a
/java_console/ui/src/com/rusefi/ui/widgets/EtbTestSequence.java
d7055f83a60ce310c8e4e0966d735f5ff635b8b2
[]
no_license
aldalbert/rusefi
https://github.com/aldalbert/rusefi
79a6aed292a92a4f8d7c6156f3af47a79866c894
8d924a2f49a2d4907f39ccd67bbb67af40ae24df
refs/heads/master
2020-05-07T12:43:40.939000
2019-04-10T03:17:09
2019-04-10T03:17:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rusefi.ui.widgets; import com.rusefi.FileLog; import com.rusefi.TimeBasedBuffer; import com.rusefi.core.MessagesCentral; import com.rusefi.core.Sensor; import com.rusefi.core.SensorCentral; import com.rusefi.io.CommandQueue; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Here we initiate a sequence of commands which would change target electronic throttle position so that we can * see how far the result would be how soon. * <p> * Error standard deviation is posted to {@link Sensor#ETB_CONTROL_QUALITY} * <p> * https://github.com/rusefi/rusefi/issues/494 * <p> * 11/16/2017 * (c) Andrey Belomutskiy * * @see TimeBasedBuffer */ public class EtbTestSequence { protected static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); protected final static ClosedLoopControlQualityMetric metric = createMetric(); @NotNull protected static ClosedLoopControlQualityMetric createMetric() { return new ClosedLoopControlQualityMetric( SensorCentral.getInstance().getValueSource(Sensor.PPS), SensorCentral.getInstance().getValueSource(Sensor.TPS), Sensor.ETB_CONTROL_QUALITY ); } private final static long SECOND = 1000; private final JButton button = new JButton("ETB Test"); protected static SequenceStep addSequence(SequenceStep first_step) { return first_step.addNext(new SequenceStep(SECOND) { @Override protected void doJob() { metric.reset(); } }) .addNext(10 * SECOND, 4 /*position*/) .addNext(5 * SECOND, 6 /*position*/) .addNext(5 * SECOND, 8 /*position*/) .addNext(5 * SECOND, 6 /*position*/) .addNext(5 * SECOND, 4 /*position*/) .addNext(5 * SECOND, 2 /*position*/) .addNext(5 * SECOND, 0 /*position*/) .addNext(5 * SECOND, 10 /*position*/) .addNext(3 * SECOND, 0 /*position*/) .addNext(1 * SECOND, 6 /*position*/) .addNext(1 * SECOND, 8 /*position*/) .addNext(1 * SECOND, 6 /*position*/) .addNext(1 * SECOND, 4 /*position*/) .addNext(1 * SECOND, 2 /*position*/) .addNext(1 * SECOND, 0 /*position*/) .addNext(1 * SECOND, 10 /*position*/) .addNext(3 * SECOND, 7 /*position*/) .addNext(3 * SECOND, 6 /*position*/) .addNext(3 * SECOND, 5 /*position*/) .addNext(3 * SECOND, 4 /*position*/) .addNext(3 * SECOND, 3 /*position*/) .addNext(3 * SECOND, 2 /*position*/) .addNext(3 * SECOND, 1 /*position*/) .addNext(3 * SECOND, 0 /*position*/) .addNext(10 * SECOND, 6 /*position*/) .addNext(10 * SECOND, 30 /*position*/) .addNext(10 * SECOND, 50 /*position*/) .addNext(10 * SECOND, 70 /*position*/) .addNext(10 * SECOND, 95 /*position*/) .addNext(10 * SECOND, 50 /*position*/) .addNext(10 * SECOND, 70 /*position*/) .addNext(10 * SECOND, 4 /*position*/) .addNext(10 * SECOND, 0 /*position*/) ; } public EtbTestSequence() { button.addActionListener(e -> { // 3000 data points at 10Hz should be 300 seconds worth of data metric.start(/* buffer size: */3000, /*period, ms: */ 100); SequenceStep firstStep = new EtbTarget(10 * SECOND, 4 /*position*/); addSequence(firstStep); firstStep.execute(executor); }); } public JButton getButton() { return button; } static abstract class SequenceStep { final long duration; SequenceStep next; public SequenceStep(long duration) { this.duration = duration; } public void execute(ScheduledExecutorService executor) { doJob(); if (next != null) { FileLog.MAIN.logLine("Scheduling " + next + " with " + duration + "ms delay"); executor.schedule(() -> next.execute(executor), duration, TimeUnit.MILLISECONDS); } else { MessagesCentral.getInstance().postMessage(EtbTestSequence.class, "ETB test sequence done!"); } } protected abstract void doJob(); public SequenceStep addNext(long duration, double position) { return addNext(new EtbTarget(duration, position)); } public SequenceStep addNext(SequenceStep step) { next = step; return next; } } static class EtbTarget extends SequenceStep { /** * 0-100 percent open */ final double position; public EtbTarget(long duration, double position) { super(duration); this.position = position; } protected void doJob() { CommandQueue.getInstance().write("set mock_pedal_position " + position); } @Override public String toString() { return "EtbTarget{" + "duration=" + duration + ", position=" + position + '}'; } } }
UTF-8
Java
5,577
java
EtbTestSequence.java
Java
[ { "context": "ETB_CONTROL_QUALITY}\n * <p>\n * https://github.com/rusefi/rusefi/issues/494\n * <p>\n * 11/16/2017\n * (c) And", "end": 715, "score": 0.8145756721496582, "start": 709, "tag": "USERNAME", "value": "rusefi" }, { "context": "sefi/rusefi/issues/494\n * <p>\n * 11/16/2017\n * (c) Andrey Belomutskiy\n *\n * @see TimeBasedBuffer\n */\npublic class EtbTe", "end": 780, "score": 0.9998086094856262, "start": 762, "tag": "NAME", "value": "Andrey Belomutskiy" } ]
null
[]
package com.rusefi.ui.widgets; import com.rusefi.FileLog; import com.rusefi.TimeBasedBuffer; import com.rusefi.core.MessagesCentral; import com.rusefi.core.Sensor; import com.rusefi.core.SensorCentral; import com.rusefi.io.CommandQueue; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Here we initiate a sequence of commands which would change target electronic throttle position so that we can * see how far the result would be how soon. * <p> * Error standard deviation is posted to {@link Sensor#ETB_CONTROL_QUALITY} * <p> * https://github.com/rusefi/rusefi/issues/494 * <p> * 11/16/2017 * (c) <NAME> * * @see TimeBasedBuffer */ public class EtbTestSequence { protected static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); protected final static ClosedLoopControlQualityMetric metric = createMetric(); @NotNull protected static ClosedLoopControlQualityMetric createMetric() { return new ClosedLoopControlQualityMetric( SensorCentral.getInstance().getValueSource(Sensor.PPS), SensorCentral.getInstance().getValueSource(Sensor.TPS), Sensor.ETB_CONTROL_QUALITY ); } private final static long SECOND = 1000; private final JButton button = new JButton("ETB Test"); protected static SequenceStep addSequence(SequenceStep first_step) { return first_step.addNext(new SequenceStep(SECOND) { @Override protected void doJob() { metric.reset(); } }) .addNext(10 * SECOND, 4 /*position*/) .addNext(5 * SECOND, 6 /*position*/) .addNext(5 * SECOND, 8 /*position*/) .addNext(5 * SECOND, 6 /*position*/) .addNext(5 * SECOND, 4 /*position*/) .addNext(5 * SECOND, 2 /*position*/) .addNext(5 * SECOND, 0 /*position*/) .addNext(5 * SECOND, 10 /*position*/) .addNext(3 * SECOND, 0 /*position*/) .addNext(1 * SECOND, 6 /*position*/) .addNext(1 * SECOND, 8 /*position*/) .addNext(1 * SECOND, 6 /*position*/) .addNext(1 * SECOND, 4 /*position*/) .addNext(1 * SECOND, 2 /*position*/) .addNext(1 * SECOND, 0 /*position*/) .addNext(1 * SECOND, 10 /*position*/) .addNext(3 * SECOND, 7 /*position*/) .addNext(3 * SECOND, 6 /*position*/) .addNext(3 * SECOND, 5 /*position*/) .addNext(3 * SECOND, 4 /*position*/) .addNext(3 * SECOND, 3 /*position*/) .addNext(3 * SECOND, 2 /*position*/) .addNext(3 * SECOND, 1 /*position*/) .addNext(3 * SECOND, 0 /*position*/) .addNext(10 * SECOND, 6 /*position*/) .addNext(10 * SECOND, 30 /*position*/) .addNext(10 * SECOND, 50 /*position*/) .addNext(10 * SECOND, 70 /*position*/) .addNext(10 * SECOND, 95 /*position*/) .addNext(10 * SECOND, 50 /*position*/) .addNext(10 * SECOND, 70 /*position*/) .addNext(10 * SECOND, 4 /*position*/) .addNext(10 * SECOND, 0 /*position*/) ; } public EtbTestSequence() { button.addActionListener(e -> { // 3000 data points at 10Hz should be 300 seconds worth of data metric.start(/* buffer size: */3000, /*period, ms: */ 100); SequenceStep firstStep = new EtbTarget(10 * SECOND, 4 /*position*/); addSequence(firstStep); firstStep.execute(executor); }); } public JButton getButton() { return button; } static abstract class SequenceStep { final long duration; SequenceStep next; public SequenceStep(long duration) { this.duration = duration; } public void execute(ScheduledExecutorService executor) { doJob(); if (next != null) { FileLog.MAIN.logLine("Scheduling " + next + " with " + duration + "ms delay"); executor.schedule(() -> next.execute(executor), duration, TimeUnit.MILLISECONDS); } else { MessagesCentral.getInstance().postMessage(EtbTestSequence.class, "ETB test sequence done!"); } } protected abstract void doJob(); public SequenceStep addNext(long duration, double position) { return addNext(new EtbTarget(duration, position)); } public SequenceStep addNext(SequenceStep step) { next = step; return next; } } static class EtbTarget extends SequenceStep { /** * 0-100 percent open */ final double position; public EtbTarget(long duration, double position) { super(duration); this.position = position; } protected void doJob() { CommandQueue.getInstance().write("set mock_pedal_position " + position); } @Override public String toString() { return "EtbTarget{" + "duration=" + duration + ", position=" + position + '}'; } } }
5,565
0.560696
0.53882
159
34.07547
26.082006
112
false
false
0
0
0
0
0
0
0.540881
false
false
5
add1fee846c22f9660ae156c128081456d77872d
12,635,793,839,717
b6da12c2ac6f4459939d928668cd980a32ccc626
/src/main/java/pers/linus/behavior/memento/Client.java
9646bab5669289a6cc0889a1adba68d4923bd9bc
[]
no_license
ZexinPeng/DesignPattern
https://github.com/ZexinPeng/DesignPattern
3e874ee1de77db860fff2ecb941c79d60a9a0419
ba5cdb582cd5767e5c5d672c4fd2600ca2420c3e
refs/heads/master
2022-11-12T07:00:25.158000
2020-07-06T09:21:23
2020-07-06T09:21:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.java.pers.linus.behavior.memento; /** * 备忘录模式(Memento) * 适用:当必须保存一个对象在某个时刻的部分状态,并且在之后的某个时刻需要恢复它时可以使用备忘录模式。 * 关键点:Originator封装Memento来获得状态,所有状态全部保存在careTaker中 */ public class Client { public static void main(String[] args) { Originator originator = new Originator("State 0"); CareTaker careTaker = new CareTaker(); careTaker.saveMemento(originator.saveToMemento()); originator.setState("State 1"); careTaker.saveMemento(originator.saveToMemento()); originator.setState("State 2"); careTaker.saveMemento(originator.saveToMemento()); System.out.println(originator.getStateFromMemento(careTaker.getMemento(0))); System.out.println(originator.getStateFromMemento(careTaker.getMemento(1))); System.out.println(originator.getCurrentState()); } }
UTF-8
Java
1,003
java
Client.java
Java
[]
null
[]
package main.java.pers.linus.behavior.memento; /** * 备忘录模式(Memento) * 适用:当必须保存一个对象在某个时刻的部分状态,并且在之后的某个时刻需要恢复它时可以使用备忘录模式。 * 关键点:Originator封装Memento来获得状态,所有状态全部保存在careTaker中 */ public class Client { public static void main(String[] args) { Originator originator = new Originator("State 0"); CareTaker careTaker = new CareTaker(); careTaker.saveMemento(originator.saveToMemento()); originator.setState("State 1"); careTaker.saveMemento(originator.saveToMemento()); originator.setState("State 2"); careTaker.saveMemento(originator.saveToMemento()); System.out.println(originator.getStateFromMemento(careTaker.getMemento(0))); System.out.println(originator.getStateFromMemento(careTaker.getMemento(1))); System.out.println(originator.getCurrentState()); } }
1,003
0.716647
0.710744
23
35.826088
26.85331
84
false
false
0
0
0
0
0
0
0.478261
false
false
5
042afcabc60f457c7b8cdce5eacb4870323325bb
12,412,455,528,131
b37c8799ba3b270ccbf8489d226cdc32d1c5b4dc
/ModeVonMorgen/src/MainPackage/GUIKontoVerwalten.java
3a0dfab0a08718b1c4533b1087796fc288330d94
[]
no_license
LucasHnz/ModeVonMorgenSWP
https://github.com/LucasHnz/ModeVonMorgenSWP
6b0d785615a16de0ae86e9d1f50e82e4e059a375
7bbf44e60c5dffd467b13d3bef28aecce7cf5520
refs/heads/master
2021-05-15T03:47:21.550000
2017-12-07T08:16:54
2017-12-07T08:16:54
112,632,946
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package MainPackage; import java.awt.Color; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.awt.SystemColor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class GUIKontoVerwalten implements ActionListener{ JButton btnZurück = new JButton(); public JComboBox comboBoxHerren = new JComboBox(); public JComboBox comboBoxDamen = new JComboBox(); public JComboBox comboBoxAnmelden = new JComboBox(); public String[] damenCbList; public String[] herrenCbList; public String[] anmeldenCbList; private JFrame frame; private JTextField textFieldKontoVorname; private JTextField textFieldKontoName; private JTextField textFieldKontoEmail; private JTextField textFieldKontoStraße; private JTextField textFieldKontoPlz; private JTextField textFieldKontoOrt; private JTextField textFieldIBAN; public String testName = "Küster"; public String testVorname = "Jochen"; public String testEmail = "jochen.kuester@fh-bielefeld.de"; public String testStraße = "Softwarestraße"; public String testPLZ = "4711"; public String testOrt = "MainbORT"; public String testIBAN = "DE 1234 5678 9"; /** * Create the application. */ public GUIKontoVerwalten(String[]damenCbList, String[]herrenCbList, String[]anmeldenCbList) { this.damenCbList = damenCbList; this.herrenCbList = herrenCbList; this.anmeldenCbList = anmeldenCbList; initialize(damenCbList, herrenCbList, anmeldenCbList); } /** * Initialize the contents of the frame. */ private void initialize(String[]damenCbList, String[]herrenCbList, String[]anmeldenCbList) { frame = new JFrame(); frame.setBounds(20, 20, 1250, 750); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JPanel panelLogo = new JPanel(); panelLogo.setBackground(Color.WHITE); panelLogo.setBounds(0, 0, 1234, 99); frame.getContentPane().add(panelLogo); panelLogo.setLayout(null); JLabel labelLogo = new JLabel("New label"); labelLogo.setBounds(56, 0, 1226, 99); labelLogo.setIcon(new ImageIcon("C:\\Users\\hinzl\\Desktop\\SWP-Bilder\\modeLogo.jpg")); panelLogo.add(labelLogo); JPanel panelBar = new JPanel(); panelBar.setBackground(SystemColor.control); panelBar.setBounds(0, 98, 1234, 50); frame.getContentPane().add(panelBar); panelBar.setLayout(null); comboBoxDamen = new JComboBox(damenCbList); comboBoxDamen.setFont(new Font("Lucida Bright", Font.BOLD, 15)); comboBoxDamen.setBackground(SystemColor.control); comboBoxDamen.setBounds(10, 0, 250, 50); comboBoxDamen.addActionListener(this); panelBar.add(comboBoxDamen); comboBoxHerren = new JComboBox(herrenCbList); comboBoxHerren.setFont(new Font("Lucida Bright", Font.BOLD, 15)); comboBoxHerren.setBackground(SystemColor.control); comboBoxHerren.setBounds(270, 0, 250, 50); comboBoxHerren.addActionListener(this); panelBar.add(comboBoxHerren); comboBoxAnmelden = new JComboBox(anmeldenCbList); comboBoxAnmelden.setBounds(1040, 0, 173, 50); comboBoxAnmelden.setFont(new Font("Lucida Bright", Font.BOLD, 15)); comboBoxAnmelden.setBackground(SystemColor.control); comboBoxAnmelden.addActionListener(this); panelBar.add(comboBoxAnmelden); JPanel panelMain = new JPanel(); panelMain.setBackground(Color.WHITE); panelMain.setBounds(0, 148, 1234, 563); frame.getContentPane().add(panelMain); panelMain.setLayout(null); btnZurück = new JButton("Zur\u00FCck"); btnZurück.setFont(new Font("Lucida Bright", Font.BOLD, 15)); btnZurück.setBackground(Color.WHITE); btnZurück.setBounds(10, 11, 89, 35); btnZurück.addActionListener(this); panelMain.add(btnZurück); JPanel panelKontoverwaltung = new JPanel(); panelKontoverwaltung.setBackground(SystemColor.control); JScrollPane scrollPaneKontoVerwalten = new JScrollPane(panelKontoverwaltung); scrollPaneKontoVerwalten.setBounds(206, 103, 590, 433); panelMain.add(scrollPaneKontoVerwalten); panelKontoverwaltung.setLayout(null); JLabel lblVorname = new JLabel("Vorname:"); lblVorname.setBounds(0, 0, 0, 0); panelKontoverwaltung.add(lblVorname); JLabel lblVorname_1 = new JLabel("Vorname:"); lblVorname_1.setBounds(60, 35, 90, 28); lblVorname_1.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblVorname_1); JLabel lblName = new JLabel("Name:"); lblName.setBounds(60, 88, 71, 28); lblName.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblName); JLabel lblEmail = new JLabel("E-Mail:"); lblEmail.setBounds(60, 143, 71, 28); lblEmail.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblEmail); JLabel lblStrae = new JLabel("Stra\u00DFe:"); lblStrae.setBounds(60, 201, 71, 28); lblStrae.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblStrae); JLabel lblPlz = new JLabel("PLZ:"); lblPlz.setBounds(60, 254, 71, 28); lblPlz.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblPlz); JLabel lblOrt = new JLabel("Ort:"); lblOrt.setBounds(60, 305, 71, 28); lblOrt.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblOrt); JLabel lblIban = new JLabel("IBAN:"); lblIban.setBounds(60, 359, 71, 28); lblIban.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblIban); textFieldKontoVorname = new JTextField(testVorname); textFieldKontoVorname.setBounds(205, 33, 164, 28); panelKontoverwaltung.add(textFieldKontoVorname); textFieldKontoVorname.setColumns(10); textFieldKontoName = new JTextField(testName); textFieldKontoName.setBounds(205, 94, 164, 28); textFieldKontoName.setColumns(10); panelKontoverwaltung.add(textFieldKontoName); textFieldKontoEmail = new JTextField(testEmail); textFieldKontoEmail.setBounds(205, 149, 164, 28); textFieldKontoEmail.setColumns(10); panelKontoverwaltung.add(textFieldKontoEmail); textFieldKontoStraße = new JTextField(testStraße); textFieldKontoStraße.setBounds(205, 201, 164, 28); textFieldKontoStraße.setColumns(10); panelKontoverwaltung.add(textFieldKontoStraße); textFieldKontoPlz = new JTextField(testPLZ); textFieldKontoPlz.setBounds(205, 256, 164, 28); textFieldKontoPlz.setColumns(10); panelKontoverwaltung.add(textFieldKontoPlz); textFieldKontoOrt = new JTextField(testOrt); textFieldKontoOrt.setBounds(205, 305, 164, 28); textFieldKontoOrt.setColumns(10); panelKontoverwaltung.add(textFieldKontoOrt); textFieldIBAN = new JTextField(testIBAN); textFieldIBAN.setBounds(205, 359, 164, 28); textFieldIBAN.setColumns(10); panelKontoverwaltung.add(textFieldIBAN); JButton btnNewButton = new JButton("New button"); btnNewButton.setBounds(379, 35, 33, 23); panelKontoverwaltung.add(btnNewButton); JButton button = new JButton("New button"); button.setBounds(379, 93, 33, 23); panelKontoverwaltung.add(button); JButton button_1 = new JButton("New button"); button_1.setBounds(379, 148, 33, 23); panelKontoverwaltung.add(button_1); JButton button_2 = new JButton("New button"); button_2.setBounds(379, 201, 33, 23); panelKontoverwaltung.add(button_2); JButton button_3 = new JButton("New button"); button_3.setBounds(379, 254, 33, 23); panelKontoverwaltung.add(button_3); JButton button_4 = new JButton("New button"); button_4.setBounds(379, 308, 33, 23); panelKontoverwaltung.add(button_4); JButton button_5 = new JButton("New button"); button_5.setBounds(379, 359, 33, 23); panelKontoverwaltung.add(button_5); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == btnZurück) { frame.dispose(); new GUI(); } if(e.getSource() == comboBoxHerren){ String auswahl = (String) comboBoxHerren.getSelectedItem(); if(auswahl == "Kleidung"){ frame.dispose(); new GUIHerrenKleidung(damenCbList, herrenCbList, anmeldenCbList); } if(auswahl == "Schuhe"){ frame.dispose(); new GUIHerrenSchuhe(damenCbList, herrenCbList, anmeldenCbList); } if(auswahl == "Accessoires"){ frame.dispose(); new GUIHerrenAccessoires(damenCbList, herrenCbList, anmeldenCbList); } } if(e.getSource() == comboBoxDamen){ String auswahl = (String) comboBoxDamen.getSelectedItem(); if(auswahl == "Kleidung"){ frame.dispose(); new GUIDamenKleidung(damenCbList, herrenCbList, anmeldenCbList); } if(auswahl == "Schuhe"){ frame.dispose(); new GUIDamenSchuhe(damenCbList, herrenCbList, anmeldenCbList); } if(auswahl == "Accessoires"){ frame.dispose(); new GUIDamenAccessoires(damenCbList, herrenCbList, anmeldenCbList); } } if (e.getSource() == comboBoxAnmelden) { String auswahl = (String) comboBoxAnmelden.getSelectedItem(); if(auswahl == "Anmelden") { new GUIAnmelden(); } if(auswahl == "Meine Bestellungen") { new GUIKontoBestellungen(damenCbList, herrenCbList, anmeldenCbList); } if(auswahl == "Konto verwalten") { new GUIKontoVerwalten(damenCbList, herrenCbList, anmeldenCbList); } } } }
ISO-8859-1
Java
9,736
java
GUIKontoVerwalten.java
Java
[ { "context": "eld textFieldIBAN;\r\n\t\r\n\tpublic String testName = \"Küster\";\r\n\tpublic String testVorname = \"Jochen\";\r\n\tpubli", "end": 965, "score": 0.9998101592063904, "start": 959, "tag": "NAME", "value": "Küster" }, { "context": "stName = \"Küster\";\r\n\tpublic String testVorname = \"Jochen\";\r\n\tpublic String testEmail = \"jochen.kuester@fh-", "end": 1005, "score": 0.9997994303703308, "start": 999, "tag": "NAME", "value": "Jochen" }, { "context": "tVorname = \"Jochen\";\r\n\tpublic String testEmail = \"jochen.kuester@fh-bielefeld.de\";\r\n\tpublic String testStraße = \"Softwarestraße\";\r", "end": 1067, "score": 0.999828040599823, "start": 1037, "tag": "EMAIL", "value": "jochen.kuester@fh-bielefeld.de" }, { "context": ");\r\n\t\tlabelLogo.setIcon(new ImageIcon(\"C:\\\\Users\\\\hinzl\\\\Desktop\\\\SWP-Bilder\\\\modeLogo.jpg\"));\r\n\t\tpanelLo", "end": 2270, "score": 0.9992077350616455, "start": 2265, "tag": "USERNAME", "value": "hinzl" } ]
null
[]
package MainPackage; import java.awt.Color; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.awt.SystemColor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class GUIKontoVerwalten implements ActionListener{ JButton btnZurück = new JButton(); public JComboBox comboBoxHerren = new JComboBox(); public JComboBox comboBoxDamen = new JComboBox(); public JComboBox comboBoxAnmelden = new JComboBox(); public String[] damenCbList; public String[] herrenCbList; public String[] anmeldenCbList; private JFrame frame; private JTextField textFieldKontoVorname; private JTextField textFieldKontoName; private JTextField textFieldKontoEmail; private JTextField textFieldKontoStraße; private JTextField textFieldKontoPlz; private JTextField textFieldKontoOrt; private JTextField textFieldIBAN; public String testName = "Küster"; public String testVorname = "Jochen"; public String testEmail = "<EMAIL>"; public String testStraße = "Softwarestraße"; public String testPLZ = "4711"; public String testOrt = "MainbORT"; public String testIBAN = "DE 1234 5678 9"; /** * Create the application. */ public GUIKontoVerwalten(String[]damenCbList, String[]herrenCbList, String[]anmeldenCbList) { this.damenCbList = damenCbList; this.herrenCbList = herrenCbList; this.anmeldenCbList = anmeldenCbList; initialize(damenCbList, herrenCbList, anmeldenCbList); } /** * Initialize the contents of the frame. */ private void initialize(String[]damenCbList, String[]herrenCbList, String[]anmeldenCbList) { frame = new JFrame(); frame.setBounds(20, 20, 1250, 750); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JPanel panelLogo = new JPanel(); panelLogo.setBackground(Color.WHITE); panelLogo.setBounds(0, 0, 1234, 99); frame.getContentPane().add(panelLogo); panelLogo.setLayout(null); JLabel labelLogo = new JLabel("New label"); labelLogo.setBounds(56, 0, 1226, 99); labelLogo.setIcon(new ImageIcon("C:\\Users\\hinzl\\Desktop\\SWP-Bilder\\modeLogo.jpg")); panelLogo.add(labelLogo); JPanel panelBar = new JPanel(); panelBar.setBackground(SystemColor.control); panelBar.setBounds(0, 98, 1234, 50); frame.getContentPane().add(panelBar); panelBar.setLayout(null); comboBoxDamen = new JComboBox(damenCbList); comboBoxDamen.setFont(new Font("Lucida Bright", Font.BOLD, 15)); comboBoxDamen.setBackground(SystemColor.control); comboBoxDamen.setBounds(10, 0, 250, 50); comboBoxDamen.addActionListener(this); panelBar.add(comboBoxDamen); comboBoxHerren = new JComboBox(herrenCbList); comboBoxHerren.setFont(new Font("Lucida Bright", Font.BOLD, 15)); comboBoxHerren.setBackground(SystemColor.control); comboBoxHerren.setBounds(270, 0, 250, 50); comboBoxHerren.addActionListener(this); panelBar.add(comboBoxHerren); comboBoxAnmelden = new JComboBox(anmeldenCbList); comboBoxAnmelden.setBounds(1040, 0, 173, 50); comboBoxAnmelden.setFont(new Font("Lucida Bright", Font.BOLD, 15)); comboBoxAnmelden.setBackground(SystemColor.control); comboBoxAnmelden.addActionListener(this); panelBar.add(comboBoxAnmelden); JPanel panelMain = new JPanel(); panelMain.setBackground(Color.WHITE); panelMain.setBounds(0, 148, 1234, 563); frame.getContentPane().add(panelMain); panelMain.setLayout(null); btnZurück = new JButton("Zur\u00FCck"); btnZurück.setFont(new Font("Lucida Bright", Font.BOLD, 15)); btnZurück.setBackground(Color.WHITE); btnZurück.setBounds(10, 11, 89, 35); btnZurück.addActionListener(this); panelMain.add(btnZurück); JPanel panelKontoverwaltung = new JPanel(); panelKontoverwaltung.setBackground(SystemColor.control); JScrollPane scrollPaneKontoVerwalten = new JScrollPane(panelKontoverwaltung); scrollPaneKontoVerwalten.setBounds(206, 103, 590, 433); panelMain.add(scrollPaneKontoVerwalten); panelKontoverwaltung.setLayout(null); JLabel lblVorname = new JLabel("Vorname:"); lblVorname.setBounds(0, 0, 0, 0); panelKontoverwaltung.add(lblVorname); JLabel lblVorname_1 = new JLabel("Vorname:"); lblVorname_1.setBounds(60, 35, 90, 28); lblVorname_1.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblVorname_1); JLabel lblName = new JLabel("Name:"); lblName.setBounds(60, 88, 71, 28); lblName.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblName); JLabel lblEmail = new JLabel("E-Mail:"); lblEmail.setBounds(60, 143, 71, 28); lblEmail.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblEmail); JLabel lblStrae = new JLabel("Stra\u00DFe:"); lblStrae.setBounds(60, 201, 71, 28); lblStrae.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblStrae); JLabel lblPlz = new JLabel("PLZ:"); lblPlz.setBounds(60, 254, 71, 28); lblPlz.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblPlz); JLabel lblOrt = new JLabel("Ort:"); lblOrt.setBounds(60, 305, 71, 28); lblOrt.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblOrt); JLabel lblIban = new JLabel("IBAN:"); lblIban.setBounds(60, 359, 71, 28); lblIban.setFont(new Font("Lucida Bright", Font.BOLD, 15)); panelKontoverwaltung.add(lblIban); textFieldKontoVorname = new JTextField(testVorname); textFieldKontoVorname.setBounds(205, 33, 164, 28); panelKontoverwaltung.add(textFieldKontoVorname); textFieldKontoVorname.setColumns(10); textFieldKontoName = new JTextField(testName); textFieldKontoName.setBounds(205, 94, 164, 28); textFieldKontoName.setColumns(10); panelKontoverwaltung.add(textFieldKontoName); textFieldKontoEmail = new JTextField(testEmail); textFieldKontoEmail.setBounds(205, 149, 164, 28); textFieldKontoEmail.setColumns(10); panelKontoverwaltung.add(textFieldKontoEmail); textFieldKontoStraße = new JTextField(testStraße); textFieldKontoStraße.setBounds(205, 201, 164, 28); textFieldKontoStraße.setColumns(10); panelKontoverwaltung.add(textFieldKontoStraße); textFieldKontoPlz = new JTextField(testPLZ); textFieldKontoPlz.setBounds(205, 256, 164, 28); textFieldKontoPlz.setColumns(10); panelKontoverwaltung.add(textFieldKontoPlz); textFieldKontoOrt = new JTextField(testOrt); textFieldKontoOrt.setBounds(205, 305, 164, 28); textFieldKontoOrt.setColumns(10); panelKontoverwaltung.add(textFieldKontoOrt); textFieldIBAN = new JTextField(testIBAN); textFieldIBAN.setBounds(205, 359, 164, 28); textFieldIBAN.setColumns(10); panelKontoverwaltung.add(textFieldIBAN); JButton btnNewButton = new JButton("New button"); btnNewButton.setBounds(379, 35, 33, 23); panelKontoverwaltung.add(btnNewButton); JButton button = new JButton("New button"); button.setBounds(379, 93, 33, 23); panelKontoverwaltung.add(button); JButton button_1 = new JButton("New button"); button_1.setBounds(379, 148, 33, 23); panelKontoverwaltung.add(button_1); JButton button_2 = new JButton("New button"); button_2.setBounds(379, 201, 33, 23); panelKontoverwaltung.add(button_2); JButton button_3 = new JButton("New button"); button_3.setBounds(379, 254, 33, 23); panelKontoverwaltung.add(button_3); JButton button_4 = new JButton("New button"); button_4.setBounds(379, 308, 33, 23); panelKontoverwaltung.add(button_4); JButton button_5 = new JButton("New button"); button_5.setBounds(379, 359, 33, 23); panelKontoverwaltung.add(button_5); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == btnZurück) { frame.dispose(); new GUI(); } if(e.getSource() == comboBoxHerren){ String auswahl = (String) comboBoxHerren.getSelectedItem(); if(auswahl == "Kleidung"){ frame.dispose(); new GUIHerrenKleidung(damenCbList, herrenCbList, anmeldenCbList); } if(auswahl == "Schuhe"){ frame.dispose(); new GUIHerrenSchuhe(damenCbList, herrenCbList, anmeldenCbList); } if(auswahl == "Accessoires"){ frame.dispose(); new GUIHerrenAccessoires(damenCbList, herrenCbList, anmeldenCbList); } } if(e.getSource() == comboBoxDamen){ String auswahl = (String) comboBoxDamen.getSelectedItem(); if(auswahl == "Kleidung"){ frame.dispose(); new GUIDamenKleidung(damenCbList, herrenCbList, anmeldenCbList); } if(auswahl == "Schuhe"){ frame.dispose(); new GUIDamenSchuhe(damenCbList, herrenCbList, anmeldenCbList); } if(auswahl == "Accessoires"){ frame.dispose(); new GUIDamenAccessoires(damenCbList, herrenCbList, anmeldenCbList); } } if (e.getSource() == comboBoxAnmelden) { String auswahl = (String) comboBoxAnmelden.getSelectedItem(); if(auswahl == "Anmelden") { new GUIAnmelden(); } if(auswahl == "Meine Bestellungen") { new GUIKontoBestellungen(damenCbList, herrenCbList, anmeldenCbList); } if(auswahl == "Konto verwalten") { new GUIKontoVerwalten(damenCbList, herrenCbList, anmeldenCbList); } } } }
9,713
0.703879
0.665295
298
30.614094
21.363474
94
false
false
0
0
0
0
0
0
3.083893
false
false
5
3a1ad0b7048a9cacc1a51c5fcd33bfa59b12036c
20,126,216,792,591
570b1ea0d00c98809b374ce7da557b250c06bbbf
/src/main/java/com/taskmgmt/controller/LoginController.java
5943e78d0342da222357df33bef8eebf848e59a7
[]
no_license
nithyancse/taskmgmt-springboot
https://github.com/nithyancse/taskmgmt-springboot
51b58b14232511b4fe3aeaf42feadb39e96faf90
1409b5cc82ba1cbc730e743b1ed7f6380b48e1c6
refs/heads/master
2020-03-17T14:59:47.502000
2018-06-10T20:51:45
2018-06-10T20:51:45
133,694,271
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.taskmgmt.controller; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.taskmgmt.domain.Company; import com.taskmgmt.domain.CustError; import com.taskmgmt.domain.User; import com.taskmgmt.domain.wrapper.UserCompanyWrap; import com.taskmgmt.service.inter.ICompanyService; import com.taskmgmt.service.inter.IMessageByLocaleService; import com.taskmgmt.service.inter.IUserService; import com.taskmgmt.util.Utils; @RestController @RequestMapping("/") public class LoginController { Logger logger = LoggerFactory.getLogger(LoginController.class); @Autowired private IUserService iUserService; @Autowired private ICompanyService iCompanyService; @Autowired private UserCompanyWrap userCompanyWrap; @Autowired IMessageByLocaleService messageLocale; @PostMapping("login") public ResponseEntity<?> validateLogin(@RequestParam(value = "emailId") String emailId, @RequestParam(value = "password") String password) { String errorMsg = null; Long userId = 0L; Company company = null; User user = null; /*errorMsg = messageLocale.getMessage("welcome.message"); errorMsg = messageLocale.getMessage("welcome.message", Locale.US);*/ if (!Utils.isEmpty(emailId) && !Utils.isEmpty(password)) { userId = iUserService.validateUser(emailId, password); if (userId == 0) { errorMsg = "Incorrect Username and Password :( "; logger.info("Authendication failed --> emailId:" + emailId + ", password: " + password); } } else { errorMsg = "Username and Password should not be Empty"; } if (!Utils.isEmpty(errorMsg)) { CustError error = new CustError(errorMsg); if (error != null) { return ResponseEntity.badRequest().body(error); } } user = iUserService.fetchUserDetail(userId); if (user.getCompanyId() != 0) { company = iCompanyService.getCompanyDetails(user.getCompanyId()); } userCompanyWrap.setUser(user); userCompanyWrap.setCompany(company); return new ResponseEntity<UserCompanyWrap>(userCompanyWrap, HttpStatus.OK); } }
UTF-8
Java
2,517
java
LoginController.java
Java
[]
null
[]
package com.taskmgmt.controller; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.taskmgmt.domain.Company; import com.taskmgmt.domain.CustError; import com.taskmgmt.domain.User; import com.taskmgmt.domain.wrapper.UserCompanyWrap; import com.taskmgmt.service.inter.ICompanyService; import com.taskmgmt.service.inter.IMessageByLocaleService; import com.taskmgmt.service.inter.IUserService; import com.taskmgmt.util.Utils; @RestController @RequestMapping("/") public class LoginController { Logger logger = LoggerFactory.getLogger(LoginController.class); @Autowired private IUserService iUserService; @Autowired private ICompanyService iCompanyService; @Autowired private UserCompanyWrap userCompanyWrap; @Autowired IMessageByLocaleService messageLocale; @PostMapping("login") public ResponseEntity<?> validateLogin(@RequestParam(value = "emailId") String emailId, @RequestParam(value = "password") String password) { String errorMsg = null; Long userId = 0L; Company company = null; User user = null; /*errorMsg = messageLocale.getMessage("welcome.message"); errorMsg = messageLocale.getMessage("welcome.message", Locale.US);*/ if (!Utils.isEmpty(emailId) && !Utils.isEmpty(password)) { userId = iUserService.validateUser(emailId, password); if (userId == 0) { errorMsg = "Incorrect Username and Password :( "; logger.info("Authendication failed --> emailId:" + emailId + ", password: " + password); } } else { errorMsg = "Username and Password should not be Empty"; } if (!Utils.isEmpty(errorMsg)) { CustError error = new CustError(errorMsg); if (error != null) { return ResponseEntity.badRequest().body(error); } } user = iUserService.fetchUserDetail(userId); if (user.getCompanyId() != 0) { company = iCompanyService.getCompanyDetails(user.getCompanyId()); } userCompanyWrap.setUser(user); userCompanyWrap.setCompany(company); return new ResponseEntity<UserCompanyWrap>(userCompanyWrap, HttpStatus.OK); } }
2,517
0.770362
0.768375
82
29.695122
24.816738
92
false
false
0
0
0
0
0
0
1.634146
false
false
5
b8104fe926eadb4b1819f1f797ceaaf2ba779741
32,392,643,401,853
a5e0521dcde8833e99afbb94dc965ed0482b12f8
/pokemoncore/src/main/java/aiki/game/fight/animations/AnimationInt.java
9f5292da67eff51458cc98c9f93a387870ac9f25
[]
no_license
Cardman/util
https://github.com/Cardman/util
79b4058b574eb02e4ab4a5d3b20005f78258c75d
738de94c8369391daec861762a55fd91a76dbe05
refs/heads/master
2020-05-23T01:15:08.932000
2020-05-20T16:15:50
2020-05-20T16:15:50
34,724,613
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package aiki.game.fight.animations; public interface AnimationInt { }
UTF-8
Java
72
java
AnimationInt.java
Java
[]
null
[]
package aiki.game.fight.animations; public interface AnimationInt { }
72
0.791667
0.791667
5
13.4
16.057398
35
false
false
0
0
0
0
0
0
0.2
false
false
5
8fca65cdad1a6ffce53648dc06c8ff436f160e5c
21,827,023,834,213
e0cfa4222f3e40c841e3eb40c2ef11bfa122645c
/src/clps_sms/dao/DaoFactory.java
b80b79443e3fcf8c13d2615f2077fb6bf54e6d7d
[]
no_license
LeoHYS/myRepository
https://github.com/LeoHYS/myRepository
583ca28c571a1007ccd87be66a8978904c1f5d4a
dc9caf3e9d3c9fbaac8243c6b4ca7e771bf19ad3
refs/heads/master
2021-01-18T16:56:46.396000
2017-08-16T14:03:48
2017-08-16T14:03:48
100,476,285
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * All rights Reserved, Designed By Android_Robot * @Title: DaoFactory.java * @Package clps_sms.dao * @Description: TODO(用一句话描述该文件做什么) * @author: Android_Robot * @date: Aug 16, 2017 9:54:44 PM * @version V1.0 */ package clps_sms.dao; /** * @ClassName: DaoFactory * @Description:TODO(这里用一句话描述这个类的作用) * @author: Android_Robot * @date: Aug 16, 2017 9:54:44 PM * */ import clps_sms.dao.impl.AccountDaoImpl; import clps_sms.dao.impl.MenuDaoImpl; import clps_sms.dao.impl.RoleDaoImpl; public class DaoFactory { public AccountDao getAccountDaoInstance() { return new AccountDaoImpl(); } public RoleDao getRoleDaoInstance() { return new RoleDaoImpl(); } public MenuDao getMenuDaoInstance() { return new MenuDaoImpl(); } }
UTF-8
Java
914
java
DaoFactory.java
Java
[ { "context": "Description: TODO(用一句话描述该文件做什么) \r\n * @author: Android_Robot \r\n * @date: Aug 16, 2017 9:54:44 PM \r\n * ", "end": 193, "score": 0.9996551871299744, "start": 180, "tag": "USERNAME", "value": "Android_Robot" }, { "context": " @Description:TODO(这里用一句话描述这个类的作用) \r\n * @author: Android_Robot \r\n * @date: Aug 16, 2017 9:54:44 PM \r\n * ", "end": 407, "score": 0.9996517300605774, "start": 394, "tag": "USERNAME", "value": "Android_Robot" } ]
null
[]
/** * All rights Reserved, Designed By Android_Robot * @Title: DaoFactory.java * @Package clps_sms.dao * @Description: TODO(用一句话描述该文件做什么) * @author: Android_Robot * @date: Aug 16, 2017 9:54:44 PM * @version V1.0 */ package clps_sms.dao; /** * @ClassName: DaoFactory * @Description:TODO(这里用一句话描述这个类的作用) * @author: Android_Robot * @date: Aug 16, 2017 9:54:44 PM * */ import clps_sms.dao.impl.AccountDaoImpl; import clps_sms.dao.impl.MenuDaoImpl; import clps_sms.dao.impl.RoleDaoImpl; public class DaoFactory { public AccountDao getAccountDaoInstance() { return new AccountDaoImpl(); } public RoleDao getRoleDaoInstance() { return new RoleDaoImpl(); } public MenuDao getMenuDaoInstance() { return new MenuDaoImpl(); } }
914
0.617169
0.589327
38
20.552631
16.391104
52
false
false
0
0
0
0
0
0
0.684211
false
false
5
5760ef8d6dfe18ea90a9bd78b09608186b632fd6
21,827,023,833,134
235e61db2c364d432bc6dec0866fe7a6b00d945f
/app/src/main/java/com/example/wings/startactivity/fragments/RegisterOneFragment.java
26fa2d727c16e355fe66e564465198b73270719d
[]
no_license
NSLJ/Wings
https://github.com/NSLJ/Wings
aacfc9379e0f571813c5c03db8f8dfca58f280c9
98749f6e5e794b75ec4260d19cdb3f072f58433a
refs/heads/master
2023-05-24T04:38:44.186000
2021-06-12T21:35:17
2021-06-12T21:35:17
351,955,942
0
4
null
false
2021-06-12T21:35:18
2021-03-27T01:39:47
2021-06-12T16:38:49
2021-06-12T21:35:17
74,596
0
3
13
Java
false
false
package com.example.wings.startactivity.fragments; import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.wings.R; import com.example.wings.models.User; import com.example.wings.startactivity.SAFragmentsListener; import com.parse.ParseException; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.ArrayList; import java.util.List; /** * RegisterOneFragment.java * Purpose: This displays the first screen of registering a new user/creating an account! * * Hello Coders! Here is a good sample of how the interface works with the Fragments! Please read through the documentation and let me know if you have any questions or comments on how we could be * implementing this better! * */ public class RegisterOneFragment extends Fragment { public static final String TAG = "RegisterOneFragment"; private SAFragmentsListener listener; private List<ParseUser> currUsers; //To error check if new user is already a user private Button signUpBtn; private TextView tvToLogin; private EditText etFName; private EditText etLName; private EditText etEmail; public RegisterOneFragment() {} // Required empty public constructor @Override /** * Purpose: Called automatically. When this Fragment is being attached to the parent activity, REQUIRE the activity to implement SAFragmentsListener. Otherwise throw an exception! * Connect the Fragment's listener to the activity! */ public void onAttach(@NonNull Context context) { super.onAttach(context); if (context instanceof SAFragmentsListener) { listener = (SAFragmentsListener) context; } else { throw new ClassCastException(context.toString() + " must implement SAFragmentsListener"); } } @Override /** * Purpose: Called automatically when creating Fragment instance. To inflate a corresponding layout file "fragment_register_one.xml" */ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_register_one, container, false); } @Override /** * Purpose: Called automatically when creating a Fragment instance, after onCreateView(). Ensures root View is not null. Sets up all Views and event handlers here. */ public void onViewCreated(View view, Bundle savedInstanceState) { currUsers = new ArrayList<ParseUser>(); //1.) Get references to Views: signUpBtn = view.findViewById(R.id.signUpBtn); tvToLogin = view.findViewById(R.id.tvToLogin); etFName = view.findViewById(R.id.etFName); etLName = view.findViewById(R.id.etLName); etEmail= view.findViewById(R.id.etEmail); //2.) Set on click listeners: //2a.) clickable login link --> back to Login page tvToLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.toLoginFragment(); } }); //2b.) signUpBtn --> check user inputs and attempt to register User: signUpBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, ": sign up button clicked!"); if(etEmail != null && etFName != null && etLName != null) { String email = etEmail.getText().toString(); //Check if email and username is valid: String errorString = null; try { errorString = isValid(email); } catch (InterruptedException e) { e.printStackTrace(); } // If no error string --> user's info is valid! // Create a user and send to RegisterTwoFragment: if (errorString.equals("")) { User user = new User(); user.setFirstName(etFName.getText().toString()); user.setLastName(etLName.getText().toString()); user.setEmail(email); user.setUsername(email.substring(0, email.length() - 8)); user.setProfileSetUp(false); //ensure flag on --> show this user has not set up profile listener.toRegisterTwoFragment(user); } else { showLongTopToast(errorString); } } else{ showLongTopToast("You did not fill in all of the fields!"); } } }); } /** * Purpose: Determines if the given email and username. If not, the method returns the corresponding error String to display. If valid, the String will be empty. * @param email * @return */ private String isValid(String email) throws InterruptedException { Log.d(TAG, "in isValid()"); String result = ""; //2.) Check if email ends with "@cpp.edu": if(email.length() > 8) { String lastChars = email.substring(email.length() - 8, email.length()); if (!(lastChars.equals("@cpp.edu"))) { result += "Your email does not end with \"@cpp.edu\""; } //otherwise --> email is valid, we can check if the username is unique! i.e. this email has not already been registered else{ String username = email.substring(0, email.length()-8); Log.d(TAG, "Checking if username=" + username + " is valid! Querying for all existing users"); result += queryUsernames(); boolean validUsername = validUsername(username); Log.d(TAG, "validUsername = "+validUsername); if(!validUsername) { result += "This username/email is already registered!"; } } } else{ //if email wasn't even long enough: result += "Your email does not end with \"@cpp.edu\""; } return result; } /** * Purpose; Obtains a list of all current users and updates the "currUsers" List field. Returns an error string if error occurs, and "" if not */ private String queryUsernames(){ Log.d(TAG, "in queryUsernames() "); ParseQuery<ParseUser> query = ParseUser.getQuery(); //To get all users: try { currUsers.addAll(query.find()); Log.i(TAG, "queryUsernames(): -users: " + currUsers.toString()); return ""; } catch (ParseException e) { Log.e(TAG, "queryUsernames(): failure: error=", e); return "Your session is expired! Please try again."; } } /** * Purpose: Returns whether the given username is in the List of current users. (returns whether the given username is unique/valid) * @param username, the username to test uniqueness for * @return whether or not the username is unique/valid */ private boolean validUsername(String username) { Log.d(TAG, "in validUsername(" + username + ")"); Log.d(TAG, "validUsername(): currUsers = " + currUsers.toString()); for(ParseUser user: currUsers) { if(user.getUsername().equalsIgnoreCase(username)){ return false; } } return true; } private void showLongTopToast(String message){ Toast toast = Toast.makeText(getContext(), message, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP, 0, 0); toast.show(); } }
UTF-8
Java
8,295
java
RegisterOneFragment.java
Java
[]
null
[]
package com.example.wings.startactivity.fragments; import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.wings.R; import com.example.wings.models.User; import com.example.wings.startactivity.SAFragmentsListener; import com.parse.ParseException; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.ArrayList; import java.util.List; /** * RegisterOneFragment.java * Purpose: This displays the first screen of registering a new user/creating an account! * * Hello Coders! Here is a good sample of how the interface works with the Fragments! Please read through the documentation and let me know if you have any questions or comments on how we could be * implementing this better! * */ public class RegisterOneFragment extends Fragment { public static final String TAG = "RegisterOneFragment"; private SAFragmentsListener listener; private List<ParseUser> currUsers; //To error check if new user is already a user private Button signUpBtn; private TextView tvToLogin; private EditText etFName; private EditText etLName; private EditText etEmail; public RegisterOneFragment() {} // Required empty public constructor @Override /** * Purpose: Called automatically. When this Fragment is being attached to the parent activity, REQUIRE the activity to implement SAFragmentsListener. Otherwise throw an exception! * Connect the Fragment's listener to the activity! */ public void onAttach(@NonNull Context context) { super.onAttach(context); if (context instanceof SAFragmentsListener) { listener = (SAFragmentsListener) context; } else { throw new ClassCastException(context.toString() + " must implement SAFragmentsListener"); } } @Override /** * Purpose: Called automatically when creating Fragment instance. To inflate a corresponding layout file "fragment_register_one.xml" */ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_register_one, container, false); } @Override /** * Purpose: Called automatically when creating a Fragment instance, after onCreateView(). Ensures root View is not null. Sets up all Views and event handlers here. */ public void onViewCreated(View view, Bundle savedInstanceState) { currUsers = new ArrayList<ParseUser>(); //1.) Get references to Views: signUpBtn = view.findViewById(R.id.signUpBtn); tvToLogin = view.findViewById(R.id.tvToLogin); etFName = view.findViewById(R.id.etFName); etLName = view.findViewById(R.id.etLName); etEmail= view.findViewById(R.id.etEmail); //2.) Set on click listeners: //2a.) clickable login link --> back to Login page tvToLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.toLoginFragment(); } }); //2b.) signUpBtn --> check user inputs and attempt to register User: signUpBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, ": sign up button clicked!"); if(etEmail != null && etFName != null && etLName != null) { String email = etEmail.getText().toString(); //Check if email and username is valid: String errorString = null; try { errorString = isValid(email); } catch (InterruptedException e) { e.printStackTrace(); } // If no error string --> user's info is valid! // Create a user and send to RegisterTwoFragment: if (errorString.equals("")) { User user = new User(); user.setFirstName(etFName.getText().toString()); user.setLastName(etLName.getText().toString()); user.setEmail(email); user.setUsername(email.substring(0, email.length() - 8)); user.setProfileSetUp(false); //ensure flag on --> show this user has not set up profile listener.toRegisterTwoFragment(user); } else { showLongTopToast(errorString); } } else{ showLongTopToast("You did not fill in all of the fields!"); } } }); } /** * Purpose: Determines if the given email and username. If not, the method returns the corresponding error String to display. If valid, the String will be empty. * @param email * @return */ private String isValid(String email) throws InterruptedException { Log.d(TAG, "in isValid()"); String result = ""; //2.) Check if email ends with "@cpp.edu": if(email.length() > 8) { String lastChars = email.substring(email.length() - 8, email.length()); if (!(lastChars.equals("@cpp.edu"))) { result += "Your email does not end with \"@cpp.edu\""; } //otherwise --> email is valid, we can check if the username is unique! i.e. this email has not already been registered else{ String username = email.substring(0, email.length()-8); Log.d(TAG, "Checking if username=" + username + " is valid! Querying for all existing users"); result += queryUsernames(); boolean validUsername = validUsername(username); Log.d(TAG, "validUsername = "+validUsername); if(!validUsername) { result += "This username/email is already registered!"; } } } else{ //if email wasn't even long enough: result += "Your email does not end with \"@cpp.edu\""; } return result; } /** * Purpose; Obtains a list of all current users and updates the "currUsers" List field. Returns an error string if error occurs, and "" if not */ private String queryUsernames(){ Log.d(TAG, "in queryUsernames() "); ParseQuery<ParseUser> query = ParseUser.getQuery(); //To get all users: try { currUsers.addAll(query.find()); Log.i(TAG, "queryUsernames(): -users: " + currUsers.toString()); return ""; } catch (ParseException e) { Log.e(TAG, "queryUsernames(): failure: error=", e); return "Your session is expired! Please try again."; } } /** * Purpose: Returns whether the given username is in the List of current users. (returns whether the given username is unique/valid) * @param username, the username to test uniqueness for * @return whether or not the username is unique/valid */ private boolean validUsername(String username) { Log.d(TAG, "in validUsername(" + username + ")"); Log.d(TAG, "validUsername(): currUsers = " + currUsers.toString()); for(ParseUser user: currUsers) { if(user.getUsername().equalsIgnoreCase(username)){ return false; } } return true; } private void showLongTopToast(String message){ Toast toast = Toast.makeText(getContext(), message, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP, 0, 0); toast.show(); } }
8,295
0.600241
0.598674
211
38.317535
36.503571
196
false
false
0
0
0
0
0
0
0.535545
false
false
5
98d219d82d75d62503f40b20e21b5af48b2bf68a
32,633,161,560,093
521258495e4a060c1c24e1cd4a4faea4a37e3c4e
/src/Others/Power.java
3ea683c1242a4e0fdea3410c075c60a36a24c3c0
[]
no_license
nikhilesh1702/DataStructurePrograms
https://github.com/nikhilesh1702/DataStructurePrograms
d623256524601d95330e1029e2ddb322991f731e
ef580e3dc42ae2146bc757029b6880438f32efbe
refs/heads/master
2020-06-03T22:52:46.976000
2015-03-12T05:43:42
2015-03-12T05:43:42
32,059,317
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Others; public class Power { public static double power(double a, int b) { // Base case with 0 exponent if (b == 0) return 1; // Negative exponent if (b < 0) { assert a != 0; // Negative exponent for base 0 is not allowed return 1. / power(a, -b); } // General case of positive exponent double half = power(a, b / 2); return half * half * ( (b % 2 == 1) ? a : 1 ); } public static void main(String[] args) { System.out.println("result "+ power(0,-2)); } }
UTF-8
Java
483
java
Power.java
Java
[]
null
[]
package Others; public class Power { public static double power(double a, int b) { // Base case with 0 exponent if (b == 0) return 1; // Negative exponent if (b < 0) { assert a != 0; // Negative exponent for base 0 is not allowed return 1. / power(a, -b); } // General case of positive exponent double half = power(a, b / 2); return half * half * ( (b % 2 == 1) ? a : 1 ); } public static void main(String[] args) { System.out.println("result "+ power(0,-2)); } }
483
0.616977
0.590062
24
19.125
18.820007
63
false
false
0
0
0
0
0
0
1
false
false
5
0e614537a61349e0eeb52044a00b8d4238367b6d
9,947,144,314,128
3c61fb5c8768f4b50893e6dd6732275b819c2255
/2-java/prueba2/Lavadora.java
8acfa6450d3899d53b7198dd515ae8f886a97940
[]
no_license
cristobalgvera/fullstack-java-course-evaluations
https://github.com/cristobalgvera/fullstack-java-course-evaluations
6b43e4c76629656589fc2df106a274185f47d92a
a7da553c182f93e577e3f31840421e38da46b1ea
refs/heads/master
2022-11-16T14:46:49.233000
2020-07-15T12:54:42
2020-07-15T12:54:42
279,744,551
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package prueba2; public class Lavadora extends Electrodoméstico { private double carga; // Constructor "vacío" por defecto public Lavadora() { super(); this.carga = CARGADEFECTO; } public Lavadora(double precioBase, double peso) { super(precioBase, peso); this.carga = CARGADEFECTO; } public Lavadora(double precioBase, String color, char consumoEnergético, double peso, double carga) { super(precioBase, color, consumoEnergético, peso); this.carga = carga; } public String toString() { StringBuilder builder = new StringBuilder(); // Creamos un objeto para un orden mayor builder.append("LAVADORA\n"); builder.append("\nPrecio base: \t" + getPrecioBase() + " €"); builder.append("\nColor: \t" + getColor()); builder.append("\nConsumo energético: \t" + getConsumoEnergético()); builder.append("\nPeso: \t" + getPeso() + " kg"); builder.append("\nCarga: \t" + getCarga() + " kg"); builder.append("\nPrecio final: \t" + precioFinal() + " €"); return builder.toString(); } public double getCarga() { return carga; } double precioFinal() { double precioFinal = precioFinalElectrodoméstico(); // Asignamos el valor que entrega el método de la clase // padre para luego sumar el valor adherido por la clase // hija if (getCarga() > 30) precioFinal += 50; return precioFinal; } }
WINDOWS-1252
Java
1,430
java
Lavadora.java
Java
[]
null
[]
package prueba2; public class Lavadora extends Electrodoméstico { private double carga; // Constructor "vacío" por defecto public Lavadora() { super(); this.carga = CARGADEFECTO; } public Lavadora(double precioBase, double peso) { super(precioBase, peso); this.carga = CARGADEFECTO; } public Lavadora(double precioBase, String color, char consumoEnergético, double peso, double carga) { super(precioBase, color, consumoEnergético, peso); this.carga = carga; } public String toString() { StringBuilder builder = new StringBuilder(); // Creamos un objeto para un orden mayor builder.append("LAVADORA\n"); builder.append("\nPrecio base: \t" + getPrecioBase() + " €"); builder.append("\nColor: \t" + getColor()); builder.append("\nConsumo energético: \t" + getConsumoEnergético()); builder.append("\nPeso: \t" + getPeso() + " kg"); builder.append("\nCarga: \t" + getCarga() + " kg"); builder.append("\nPrecio final: \t" + precioFinal() + " €"); return builder.toString(); } public double getCarga() { return carga; } double precioFinal() { double precioFinal = precioFinalElectrodoméstico(); // Asignamos el valor que entrega el método de la clase // padre para luego sumar el valor adherido por la clase // hija if (getCarga() > 30) precioFinal += 50; return precioFinal; } }
1,430
0.653032
0.649506
46
29.826086
29.054899
109
false
false
0
0
0
0
0
0
2.5
false
false
5
283607e9b2a6694e47d152a2077ba15a96c7d146
4,148,938,455,850
188ef15404129450a736acc5c377a704e13278fa
/src/main/java/com/phincon/talents/app/dto/UserInfoDTO.java
f72917aee53d162b3b3b8a313804c75397e66b20
[]
no_license
michael1234567890/Talents
https://github.com/michael1234567890/Talents
6b0f649fe04f69132dae26f8e48ce3272488fecf
c4b29e39e9c68cb789f7c54163e2bd5d4019c2ae
refs/heads/master
2021-01-20T02:38:04.346000
2018-03-07T08:56:35
2018-03-07T08:56:35
89,433,864
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.phincon.talents.app.dto; public class UserInfoDTO { private String username; private String password; private String repassword; private String companyCode; private Long company; private String email; private String firstName; private String lastName; private String fullName; private boolean isLeader; private boolean isAdmin; private String employeeExtId; private Long employeeId; public UserInfoDTO() { } public String getEmployeeExtId() { return employeeExtId; } public void setEmployeeExtId(String employeeExtId) { this.employeeExtId = employeeExtId; } 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 UserInfoDTO(String username) { this.username = username; } public String getCompanyCode() { return companyCode; } public void setCompanyCode(String companyCode) { this.companyCode = companyCode; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public String getRepassword() { return repassword; } public void setRepassword(String repassword) { this.repassword = repassword; } public Long getCompany() { return company; } public void setCompany(Long company) { this.company = company; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public boolean isLeader() { return isLeader; } public void setLeader(boolean isLeader) { this.isLeader = isLeader; } public boolean isAdmin() { return isAdmin; } public void setAdmin(boolean isAdmin) { this.isAdmin = isAdmin; } }
UTF-8
Java
2,409
java
UserInfoDTO.java
Java
[ { "context": " setUsername(String username) {\r\n\t\tthis.username = username;\r\n\t}\r\n\r\n\tpublic String getPassword() {\r\n\t\treturn ", "end": 767, "score": 0.710605263710022, "start": 759, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.phincon.talents.app.dto; public class UserInfoDTO { private String username; private String password; private String repassword; private String companyCode; private Long company; private String email; private String firstName; private String lastName; private String fullName; private boolean isLeader; private boolean isAdmin; private String employeeExtId; private Long employeeId; public UserInfoDTO() { } public String getEmployeeExtId() { return employeeExtId; } public void setEmployeeExtId(String employeeExtId) { this.employeeExtId = employeeExtId; } 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 UserInfoDTO(String username) { this.username = username; } public String getCompanyCode() { return companyCode; } public void setCompanyCode(String companyCode) { this.companyCode = companyCode; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public String getRepassword() { return repassword; } public void setRepassword(String repassword) { this.repassword = repassword; } public Long getCompany() { return company; } public void setCompany(Long company) { this.company = company; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public boolean isLeader() { return isLeader; } public void setLeader(boolean isLeader) { this.isLeader = isLeader; } public boolean isAdmin() { return isAdmin; } public void setAdmin(boolean isAdmin) { this.isAdmin = isAdmin; } }
2,409
0.676214
0.676214
147
14.387755
15.396991
53
false
false
0
0
0
0
0
0
1.176871
false
false
5
163f12060bd3c7c6873b0cdf137c435d88c01f09
26,061,861,595,240
ca030864a3a1c24be6b9d1802c2353da4ca0d441
/classes5.dex_source_from_JADX/com/facebook/graphql/model/GraphQLTaggableActivity__JsonHelper.java
d7b8be35883dc4a409d04b1fffe69f82e53b5ada
[]
no_license
pxson001/facebook-app
https://github.com/pxson001/facebook-app
87aa51e29195eeaae69adeb30219547f83a5b7b1
640630f078980f9818049625ebc42569c67c69f7
refs/heads/master
2020-04-07T20:36:45.758000
2018-03-07T09:04:57
2018-03-07T09:04:57
124,208,458
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.facebook.graphql.model; import com.facebook.debug.fieldusage.FieldAccessQueryTracker; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; /* compiled from: UNPINNED */ public final class GraphQLTaggableActivity__JsonHelper { public static GraphQLTaggableActivity m22082a(JsonParser jsonParser) { GraphQLTaggableActivity graphQLTaggableActivity = new GraphQLTaggableActivity(); if (jsonParser.g() != JsonToken.START_OBJECT) { jsonParser.f(); return null; } while (jsonParser.c() != JsonToken.END_OBJECT) { String i = jsonParser.i(); jsonParser.c(); m22084a(graphQLTaggableActivity, i, jsonParser); jsonParser.f(); } return graphQLTaggableActivity; } private static boolean m22084a(GraphQLTaggableActivity graphQLTaggableActivity, String str, JsonParser jsonParser) { String str2 = null; if ("all_icons".equals(str)) { GraphQLTaggableActivityAllIconsConnection a; if (jsonParser.g() != JsonToken.VALUE_NULL) { a = GraphQLTaggableActivityAllIconsConnection__JsonHelper.m22046a(FieldAccessQueryTracker.a(jsonParser, "all_icons")); } graphQLTaggableActivity.d = a; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "all_icons", graphQLTaggableActivity.a_, 0, true); return true; } else if ("glyph".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLImage__JsonHelper.a(FieldAccessQueryTracker.a(jsonParser, "glyph")); } graphQLTaggableActivity.e = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "glyph", graphQLTaggableActivity.B_(), 1, true); return true; } else if ("iconImageLarge".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLImage__JsonHelper.a(FieldAccessQueryTracker.a(jsonParser, "iconImageLarge")); } graphQLTaggableActivity.f = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "iconImageLarge", graphQLTaggableActivity.B_(), 2, true); return true; } else if ("id".equals(str)) { if (!(jsonParser.g() == JsonToken.VALUE_NULL || jsonParser.g() == JsonToken.VALUE_NULL)) { str2 = jsonParser.o(); } graphQLTaggableActivity.g = str2; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "id", graphQLTaggableActivity.B_(), 3, false); return true; } else if ("is_linking_verb".equals(str)) { graphQLTaggableActivity.h = jsonParser.g() == JsonToken.VALUE_NULL ? false : jsonParser.H(); FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "is_linking_verb", graphQLTaggableActivity.B_(), 4, false); return true; } else if ("legacy_api_id".equals(str)) { if (!(jsonParser.g() == JsonToken.VALUE_NULL || jsonParser.g() == JsonToken.VALUE_NULL)) { str2 = jsonParser.o(); } graphQLTaggableActivity.i = str2; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "legacy_api_id", graphQLTaggableActivity.B_(), 5, false); return true; } else if ("prefetch_priority".equals(str)) { graphQLTaggableActivity.j = jsonParser.g() == JsonToken.VALUE_NULL ? 0 : jsonParser.E(); FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "prefetch_priority", graphQLTaggableActivity.B_(), 6, false); return true; } else if ("present_participle".equals(str)) { if (!(jsonParser.g() == JsonToken.VALUE_NULL || jsonParser.g() == JsonToken.VALUE_NULL)) { str2 = jsonParser.o(); } graphQLTaggableActivity.k = str2; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "present_participle", graphQLTaggableActivity.B_(), 7, false); return true; } else if ("previewTemplateAtPlace".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateAtPlace")); } graphQLTaggableActivity.l = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateAtPlace", graphQLTaggableActivity.B_(), 8, true); return true; } else if ("previewTemplateNoTags".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateNoTags")); } graphQLTaggableActivity.m = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateNoTags", graphQLTaggableActivity.B_(), 9, true); return true; } else if ("previewTemplateWithPeople".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateWithPeople")); } graphQLTaggableActivity.n = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateWithPeople", graphQLTaggableActivity.B_(), 10, true); return true; } else if ("previewTemplateWithPeopleAtPlace".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateWithPeopleAtPlace")); } graphQLTaggableActivity.o = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateWithPeopleAtPlace", graphQLTaggableActivity.B_(), 11, true); return true; } else if ("previewTemplateWithPerson".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateWithPerson")); } graphQLTaggableActivity.p = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateWithPerson", graphQLTaggableActivity.B_(), 12, true); return true; } else if ("previewTemplateWithPersonAtPlace".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateWithPersonAtPlace")); } graphQLTaggableActivity.q = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateWithPersonAtPlace", graphQLTaggableActivity.B_(), 13, true); return true; } else if ("prompt".equals(str)) { if (!(jsonParser.g() == JsonToken.VALUE_NULL || jsonParser.g() == JsonToken.VALUE_NULL)) { str2 = jsonParser.o(); } graphQLTaggableActivity.r = str2; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "prompt", graphQLTaggableActivity.B_(), 14, false); return true; } else if ("supports_audio_suggestions".equals(str)) { graphQLTaggableActivity.s = jsonParser.g() == JsonToken.VALUE_NULL ? false : jsonParser.H(); FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "supports_audio_suggestions", graphQLTaggableActivity.B_(), 15, false); return true; } else if ("supports_freeform".equals(str)) { graphQLTaggableActivity.t = jsonParser.g() == JsonToken.VALUE_NULL ? false : jsonParser.H(); FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "supports_freeform", graphQLTaggableActivity.B_(), 16, false); return true; } else if ("supports_offline_posting".equals(str)) { graphQLTaggableActivity.u = jsonParser.g() == JsonToken.VALUE_NULL ? false : jsonParser.H(); FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "supports_offline_posting", graphQLTaggableActivity.B_(), 17, false); return true; } else if (!"url".equals(str)) { return false; } else { if (!(jsonParser.g() == JsonToken.VALUE_NULL || jsonParser.g() == JsonToken.VALUE_NULL)) { str2 = jsonParser.o(); } graphQLTaggableActivity.v = str2; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "url", graphQLTaggableActivity.B_(), 18, false); return true; } } public static void m22083a(JsonGenerator jsonGenerator, GraphQLTaggableActivity graphQLTaggableActivity, boolean z) { if (z) { jsonGenerator.f(); } if (graphQLTaggableActivity.j() != null) { jsonGenerator.a("all_icons"); GraphQLTaggableActivityAllIconsConnection__JsonHelper.m22047a(jsonGenerator, graphQLTaggableActivity.j(), true); } if (graphQLTaggableActivity.k() != null) { jsonGenerator.a("glyph"); GraphQLImage__JsonHelper.a(jsonGenerator, graphQLTaggableActivity.k(), true); } if (graphQLTaggableActivity.l() != null) { jsonGenerator.a("iconImageLarge"); GraphQLImage__JsonHelper.a(jsonGenerator, graphQLTaggableActivity.l(), true); } if (graphQLTaggableActivity.m() != null) { jsonGenerator.a("id", graphQLTaggableActivity.m()); } jsonGenerator.a("is_linking_verb", graphQLTaggableActivity.n()); if (graphQLTaggableActivity.o() != null) { jsonGenerator.a("legacy_api_id", graphQLTaggableActivity.o()); } jsonGenerator.a("prefetch_priority", graphQLTaggableActivity.p()); if (graphQLTaggableActivity.q() != null) { jsonGenerator.a("present_participle", graphQLTaggableActivity.q()); } if (graphQLTaggableActivity.r() != null) { jsonGenerator.a("previewTemplateAtPlace"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.r(), true); } if (graphQLTaggableActivity.s() != null) { jsonGenerator.a("previewTemplateNoTags"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.s(), true); } if (graphQLTaggableActivity.t() != null) { jsonGenerator.a("previewTemplateWithPeople"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.t(), true); } if (graphQLTaggableActivity.u() != null) { jsonGenerator.a("previewTemplateWithPeopleAtPlace"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.u(), true); } if (graphQLTaggableActivity.v() != null) { jsonGenerator.a("previewTemplateWithPerson"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.v(), true); } if (graphQLTaggableActivity.w() != null) { jsonGenerator.a("previewTemplateWithPersonAtPlace"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.w(), true); } if (graphQLTaggableActivity.x() != null) { jsonGenerator.a("prompt", graphQLTaggableActivity.x()); } jsonGenerator.a("supports_audio_suggestions", graphQLTaggableActivity.y()); jsonGenerator.a("supports_freeform", graphQLTaggableActivity.z()); jsonGenerator.a("supports_offline_posting", graphQLTaggableActivity.A()); if (graphQLTaggableActivity.B() != null) { jsonGenerator.a("url", graphQLTaggableActivity.B()); } if (z) { jsonGenerator.g(); } } }
UTF-8
Java
12,421
java
GraphQLTaggableActivity__JsonHelper.java
Java
[]
null
[]
package com.facebook.graphql.model; import com.facebook.debug.fieldusage.FieldAccessQueryTracker; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; /* compiled from: UNPINNED */ public final class GraphQLTaggableActivity__JsonHelper { public static GraphQLTaggableActivity m22082a(JsonParser jsonParser) { GraphQLTaggableActivity graphQLTaggableActivity = new GraphQLTaggableActivity(); if (jsonParser.g() != JsonToken.START_OBJECT) { jsonParser.f(); return null; } while (jsonParser.c() != JsonToken.END_OBJECT) { String i = jsonParser.i(); jsonParser.c(); m22084a(graphQLTaggableActivity, i, jsonParser); jsonParser.f(); } return graphQLTaggableActivity; } private static boolean m22084a(GraphQLTaggableActivity graphQLTaggableActivity, String str, JsonParser jsonParser) { String str2 = null; if ("all_icons".equals(str)) { GraphQLTaggableActivityAllIconsConnection a; if (jsonParser.g() != JsonToken.VALUE_NULL) { a = GraphQLTaggableActivityAllIconsConnection__JsonHelper.m22046a(FieldAccessQueryTracker.a(jsonParser, "all_icons")); } graphQLTaggableActivity.d = a; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "all_icons", graphQLTaggableActivity.a_, 0, true); return true; } else if ("glyph".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLImage__JsonHelper.a(FieldAccessQueryTracker.a(jsonParser, "glyph")); } graphQLTaggableActivity.e = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "glyph", graphQLTaggableActivity.B_(), 1, true); return true; } else if ("iconImageLarge".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLImage__JsonHelper.a(FieldAccessQueryTracker.a(jsonParser, "iconImageLarge")); } graphQLTaggableActivity.f = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "iconImageLarge", graphQLTaggableActivity.B_(), 2, true); return true; } else if ("id".equals(str)) { if (!(jsonParser.g() == JsonToken.VALUE_NULL || jsonParser.g() == JsonToken.VALUE_NULL)) { str2 = jsonParser.o(); } graphQLTaggableActivity.g = str2; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "id", graphQLTaggableActivity.B_(), 3, false); return true; } else if ("is_linking_verb".equals(str)) { graphQLTaggableActivity.h = jsonParser.g() == JsonToken.VALUE_NULL ? false : jsonParser.H(); FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "is_linking_verb", graphQLTaggableActivity.B_(), 4, false); return true; } else if ("legacy_api_id".equals(str)) { if (!(jsonParser.g() == JsonToken.VALUE_NULL || jsonParser.g() == JsonToken.VALUE_NULL)) { str2 = jsonParser.o(); } graphQLTaggableActivity.i = str2; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "legacy_api_id", graphQLTaggableActivity.B_(), 5, false); return true; } else if ("prefetch_priority".equals(str)) { graphQLTaggableActivity.j = jsonParser.g() == JsonToken.VALUE_NULL ? 0 : jsonParser.E(); FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "prefetch_priority", graphQLTaggableActivity.B_(), 6, false); return true; } else if ("present_participle".equals(str)) { if (!(jsonParser.g() == JsonToken.VALUE_NULL || jsonParser.g() == JsonToken.VALUE_NULL)) { str2 = jsonParser.o(); } graphQLTaggableActivity.k = str2; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "present_participle", graphQLTaggableActivity.B_(), 7, false); return true; } else if ("previewTemplateAtPlace".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateAtPlace")); } graphQLTaggableActivity.l = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateAtPlace", graphQLTaggableActivity.B_(), 8, true); return true; } else if ("previewTemplateNoTags".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateNoTags")); } graphQLTaggableActivity.m = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateNoTags", graphQLTaggableActivity.B_(), 9, true); return true; } else if ("previewTemplateWithPeople".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateWithPeople")); } graphQLTaggableActivity.n = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateWithPeople", graphQLTaggableActivity.B_(), 10, true); return true; } else if ("previewTemplateWithPeopleAtPlace".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateWithPeopleAtPlace")); } graphQLTaggableActivity.o = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateWithPeopleAtPlace", graphQLTaggableActivity.B_(), 11, true); return true; } else if ("previewTemplateWithPerson".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateWithPerson")); } graphQLTaggableActivity.p = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateWithPerson", graphQLTaggableActivity.B_(), 12, true); return true; } else if ("previewTemplateWithPersonAtPlace".equals(str)) { if (jsonParser.g() != JsonToken.VALUE_NULL) { r0 = GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22061a(FieldAccessQueryTracker.a(jsonParser, "previewTemplateWithPersonAtPlace")); } graphQLTaggableActivity.q = r0; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "previewTemplateWithPersonAtPlace", graphQLTaggableActivity.B_(), 13, true); return true; } else if ("prompt".equals(str)) { if (!(jsonParser.g() == JsonToken.VALUE_NULL || jsonParser.g() == JsonToken.VALUE_NULL)) { str2 = jsonParser.o(); } graphQLTaggableActivity.r = str2; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "prompt", graphQLTaggableActivity.B_(), 14, false); return true; } else if ("supports_audio_suggestions".equals(str)) { graphQLTaggableActivity.s = jsonParser.g() == JsonToken.VALUE_NULL ? false : jsonParser.H(); FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "supports_audio_suggestions", graphQLTaggableActivity.B_(), 15, false); return true; } else if ("supports_freeform".equals(str)) { graphQLTaggableActivity.t = jsonParser.g() == JsonToken.VALUE_NULL ? false : jsonParser.H(); FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "supports_freeform", graphQLTaggableActivity.B_(), 16, false); return true; } else if ("supports_offline_posting".equals(str)) { graphQLTaggableActivity.u = jsonParser.g() == JsonToken.VALUE_NULL ? false : jsonParser.H(); FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "supports_offline_posting", graphQLTaggableActivity.B_(), 17, false); return true; } else if (!"url".equals(str)) { return false; } else { if (!(jsonParser.g() == JsonToken.VALUE_NULL || jsonParser.g() == JsonToken.VALUE_NULL)) { str2 = jsonParser.o(); } graphQLTaggableActivity.v = str2; FieldAccessQueryTracker.a(jsonParser, graphQLTaggableActivity, "url", graphQLTaggableActivity.B_(), 18, false); return true; } } public static void m22083a(JsonGenerator jsonGenerator, GraphQLTaggableActivity graphQLTaggableActivity, boolean z) { if (z) { jsonGenerator.f(); } if (graphQLTaggableActivity.j() != null) { jsonGenerator.a("all_icons"); GraphQLTaggableActivityAllIconsConnection__JsonHelper.m22047a(jsonGenerator, graphQLTaggableActivity.j(), true); } if (graphQLTaggableActivity.k() != null) { jsonGenerator.a("glyph"); GraphQLImage__JsonHelper.a(jsonGenerator, graphQLTaggableActivity.k(), true); } if (graphQLTaggableActivity.l() != null) { jsonGenerator.a("iconImageLarge"); GraphQLImage__JsonHelper.a(jsonGenerator, graphQLTaggableActivity.l(), true); } if (graphQLTaggableActivity.m() != null) { jsonGenerator.a("id", graphQLTaggableActivity.m()); } jsonGenerator.a("is_linking_verb", graphQLTaggableActivity.n()); if (graphQLTaggableActivity.o() != null) { jsonGenerator.a("legacy_api_id", graphQLTaggableActivity.o()); } jsonGenerator.a("prefetch_priority", graphQLTaggableActivity.p()); if (graphQLTaggableActivity.q() != null) { jsonGenerator.a("present_participle", graphQLTaggableActivity.q()); } if (graphQLTaggableActivity.r() != null) { jsonGenerator.a("previewTemplateAtPlace"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.r(), true); } if (graphQLTaggableActivity.s() != null) { jsonGenerator.a("previewTemplateNoTags"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.s(), true); } if (graphQLTaggableActivity.t() != null) { jsonGenerator.a("previewTemplateWithPeople"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.t(), true); } if (graphQLTaggableActivity.u() != null) { jsonGenerator.a("previewTemplateWithPeopleAtPlace"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.u(), true); } if (graphQLTaggableActivity.v() != null) { jsonGenerator.a("previewTemplateWithPerson"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.v(), true); } if (graphQLTaggableActivity.w() != null) { jsonGenerator.a("previewTemplateWithPersonAtPlace"); GraphQLTaggableActivityPreviewTemplate__JsonHelper.m22062a(jsonGenerator, graphQLTaggableActivity.w(), true); } if (graphQLTaggableActivity.x() != null) { jsonGenerator.a("prompt", graphQLTaggableActivity.x()); } jsonGenerator.a("supports_audio_suggestions", graphQLTaggableActivity.y()); jsonGenerator.a("supports_freeform", graphQLTaggableActivity.z()); jsonGenerator.a("supports_offline_posting", graphQLTaggableActivity.A()); if (graphQLTaggableActivity.B() != null) { jsonGenerator.a("url", graphQLTaggableActivity.B()); } if (z) { jsonGenerator.g(); } } }
12,421
0.6456
0.633846
215
56.772095
42.245453
155
false
false
0
0
0
0
0
0
1.232558
false
false
5
d435dd440b7dc7fc43abd48117541cd46c3ed7ba
21,217,138,493,256
bd464b880a35000dfee6a674e4184c5e0eff49a4
/p1/adb_privalia/src/com/model/Familia.java
2591979118032d77010ccaf3cb3250a5e05babe3
[]
no_license
polo070770/ADB
https://github.com/polo070770/ADB
14d89673a26ef3474390b55065b897a9e29cf7b9
9d1a48f5bafe752d32c74366d80d67daae5b4640
refs/heads/master
2021-01-10T21:01:50.119000
2014-11-25T18:29:42
2014-11-25T18:29:42
24,838,187
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.model; import java.util.Set; public class Familia { private int id_familia; private String nom; private Set<Subfamilia> subfamilies; public Familia() { } public int getId_familia() { return id_familia; } public void setId_familia(int id_familia) { this.id_familia = id_familia; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public Set<Subfamilia> getSubfamilies() { return subfamilies; } public void setSubfamilies(Set<Subfamilia> subfamilies) { this.subfamilies = subfamilies; } }
UTF-8
Java
669
java
Familia.java
Java
[]
null
[]
package com.model; import java.util.Set; public class Familia { private int id_familia; private String nom; private Set<Subfamilia> subfamilies; public Familia() { } public int getId_familia() { return id_familia; } public void setId_familia(int id_familia) { this.id_familia = id_familia; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public Set<Subfamilia> getSubfamilies() { return subfamilies; } public void setSubfamilies(Set<Subfamilia> subfamilies) { this.subfamilies = subfamilies; } }
669
0.608371
0.608371
40
15.725
16.673313
61
false
false
0
0
0
0
0
0
0.275
false
false
5
0cc78d8964cf5993a512c07da1cb6a048a856105
21,217,138,489,572
ecdd66391f206c348dbeb3d527922bde30e49a67
/lesson_with_teacher/src/main/java/my/project/dao/PersonHibernateDao.java
dea590df97c4ece73079825a9b93f4eb5876723f
[]
no_license
iharMarkevich/learning_web_java
https://github.com/iharMarkevich/learning_web_java
bee3df5c7267f1b64e44c095ff1cfcac8ee3af9f
b72a90ddae2142094133ab98e1370b0becdc426d
refs/heads/master
2023-06-05T00:35:41.573000
2021-06-26T07:02:27
2021-06-26T07:02:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package my.project.dao; import my.project.entity.Person; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Restrictions; import org.hibernate.criterion.SimpleExpression; import java.util.List; public class PersonHibernateDao implements PersonDao { static final SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); public static void main(String[] args) { List<Person> people = new PersonHibernateDao().readAllPersons(); System.out.println(); // new PersonHibernateDao().createPerson(new Person("Sergej", 12)); // new PersonHibernateDao().createPerson(new Person("Ivan", 34)); // new PersonHibernateDao().createPerson(new Person("Sasa", 56)); // new PersonHibernateDao().createPerson(new Person("Dima", 67)); // new PersonHibernateDao().createPerson(new Person("Kolia", 68)); // new PersonHibernateDao().createPerson(new Person("Kolia", 68)); //// List<Person> people = new PersonHibernateDao().readAllPersonsByName("Ivan"); // new PersonHibernateDao().getAllPersonsWithNameAndAge("Kolia", 68); } public PersonHibernateDao() { } @Override public void createPerson(int id, String name, int age) { createPerson(new Person(id, name, age)); } @Override public void createPerson(Person person) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); try { session.save(person); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } } @Override public void updatePerson(int id, String updateName, int updateAge) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Person person = new Person(id, updateName, updateAge); try { session.update(person); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } } @Override public void deletePerson(int id) { Person person = readPersonById(id); Session session = sessionFactory.getCurrentSession(); Transaction transaction = session.beginTransaction(); try { session.delete(person); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } } @Override public List<Person> readAllPersons() { Session session = sessionFactory.openSession(); List<Person> personList = session.createQuery("from Person", Person.class).list(); return personList; } public List<Person> readAllPersonsByName(String name) { Session session = sessionFactory.openSession(); String sql = "SELECT * from person where person.name='" + name + "'"; List<Person> personList = session.createSQLQuery(sql).list(); return personList; } public List<Person> getAllPersonsWithNameAndAge(String name, int age) { Session session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(Person.class); SimpleExpression nameRestriction = Restrictions.like("name", "%"); SimpleExpression ageRestriction = Restrictions.gt("age", 65); // Criterion rest1= Restrictions.and(nameRestriction, // Restrictions.in("B", Arrays.asList("X",Y))); // Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"), // Restrictions.eq(B, "Z")); criteria.add(Restrictions.and(nameRestriction, ageRestriction)); List<Person> list = criteria.list(); return list; } @Override public Person readPersonById(int id) { Session session = sessionFactory.getCurrentSession(); Transaction transaction = session.beginTransaction(); Person person = null; try { person = session.get(Person.class, id); transaction.commit(); } catch (Exception e) { transaction.rollback(); e.printStackTrace(); } return person; } }
UTF-8
Java
4,439
java
PersonHibernateDao.java
Java
[ { "context": "new PersonHibernateDao().createPerson(new Person(\"Sergej\", 12));\n// new PersonHibernateDao().create", "end": 724, "score": 0.9996636509895325, "start": 718, "tag": "NAME", "value": "Sergej" }, { "context": "new PersonHibernateDao().createPerson(new Person(\"Ivan\", 34));\n// new PersonHibernateDao().create", "end": 797, "score": 0.9994214773178101, "start": 793, "tag": "NAME", "value": "Ivan" }, { "context": "new PersonHibernateDao().createPerson(new Person(\"Sasa\", 56));\n// new PersonHibernateDao().create", "end": 870, "score": 0.9989339113235474, "start": 866, "tag": "NAME", "value": "Sasa" }, { "context": "new PersonHibernateDao().createPerson(new Person(\"Dima\", 67));\n// new PersonHibernateDao().create", "end": 943, "score": 0.9995260238647461, "start": 939, "tag": "NAME", "value": "Dima" }, { "context": "new PersonHibernateDao().createPerson(new Person(\"Kolia\", 68));\n// new PersonHibernateDao().create", "end": 1017, "score": 0.9995646476745605, "start": 1012, "tag": "NAME", "value": "Kolia" }, { "context": "new PersonHibernateDao().createPerson(new Person(\"Kolia\", 68));\n//// List<Person> people = new Per", "end": 1091, "score": 0.9995753169059753, "start": 1086, "tag": "NAME", "value": "Kolia" }, { "context": " = new PersonHibernateDao().readAllPersonsByName(\"Ivan\");\n// new PersonHibernateDao().getAllPerso", "end": 1185, "score": 0.9992197751998901, "start": 1181, "tag": "NAME", "value": "Ivan" } ]
null
[]
package my.project.dao; import my.project.entity.Person; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Restrictions; import org.hibernate.criterion.SimpleExpression; import java.util.List; public class PersonHibernateDao implements PersonDao { static final SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); public static void main(String[] args) { List<Person> people = new PersonHibernateDao().readAllPersons(); System.out.println(); // new PersonHibernateDao().createPerson(new Person("Sergej", 12)); // new PersonHibernateDao().createPerson(new Person("Ivan", 34)); // new PersonHibernateDao().createPerson(new Person("Sasa", 56)); // new PersonHibernateDao().createPerson(new Person("Dima", 67)); // new PersonHibernateDao().createPerson(new Person("Kolia", 68)); // new PersonHibernateDao().createPerson(new Person("Kolia", 68)); //// List<Person> people = new PersonHibernateDao().readAllPersonsByName("Ivan"); // new PersonHibernateDao().getAllPersonsWithNameAndAge("Kolia", 68); } public PersonHibernateDao() { } @Override public void createPerson(int id, String name, int age) { createPerson(new Person(id, name, age)); } @Override public void createPerson(Person person) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); try { session.save(person); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } } @Override public void updatePerson(int id, String updateName, int updateAge) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Person person = new Person(id, updateName, updateAge); try { session.update(person); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } } @Override public void deletePerson(int id) { Person person = readPersonById(id); Session session = sessionFactory.getCurrentSession(); Transaction transaction = session.beginTransaction(); try { session.delete(person); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } } @Override public List<Person> readAllPersons() { Session session = sessionFactory.openSession(); List<Person> personList = session.createQuery("from Person", Person.class).list(); return personList; } public List<Person> readAllPersonsByName(String name) { Session session = sessionFactory.openSession(); String sql = "SELECT * from person where person.name='" + name + "'"; List<Person> personList = session.createSQLQuery(sql).list(); return personList; } public List<Person> getAllPersonsWithNameAndAge(String name, int age) { Session session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(Person.class); SimpleExpression nameRestriction = Restrictions.like("name", "%"); SimpleExpression ageRestriction = Restrictions.gt("age", 65); // Criterion rest1= Restrictions.and(nameRestriction, // Restrictions.in("B", Arrays.asList("X",Y))); // Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"), // Restrictions.eq(B, "Z")); criteria.add(Restrictions.and(nameRestriction, ageRestriction)); List<Person> list = criteria.list(); return list; } @Override public Person readPersonById(int id) { Session session = sessionFactory.getCurrentSession(); Transaction transaction = session.beginTransaction(); Person person = null; try { person = session.get(Person.class, id); transaction.commit(); } catch (Exception e) { transaction.rollback(); e.printStackTrace(); } return person; } }
4,439
0.640234
0.636179
130
33.146152
26.338072
103
false
false
0
0
0
0
0
0
0.715385
false
false
5
d6b5f20a69700ccf8358b71835df3e78383dcd78
5,961,414,662,733
e11531b9d6b5c1aa435c0d2700dde37d6548635e
/src/main/java/gestion/banque/repository/jdbc/JdbcBasedEmployeRepository.java
412ab70bcc7e429467a1ddf70cfb4dc49dd8a552
[]
no_license
Badoulahi8/Projet.JEE.M1GL
https://github.com/Badoulahi8/Projet.JEE.M1GL
57d4566864d4374e55e6501911521d0267fd7eb8
7c845c8085a4a346a9194e7f734bf41b096cd632
refs/heads/master
2023-03-28T02:42:53.520000
2021-03-27T10:17:16
2021-03-27T10:17:16
348,157,157
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gestion.banque.repository.jdbc; import gestion.banque.domain.Employe; import gestion.banque.repository.DataSource; import gestion.banque.repository.EmployeRepository; import java.sql.*; import java.util.ArrayList; import java.util.List; public class JdbcBasedEmployeRepository implements EmployeRepository { DataSource jdbcBasedDataSourceRepository ; EmployeRepository employeRepository; Employe employe ; public JdbcBasedEmployeRepository() { jdbcBasedDataSourceRepository = new JDBCBasedDataSourceRepository(); } @Override public Employe connection(String login, String password) { employeRepository = new JdbcBasedEmployeRepository(); String query = "SELECT * FROM employe WHERE login = ? AND password = ?"; try { Connection connection = jdbcBasedDataSourceRepository.createConnection(); PreparedStatement statement = connection.prepareStatement(query); statement.setString(1, login); statement.setString(2, password); ResultSet rs = statement.executeQuery(); while(rs.next()) { employe = new Employe(); employe.setIdEmploye(rs.getInt("idemploye")); employe.setNomEmploye(rs.getString("nomemploye")); employe.setNomEmploye(rs.getString("prenomemploye")); employe.setNomEmploye(rs.getString("login")); employe.setNomEmploye(rs.getString("password")); } } catch (Exception ex){ ex.printStackTrace(); } return employe; } @Override public List<Employe> allEmploye() { String query = "SELECT * FROM employe"; List<Employe> employes = new ArrayList<Employe>(); try { Connection connection = jdbcBasedDataSourceRepository.createConnection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(query) ; while (rs.next()) { Employe emp = new Employe(); emp.setIdEmploye(rs.getInt("idemploye")); emp.setNomEmploye(rs.getString("nomemploye")); emp.setPrenomEmploye(rs.getString("prenomemploye")); emp.setLogin(rs.getString("login")); emp.setPassword(rs.getString("password")); employes.add(emp); } return employes; } catch (SQLException e) { return null; } catch (Exception ex) { return null; } } }
UTF-8
Java
2,628
java
JdbcBasedEmployeRepository.java
Java
[]
null
[]
package gestion.banque.repository.jdbc; import gestion.banque.domain.Employe; import gestion.banque.repository.DataSource; import gestion.banque.repository.EmployeRepository; import java.sql.*; import java.util.ArrayList; import java.util.List; public class JdbcBasedEmployeRepository implements EmployeRepository { DataSource jdbcBasedDataSourceRepository ; EmployeRepository employeRepository; Employe employe ; public JdbcBasedEmployeRepository() { jdbcBasedDataSourceRepository = new JDBCBasedDataSourceRepository(); } @Override public Employe connection(String login, String password) { employeRepository = new JdbcBasedEmployeRepository(); String query = "SELECT * FROM employe WHERE login = ? AND password = ?"; try { Connection connection = jdbcBasedDataSourceRepository.createConnection(); PreparedStatement statement = connection.prepareStatement(query); statement.setString(1, login); statement.setString(2, password); ResultSet rs = statement.executeQuery(); while(rs.next()) { employe = new Employe(); employe.setIdEmploye(rs.getInt("idemploye")); employe.setNomEmploye(rs.getString("nomemploye")); employe.setNomEmploye(rs.getString("prenomemploye")); employe.setNomEmploye(rs.getString("login")); employe.setNomEmploye(rs.getString("password")); } } catch (Exception ex){ ex.printStackTrace(); } return employe; } @Override public List<Employe> allEmploye() { String query = "SELECT * FROM employe"; List<Employe> employes = new ArrayList<Employe>(); try { Connection connection = jdbcBasedDataSourceRepository.createConnection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(query) ; while (rs.next()) { Employe emp = new Employe(); emp.setIdEmploye(rs.getInt("idemploye")); emp.setNomEmploye(rs.getString("nomemploye")); emp.setPrenomEmploye(rs.getString("prenomemploye")); emp.setLogin(rs.getString("login")); emp.setPassword(rs.getString("password")); employes.add(emp); } return employes; } catch (SQLException e) { return null; } catch (Exception ex) { return null; } } }
2,628
0.613394
0.612633
72
35.5
24.399454
85
false
false
0
0
0
0
0
0
0.611111
false
false
5
8bf99c0e6d4909cc291b9fef3d0d248a76d6e235
28,587,302,372,041
449035ebc0e2eac2f87a4c872f9d6a166c89d8b1
/src/org/fanhongtao/messenger/App.java
38508e56c2de185dd2e4416f3156d4890bcf74ca
[]
no_license
fanhongtao/android-messenger
https://github.com/fanhongtao/android-messenger
d88e6c937caaefc524262252f58376666b40ef34
8e0e350548191cd007f76c376b054614bc21c2d9
refs/heads/master
2021-01-16T18:40:30.069000
2012-11-13T18:05:19
2012-11-13T18:05:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2012 Fan Hongtao (http://www.fanhongtao.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fanhongtao.messenger; import java.util.List; import org.fanhongtao.messenger.bean.Filter; import org.fanhongtao.messenger.db.FilterDatabase; import org.fanhongtao.messenger.db.SmsDbHelper; import android.app.Application; import android.database.sqlite.SQLiteDatabase; /** * * @author Fan Hongtao &ltfanhongtao@gmail.com&gt */ public class App extends Application { private static App instance; private SmsDbHelper dbHelper; @Override public void onCreate() { super.onCreate(); instance = this; dbHelper = new SmsDbHelper(this); List<Filter> filters = FilterDatabase.queryAllFilters(); if ((filters == null) || (filters.isEmpty())) { FilterDatabase.addFilter("95566", 2); FilterDatabase.addFilter("10010", 2); } } @Override public void onTerminate() { super.onTerminate(); dbHelper.close(); } public SmsDbHelper getDbHelper() { return dbHelper; } public static App getInstance() { return instance; } public static SQLiteDatabase getReadableDatabase() { return getInstance().dbHelper.getReadableDatabase(); } }
UTF-8
Java
1,833
java
App.java
Java
[ { "context": "/*\n * Copyright (C) 2012 Fan Hongtao (http://www.fanhongtao.org)\n *\n * Licensed under ", "end": 36, "score": 0.9998771548271179, "start": 25, "tag": "NAME", "value": "Fan Hongtao" }, { "context": "atabase.sqlite.SQLiteDatabase;\n\n/**\n * \n * @author Fan Hongtao &ltfanhongtao@gmail.com&gt \n */\npublic class App ", "end": 942, "score": 0.999878466129303, "start": 931, "tag": "NAME", "value": "Fan Hongtao" }, { "context": "QLiteDatabase;\n\n/**\n * \n * @author Fan Hongtao &ltfanhongtao@gmail.com&gt \n */\npublic class App extends Application {\n\n ", "end": 966, "score": 0.9998900890350342, "start": 946, "tag": "EMAIL", "value": "fanhongtao@gmail.com" } ]
null
[]
/* * Copyright (C) 2012 <NAME> (http://www.fanhongtao.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fanhongtao.messenger; import java.util.List; import org.fanhongtao.messenger.bean.Filter; import org.fanhongtao.messenger.db.FilterDatabase; import org.fanhongtao.messenger.db.SmsDbHelper; import android.app.Application; import android.database.sqlite.SQLiteDatabase; /** * * @author <NAME> &lt<EMAIL>&gt */ public class App extends Application { private static App instance; private SmsDbHelper dbHelper; @Override public void onCreate() { super.onCreate(); instance = this; dbHelper = new SmsDbHelper(this); List<Filter> filters = FilterDatabase.queryAllFilters(); if ((filters == null) || (filters.isEmpty())) { FilterDatabase.addFilter("95566", 2); FilterDatabase.addFilter("10010", 2); } } @Override public void onTerminate() { super.onTerminate(); dbHelper.close(); } public SmsDbHelper getDbHelper() { return dbHelper; } public static App getInstance() { return instance; } public static SQLiteDatabase getReadableDatabase() { return getInstance().dbHelper.getReadableDatabase(); } }
1,810
0.68467
0.673759
66
26.772728
23.763224
75
false
false
0
0
0
0
0
0
0.439394
false
false
5
b0746a1050cbc558dcd37f2cf995b6dd108fc7a5
3,186,865,798,712
8f812a486c9aa2e224fe3f7e41af1a20a4f092f2
/LibSqliteDemo/src/androidTest/java/com/lib/sqlite/demo/ByteSimpleModelTest.java
c88ddcff3376e77599808a97c8d8c661d1ff42d8
[]
no_license
yline/as_lib_sqlite
https://github.com/yline/as_lib_sqlite
7923d18289e037406d6e087d730410e7514e8221
2e432cc2c7540a114b52bc42cc22a91fade90c69
refs/heads/master
2021-07-06T12:03:40.327000
2018-12-28T10:30:25
2018-12-28T10:30:25
119,014,632
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lib.sqlite.demo; import com.lib.sqlite.demo.common.AbstractByteModelTest; import com.yline.sqlite.helper.SQLiteIOUtils; import com.lib.sqlite.demo.dao.model.ByteModel; import com.lib.sqlite.demo.dao.model.StringModel; import org.junit.Assert; /** * NetCacheModel 装载 SimpleModel * * @author yline 2017/9/14 -- 14:26 * @version 1.0.0 */ public class ByteSimpleModelTest extends AbstractByteModelTest { @Override protected void assertObject(byte[] tom, byte[] joe) { if (null == tom && null == joe) { Assert.assertEquals(true, true); return; } Object tomObject = SQLiteIOUtils.byte2Object(tom); Object joeObject = SQLiteIOUtils.byte2Object(tom); Assert.assertTrue(tomObject instanceof StringModel); // 断言一波 Assert.assertTrue(joeObject instanceof StringModel); // 断言一波 Assert.assertEquals(((StringModel) tomObject).getKey(), ((StringModel) joeObject).getKey()); Assert.assertEquals(((StringModel) tomObject).getValue(), ((StringModel) joeObject).getValue()); } @Override protected ByteModel createModel(String pk) { byte[] modelByte = SQLiteIOUtils.object2Byte(new StringModel(pk, pk + "-value")); return new ByteModel(pk, modelByte); } }
UTF-8
Java
1,307
java
ByteSimpleModelTest.java
Java
[ { "context": "\n/**\n * NetCacheModel 装载 SimpleModel\n *\n * @author yline 2017/9/14 -- 14:26\n * @version 1.0.0\n */\npublic c", "end": 313, "score": 0.9994447827339172, "start": 308, "tag": "USERNAME", "value": "yline" } ]
null
[]
package com.lib.sqlite.demo; import com.lib.sqlite.demo.common.AbstractByteModelTest; import com.yline.sqlite.helper.SQLiteIOUtils; import com.lib.sqlite.demo.dao.model.ByteModel; import com.lib.sqlite.demo.dao.model.StringModel; import org.junit.Assert; /** * NetCacheModel 装载 SimpleModel * * @author yline 2017/9/14 -- 14:26 * @version 1.0.0 */ public class ByteSimpleModelTest extends AbstractByteModelTest { @Override protected void assertObject(byte[] tom, byte[] joe) { if (null == tom && null == joe) { Assert.assertEquals(true, true); return; } Object tomObject = SQLiteIOUtils.byte2Object(tom); Object joeObject = SQLiteIOUtils.byte2Object(tom); Assert.assertTrue(tomObject instanceof StringModel); // 断言一波 Assert.assertTrue(joeObject instanceof StringModel); // 断言一波 Assert.assertEquals(((StringModel) tomObject).getKey(), ((StringModel) joeObject).getKey()); Assert.assertEquals(((StringModel) tomObject).getValue(), ((StringModel) joeObject).getValue()); } @Override protected ByteModel createModel(String pk) { byte[] modelByte = SQLiteIOUtils.object2Byte(new StringModel(pk, pk + "-value")); return new ByteModel(pk, modelByte); } }
1,307
0.686869
0.67366
39
32
29.715748
104
false
false
0
0
0
0
0
0
0.564103
false
false
5
4d6a55a85cb9c337b4c671eb5e0ddd38ed6369ce
816,043,830,290
3e56e722ce72c54706e202902bb8227f5d54b99c
/src/main/java/net/minestorm/server/adventure/audience/IterableAudienceProvider.java
ca393a3dba4163106ab1ca0a195be074717514bd
[ "Apache-2.0" ]
permissive
NotGeri/Minestorm
https://github.com/NotGeri/Minestorm
7485ce0051ccdfbf645c5032677874ac1f063ccc
f99da13ad4306c1580528874574372bf30291136
refs/heads/master
2023-08-21T11:55:08.852000
2021-10-10T19:20:54
2021-10-10T19:20:54
415,670,490
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.minestorm.server.adventure.audience; import com.google.common.collect.Iterables; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; import net.minestorm.server.MinecraftServer; import net.minestorm.server.command.ConsoleSender; import net.minestorm.server.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.StreamSupport; /** * A provider of iterable audiences. */ class IterableAudienceProvider implements AudienceProvider<Iterable<? extends Audience>> { private final Collection<ConsoleSender> console = Collections.singleton(MinecraftServer.getCommandManager().getConsoleSender()); private final AudienceRegistry registry = new AudienceRegistry(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new); protected IterableAudienceProvider() { } @Override public @NotNull Iterable<? extends Audience> all() { return Iterables.concat(this.players(), this.console(), this.customs()); } @Override public @NotNull Iterable<? extends Audience> players() { return MinecraftServer.getConnectionManager().getOnlinePlayers(); } @Override public @NotNull Iterable<? extends Audience> players(@NotNull Predicate<Player> filter) { return MinecraftServer.getConnectionManager().getOnlinePlayers().stream().filter(filter).collect(Collectors.toList()); } @Override public @NotNull Iterable<? extends Audience> console() { return this.console; } @Override public @NotNull Iterable<? extends Audience> server() { return Iterables.concat(this.players(), this.console()); } @Override public @NotNull Iterable<? extends Audience> customs() { return this.registry.all(); } @Override public @NotNull Iterable<? extends Audience> custom(@NotNull Key key) { return this.registry.of(key); } @Override public @NotNull Iterable<? extends Audience> custom(@NotNull Key key, Predicate<Audience> filter) { return StreamSupport.stream(this.registry.of(key).spliterator(), false).filter(filter).collect(Collectors.toList()); } @Override public @NotNull Iterable<? extends Audience> customs(@NotNull Predicate<Audience> filter) { return this.registry.of(filter); } @Override public @NotNull Iterable<? extends Audience> all(@NotNull Predicate<Audience> filter) { return StreamSupport.stream(this.all().spliterator(), false).filter(filter).collect(Collectors.toList()); } @Override public @NotNull AudienceRegistry registry() { return this.registry; } }
UTF-8
Java
2,874
java
IterableAudienceProvider.java
Java
[]
null
[]
package net.minestorm.server.adventure.audience; import com.google.common.collect.Iterables; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.key.Key; import net.minestorm.server.MinecraftServer; import net.minestorm.server.command.ConsoleSender; import net.minestorm.server.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.StreamSupport; /** * A provider of iterable audiences. */ class IterableAudienceProvider implements AudienceProvider<Iterable<? extends Audience>> { private final Collection<ConsoleSender> console = Collections.singleton(MinecraftServer.getCommandManager().getConsoleSender()); private final AudienceRegistry registry = new AudienceRegistry(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new); protected IterableAudienceProvider() { } @Override public @NotNull Iterable<? extends Audience> all() { return Iterables.concat(this.players(), this.console(), this.customs()); } @Override public @NotNull Iterable<? extends Audience> players() { return MinecraftServer.getConnectionManager().getOnlinePlayers(); } @Override public @NotNull Iterable<? extends Audience> players(@NotNull Predicate<Player> filter) { return MinecraftServer.getConnectionManager().getOnlinePlayers().stream().filter(filter).collect(Collectors.toList()); } @Override public @NotNull Iterable<? extends Audience> console() { return this.console; } @Override public @NotNull Iterable<? extends Audience> server() { return Iterables.concat(this.players(), this.console()); } @Override public @NotNull Iterable<? extends Audience> customs() { return this.registry.all(); } @Override public @NotNull Iterable<? extends Audience> custom(@NotNull Key key) { return this.registry.of(key); } @Override public @NotNull Iterable<? extends Audience> custom(@NotNull Key key, Predicate<Audience> filter) { return StreamSupport.stream(this.registry.of(key).spliterator(), false).filter(filter).collect(Collectors.toList()); } @Override public @NotNull Iterable<? extends Audience> customs(@NotNull Predicate<Audience> filter) { return this.registry.of(filter); } @Override public @NotNull Iterable<? extends Audience> all(@NotNull Predicate<Audience> filter) { return StreamSupport.stream(this.all().spliterator(), false).filter(filter).collect(Collectors.toList()); } @Override public @NotNull AudienceRegistry registry() { return this.registry; } }
2,874
0.727557
0.727557
84
33.214287
35.48946
132
false
false
0
0
0
0
0
0
0.416667
false
false
5
1f5a5727995ac43c28ba13ff2b0cf4183d969d04
23,175,643,563,032
3d38d8a7764570542a4ff7368879a120dda7883b
/src/practice/Passage.java
1e2112aa954cae2a25a27e650641d2d96e207bca
[ "MIT" ]
permissive
AmidSanai/JavaProgramming
https://github.com/AmidSanai/JavaProgramming
c41289c373852a0a7b7b8760b4ccba54772351c7
228e0d5e8d0663a5a4eb055c8ea6e4b372490c58
refs/heads/master
2023-01-19T06:04:23.881000
2020-11-21T15:48:00
2020-11-21T15:48:00
290,460,099
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package practice; import java.util.Scanner; public class Passage { public static void main(String[] args) { //Scanner Scanner scan = new Scanner(System.in); //asking for drawing System.out.println("Draw the people who are walking through the passage."); System.out.println("e.g = --->---<"); System.out.println("<&> for person who is walking and - for distance between people."); //string of passage String peopleInPassage = scan.nextLine(); System.out.println(helloNum(peopleInPassage)); } public static int helloNum(String peopleInPassage){ int pipLength = peopleInPassage.length(); char charPIP; int bigger = 0; int oneSideHello = 0; int twoSideHello = 0; for (int i = 0; i < pipLength; i++){ charPIP = peopleInPassage.charAt(i); if (charPIP == '>'){ bigger += 2; } else if (charPIP == '<'){ oneSideHello = oneSideHello + bigger; } } twoSideHello = oneSideHello; return twoSideHello; } }
UTF-8
Java
1,146
java
Passage.java
Java
[]
null
[]
package practice; import java.util.Scanner; public class Passage { public static void main(String[] args) { //Scanner Scanner scan = new Scanner(System.in); //asking for drawing System.out.println("Draw the people who are walking through the passage."); System.out.println("e.g = --->---<"); System.out.println("<&> for person who is walking and - for distance between people."); //string of passage String peopleInPassage = scan.nextLine(); System.out.println(helloNum(peopleInPassage)); } public static int helloNum(String peopleInPassage){ int pipLength = peopleInPassage.length(); char charPIP; int bigger = 0; int oneSideHello = 0; int twoSideHello = 0; for (int i = 0; i < pipLength; i++){ charPIP = peopleInPassage.charAt(i); if (charPIP == '>'){ bigger += 2; } else if (charPIP == '<'){ oneSideHello = oneSideHello + bigger; } } twoSideHello = oneSideHello; return twoSideHello; } }
1,146
0.561082
0.556719
37
30
22.094393
95
false
false
0
0
0
0
0
0
0.540541
false
false
5
ccf58659229878f3c0468bf29684f82911d64969
27,582,280,002,085
ad6c1790b998fa65959b0818e9c26d498723e515
/WhippyGuard/src/main/java/com/whippy/sponge/guard/beans/Area.java
656f8bc44aaa37dafeb7708d3aad63e01e951656
[ "Apache-2.0" ]
permissive
WhippyCleric/WhipPlugins
https://github.com/WhippyCleric/WhipPlugins
0d763918a8fac38d550e6c66a8caebde8e9d267e
a9e3a883dcaf5f0ac9aabacefbb24743365a6f66
refs/heads/master
2021-01-21T12:50:01.701000
2016-05-10T12:11:23
2016-05-10T12:11:23
36,115,281
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.whippy.sponge.guard.beans; import java.awt.Rectangle; import java.awt.geom.GeneralPath; import java.util.ArrayList; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import com.flowpowered.math.vector.Vector3i; import com.whippy.sponge.guard.exceptions.AreaFinalisedException; import com.whippy.sponge.guard.exceptions.MultipleWorldInAreaException; public class Area { private List<Vector3i> points; private boolean finalised = false; private String areaName; private double height; private double base; private AreaRights rights; private GeneralPath polygon; private String worldName; private GeneralPath buildPolygon(){ Vector3i start = points.get(0); GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,points.size()); polygon.moveTo(start.getX(), start.getZ()); for (int i = 1; i < points.size(); i++) { polygon.lineTo(points.get(i).getX(), points.get(i).getZ()); }; polygon.closePath(); return polygon; } public Area(){ points = new ArrayList<Vector3i>(); height = StaticsHandler.BOUNDLESS_NUMBER; base = StaticsHandler.BOUNDLESS_NUMBER; rights = new AreaRights(); } public Area(double height, double base){ points = new ArrayList<Vector3i>(); this.height = height; this.base = base; rights = new AreaRights(); } public Area(String areaName, String worldName, List<Vector3i> points, Double height, Double base, AreaRights playerAreaRights) { finalised = true; this.areaName = areaName; this.worldName = worldName; this.points = points; this.height = height; this.base = base; this.rights = playerAreaRights; this.polygon = buildPolygon(); } public void addPoint(WorldLocation point) throws AreaFinalisedException, MultipleWorldInAreaException { if(finalised){ throw new AreaFinalisedException(); }else{ if(getPoints().isEmpty()){ worldName = point.getWorldName(); getPoints().add(new Vector3i(point.getX(), point.getY(), point.getZ())); }else{ if(worldName.equals(point.getWorldName())){ getPoints().add(new Vector3i(point.getX(), point.getY(), point.getZ())); }else{ throw new MultipleWorldInAreaException(); } } } } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getBase() { return base; } public void setBase(double base) { this.base = base; } public String getWorldName() { return worldName; } public String getName(){ return areaName; } public void finalise(String areaName, Double height, Double base){ this.areaName = areaName; this.height = height; this.base = base; this.finalised = true; this.polygon = buildPolygon(); } public boolean isFinalised(){ return finalised; } public List<Vector3i> getPoints() { return points; } public boolean contains(WorldLocation worldLocation, double height, double base) { if(isFinalised()){ if(!worldLocation.getWorldName().equals(worldName)){ return false; } if(overlapsOnVertical(height, base)){ return polygon.contains(worldLocation.getX(), worldLocation.getZ()); }else{ return false; } }else{ return false; } } public boolean overlapsOnVertical( double height, double base){ if(this.height==StaticsHandler.BOUNDLESS_NUMBER && this.base ==StaticsHandler.BOUNDLESS_NUMBER){ return true; }else if(height ==StaticsHandler.BOUNDLESS_NUMBER && base==StaticsHandler.BOUNDLESS_NUMBER){ return true; }else if(this.height==StaticsHandler.BOUNDLESS_NUMBER){ if(height>=this.base || height==StaticsHandler.BOUNDLESS_NUMBER){ //They do overlap vertically return true; }else{ //New area is below current area return false; } }else if(this.base==StaticsHandler.BOUNDLESS_NUMBER){ if(base<=this.height || base == StaticsHandler.BOUNDLESS_NUMBER){ return true; }else{ //New area is above current area return false; } }else if(height==StaticsHandler.BOUNDLESS_NUMBER){ if(this.height>=base || this.height==StaticsHandler.BOUNDLESS_NUMBER){ //They do overlap vertically return true; }else{ //Old Area is below new area return false; } }else if(base ==StaticsHandler.BOUNDLESS_NUMBER){ if(this.base<=height || this.base == StaticsHandler.BOUNDLESS_NUMBER){ return true; }else{ //Old area is above current area return false; } }else{ if(this.base>height){ return false; }else if(base > this.height){ return false; }else{ return true; } } } public JSONObject toJSONObject() { JSONObject jsonObject = new JSONObject(); jsonObject.put("areaName", areaName); jsonObject.put("worldName", worldName); jsonObject.put("height", height); jsonObject.put("base", base); JSONArray arrayOfPoints = new JSONArray(); for (Vector3i vector3i : points) { JSONObject vector = new JSONObject(); vector.put("x", vector3i.getX()); vector.put("y", vector3i.getY()); vector.put("z", vector3i.getZ()); arrayOfPoints.add(vector); } jsonObject.put("points", arrayOfPoints); jsonObject.put("areaRights", rights.toJSONObject()); return jsonObject; } public boolean overlaps(Area area) { if(!area.getWorldName().equals(worldName)){ return false; } if(overlapsOnVertical(area.getHeight(), area.getBase())){ boolean doesOverlap = false; GeneralPath areaPolygon = area.buildPolygon(); GeneralPath ourPolygon = buildPolygon(); java.awt.geom.Area areaGemo = new java.awt.geom.Area(areaPolygon); java.awt.geom.Area ourGemo = new java.awt.geom.Area(ourPolygon); areaGemo.intersect(ourGemo); Rectangle bounds = areaGemo.getBounds(); if(bounds.height>0 || bounds.width >0){ doesOverlap = true; }else{ doesOverlap = false; } return doesOverlap; }else{ return false; } } public void giveFullRights(String identifier) { rights.givePlayerFullRights(identifier); } public boolean canBreak(String identifier) { return rights.canBreak(identifier); } public boolean canPlace(String identifier) { return rights.canPlace(identifier); } public boolean canOpenDoor(String identifier) { return rights.canOpenDoor(identifier); } public boolean canOpenChests(String identifier) { return rights.canOpenChests(identifier); } public boolean canAttackPlayers(String identifier) { return rights.canAttackPlayers(identifier); } public boolean canAttackAnimals(String identifier) { return rights.canAttackAnimals(identifier); } }
UTF-8
Java
6,621
java
Area.java
Java
[]
null
[]
package com.whippy.sponge.guard.beans; import java.awt.Rectangle; import java.awt.geom.GeneralPath; import java.util.ArrayList; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import com.flowpowered.math.vector.Vector3i; import com.whippy.sponge.guard.exceptions.AreaFinalisedException; import com.whippy.sponge.guard.exceptions.MultipleWorldInAreaException; public class Area { private List<Vector3i> points; private boolean finalised = false; private String areaName; private double height; private double base; private AreaRights rights; private GeneralPath polygon; private String worldName; private GeneralPath buildPolygon(){ Vector3i start = points.get(0); GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,points.size()); polygon.moveTo(start.getX(), start.getZ()); for (int i = 1; i < points.size(); i++) { polygon.lineTo(points.get(i).getX(), points.get(i).getZ()); }; polygon.closePath(); return polygon; } public Area(){ points = new ArrayList<Vector3i>(); height = StaticsHandler.BOUNDLESS_NUMBER; base = StaticsHandler.BOUNDLESS_NUMBER; rights = new AreaRights(); } public Area(double height, double base){ points = new ArrayList<Vector3i>(); this.height = height; this.base = base; rights = new AreaRights(); } public Area(String areaName, String worldName, List<Vector3i> points, Double height, Double base, AreaRights playerAreaRights) { finalised = true; this.areaName = areaName; this.worldName = worldName; this.points = points; this.height = height; this.base = base; this.rights = playerAreaRights; this.polygon = buildPolygon(); } public void addPoint(WorldLocation point) throws AreaFinalisedException, MultipleWorldInAreaException { if(finalised){ throw new AreaFinalisedException(); }else{ if(getPoints().isEmpty()){ worldName = point.getWorldName(); getPoints().add(new Vector3i(point.getX(), point.getY(), point.getZ())); }else{ if(worldName.equals(point.getWorldName())){ getPoints().add(new Vector3i(point.getX(), point.getY(), point.getZ())); }else{ throw new MultipleWorldInAreaException(); } } } } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getBase() { return base; } public void setBase(double base) { this.base = base; } public String getWorldName() { return worldName; } public String getName(){ return areaName; } public void finalise(String areaName, Double height, Double base){ this.areaName = areaName; this.height = height; this.base = base; this.finalised = true; this.polygon = buildPolygon(); } public boolean isFinalised(){ return finalised; } public List<Vector3i> getPoints() { return points; } public boolean contains(WorldLocation worldLocation, double height, double base) { if(isFinalised()){ if(!worldLocation.getWorldName().equals(worldName)){ return false; } if(overlapsOnVertical(height, base)){ return polygon.contains(worldLocation.getX(), worldLocation.getZ()); }else{ return false; } }else{ return false; } } public boolean overlapsOnVertical( double height, double base){ if(this.height==StaticsHandler.BOUNDLESS_NUMBER && this.base ==StaticsHandler.BOUNDLESS_NUMBER){ return true; }else if(height ==StaticsHandler.BOUNDLESS_NUMBER && base==StaticsHandler.BOUNDLESS_NUMBER){ return true; }else if(this.height==StaticsHandler.BOUNDLESS_NUMBER){ if(height>=this.base || height==StaticsHandler.BOUNDLESS_NUMBER){ //They do overlap vertically return true; }else{ //New area is below current area return false; } }else if(this.base==StaticsHandler.BOUNDLESS_NUMBER){ if(base<=this.height || base == StaticsHandler.BOUNDLESS_NUMBER){ return true; }else{ //New area is above current area return false; } }else if(height==StaticsHandler.BOUNDLESS_NUMBER){ if(this.height>=base || this.height==StaticsHandler.BOUNDLESS_NUMBER){ //They do overlap vertically return true; }else{ //Old Area is below new area return false; } }else if(base ==StaticsHandler.BOUNDLESS_NUMBER){ if(this.base<=height || this.base == StaticsHandler.BOUNDLESS_NUMBER){ return true; }else{ //Old area is above current area return false; } }else{ if(this.base>height){ return false; }else if(base > this.height){ return false; }else{ return true; } } } public JSONObject toJSONObject() { JSONObject jsonObject = new JSONObject(); jsonObject.put("areaName", areaName); jsonObject.put("worldName", worldName); jsonObject.put("height", height); jsonObject.put("base", base); JSONArray arrayOfPoints = new JSONArray(); for (Vector3i vector3i : points) { JSONObject vector = new JSONObject(); vector.put("x", vector3i.getX()); vector.put("y", vector3i.getY()); vector.put("z", vector3i.getZ()); arrayOfPoints.add(vector); } jsonObject.put("points", arrayOfPoints); jsonObject.put("areaRights", rights.toJSONObject()); return jsonObject; } public boolean overlaps(Area area) { if(!area.getWorldName().equals(worldName)){ return false; } if(overlapsOnVertical(area.getHeight(), area.getBase())){ boolean doesOverlap = false; GeneralPath areaPolygon = area.buildPolygon(); GeneralPath ourPolygon = buildPolygon(); java.awt.geom.Area areaGemo = new java.awt.geom.Area(areaPolygon); java.awt.geom.Area ourGemo = new java.awt.geom.Area(ourPolygon); areaGemo.intersect(ourGemo); Rectangle bounds = areaGemo.getBounds(); if(bounds.height>0 || bounds.width >0){ doesOverlap = true; }else{ doesOverlap = false; } return doesOverlap; }else{ return false; } } public void giveFullRights(String identifier) { rights.givePlayerFullRights(identifier); } public boolean canBreak(String identifier) { return rights.canBreak(identifier); } public boolean canPlace(String identifier) { return rights.canPlace(identifier); } public boolean canOpenDoor(String identifier) { return rights.canOpenDoor(identifier); } public boolean canOpenChests(String identifier) { return rights.canOpenChests(identifier); } public boolean canAttackPlayers(String identifier) { return rights.canAttackPlayers(identifier); } public boolean canAttackAnimals(String identifier) { return rights.canAttackAnimals(identifier); } }
6,621
0.701254
0.698535
269
23.613382
22.933214
129
false
false
0
0
0
0
0
0
2.501859
false
false
5
a3e02ee0409637250d67c58454b6d15b57a62eb1
15,281,493,659,791
7464f3c8d60d9ce8eb8c44b3a44f22afbd3571f6
/src/main/java/com/spring/b2b/admin/config/ErrorLogController.java
d08714b2921944d0e704ac9053e2c16d85f5df67
[]
no_license
ShawnJoen/springb2b
https://github.com/ShawnJoen/springb2b
0da2551db3e47a0ffeeab948abf880900304d874
6ce67e21613df86d59e1a2c5add61ea2c4ed2c94
refs/heads/master
2022-01-17T14:56:28.602000
2018-02-09T04:41:10
2018-02-09T04:41:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.spring.b2b.admin.config; import static com.spring.util.Common.output; import java.util.List; import java.util.Locale; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageInfo; import com.spring.b2b.admin.EnvController; import com.spring.dto.config.ErrorLog; import com.spring.util.validation.ValidationResult; import com.spring.util.validation.ValidationUtils; import com.spring.vo.config.ErrorLogVO; @Controller @RequestMapping("/admin/config") public class ErrorLogController extends EnvController { private final Logger logger = LoggerFactory.getLogger(ErrorLogController.class); @Autowired private MessageSource messageSource; /* * 创建商品库商品 from * */ @RequestMapping(value = "/createErrorLog.do", method = RequestMethod.GET) public String createErrorLogForm(ModelMap model) { model.addAttribute("errorLog", new ErrorLog()); return "admin/config/createErrorLog"; } /* * 创建商品库商品处理 * */ @RequestMapping(value = "/createErrorLog.do", method = RequestMethod.POST) public @ResponseBody Map<String, Object> createErrorLog(@ModelAttribute("errorLog") ErrorLog errorLog, BindingResult result, Locale locale) throws Exception { if (result.hasErrors()) { return output("1", null, messageSource.getMessage("program_error", null, locale)); } final ValidationResult ValidResult = ValidationUtils.validation(errorLog); if (ValidResult.isHasErrors()) { return output("1", null, ValidResult.getErrorMessage()); } return errorLogService.createErrorLog(errorLog, locale); } /* * 获取商品库商品列表 * */ @RequestMapping(value = "/errorLogList.do", method = RequestMethod.GET) public String errorLogList(@RequestParam(value = "pageNum", required = false, defaultValue="1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue="20") Integer pageSize, @ModelAttribute("errorLogVO") ErrorLogVO errorLogVO, ModelMap model) { super.setPageHelper(pageNum, pageSize); List<ErrorLogVO> errorLogVOs = errorLogService.getErrorLogs(errorLogVO); PageInfo<ErrorLogVO> pageInfo = new PageInfo<>(errorLogVOs); model.addAttribute("pageInfo", pageInfo); //序号 long sequence = pageInfo.getTotal() - (pageInfo.getPageNum() - 1) * pageInfo.getPageSize() + 1; model.addAttribute("sequence", sequence); //搜索框绑定搜索字段 model.addAttribute("errorLog", errorLogVO); return "admin/config/errorLogList"; } /* * 创建商品库商品 from * */ @RequestMapping(value = "/viewErrorLog.do", method = RequestMethod.GET) public String viewErrorLog(@RequestParam(value = "id", required = true) Integer id, ModelMap model) { final ErrorLog errorLog = errorLogService.getErrorLogById(id); model.addAttribute("errorLog", errorLog); return "admin/config/viewErrorLog"; } }
UTF-8
Java
3,627
java
ErrorLogController.java
Java
[]
null
[]
package com.spring.b2b.admin.config; import static com.spring.util.Common.output; import java.util.List; import java.util.Locale; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageInfo; import com.spring.b2b.admin.EnvController; import com.spring.dto.config.ErrorLog; import com.spring.util.validation.ValidationResult; import com.spring.util.validation.ValidationUtils; import com.spring.vo.config.ErrorLogVO; @Controller @RequestMapping("/admin/config") public class ErrorLogController extends EnvController { private final Logger logger = LoggerFactory.getLogger(ErrorLogController.class); @Autowired private MessageSource messageSource; /* * 创建商品库商品 from * */ @RequestMapping(value = "/createErrorLog.do", method = RequestMethod.GET) public String createErrorLogForm(ModelMap model) { model.addAttribute("errorLog", new ErrorLog()); return "admin/config/createErrorLog"; } /* * 创建商品库商品处理 * */ @RequestMapping(value = "/createErrorLog.do", method = RequestMethod.POST) public @ResponseBody Map<String, Object> createErrorLog(@ModelAttribute("errorLog") ErrorLog errorLog, BindingResult result, Locale locale) throws Exception { if (result.hasErrors()) { return output("1", null, messageSource.getMessage("program_error", null, locale)); } final ValidationResult ValidResult = ValidationUtils.validation(errorLog); if (ValidResult.isHasErrors()) { return output("1", null, ValidResult.getErrorMessage()); } return errorLogService.createErrorLog(errorLog, locale); } /* * 获取商品库商品列表 * */ @RequestMapping(value = "/errorLogList.do", method = RequestMethod.GET) public String errorLogList(@RequestParam(value = "pageNum", required = false, defaultValue="1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue="20") Integer pageSize, @ModelAttribute("errorLogVO") ErrorLogVO errorLogVO, ModelMap model) { super.setPageHelper(pageNum, pageSize); List<ErrorLogVO> errorLogVOs = errorLogService.getErrorLogs(errorLogVO); PageInfo<ErrorLogVO> pageInfo = new PageInfo<>(errorLogVOs); model.addAttribute("pageInfo", pageInfo); //序号 long sequence = pageInfo.getTotal() - (pageInfo.getPageNum() - 1) * pageInfo.getPageSize() + 1; model.addAttribute("sequence", sequence); //搜索框绑定搜索字段 model.addAttribute("errorLog", errorLogVO); return "admin/config/errorLogList"; } /* * 创建商品库商品 from * */ @RequestMapping(value = "/viewErrorLog.do", method = RequestMethod.GET) public String viewErrorLog(@RequestParam(value = "id", required = true) Integer id, ModelMap model) { final ErrorLog errorLog = errorLogService.getErrorLogById(id); model.addAttribute("errorLog", errorLog); return "admin/config/viewErrorLog"; } }
3,627
0.734821
0.731714
101
33.079208
29.287136
113
false
false
0
0
0
0
0
0
1.663366
false
false
5
c4451cb2b2743b769782d851361004d8b7dda5b6
15,281,493,660,364
6dea0ed70aacc83d4af06175bb9c282410581660
/common/src/main/java/com/yd/ydsp/common/constants/GlobalConstant.java
f68d0db942f257885599a8226880e01261b6317f
[]
no_license
P79N6A/ydjs
https://github.com/P79N6A/ydjs
db2bf166c4f4332bb76fb5a90bba66ed4c231fc7
299920f79de93e4e1d10d44fe1e694cd79a7e1e7
refs/heads/master
2020-04-06T17:23:07.588000
2018-11-15T05:26:15
2018-11-15T05:26:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yd.ydsp.common.constants; /** * @author zengyixun * @date 17/12/2 */ public class GlobalConstant { public static final String SMS_LOGIN = "smsLogin"; }
UTF-8
Java
172
java
GlobalConstant.java
Java
[ { "context": "kage com.yd.ydsp.common.constants;\n\n/**\n * @author zengyixun\n * @date 17/12/2\n */\npublic class GlobalConstant ", "end": 63, "score": 0.9994212985038757, "start": 54, "tag": "USERNAME", "value": "zengyixun" } ]
null
[]
package com.yd.ydsp.common.constants; /** * @author zengyixun * @date 17/12/2 */ public class GlobalConstant { public static final String SMS_LOGIN = "smsLogin"; }
172
0.69186
0.662791
9
18.111111
17.79166
54
false
false
0
0
0
0
0
0
0.222222
false
false
5
1d12754f0ebfcf9a17f725bf8c647008c1dc01d2
31,344,671,351,032
e8b7bc17677840a76581d46c0ec565a8bb896b0c
/src/EulerTest/Test09.java
02d68207469b7e6aaf4423d76a7cc14fb71ddba0
[]
no_license
star9264/HBSelfstudy
https://github.com/star9264/HBSelfstudy
53186d48077239548cfa392959e8127f6569109f
9d8b953c391a813573d3fb5a769e3a117f9b88b1
refs/heads/master
2020-12-02T15:01:45.057000
2016-09-13T08:40:54
2016-09-13T08:40:54
67,431,586
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package EulerTest; //세 자연수 a, b, c 가 피타고라스 정리 a^2 + b^2 = c^2 를 만족하면 피타고라스 수라고 부릅니다 (여기서 a < b < c ). //예를 들면 3^2 + 4^2 = 9 + 16 = 25 = 5^2이므로 3, 4, 5는 피타고라스 수입니다. //a + b + c = 1000 인 피타고라스 수 a, b, c는 한 가지 뿐입니다. 이 때, a × b × c 는 얼마입니까? public class Test09 { public static void main(String[] args) { boolean result = false; for (int a = 1; a <=1000; a++) { for (int b = 1; b <=1000; b++) { int c = 1000-(a+b); if(a*a+b*b==c*c){ result = true; System.out.println(a*b*c); }if(result) break; }if(result) break; } } }
UHC
Java
732
java
Test09.java
Java
[]
null
[]
package EulerTest; //세 자연수 a, b, c 가 피타고라스 정리 a^2 + b^2 = c^2 를 만족하면 피타고라스 수라고 부릅니다 (여기서 a < b < c ). //예를 들면 3^2 + 4^2 = 9 + 16 = 25 = 5^2이므로 3, 4, 5는 피타고라스 수입니다. //a + b + c = 1000 인 피타고라스 수 a, b, c는 한 가지 뿐입니다. 이 때, a × b × c 는 얼마입니까? public class Test09 { public static void main(String[] args) { boolean result = false; for (int a = 1; a <=1000; a++) { for (int b = 1; b <=1000; b++) { int c = 1000-(a+b); if(a*a+b*b==c*c){ result = true; System.out.println(a*b*c); }if(result) break; }if(result) break; } } }
732
0.5
0.43686
23
23.47826
22.646374
82
false
false
0
0
0
0
0
0
2.652174
false
false
5
3776407d5345e92c5c5aae8ca728ac03681f79c7
13,039,520,736,227
c2d40681d04e11db475a5f0be7b3fe53684a8d33
/src/Puzzle11/LastLaugh.java
3f868b2c3a0d1ce9b6f93fbfbb584c4a9529db24
[]
no_license
a0x/Java-Puzzlers
https://github.com/a0x/Java-Puzzlers
290955db31bca771b40998ee84d5316a608669c9
b121a74b18d1edd812fb9e12df1e93a1bdeede6f
refs/heads/master
2020-04-15T20:08:54.459000
2013-04-06T09:21:32
2013-04-06T09:21:32
8,845,263
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package Puzzle11; public class LastLaugh { public static void main(String[] args){ System.out.print("H" + "a"); //System.out.print('H' + 'a'); StringBuffer sb = new StringBuffer(); sb.append('H'); sb.append('a'); System.out.print(sb); //System.out.println("2+2=" + 2 + 2); System.out.printf("%c%c", 'H','a'); } /* * 当且仅当+操作符的操作数中至少有一个是String类型时,才会执行字符串连接操作;否则,执行加法。 * 如果要链接的数值中没有一个是字符串类型的,那么可以: * 预置一个空字符串 * 将第一个数值用String.valueOf显式地转换成一个字符串 * 使用StringBuffer * 使用System.out.printf*/ }
UTF-8
Java
717
java
LastLaugh.java
Java
[]
null
[]
package Puzzle11; public class LastLaugh { public static void main(String[] args){ System.out.print("H" + "a"); //System.out.print('H' + 'a'); StringBuffer sb = new StringBuffer(); sb.append('H'); sb.append('a'); System.out.print(sb); //System.out.println("2+2=" + 2 + 2); System.out.printf("%c%c", 'H','a'); } /* * 当且仅当+操作符的操作数中至少有一个是String类型时,才会执行字符串连接操作;否则,执行加法。 * 如果要链接的数值中没有一个是字符串类型的,那么可以: * 预置一个空字符串 * 将第一个数值用String.valueOf显式地转换成一个字符串 * 使用StringBuffer * 使用System.out.printf*/ }
717
0.646833
0.635317
23
21.695652
15.037445
53
false
false
0
0
0
0
0
0
1.73913
false
false
5
61aba47996cd094f114db1b3785c6c5812060df3
26,972,394,621,021
a7f6c2e39db3239380f7e19843a0a7e5b81977a4
/src/punching/WritePlcDialog.java
916a913901ca29f90ca8014e93f3f80a1c0983bf
[]
no_license
duonghuynh/Punching
https://github.com/duonghuynh/Punching
b66bf2b62736d4e9e5b2baeb09f0927a1dccac34
2e82895a3c0cff7e82527d7359f4fe415d9b4edb
refs/heads/master
2021-01-18T21:22:12
2015-07-18T03:07:25
2015-07-18T03:07:25
39,284,780
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 punching; import java.util.List; import java.util.logging.Level; import org.apache.log4j.Logger; import javax.swing.SwingUtilities; /** * * @author admin */ public class WritePlcDialog extends javax.swing.JDialog { /** * Creates new form WritePlcDialog */ public WritePlcDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); taConsole = new javax.swing.JTextArea(); btnStart = new javax.swing.JButton(); btnClear = new javax.swing.JButton(); btnStop = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Write to PLC"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); taConsole.setColumns(20); taConsole.setRows(5); jScrollPane1.setViewportView(taConsole); btnStart.setText("Nạp Lại"); btnStart.setToolTipText("Open port and write to PLC"); btnStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStartActionPerformed(evt); } }); btnClear.setText("Xóa log"); btnClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnClearActionPerformed(evt); } }); btnStop.setText("Ngừng"); btnStop.setToolTipText("Close COMM port"); btnStop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStopActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(btnStart) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnStop) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnClear)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnStart) .addComponent(btnClear) .addComponent(btnStop)) .addGap(0, 11, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed taConsole.setText(""); }//GEN-LAST:event_btnClearActionPerformed private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed if (!isRunning) { (new Thread() { public void run() { writePLC(); } }).start(); } }//GEN-LAST:event_btnStartActionPerformed private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopActionPerformed Plc plc = Plc.getInstance(); if (plc.isOpenComm()) { plc.closeComm(); appendText("Close COMM port " + Environment.getInstance().getSetting().getComPort() + "\r\n"); } }//GEN-LAST:event_btnStopActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened System.out.println("formWindowOpened"); btnStartActionPerformed(null); }//GEN-LAST:event_formWindowOpened /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(WritePlcDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(WritePlcDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(WritePlcDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(WritePlcDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { WritePlcDialog dialog = new WritePlcDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnClear; private javax.swing.JButton btnStart; private javax.swing.JButton btnStop; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea taConsole; // End of variables declaration//GEN-END:variables private List<Hole> data; private float length; final static Logger log = Logger.getLogger(WritePlcDialog.class); private boolean isRunning = false; private boolean isFirstActive = false; public int COMMAND_DELAY = 100; public List<Hole> getData() { return data; } public void setData(List<Hole> data) { this.data = data; } public float getLength() { return length; } public void setLength(float length) { this.length = length; } private void appendText(final String text) { // SwingUtilities.invokeLater(new Runnable() { // public void run() { taConsole.append(text); log.info(text); // } // }); } public void writePLC() { btnStart.setEnabled(false); btnStop.setEnabled(true); isRunning = true; Plc plc = Plc.getInstance(); if (plc.isOpenComm()) { appendText("COMM port is openned on " + Environment.getInstance().getSetting().getComPort() + "\r\n"); } else { if (plc.openComm()) { appendText("Open COMM port " + Environment.getInstance().getSetting().getComPort() + "\r\n"); } else { appendText("FAILED on openning COMM port " + Environment.getInstance().getSetting().getComPort() + "\r\n"); isRunning = false; btnStart.setEnabled(true); btnStop.setEnabled(false); return; } } // start to write int position = 1000; if (data != null) { try { appendText("Write length: " + length + "\r\n"); position = 1000; plc.writePLC32((int) (length * 10), position); // D1000, multiple 10 for decimal fraction Thread.sleep(COMMAND_DELAY); appendText("Write number of hole: " + data.size() + "\r\n"); position = 1002; //D1002 plc.writePLC(data.size(), position); //write size to D1002 Thread.sleep(COMMAND_DELAY); float thickness = Environment.getInstance().getSetting().getThickness(); appendText("Write V thickness: " + thickness + "\r\n"); position = 1008; //D1008 plc.writePLC((int) (thickness * 10), position); //write size to D1008, multiple 10 for decimal fraction Thread.sleep(COMMAND_DELAY); position = 1010; // start data at 1010 for (Hole hole : data) { appendText("Write " + hole.getName() + "\r\n"); //multiple 10 for decimal fraction plc.writeHole((int) (hole.getMachineY() * 10), (int) (hole.getX() * 10), hole.getT().getValue(), position); Thread.sleep(COMMAND_DELAY); position += 5; //move to next 5 } } catch (InterruptedException ex) { log.error(ex); } } appendText("Finish! " + "\r\n"); isRunning = false; btnStart.setEnabled(true); btnStop.setEnabled(false); } public boolean isIsRunning() { return isRunning; } public void setIsRunning(boolean isRunning) { this.isRunning = isRunning; } public boolean isIsFirstActive() { return isFirstActive; } public void setIsFirstActive(boolean isFirstActive) { this.isFirstActive = isFirstActive; } }
UTF-8
Java
11,544
java
WritePlcDialog.java
Java
[ { "context": "ort javax.swing.SwingUtilities;\n\n/**\n *\n * @author admin\n */\npublic class WritePlcDialog extends javax.swi", "end": 350, "score": 0.9987742304801941, "start": 345, "tag": "USERNAME", "value": "admin" } ]
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 punching; import java.util.List; import java.util.logging.Level; import org.apache.log4j.Logger; import javax.swing.SwingUtilities; /** * * @author admin */ public class WritePlcDialog extends javax.swing.JDialog { /** * Creates new form WritePlcDialog */ public WritePlcDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); taConsole = new javax.swing.JTextArea(); btnStart = new javax.swing.JButton(); btnClear = new javax.swing.JButton(); btnStop = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Write to PLC"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); taConsole.setColumns(20); taConsole.setRows(5); jScrollPane1.setViewportView(taConsole); btnStart.setText("Nạp Lại"); btnStart.setToolTipText("Open port and write to PLC"); btnStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStartActionPerformed(evt); } }); btnClear.setText("Xóa log"); btnClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnClearActionPerformed(evt); } }); btnStop.setText("Ngừng"); btnStop.setToolTipText("Close COMM port"); btnStop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStopActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(btnStart) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnStop) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnClear)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnStart) .addComponent(btnClear) .addComponent(btnStop)) .addGap(0, 11, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed taConsole.setText(""); }//GEN-LAST:event_btnClearActionPerformed private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed if (!isRunning) { (new Thread() { public void run() { writePLC(); } }).start(); } }//GEN-LAST:event_btnStartActionPerformed private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopActionPerformed Plc plc = Plc.getInstance(); if (plc.isOpenComm()) { plc.closeComm(); appendText("Close COMM port " + Environment.getInstance().getSetting().getComPort() + "\r\n"); } }//GEN-LAST:event_btnStopActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened System.out.println("formWindowOpened"); btnStartActionPerformed(null); }//GEN-LAST:event_formWindowOpened /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(WritePlcDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(WritePlcDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(WritePlcDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(WritePlcDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { WritePlcDialog dialog = new WritePlcDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnClear; private javax.swing.JButton btnStart; private javax.swing.JButton btnStop; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea taConsole; // End of variables declaration//GEN-END:variables private List<Hole> data; private float length; final static Logger log = Logger.getLogger(WritePlcDialog.class); private boolean isRunning = false; private boolean isFirstActive = false; public int COMMAND_DELAY = 100; public List<Hole> getData() { return data; } public void setData(List<Hole> data) { this.data = data; } public float getLength() { return length; } public void setLength(float length) { this.length = length; } private void appendText(final String text) { // SwingUtilities.invokeLater(new Runnable() { // public void run() { taConsole.append(text); log.info(text); // } // }); } public void writePLC() { btnStart.setEnabled(false); btnStop.setEnabled(true); isRunning = true; Plc plc = Plc.getInstance(); if (plc.isOpenComm()) { appendText("COMM port is openned on " + Environment.getInstance().getSetting().getComPort() + "\r\n"); } else { if (plc.openComm()) { appendText("Open COMM port " + Environment.getInstance().getSetting().getComPort() + "\r\n"); } else { appendText("FAILED on openning COMM port " + Environment.getInstance().getSetting().getComPort() + "\r\n"); isRunning = false; btnStart.setEnabled(true); btnStop.setEnabled(false); return; } } // start to write int position = 1000; if (data != null) { try { appendText("Write length: " + length + "\r\n"); position = 1000; plc.writePLC32((int) (length * 10), position); // D1000, multiple 10 for decimal fraction Thread.sleep(COMMAND_DELAY); appendText("Write number of hole: " + data.size() + "\r\n"); position = 1002; //D1002 plc.writePLC(data.size(), position); //write size to D1002 Thread.sleep(COMMAND_DELAY); float thickness = Environment.getInstance().getSetting().getThickness(); appendText("Write V thickness: " + thickness + "\r\n"); position = 1008; //D1008 plc.writePLC((int) (thickness * 10), position); //write size to D1008, multiple 10 for decimal fraction Thread.sleep(COMMAND_DELAY); position = 1010; // start data at 1010 for (Hole hole : data) { appendText("Write " + hole.getName() + "\r\n"); //multiple 10 for decimal fraction plc.writeHole((int) (hole.getMachineY() * 10), (int) (hole.getX() * 10), hole.getT().getValue(), position); Thread.sleep(COMMAND_DELAY); position += 5; //move to next 5 } } catch (InterruptedException ex) { log.error(ex); } } appendText("Finish! " + "\r\n"); isRunning = false; btnStart.setEnabled(true); btnStop.setEnabled(false); } public boolean isIsRunning() { return isRunning; } public void setIsRunning(boolean isRunning) { this.isRunning = isRunning; } public boolean isIsFirstActive() { return isFirstActive; } public void setIsFirstActive(boolean isFirstActive) { this.isFirstActive = isFirstActive; } }
11,544
0.600329
0.592962
293
38.375427
32.707134
152
false
false
0
0
0
0
0
0
0.494881
false
false
5
aa2961a7fc4c964ba1208b3a49062f5eab41b565
19,628,000,551,595
3bc5369183bd314e04e60f33f0ed7c4c132da69c
/allSorts.java
2e02bf68252b7b0c265cec5d8497da4992796786
[]
no_license
mvakili/all-sorts
https://github.com/mvakili/all-sorts
be53648c450ec7600abcc4c9c7ec759155bb9d51
a15a98043999817dd098db7ad8e9f1a89c245b4c
refs/heads/master
2022-11-05T15:11:10.032000
2020-06-25T04:46:42
2020-06-25T04:46:42
274,726,763
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Font; class Sort { static int delay; public static void swap(double [] a, int i, int j) { double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void show(double [] a, double hi, int first, int second, String title) { int N = a.length; StdDraw.clear(StdDraw.WHITE); for (int i = 0; i < N; i++) { StdDraw.setPenColor(StdDraw.GRAY); if (i == first || i == second) { StdDraw.setPenColor(StdDraw.RED); } StdDraw.line(i, 0, i, hi * a[i]); StdDraw.text(i, -0.08, Double.toString(a[i]), 90); } StdDraw.setPenColor(StdDraw.BOOK_RED); StdDraw.text(- 1, 0, title); StdDraw.show(delay); } public static void initDraw(int N, int _delay) { StdDraw.show(2); StdDraw.setCanvasSize(1100, 900); StdDraw.setXscale(-2, N+1); StdDraw.setYscale(-1, 1.2); StdDraw.setFont(new Font("SansSerif", Font.PLAIN, 12)); StdDraw.setPenRadius(.01); delay = _delay; } } class BubbleSort extends Sort{ public static double [] sort (double [] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } for (int i = 0; i < N ; i ++ ) { for (int j = 1; j < N - i ; j ++ ) { if (b[j] > b[j - 1]) { Sort.swap(b, j, j - 1); show(b, hi, j, j - 1, "Bubble "); } } } return b; } } class SelectionSort extends Sort{ public static double [] sort (double [] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } for (int i = 0; i < N ; i ++ ) { for (int j = i + 1; j < N ; j ++ ) { Sort.show(b, hi, i, j, "SELECTION "); if (b[i] < b[j]) { Sort.swap(b, i, j); show(b, hi, j, j - 1, "Selection "); } } } return b; } } class InsertionSort extends Sort{ public static double [] sort (double [] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } for (int i = 1 ; i < N ; i++) { for (int j = i ; j > 0; j--) { if (b[j-1] < b[j] ) { Sort.swap(b, j, j - 1); Sort.show(b, hi, j, j - 1, "INSERTION "); } else { Sort.show(b, hi, j, j - 1, "INSERTION "); break; } } } return b; } } class QuickSort extends Sort{ public static double [] sort (double [] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } QuickSort.sort(b, 0, N - 1, hi); return b; } private static void sort(double[] a, int lo, int hi, double hi2) { if (hi <= lo) return; int j = QuickSort.partition(a, lo, hi, hi2); QuickSort.sort(a, lo, j-1, hi2); QuickSort.sort(a, j+1, hi, hi2); } private static int partition(double[] a, int lo, int hi, double hi2) { int i = lo; int j = hi + 1; double v = a[lo]; while (true) { while (a[++i] > v) { if (i == hi) break; } while (v > a[--j]) { if (j == lo) break; } if (i >= j) break; Sort.swap(a, i, j);; Sort.show(a, hi2, j, i, "QUICK "); } Sort.swap(a, lo, j); Sort.show(a, hi2, j, lo, "QUICK "); return j; } } class MergeSort extends Sort{ private static void merge(double[] a, double[] aux, int lo, int mid, int hi, double hi2) { for (int k = lo; k <= hi; k++) { aux[k] = a[k]; } int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) { a[k] = aux[j++]; } else if (j > hi) { a[k] = aux[i++]; } else if (aux[j] > aux[i]) { a[k] = aux[j++]; } else { a[k] = aux[i++]; } Sort.show(a, hi2, k, -1, "MERGE "); } } private static void sort(double[] a, double[] aux, int lo, int hi, double hi2) { if (hi <= lo) return; int mid = lo + (hi - lo) / 2; MergeSort.sort(a, aux, lo, mid, hi2); MergeSort.sort(a, aux, mid + 1, hi, hi2); merge(a, aux, lo, mid, hi, hi2); } public static double [] sort(double[] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } double[] aux = new double[N]; MergeSort.sort(b, aux, 0, N -1, hi); return b; } } class ShellSort extends Sort{ public static double [] sort(double[] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } int k = 1; int h = 1; while (h < N/3) { h = 3*h + 1; k++; } while (h >= 1) { for (int i = h; i < N; i++) { for (int j = i; j >= h; j -= h) { Sort.show(b, hi, j, j - h, "SHELL "); if (b[j] > b[j-h]) { Sort.swap(b, j, j-h); } else break; } } h /= 3; } return b; } } class allSorts { public static void main(String[] args) { if (args.length == 0 || args.length == 1) { System.out.println("Help: "); System.out.println("java allSort [Algorithm Name] [Count] <delay>\n"); System.out.println("Algorithm Names: "); System.out.println("bubble: Bubble Sort"); System.out.println("selection: Selection Sort"); System.out.println("insertion: Insertion Sort"); System.out.println("quick: Quick Sort"); System.out.println("merge: Merge Sort"); System.out.println("shell: Shell Sort"); System.out.println("\nDelay: "); System.out.println("time for each compare to show graphics in milisecond "); return; } String sortName = args[0]; int N = Integer.parseInt(args[1]); int delay = 50; if (args.length >= 3) { delay = Integer.parseInt(args[2]); } double [] unsortedArray = new double[N]; double [] sortedArray; for (int i = 0; i < N; i++) unsortedArray[i] = StdRandom.uniform(10000); System.out.println("Unsorted Array:"); for (int i = 0; i < N; i++) { System.out.print(unsortedArray[i] + "\t"); } System.out.println(""); Sort.initDraw(N, delay); switch (sortName) { case "bubble": sortedArray = BubbleSort.sort(unsortedArray, 0.00008); break; case "selection": sortedArray = SelectionSort.sort(unsortedArray, 0.00008); break; case "insertion": sortedArray = InsertionSort.sort(unsortedArray, 0.00008); break; case "quick": sortedArray = QuickSort.sort(unsortedArray, 0.00008); break; case "merge": sortedArray = MergeSort.sort(unsortedArray, 0.00008); break; case "shell": sortedArray = ShellSort.sort(unsortedArray, 0.00008); break; default: sortedArray = BubbleSort.sort(unsortedArray, 0.00008); } System.out.println("Sorted Array:"); for (int i = 0; i < N; i++) { System.out.print(sortedArray[i] + "\t"); } System.out.println(""); } }
UTF-8
Java
7,359
java
allSorts.java
Java
[]
null
[]
import java.awt.Font; class Sort { static int delay; public static void swap(double [] a, int i, int j) { double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void show(double [] a, double hi, int first, int second, String title) { int N = a.length; StdDraw.clear(StdDraw.WHITE); for (int i = 0; i < N; i++) { StdDraw.setPenColor(StdDraw.GRAY); if (i == first || i == second) { StdDraw.setPenColor(StdDraw.RED); } StdDraw.line(i, 0, i, hi * a[i]); StdDraw.text(i, -0.08, Double.toString(a[i]), 90); } StdDraw.setPenColor(StdDraw.BOOK_RED); StdDraw.text(- 1, 0, title); StdDraw.show(delay); } public static void initDraw(int N, int _delay) { StdDraw.show(2); StdDraw.setCanvasSize(1100, 900); StdDraw.setXscale(-2, N+1); StdDraw.setYscale(-1, 1.2); StdDraw.setFont(new Font("SansSerif", Font.PLAIN, 12)); StdDraw.setPenRadius(.01); delay = _delay; } } class BubbleSort extends Sort{ public static double [] sort (double [] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } for (int i = 0; i < N ; i ++ ) { for (int j = 1; j < N - i ; j ++ ) { if (b[j] > b[j - 1]) { Sort.swap(b, j, j - 1); show(b, hi, j, j - 1, "Bubble "); } } } return b; } } class SelectionSort extends Sort{ public static double [] sort (double [] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } for (int i = 0; i < N ; i ++ ) { for (int j = i + 1; j < N ; j ++ ) { Sort.show(b, hi, i, j, "SELECTION "); if (b[i] < b[j]) { Sort.swap(b, i, j); show(b, hi, j, j - 1, "Selection "); } } } return b; } } class InsertionSort extends Sort{ public static double [] sort (double [] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } for (int i = 1 ; i < N ; i++) { for (int j = i ; j > 0; j--) { if (b[j-1] < b[j] ) { Sort.swap(b, j, j - 1); Sort.show(b, hi, j, j - 1, "INSERTION "); } else { Sort.show(b, hi, j, j - 1, "INSERTION "); break; } } } return b; } } class QuickSort extends Sort{ public static double [] sort (double [] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } QuickSort.sort(b, 0, N - 1, hi); return b; } private static void sort(double[] a, int lo, int hi, double hi2) { if (hi <= lo) return; int j = QuickSort.partition(a, lo, hi, hi2); QuickSort.sort(a, lo, j-1, hi2); QuickSort.sort(a, j+1, hi, hi2); } private static int partition(double[] a, int lo, int hi, double hi2) { int i = lo; int j = hi + 1; double v = a[lo]; while (true) { while (a[++i] > v) { if (i == hi) break; } while (v > a[--j]) { if (j == lo) break; } if (i >= j) break; Sort.swap(a, i, j);; Sort.show(a, hi2, j, i, "QUICK "); } Sort.swap(a, lo, j); Sort.show(a, hi2, j, lo, "QUICK "); return j; } } class MergeSort extends Sort{ private static void merge(double[] a, double[] aux, int lo, int mid, int hi, double hi2) { for (int k = lo; k <= hi; k++) { aux[k] = a[k]; } int i = lo, j = mid+1; for (int k = lo; k <= hi; k++) { if (i > mid) { a[k] = aux[j++]; } else if (j > hi) { a[k] = aux[i++]; } else if (aux[j] > aux[i]) { a[k] = aux[j++]; } else { a[k] = aux[i++]; } Sort.show(a, hi2, k, -1, "MERGE "); } } private static void sort(double[] a, double[] aux, int lo, int hi, double hi2) { if (hi <= lo) return; int mid = lo + (hi - lo) / 2; MergeSort.sort(a, aux, lo, mid, hi2); MergeSort.sort(a, aux, mid + 1, hi, hi2); merge(a, aux, lo, mid, hi, hi2); } public static double [] sort(double[] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } double[] aux = new double[N]; MergeSort.sort(b, aux, 0, N -1, hi); return b; } } class ShellSort extends Sort{ public static double [] sort(double[] a, double hi) { int N = a.length; double [] b = new double[N]; for (int i = 0; i < N; i++) { b[i] = a[i]; } int k = 1; int h = 1; while (h < N/3) { h = 3*h + 1; k++; } while (h >= 1) { for (int i = h; i < N; i++) { for (int j = i; j >= h; j -= h) { Sort.show(b, hi, j, j - h, "SHELL "); if (b[j] > b[j-h]) { Sort.swap(b, j, j-h); } else break; } } h /= 3; } return b; } } class allSorts { public static void main(String[] args) { if (args.length == 0 || args.length == 1) { System.out.println("Help: "); System.out.println("java allSort [Algorithm Name] [Count] <delay>\n"); System.out.println("Algorithm Names: "); System.out.println("bubble: Bubble Sort"); System.out.println("selection: Selection Sort"); System.out.println("insertion: Insertion Sort"); System.out.println("quick: Quick Sort"); System.out.println("merge: Merge Sort"); System.out.println("shell: Shell Sort"); System.out.println("\nDelay: "); System.out.println("time for each compare to show graphics in milisecond "); return; } String sortName = args[0]; int N = Integer.parseInt(args[1]); int delay = 50; if (args.length >= 3) { delay = Integer.parseInt(args[2]); } double [] unsortedArray = new double[N]; double [] sortedArray; for (int i = 0; i < N; i++) unsortedArray[i] = StdRandom.uniform(10000); System.out.println("Unsorted Array:"); for (int i = 0; i < N; i++) { System.out.print(unsortedArray[i] + "\t"); } System.out.println(""); Sort.initDraw(N, delay); switch (sortName) { case "bubble": sortedArray = BubbleSort.sort(unsortedArray, 0.00008); break; case "selection": sortedArray = SelectionSort.sort(unsortedArray, 0.00008); break; case "insertion": sortedArray = InsertionSort.sort(unsortedArray, 0.00008); break; case "quick": sortedArray = QuickSort.sort(unsortedArray, 0.00008); break; case "merge": sortedArray = MergeSort.sort(unsortedArray, 0.00008); break; case "shell": sortedArray = ShellSort.sort(unsortedArray, 0.00008); break; default: sortedArray = BubbleSort.sort(unsortedArray, 0.00008); } System.out.println("Sorted Array:"); for (int i = 0; i < N; i++) { System.out.print(sortedArray[i] + "\t"); } System.out.println(""); } }
7,359
0.484169
0.465824
324
21.712963
19.686142
91
false
false
0
0
0
0
0
0
2.243827
false
false
5