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
sequence | 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
sequence | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0e1bd2548bd29b1b4f1790aa0adff99d9d00d088 | 13,383,118,150,514 | 846160213aa572b69f44d60d58ef3231d50b25e9 | /A2L1Hometask2/A2_Lesson01_01/app/src/main/java/android_2/lesson01/app01/ActMain.java | ddee4a2c6ff05aa2e8bf8ebfeefc61eac81794d3 | [] | no_license | AnnaBaturina/exercises-hometasks | https://github.com/AnnaBaturina/exercises-hometasks | 29a3a182e0b7043a4329570fbe654830c4f8dfaa | 108aa2c0cb7b2aadef31b80d072cd1696e6fd6cb | refs/heads/master | 2021-06-19T17:10:49.298000 | 2017-07-28T10:17:16 | 2017-07-28T10:17:16 | 88,287,498 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package android_2.lesson01.app01;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android_2.lesson01.app01.lib.DBEmpl;
public class ActMain extends Activity implements View.OnClickListener{
EditText nrToDel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("ActMain", "onCreate");
setContentView(R.layout.act_main);
TextView tvDept = (TextView) findViewById(R.id.tvDept);
Button btnAdd = (Button) findViewById(R.id.addnewnote);
btnAdd.setOnClickListener(this);
// nrToDel = (EditText) findViewById(R.id.nrtodelete);
//Button btnDelete = (Button) findViewById(R.id.deletenote);
//btnDelete.setOnClickListener(this);
Cursor cr = MyApp.getDB().getReadableCursor(DBEmpl.TableNotes.T_NAME);
StringBuilder sBuilder = new StringBuilder();
if (cr.moveToFirst()) {
int col_id = cr.getColumnIndex(DBEmpl.TableNotes._ID);
int col_time = cr.getColumnIndex(DBEmpl.TableNotes.C_TIME);
int col_title = cr.getColumnIndex(DBEmpl.TableNotes.C_TITLE);
int col_note = cr.getColumnIndex(DBEmpl.TableNotes.C_NOTE);
do {
sBuilder.append(cr.getString(col_id) + ". " + cr.getString(col_time) +"\n" + cr.getString(col_title) +"\n" + cr.getString(col_note) + "\n\n");
} while (cr.moveToNext());
tvDept.setText(sBuilder.toString());
}
cr.close();
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.addnewnote) {
Intent intent = new Intent(this, AddNoteActivity.class);
startActivity(intent);
}
// if (v.getId() == R.id.deletenote) {
//
//// MyApp.getDB().deleteDep(Long.parseLong(nrToDel.getText().toString()));
//
// }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.act_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add:
Intent intent = new Intent(this, AddNoteActivity.class);
startActivity(intent);
return true;
case R.id.action_delete:
AlertDialog.Builder builder = new AlertDialog.Builder(ActMain.this);
builder.setTitle("Важное сообщение!")
.setMessage("Удаление пока не работает!")
.setIcon(R.drawable.ic_delete)
.setCancelable(true)
.setNegativeButton("Ну ок!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
// MyApp.getDB().deleteDep(4);
return true;
case R.id.action_settings:
//
return true;
default:
return super.onOptionsItemSelected(item);
}
}
} | UTF-8 | Java | 3,856 | java | ActMain.java | Java | [] | null | [] | package android_2.lesson01.app01;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android_2.lesson01.app01.lib.DBEmpl;
public class ActMain extends Activity implements View.OnClickListener{
EditText nrToDel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("ActMain", "onCreate");
setContentView(R.layout.act_main);
TextView tvDept = (TextView) findViewById(R.id.tvDept);
Button btnAdd = (Button) findViewById(R.id.addnewnote);
btnAdd.setOnClickListener(this);
// nrToDel = (EditText) findViewById(R.id.nrtodelete);
//Button btnDelete = (Button) findViewById(R.id.deletenote);
//btnDelete.setOnClickListener(this);
Cursor cr = MyApp.getDB().getReadableCursor(DBEmpl.TableNotes.T_NAME);
StringBuilder sBuilder = new StringBuilder();
if (cr.moveToFirst()) {
int col_id = cr.getColumnIndex(DBEmpl.TableNotes._ID);
int col_time = cr.getColumnIndex(DBEmpl.TableNotes.C_TIME);
int col_title = cr.getColumnIndex(DBEmpl.TableNotes.C_TITLE);
int col_note = cr.getColumnIndex(DBEmpl.TableNotes.C_NOTE);
do {
sBuilder.append(cr.getString(col_id) + ". " + cr.getString(col_time) +"\n" + cr.getString(col_title) +"\n" + cr.getString(col_note) + "\n\n");
} while (cr.moveToNext());
tvDept.setText(sBuilder.toString());
}
cr.close();
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.addnewnote) {
Intent intent = new Intent(this, AddNoteActivity.class);
startActivity(intent);
}
// if (v.getId() == R.id.deletenote) {
//
//// MyApp.getDB().deleteDep(Long.parseLong(nrToDel.getText().toString()));
//
// }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.act_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add:
Intent intent = new Intent(this, AddNoteActivity.class);
startActivity(intent);
return true;
case R.id.action_delete:
AlertDialog.Builder builder = new AlertDialog.Builder(ActMain.this);
builder.setTitle("Важное сообщение!")
.setMessage("Удаление пока не работает!")
.setIcon(R.drawable.ic_delete)
.setCancelable(true)
.setNegativeButton("Ну ок!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
// MyApp.getDB().deleteDep(4);
return true;
case R.id.action_settings:
//
return true;
default:
return super.onOptionsItemSelected(item);
}
}
} | 3,856 | 0.583486 | 0.580603 | 128 | 28.8125 | 27.774975 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484375 | false | false | 13 |
06789e8f77a49190dfc107fe76fb43880875595d | 25,649,544,710,789 | 61dacd89830d2a429dc957e428823d63cfc68bca | /dwarfguide-mps/languages/Creature/source_gen/net/dwarfguide/creature/behavior/LabourRef_BehaviorDescriptor.java | 71344e5e9c4d748cd1915ff9d267e1d7ce989981 | [] | no_license | ushkinaz/dwarf-guide | https://github.com/ushkinaz/dwarf-guide | 4e9b4f6e9b5009f55c549c0e13962c9a0d4ad38f | ba6d1cfe2a2ce256f81ded02c43ba3ecf5eb521b | refs/heads/master | 2021-06-03T16:20:02.061000 | 2018-08-16T15:45:13 | 2018-08-16T15:45:13 | 2,455,048 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.dwarfguide.creature.behavior;
/*Generated by MPS */
import jetbrains.mps.lang.core.behavior.BaseConcept_BehaviorDescriptor;
public class LabourRef_BehaviorDescriptor extends BaseConcept_BehaviorDescriptor {
public LabourRef_BehaviorDescriptor() {
}
@Override
public String getConceptFqName() {
return "net.dwarfguide.creature.structure.LabourRef";
}
}
| UTF-8 | Java | 382 | java | LabourRef_BehaviorDescriptor.java | Java | [] | null | [] | package net.dwarfguide.creature.behavior;
/*Generated by MPS */
import jetbrains.mps.lang.core.behavior.BaseConcept_BehaviorDescriptor;
public class LabourRef_BehaviorDescriptor extends BaseConcept_BehaviorDescriptor {
public LabourRef_BehaviorDescriptor() {
}
@Override
public String getConceptFqName() {
return "net.dwarfguide.creature.structure.LabourRef";
}
}
| 382 | 0.787958 | 0.787958 | 15 | 24.466667 | 27.414999 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 13 |
eebc2b682791db246f2af278eba6ef77b0b5cc13 | 2,525,440,788,612 | 49f7fa89b81cd1b2fb23cc8792e4fa6132b91657 | /src/com/Ntranga/CLMS/Service/TimeRulesService.java | 6b4870c74d0498e8839031ea0536d82ecbea0c0d | [] | no_license | kjrsoftwareservices/clms | https://github.com/kjrsoftwareservices/clms | 0da46a7592bf244fa63bcdea43e24af796a4e52f | 55b9a98e2ee88c471c5ee39049e2b117a0190032 | refs/heads/master | 2021-07-11T01:46:37.021000 | 2020-01-10T19:12:02 | 2020-01-10T19:12:02 | 232,908,977 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.Ntranga.CLMS.Service;
import java.util.List;
import com.Ntranga.CLMS.vo.DefineExceptionVo;
import com.Ntranga.CLMS.vo.SimpleObject;
import com.Ntranga.CLMS.vo.TimeExceptionRulesVo;
import com.Ntranga.CLMS.vo.TimeRulesDetailsVo;
public interface TimeRulesService {
public Integer saveOrUpdateTimeRules(TimeRulesDetailsVo rulesDetailsVo);
public List<SimpleObject> getRuleCodesList(Integer customerId,Integer companyId);
public List<TimeRulesDetailsVo> getDetailsByRuleInfoId(Integer ruleInfoId);
public List<SimpleObject> getTransactionDatesListForEditingTimeRules(Integer timeRulesId);
public Integer saveException(DefineExceptionVo paramException);
public List<DefineExceptionVo> getExceptionsListBySearch(DefineExceptionVo paramException);
public List<DefineExceptionVo> getExceptionById(Integer valueOf);
public List<SimpleObject> getTransactionDatesListForException(Integer customerId, Integer companyId, Integer exceptionUniqueId);
public Integer validateExceptionCode(DefineExceptionVo paramException);
public List<SimpleObject> getExceptionsDropDown(Integer customerId, Integer companyId, Integer countryId);
public Integer validateTimeRuleCode(TimeRulesDetailsVo paramTime);
public List<TimeRulesDetailsVo> getTimeRulesListBySearch(TimeRulesDetailsVo paramTime);
public List<TimeExceptionRulesVo> getTimeExceptionById(TimeExceptionRulesVo paramException);
public Integer saveTimeException(TimeExceptionRulesVo paramException);
public List<SimpleObject> getTransactionDatesListForTimeException(Integer customerId, Integer companyId, Integer exceptionUniqueId);
}
| UTF-8 | Java | 1,620 | java | TimeRulesService.java | Java | [] | null | [] | package com.Ntranga.CLMS.Service;
import java.util.List;
import com.Ntranga.CLMS.vo.DefineExceptionVo;
import com.Ntranga.CLMS.vo.SimpleObject;
import com.Ntranga.CLMS.vo.TimeExceptionRulesVo;
import com.Ntranga.CLMS.vo.TimeRulesDetailsVo;
public interface TimeRulesService {
public Integer saveOrUpdateTimeRules(TimeRulesDetailsVo rulesDetailsVo);
public List<SimpleObject> getRuleCodesList(Integer customerId,Integer companyId);
public List<TimeRulesDetailsVo> getDetailsByRuleInfoId(Integer ruleInfoId);
public List<SimpleObject> getTransactionDatesListForEditingTimeRules(Integer timeRulesId);
public Integer saveException(DefineExceptionVo paramException);
public List<DefineExceptionVo> getExceptionsListBySearch(DefineExceptionVo paramException);
public List<DefineExceptionVo> getExceptionById(Integer valueOf);
public List<SimpleObject> getTransactionDatesListForException(Integer customerId, Integer companyId, Integer exceptionUniqueId);
public Integer validateExceptionCode(DefineExceptionVo paramException);
public List<SimpleObject> getExceptionsDropDown(Integer customerId, Integer companyId, Integer countryId);
public Integer validateTimeRuleCode(TimeRulesDetailsVo paramTime);
public List<TimeRulesDetailsVo> getTimeRulesListBySearch(TimeRulesDetailsVo paramTime);
public List<TimeExceptionRulesVo> getTimeExceptionById(TimeExceptionRulesVo paramException);
public Integer saveTimeException(TimeExceptionRulesVo paramException);
public List<SimpleObject> getTransactionDatesListForTimeException(Integer customerId, Integer companyId, Integer exceptionUniqueId);
}
| 1,620 | 0.858642 | 0.858642 | 42 | 37.57143 | 41.251923 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.119048 | false | false | 13 |
9b981190b977c48971e0b8c4dd6b6bb7c468cf39 | 23,493,471,130,843 | 183c6b4b4d4bd35fd8ee076fa8c202e48c51c596 | /src/java/com/leong/chapter02_Sorting/section21_Elementary/exercise/Q2_1_9_TraceShell.java | 9bbd335a9cadfe323318955b25890b4d13bc9885 | [] | no_license | YUZHANG001/Algorithms | https://github.com/YUZHANG001/Algorithms | ab0a19d0b6980088be838ffb614bfbb40153bc57 | f892eb913bc6d5f19a8a0edbfbd30d37c9186c3b | refs/heads/master | 2020-12-18T20:10:40.801000 | 2017-12-28T13:04:20 | 2017-12-28T13:04:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.leong.chapter02_Sorting.section21_Elementary.exercise;
import com.leong.chapter02_Sorting.BaseSort;
import edu.princeton.cs.algs4.StdDraw;
import java.awt.*;
/**
* @author: mike
* @since: 2017/4/9
*/
public class Q2_1_9_TraceShell extends BaseSort{
private static int line = 0;
@Override
public BaseSort sort(Comparable[] arr){
int n = arr.length;
// 3x+1 increment sequence: 1, 4, 13, 40, 121, 364, 1093, ...
int h = 1;
while (h < n/3)
h = 3*h + 1;
while (h >= 1) {
// h-sort the array
for (int i = h; i < n; i++) {
int j;
for (j = i; j >= h && less(arr[j], arr[j-h]); j -= h) {
exchange(arr, j, j-h);
}
draw(arr, h, i, j);
line++;
}
h /= 3;
footer(arr);
line++;
}
return this;
}
private static void draw(Comparable[] a, int h, int ith, int jth) {
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(-3.75, line, h + "");
StdDraw.text(-2.50, line, ith + "");
StdDraw.text(-1.25, line, jth + "");
for (int i = 0; i < a.length; i++) {
if (i == jth) StdDraw.setPenColor(StdDraw.BOOK_RED);
else if (i > ith) StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
else if (i < jth) StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
else if ((i % h) == (jth % h)) StdDraw.setPenColor(StdDraw.BLACK);
else StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
StdDraw.text(i, line, String.valueOf(a[i]));
}
}
// display header
public void header(Comparable[] a) {
int n = a.length;
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(n/2.0, -3, "a[ ]");
for (int i = 0; i < n; i++)
StdDraw.text(i, -2, i + "");
StdDraw.text(-3.75, -2, "h");
StdDraw.text(-2.50, -2, "i");
StdDraw.text(-1.25, -2, "j");
StdDraw.setPenColor(StdDraw.BOOK_RED);
StdDraw.line(-4, -1.65, n - 0.5, -1.65);
StdDraw.setPenColor(StdDraw.BLACK);
for (int i = 0; i < a.length; i++)
StdDraw.text(i, -1, String.valueOf(a[i]));
}
public void footer(Comparable[] a) {
int n = a.length;
StdDraw.setPenColor(StdDraw.BLACK);
for (int i = 0; i < n; i++)
StdDraw.text(i, line, String.valueOf(a[i]));
}
public static void main(String[] args) {
String[] a = new String[]{"E","A","S","Y","S","H","E","L","L","S","O","R","T","Q","U","E","S","T","I","O","N"};
int n = a.length;
int rows = 0;
int h = 1;
while (h < n/3){
h = 3*h + 1;
rows += (n - h +1);
}
rows += (n - h +1);
StdDraw.setCanvasSize(30*(n+3), 30*(rows+3));
StdDraw.setXscale(-4, n+1);
StdDraw.setYscale(rows, -4);
StdDraw.setFont(new Font("SansSerif", Font.PLAIN, 13));
Q2_1_9_TraceShell traceShell = new Q2_1_9_TraceShell();
// draw the header
traceShell.header(a);
// sort the array
traceShell.sort(a);
}
}
| UTF-8 | Java | 3,281 | java | Q2_1_9_TraceShell.java | Java | [
{
"context": "lgs4.StdDraw;\n\nimport java.awt.*;\n\n/**\n * @author: mike\n * @since: 2017/4/9\n */\npublic class Q2_1_9_Trace",
"end": 193,
"score": 0.999064564704895,
"start": 189,
"tag": "USERNAME",
"value": "mike"
}
] | null | [] | package com.leong.chapter02_Sorting.section21_Elementary.exercise;
import com.leong.chapter02_Sorting.BaseSort;
import edu.princeton.cs.algs4.StdDraw;
import java.awt.*;
/**
* @author: mike
* @since: 2017/4/9
*/
public class Q2_1_9_TraceShell extends BaseSort{
private static int line = 0;
@Override
public BaseSort sort(Comparable[] arr){
int n = arr.length;
// 3x+1 increment sequence: 1, 4, 13, 40, 121, 364, 1093, ...
int h = 1;
while (h < n/3)
h = 3*h + 1;
while (h >= 1) {
// h-sort the array
for (int i = h; i < n; i++) {
int j;
for (j = i; j >= h && less(arr[j], arr[j-h]); j -= h) {
exchange(arr, j, j-h);
}
draw(arr, h, i, j);
line++;
}
h /= 3;
footer(arr);
line++;
}
return this;
}
private static void draw(Comparable[] a, int h, int ith, int jth) {
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(-3.75, line, h + "");
StdDraw.text(-2.50, line, ith + "");
StdDraw.text(-1.25, line, jth + "");
for (int i = 0; i < a.length; i++) {
if (i == jth) StdDraw.setPenColor(StdDraw.BOOK_RED);
else if (i > ith) StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
else if (i < jth) StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
else if ((i % h) == (jth % h)) StdDraw.setPenColor(StdDraw.BLACK);
else StdDraw.setPenColor(StdDraw.LIGHT_GRAY);
StdDraw.text(i, line, String.valueOf(a[i]));
}
}
// display header
public void header(Comparable[] a) {
int n = a.length;
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(n/2.0, -3, "a[ ]");
for (int i = 0; i < n; i++)
StdDraw.text(i, -2, i + "");
StdDraw.text(-3.75, -2, "h");
StdDraw.text(-2.50, -2, "i");
StdDraw.text(-1.25, -2, "j");
StdDraw.setPenColor(StdDraw.BOOK_RED);
StdDraw.line(-4, -1.65, n - 0.5, -1.65);
StdDraw.setPenColor(StdDraw.BLACK);
for (int i = 0; i < a.length; i++)
StdDraw.text(i, -1, String.valueOf(a[i]));
}
public void footer(Comparable[] a) {
int n = a.length;
StdDraw.setPenColor(StdDraw.BLACK);
for (int i = 0; i < n; i++)
StdDraw.text(i, line, String.valueOf(a[i]));
}
public static void main(String[] args) {
String[] a = new String[]{"E","A","S","Y","S","H","E","L","L","S","O","R","T","Q","U","E","S","T","I","O","N"};
int n = a.length;
int rows = 0;
int h = 1;
while (h < n/3){
h = 3*h + 1;
rows += (n - h +1);
}
rows += (n - h +1);
StdDraw.setCanvasSize(30*(n+3), 30*(rows+3));
StdDraw.setXscale(-4, n+1);
StdDraw.setYscale(rows, -4);
StdDraw.setFont(new Font("SansSerif", Font.PLAIN, 13));
Q2_1_9_TraceShell traceShell = new Q2_1_9_TraceShell();
// draw the header
traceShell.header(a);
// sort the array
traceShell.sort(a);
}
}
| 3,281 | 0.477294 | 0.445596 | 101 | 31.485149 | 23.179718 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.306931 | false | false | 13 |
e95ea4c7311eb19edf6cb988bca67c6eff8f7677 | 9,629,316,700,674 | 52280cf6517f27bde1ad70037bc20f9aaa01d6c5 | /src/com/jd/lottery/lib/db/DBOpenHelper.java | 7c3594f06c34bb40e370090d77b2335c63249f08 | [] | no_license | xiangyong/JDMall | https://github.com/xiangyong/JDMall | 7730ae3395a44d03387f4d4075a1b2c8870c23be | 5ce5a7870e87a67cad500903bc169cd266b5a2e9 | refs/heads/master | 2021-01-16T18:13:41.254000 | 2014-02-26T09:59:08 | 2014-02-26T09:59:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jd.lottery.lib.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.jd.droidlib.persist.sql.AbstractDBOpenHelper;
import com.jd.lottery.lib.model.CurrIssueEntity;
import com.jd.lottery.lib.model.Entry;
import com.jd.lottery.lib.model.MainPageEntity;
import com.jd.lottery.lib.model.PrevIssueEntity;
public class DBOpenHelper
extends AbstractDBOpenHelper
{
private static final String DB_FILE = "jdlottery.db";
private static final int DB_VER = 23;
public DBOpenHelper(Context paramContext)
{
super(paramContext, "jdlottery.db", 23);
}
protected void onCreateTables(SQLiteDatabase paramSQLiteDatabase)
{
createTables(paramSQLiteDatabase, new Class[] { Entry.class });
createTables(paramSQLiteDatabase, new Class[] { MainPageEntity.class });
createTables(paramSQLiteDatabase, new Class[] { CurrIssueEntity.class });
createTables(paramSQLiteDatabase, new Class[] { PrevIssueEntity.class });
}
public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int paramInt1, int paramInt2)
{
dropTables(paramSQLiteDatabase, new String[0]);
onCreate(paramSQLiteDatabase);
}
}
/* Location: C:\Users\yepeng\Documents\classes-dex2jar.jar
* Qualified Name: com.jd.lottery.lib.db.DBOpenHelper
* JD-Core Version: 0.7.0.1
*/ | UTF-8 | Java | 1,386 | java | DBOpenHelper.java | Java | [] | null | [] | package com.jd.lottery.lib.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.jd.droidlib.persist.sql.AbstractDBOpenHelper;
import com.jd.lottery.lib.model.CurrIssueEntity;
import com.jd.lottery.lib.model.Entry;
import com.jd.lottery.lib.model.MainPageEntity;
import com.jd.lottery.lib.model.PrevIssueEntity;
public class DBOpenHelper
extends AbstractDBOpenHelper
{
private static final String DB_FILE = "jdlottery.db";
private static final int DB_VER = 23;
public DBOpenHelper(Context paramContext)
{
super(paramContext, "jdlottery.db", 23);
}
protected void onCreateTables(SQLiteDatabase paramSQLiteDatabase)
{
createTables(paramSQLiteDatabase, new Class[] { Entry.class });
createTables(paramSQLiteDatabase, new Class[] { MainPageEntity.class });
createTables(paramSQLiteDatabase, new Class[] { CurrIssueEntity.class });
createTables(paramSQLiteDatabase, new Class[] { PrevIssueEntity.class });
}
public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int paramInt1, int paramInt2)
{
dropTables(paramSQLiteDatabase, new String[0]);
onCreate(paramSQLiteDatabase);
}
}
/* Location: C:\Users\yepeng\Documents\classes-dex2jar.jar
* Qualified Name: com.jd.lottery.lib.db.DBOpenHelper
* JD-Core Version: 0.7.0.1
*/ | 1,386 | 0.730159 | 0.721501 | 45 | 28.933332 | 27.768408 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.577778 | false | false | 13 |
058e866c4030750a15acd5d327b3c5175e0db88b | 8,057,358,666,186 | 317e76451056dc6848830bdc7f7869238a777432 | /app/src/main/java/com/example/bajian/ndkdemo/NDKJniUtil.java | 8848011c0952df98334ce6769868727ab02bc42c | [] | no_license | bajian/NDKDemo | https://github.com/bajian/NDKDemo | 4775177be3c7f9340e366fbe5d977e65bdb879be | a89442cea47e3616e21d6d2747c3d79961f2df84 | refs/heads/master | 2016-08-11T22:20:52.471000 | 2015-12-28T13:27:45 | 2015-12-28T13:27:45 | 48,693,816 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.bajian.ndkdemo;
/**
* Created by bajian on 2015/12/28.
* email 313066164@qq.com
*/
public class NDKJniUtil {
static {
System.loadLibrary("NDKJniUtil"); //defaultConfig.ndk.moduleName
}
public native String getCString();
}
| UTF-8 | Java | 269 | java | NDKJniUtil.java | Java | [
{
"context": "age com.example.bajian.ndkdemo;\n\n/**\n * Created by bajian on 2015/12/28.\n * email 313066164@qq.com\n */\npubl",
"end": 61,
"score": 0.9995015263557434,
"start": 55,
"tag": "USERNAME",
"value": "bajian"
},
{
"context": "\n/**\n * Created by bajian on 2015/12/28.\n * email 313066164@qq.com\n */\npublic class NDKJniUtil {\n\n static {\n ",
"end": 102,
"score": 0.9998461008071899,
"start": 86,
"tag": "EMAIL",
"value": "313066164@qq.com"
}
] | null | [] | package com.example.bajian.ndkdemo;
/**
* Created by bajian on 2015/12/28.
* email <EMAIL>
*/
public class NDKJniUtil {
static {
System.loadLibrary("NDKJniUtil"); //defaultConfig.ndk.moduleName
}
public native String getCString();
}
| 260 | 0.67658 | 0.613383 | 13 | 19.692308 | 21.061758 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 13 |
d2be84743e0ba2d3f361fdf65c02a9cdc693df9f | 9,912,784,546,487 | 6f672fb72caedccb841ee23f53e32aceeaf1895e | /kik-source/src/org/c/b/b.java | f4b701e9994c039c379f2afb2f00ea55199c7ff0 | [] | no_license | cha63506/CompSecurity | https://github.com/cha63506/CompSecurity | 5c69743f660b9899146ed3cf21eceabe3d5f4280 | eee7e74f4088b9c02dd711c061fc04fb1e4e2654 | refs/heads/master | 2018-03-23T04:15:18.480000 | 2015-12-19T01:29:58 | 2015-12-19T01:29:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package org.c.b;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import org.c.a;
// Referenced classes of package org.c.b:
// a
public class b
implements a
{
private final Map a = new HashMap();
public b()
{
}
private org.c.b.a b(String s)
{
Object obj;
if (s != null && s.length() > 23)
{
obj = new StringTokenizer(s, ".");
if (((StringTokenizer) (obj)).hasMoreTokens())
{
Object obj1 = new StringBuilder();
do
{
Object obj2 = ((StringTokenizer) (obj)).nextToken();
if (((String) (obj2)).length() == 1)
{
((StringBuilder) (obj1)).append(((String) (obj2)));
((StringBuilder) (obj1)).append('.');
} else
if (((StringTokenizer) (obj)).hasMoreTokens())
{
((StringBuilder) (obj1)).append(((String) (obj2)).charAt(0));
((StringBuilder) (obj1)).append("*.");
} else
{
((StringBuilder) (obj1)).append(((String) (obj2)));
}
} while (((StringTokenizer) (obj)).hasMoreTokens());
obj = ((StringBuilder) (obj1)).toString();
} else
{
obj = s;
}
if (((String) (obj)).length() > 23)
{
obj = (new StringBuilder()).append(((String) (obj)).substring(0, 22)).append('*').toString();
}
} else
{
obj = s;
}
this;
JVM INSTR monitorenter ;
obj2 = (org.c.b.a)a.get(obj);
obj1 = obj2;
if (obj2 != null)
{
break MISSING_BLOCK_LABEL_203;
}
if (!((String) (obj)).equals(s))
{
org/c/b/b.getSimpleName();
(new StringBuilder("Logger name '")).append(s).append("' exceeds maximum length of 23 characters, using '").append(((String) (obj))).append("' instead.");
}
obj1 = new org.c.b.a(((String) (obj)));
a.put(obj, obj1);
this;
JVM INSTR monitorexit ;
return ((org.c.b.a) (obj1));
s;
this;
JVM INSTR monitorexit ;
throw s;
}
public final org.c.b a(String s)
{
return b(s);
}
}
| UTF-8 | Java | 2,692 | java | b.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus",
"end": 61,
"score": 0.9996436834335327,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null | [] | // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package org.c.b;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import org.c.a;
// Referenced classes of package org.c.b:
// a
public class b
implements a
{
private final Map a = new HashMap();
public b()
{
}
private org.c.b.a b(String s)
{
Object obj;
if (s != null && s.length() > 23)
{
obj = new StringTokenizer(s, ".");
if (((StringTokenizer) (obj)).hasMoreTokens())
{
Object obj1 = new StringBuilder();
do
{
Object obj2 = ((StringTokenizer) (obj)).nextToken();
if (((String) (obj2)).length() == 1)
{
((StringBuilder) (obj1)).append(((String) (obj2)));
((StringBuilder) (obj1)).append('.');
} else
if (((StringTokenizer) (obj)).hasMoreTokens())
{
((StringBuilder) (obj1)).append(((String) (obj2)).charAt(0));
((StringBuilder) (obj1)).append("*.");
} else
{
((StringBuilder) (obj1)).append(((String) (obj2)));
}
} while (((StringTokenizer) (obj)).hasMoreTokens());
obj = ((StringBuilder) (obj1)).toString();
} else
{
obj = s;
}
if (((String) (obj)).length() > 23)
{
obj = (new StringBuilder()).append(((String) (obj)).substring(0, 22)).append('*').toString();
}
} else
{
obj = s;
}
this;
JVM INSTR monitorenter ;
obj2 = (org.c.b.a)a.get(obj);
obj1 = obj2;
if (obj2 != null)
{
break MISSING_BLOCK_LABEL_203;
}
if (!((String) (obj)).equals(s))
{
org/c/b/b.getSimpleName();
(new StringBuilder("Logger name '")).append(s).append("' exceeds maximum length of 23 characters, using '").append(((String) (obj))).append("' instead.");
}
obj1 = new org.c.b.a(((String) (obj)));
a.put(obj, obj1);
this;
JVM INSTR monitorexit ;
return ((org.c.b.a) (obj1));
s;
this;
JVM INSTR monitorexit ;
throw s;
}
public final org.c.b a(String s)
{
return b(s);
}
}
| 2,682 | 0.448737 | 0.433878 | 92 | 28.26087 | 26.823849 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.445652 | false | false | 13 |
6ebabce260dd0fe935f81bf86dd8add9cb709b32 | 7,593,502,204,927 | 140d970231969fb38eb391037524dbe121e38dc7 | /prjClienteRRHH/src/main/java/ec/com/smx/rrhh/pfa/mdl/dto/id/DetalleSolicitudCompraAccionesBitacoraID.java | 39316eda8c4f898b2959ffc08ce9634e1463ff13 | [] | no_license | jxhxc/cursoGit | https://github.com/jxhxc/cursoGit | 5bb6e2d1ed73e5f4a64484a3a961e755d016b1d3 | 47deb346c16ee810629a022812af99e08df91eca | refs/heads/master | 2021-01-10T09:30:20.971000 | 2015-11-10T12:39:56 | 2015-11-10T12:39:56 | 45,911,471 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ec.com.smx.rrhh.pfa.mdl.dto.id;
import java.io.Serializable;
import java.sql.Types;
import javax.persistence.Column;
import ec.com.kruger.utilitario.dao.commons.annotations.Cast;
import ec.com.kruger.utilitario.dao.commons.annotations.SequenceDataBaseValue;
import ec.com.smx.rrhh.secuencia.DescriptorSecuenciasRRHH;
@SuppressWarnings("serial")
public class DetalleSolicitudCompraAccionesBitacoraID implements Serializable{
public static final String NOMBRE_SECUENCIA = "SPPFASECDETSOLCOMACCBIT";
@Column(name = "CODIGOCOMPANIA", nullable = false)
private Integer codigoCompania;
@Column(name = "CODIGODETALLEBITACORA", nullable = false)
@SequenceDataBaseValue(descriptorClass = DescriptorSecuenciasRRHH.class, name = NOMBRE_SECUENCIA, castTo = @Cast(sqlType = Types.NUMERIC, precision = 15, scale = 0))
private Long codigoDetalleBitacora;
public Integer getCodigoCompania() {
return codigoCompania;
}
public void setCodigoCompania(Integer codigoCompania) {
this.codigoCompania = codigoCompania;
}
public Long getCodigoDetalleBitacora() {
return codigoDetalleBitacora;
}
public void setCodigoDetalleBitacora(Long codigoDetalleBitacora) {
this.codigoDetalleBitacora = codigoDetalleBitacora;
}
}
| UTF-8 | Java | 1,244 | java | DetalleSolicitudCompraAccionesBitacoraID.java | Java | [] | null | [] | package ec.com.smx.rrhh.pfa.mdl.dto.id;
import java.io.Serializable;
import java.sql.Types;
import javax.persistence.Column;
import ec.com.kruger.utilitario.dao.commons.annotations.Cast;
import ec.com.kruger.utilitario.dao.commons.annotations.SequenceDataBaseValue;
import ec.com.smx.rrhh.secuencia.DescriptorSecuenciasRRHH;
@SuppressWarnings("serial")
public class DetalleSolicitudCompraAccionesBitacoraID implements Serializable{
public static final String NOMBRE_SECUENCIA = "SPPFASECDETSOLCOMACCBIT";
@Column(name = "CODIGOCOMPANIA", nullable = false)
private Integer codigoCompania;
@Column(name = "CODIGODETALLEBITACORA", nullable = false)
@SequenceDataBaseValue(descriptorClass = DescriptorSecuenciasRRHH.class, name = NOMBRE_SECUENCIA, castTo = @Cast(sqlType = Types.NUMERIC, precision = 15, scale = 0))
private Long codigoDetalleBitacora;
public Integer getCodigoCompania() {
return codigoCompania;
}
public void setCodigoCompania(Integer codigoCompania) {
this.codigoCompania = codigoCompania;
}
public Long getCodigoDetalleBitacora() {
return codigoDetalleBitacora;
}
public void setCodigoDetalleBitacora(Long codigoDetalleBitacora) {
this.codigoDetalleBitacora = codigoDetalleBitacora;
}
}
| 1,244 | 0.799839 | 0.797428 | 42 | 28.619047 | 33.498367 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.142857 | false | false | 13 |
cf977000c642e7fa3782aa9a4b8f789e209269d7 | 24,524,263,287,359 | f7442e38caa75d85c038d43b22dcf84800b93b3e | /forgame_expense/src/com/fdrj/services/wsbasedataqueryfacade/client/JobRespone.java | 221c36abb2327973ce65668226660f5353402f52 | [] | no_license | langchaocjy/Ecology | https://github.com/langchaocjy/Ecology | 12fdc47ba0a50f6bcea39dcc4c1ff48215f6556d | 50d47606f4ad170514ba5a7d02701fa10595aaaa | refs/heads/master | 2020-04-14T07:49:25.566000 | 2019-01-01T09:39:49 | 2019-01-01T09:39:49 | 163,723,009 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fdrj.services.wsbasedataqueryfacade.client;
import java.util.List;
public class JobRespone extends BaseRespone {
private List<JobResultDTO> list;
public List<JobResultDTO> getList() {
return list;
}
public void setList(List<JobResultDTO> list) {
this.list = list;
}
}
| UTF-8 | Java | 296 | java | JobRespone.java | Java | [] | null | [] | package com.fdrj.services.wsbasedataqueryfacade.client;
import java.util.List;
public class JobRespone extends BaseRespone {
private List<JobResultDTO> list;
public List<JobResultDTO> getList() {
return list;
}
public void setList(List<JobResultDTO> list) {
this.list = list;
}
}
| 296 | 0.746622 | 0.746622 | 17 | 16.411764 | 19.195768 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.882353 | false | false | 13 |
a2463be90719239a0d920370030ca11df8b0fa88 | 11,562,051,987,570 | 8f0606017835cdc2427d925dbc4a25d8b8a894e6 | /src/java/stxship/dis/ecr/ecrInterface/service/EcrInterfaceService.java | 5750d5a7c1fbc1224215b0dc871ae68e74cd205a | [] | no_license | heumjun/common | https://github.com/heumjun/common | 1195c863c209c2ea214318ba54c52d0ff42ba5fc | fccd452d4c2e764094df2767d509e98503bcc048 | refs/heads/master | 2021-08-10T21:10:03.632000 | 2017-11-12T23:58:30 | 2017-11-12T23:58:30 | 110,476,448 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package stxship.dis.ecr.ecrInterface.service;
import java.util.Map;
import stxship.dis.common.command.CommandMap;
public interface EcrInterfaceService {
public Map<String, Object> getEcrInterfaceList( CommandMap commandMap );
public Map<String, Object> saveECRInterface01( CommandMap commandMap ) throws Exception;
public Map<String, Object> saveECRInterface02( CommandMap commandMap ) throws Exception;
}
| UTF-8 | Java | 418 | java | EcrInterfaceService.java | Java | [] | null | [] | package stxship.dis.ecr.ecrInterface.service;
import java.util.Map;
import stxship.dis.common.command.CommandMap;
public interface EcrInterfaceService {
public Map<String, Object> getEcrInterfaceList( CommandMap commandMap );
public Map<String, Object> saveECRInterface01( CommandMap commandMap ) throws Exception;
public Map<String, Object> saveECRInterface02( CommandMap commandMap ) throws Exception;
}
| 418 | 0.80622 | 0.796651 | 14 | 28.857143 | 33.221889 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.071429 | false | false | 13 |
ae9c702f7354e39fe24aaecabc4a955ccf50b7ac | 33,054,068,341,680 | 70a39063f2ef8a5c0dd3b73c274dd88412ed48d1 | /learn/src/main/java/learn/redis/TestTrans.java | 5e787fffa86b151189e4d28d4a222e284546488c | [] | no_license | shenhufei/Katyusha | https://github.com/shenhufei/Katyusha | 2b30d83efb6508bf0f714899402c5308dd913fe6 | e1d5c4fbd5c275759d56c890437e43bea56b8ff4 | refs/heads/master | 2020-08-01T12:30:56.103000 | 2020-07-20T05:48:32 | 2020-07-20T05:48:32 | 210,996,718 | 1 | 0 | null | false | 2019-09-26T04:12:10 | 2019-09-26T04:04:02 | 2019-09-26T04:06:55 | 2019-09-26T04:12:09 | 0 | 1 | 0 | 0 | Java | false | false | package learn.redis;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
/**
* @author shenhufei 测试redis的jedis形式的事物
* @version 1.0
* @Description:
* @date 20200615
*/
public class TestTrans {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","lq");
jsonObject.put("age",23);
//开启事务
Transaction transaction =jedis.multi();
String result = jsonObject.toJSONString();
//jedis.watch(result);
try{
transaction.set("user3",result);
transaction.set("user4",result);
///int a = 1/0;
//执行事务
transaction.exec();
}catch (Exception e){
//放弃事务
transaction.discard();
e.printStackTrace();
}finally {
System.out.println(jedis.get("user3"));
System.out.println(jedis.get("user4"));
//关闭连接
jedis.close();
}
}
}
| UTF-8 | Java | 1,168 | java | TestTrans.java | Java | [
{
"context": "t redis.clients.jedis.Transaction;\n\n/**\n * @author shenhufei 测试redis的jedis形式的事物\n * @version 1.0\n * @Descripti",
"end": 161,
"score": 0.998242974281311,
"start": 152,
"tag": "USERNAME",
"value": "shenhufei"
},
{
"context": "String[] args) {\n Jedis jedis = new Jedis(\"127.0.0.1\",6379);\n\n JSONObject jsonObject = new JSON",
"end": 349,
"score": 0.9997736811637878,
"start": 340,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " JSONObject();\n jsonObject.put(\"username\",\"lq\");\n jsonObject.put(\"age\",23);\n\n //开",
"end": 446,
"score": 0.9918783903121948,
"start": 444,
"tag": "USERNAME",
"value": "lq"
}
] | null | [] | package learn.redis;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
/**
* @author shenhufei 测试redis的jedis形式的事物
* @version 1.0
* @Description:
* @date 20200615
*/
public class TestTrans {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","lq");
jsonObject.put("age",23);
//开启事务
Transaction transaction =jedis.multi();
String result = jsonObject.toJSONString();
//jedis.watch(result);
try{
transaction.set("user3",result);
transaction.set("user4",result);
///int a = 1/0;
//执行事务
transaction.exec();
}catch (Exception e){
//放弃事务
transaction.discard();
e.printStackTrace();
}finally {
System.out.println(jedis.get("user3"));
System.out.println(jedis.get("user4"));
//关闭连接
jedis.close();
}
}
}
| 1,168 | 0.558929 | 0.533929 | 46 | 23.347826 | 17.294403 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.543478 | false | false | 13 |
e4ac262cf01946372168da3e1ec35be3df6354db | 25,718,264,234,839 | 17fe0bb0a55aa4e5e5b4facddd1449fe30a36d6d | /src/main/java/com/zhangwen/learn/zhangwenit/designmodel/visitor/ObjectStructure.java | 6ca549488ecc4bc1229cfd52132748b8ba6cf63f | [] | no_license | gudanrenao/zhangwenit | https://github.com/gudanrenao/zhangwenit | 1de13786cebed791bce83d2f258937085ca45e7c | fe49fecb2f6086a58d32e5f1302eeee92ea950ad | refs/heads/master | 2022-06-22T08:08:11.534000 | 2021-02-17T12:07:12 | 2021-02-17T12:07:12 | 137,471,474 | 2 | 0 | null | false | 2021-04-22T18:54:27 | 2018-06-15T09:55:28 | 2021-02-17T12:07:14 | 2021-04-22T18:54:27 | 12,592 | 0 | 0 | 1 | Java | false | false | package com.zhangwen.learn.zhangwenit.designmodel.visitor;
import java.util.ArrayList;
import java.util.List;
/**
* @Description 枚举元素,提供一个高层接口,允许访问者访问元素
* @Author ZWen
* @Date 2020/4/7 6:52 PM
* @Version 1.0
**/
public class ObjectStructure {
private List<Element> elements = new ArrayList<>();
public void attach(Element element) {
elements.add(element);
}
public void detach(Element element) {
elements.remove(element);
}
public void accept(Visitor visitor) {
for (Element element : elements) {
element.accept(visitor);
}
}
} | UTF-8 | Java | 654 | java | ObjectStructure.java | Java | [
{
"context": " * @Description 枚举元素,提供一个高层接口,允许访问者访问元素\n * @Author ZWen\n * @Date 2020/4/7 6:52 PM\n * @Version 1.0\n **/\npu",
"end": 171,
"score": 0.7508406639099121,
"start": 167,
"tag": "USERNAME",
"value": "ZWen"
}
] | null | [] | package com.zhangwen.learn.zhangwenit.designmodel.visitor;
import java.util.ArrayList;
import java.util.List;
/**
* @Description 枚举元素,提供一个高层接口,允许访问者访问元素
* @Author ZWen
* @Date 2020/4/7 6:52 PM
* @Version 1.0
**/
public class ObjectStructure {
private List<Element> elements = new ArrayList<>();
public void attach(Element element) {
elements.add(element);
}
public void detach(Element element) {
elements.remove(element);
}
public void accept(Visitor visitor) {
for (Element element : elements) {
element.accept(visitor);
}
}
} | 654 | 0.64918 | 0.631148 | 29 | 20.068966 | 18.281197 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.275862 | false | false | 13 |
9f654b54fc68abacd769c76c52406e491a50f8f9 | 32,925,219,314,663 | 20a7850ebcd59e97ee79646890e04e49420d41ed | /PiaoKe/src/com/piaoke/pvke/find/piaokecircle/entity/Data.java | a67dd3cf8713e859830a1d593759aa02a3892794 | [] | no_license | qingshangming/PiaoKe | https://github.com/qingshangming/PiaoKe | c4a9f6e2178aa1ed156d763115387a1835c68d5e | 7b8ec3b2d0126a6afa2867d5d0326ecf0832bfdb | refs/heads/master | 2016-06-06T13:07:44.206000 | 2015-11-06T02:19:57 | 2015-11-06T02:19:57 | 44,431,972 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.piaoke.pvke.find.piaokecircle.entity;
import java.util.List;
/**
* 描述: data类
* @author jingang
* @version 创建时间:2015-11-2 下午3:04:08
* 类说明
*/
public class Data {
private String ai_id;
private String ul_id;
private String ai_image;
private String ai_text;
private String ai_comments;
private String ai_praises;
private String ai_createtime;
private List<ArticleComment> articleComment;
private List<ArticlePraises> articlePraises;
public Data() {
super();
}
public Data(String ai_id, String ul_id, String ai_image, String ai_text,
String ai_comments, String ai_praises, String ai_createtime,
List<ArticleComment> articleComment,
List<ArticlePraises> articlePraises) {
super();
this.ai_id = ai_id;
this.ul_id = ul_id;
this.ai_image = ai_image;
this.ai_text = ai_text;
this.ai_comments = ai_comments;
this.ai_praises = ai_praises;
this.ai_createtime = ai_createtime;
this.articleComment = articleComment;
this.articlePraises = articlePraises;
}
public String getAi_id() {
return ai_id;
}
public void setAi_id(String ai_id) {
this.ai_id = ai_id;
}
public String getUl_id() {
return ul_id;
}
public void setUl_id(String ul_id) {
this.ul_id = ul_id;
}
public String getAi_image() {
return ai_image;
}
public void setAi_image(String ai_image) {
this.ai_image = ai_image;
}
public String getAi_text() {
return ai_text;
}
public void setAi_text(String ai_text) {
this.ai_text = ai_text;
}
public String getAi_comments() {
return ai_comments;
}
public void setAi_comments(String ai_comments) {
this.ai_comments = ai_comments;
}
public String getAi_praises() {
return ai_praises;
}
public void setAi_praises(String ai_praises) {
this.ai_praises = ai_praises;
}
public String getAi_createtime() {
return ai_createtime;
}
public void setAi_createtime(String ai_createtime) {
this.ai_createtime = ai_createtime;
}
public List<ArticleComment> getArticleComment() {
return articleComment;
}
public void setArticleComment(List<ArticleComment> articleComment) {
this.articleComment = articleComment;
}
public List<ArticlePraises> getArticlePraises() {
return articlePraises;
}
public void setArticlePraises(List<ArticlePraises> articlePraises) {
this.articlePraises = articlePraises;
}
@Override
public String toString() {
return "Data [ai_id=" + ai_id + ", ul_id=" + ul_id + ", ai_image="
+ ai_image + ", ai_text=" + ai_text + ", ai_comments="
+ ai_comments + ", ai_praises=" + ai_praises
+ ", ai_createtime=" + ai_createtime + ", articleComment="
+ articleComment + ", articlePraises=" + articlePraises + "]";
}
}
| UTF-8 | Java | 2,688 | java | Data.java | Java | [
{
"context": "port java.util.List;\n\n/**\n * 描述: data类\n * @author jingang\n * @version 创建时间:2015-11-2 下午3:04:08\n * 类说明\n */\n\n",
"end": 111,
"score": 0.9978148341178894,
"start": 104,
"tag": "USERNAME",
"value": "jingang"
}
] | null | [] | package com.piaoke.pvke.find.piaokecircle.entity;
import java.util.List;
/**
* 描述: data类
* @author jingang
* @version 创建时间:2015-11-2 下午3:04:08
* 类说明
*/
public class Data {
private String ai_id;
private String ul_id;
private String ai_image;
private String ai_text;
private String ai_comments;
private String ai_praises;
private String ai_createtime;
private List<ArticleComment> articleComment;
private List<ArticlePraises> articlePraises;
public Data() {
super();
}
public Data(String ai_id, String ul_id, String ai_image, String ai_text,
String ai_comments, String ai_praises, String ai_createtime,
List<ArticleComment> articleComment,
List<ArticlePraises> articlePraises) {
super();
this.ai_id = ai_id;
this.ul_id = ul_id;
this.ai_image = ai_image;
this.ai_text = ai_text;
this.ai_comments = ai_comments;
this.ai_praises = ai_praises;
this.ai_createtime = ai_createtime;
this.articleComment = articleComment;
this.articlePraises = articlePraises;
}
public String getAi_id() {
return ai_id;
}
public void setAi_id(String ai_id) {
this.ai_id = ai_id;
}
public String getUl_id() {
return ul_id;
}
public void setUl_id(String ul_id) {
this.ul_id = ul_id;
}
public String getAi_image() {
return ai_image;
}
public void setAi_image(String ai_image) {
this.ai_image = ai_image;
}
public String getAi_text() {
return ai_text;
}
public void setAi_text(String ai_text) {
this.ai_text = ai_text;
}
public String getAi_comments() {
return ai_comments;
}
public void setAi_comments(String ai_comments) {
this.ai_comments = ai_comments;
}
public String getAi_praises() {
return ai_praises;
}
public void setAi_praises(String ai_praises) {
this.ai_praises = ai_praises;
}
public String getAi_createtime() {
return ai_createtime;
}
public void setAi_createtime(String ai_createtime) {
this.ai_createtime = ai_createtime;
}
public List<ArticleComment> getArticleComment() {
return articleComment;
}
public void setArticleComment(List<ArticleComment> articleComment) {
this.articleComment = articleComment;
}
public List<ArticlePraises> getArticlePraises() {
return articlePraises;
}
public void setArticlePraises(List<ArticlePraises> articlePraises) {
this.articlePraises = articlePraises;
}
@Override
public String toString() {
return "Data [ai_id=" + ai_id + ", ul_id=" + ul_id + ", ai_image="
+ ai_image + ", ai_text=" + ai_text + ", ai_comments="
+ ai_comments + ", ai_praises=" + ai_praises
+ ", ai_createtime=" + ai_createtime + ", articleComment="
+ articleComment + ", articlePraises=" + articlePraises + "]";
}
}
| 2,688 | 0.695489 | 0.690977 | 105 | 24.333334 | 19.429808 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.87619 | false | false | 13 |
4ad2a92e4c4fb3ce6e017b175000cb0930b6c85c | 17,832,704,280,401 | a0dbdffe296add80ef4afee5390277768e8a3865 | /FuncionsProves/Factorial.java | ba0a2a57ad97d54af0f338e7bb1da8d225c1bf28 | [] | no_license | adriangc24/UF2 | https://github.com/adriangc24/UF2 | 39b80fb6805fabc5c199389b4d841e145752e852 | 96a48e5513ee5e1e8f697f5ba6ab1e7b8688164b | refs/heads/master | 2020-05-30T00:40:42.057000 | 2019-05-30T19:24:19 | 2019-05-30T19:24:19 | 189,464,633 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
inici();
}
public static void inici() {
System.out.println("Introdueix un número enter positiu i et diré el factorial:");
double num = validacio();
factorial(num);
}
public static double validacio() {
Scanner sc = new Scanner(System.in);
boolean valid = false;
double num = 0;
while (!valid) {
if (!sc.hasNextInt()) {
System.out.println("Has d'introduïr un enter!");
} else {
num = sc.nextInt();
if (num == 1) {
System.out.println("El factorial de 1 és 1.");
valid = true;
} else if (num < 1) {
System.out.println("Ha de ser un nombre positiu.");
} else {
valid = true;
}
}
}
sc.close();
return num;
}
public static void factorial(double num) {
if (num != 1) {
double res = num;
for (int i = 1; i < num; i++) {
res = res * i;
}
System.out.println("El factorial de " + num + " és " + res + ".");
}
}
}
| UTF-8 | Java | 1,006 | java | Factorial.java | Java | [] | null | [] | import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
inici();
}
public static void inici() {
System.out.println("Introdueix un número enter positiu i et diré el factorial:");
double num = validacio();
factorial(num);
}
public static double validacio() {
Scanner sc = new Scanner(System.in);
boolean valid = false;
double num = 0;
while (!valid) {
if (!sc.hasNextInt()) {
System.out.println("Has d'introduïr un enter!");
} else {
num = sc.nextInt();
if (num == 1) {
System.out.println("El factorial de 1 és 1.");
valid = true;
} else if (num < 1) {
System.out.println("Ha de ser un nombre positiu.");
} else {
valid = true;
}
}
}
sc.close();
return num;
}
public static void factorial(double num) {
if (num != 1) {
double res = num;
for (int i = 1; i < num; i++) {
res = res * i;
}
System.out.println("El factorial de " + num + " és " + res + ".");
}
}
}
| 1,006 | 0.581419 | 0.574426 | 47 | 20.297873 | 19.006063 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.638298 | false | false | 13 |
a947e50f5d4ea20e857d919bb8f65409e724059d | 31,293,131,778,702 | 8373ece37ffb1663b4e407f80d426ba2dfa007df | /examples/src/test/java/org/gridgain/examples/GridMemcacheRestExamplesMultiNodeSelfTest.java | 4e1f1dbcd6d6e2d2551553824b02368791b7aaab | [
"Apache-2.0"
] | permissive | sboikov/ignite-test | https://github.com/sboikov/ignite-test | 09d5f588062ecc20305f30d688682762f2ee0f27 | 2d0728e5f368b4af5495e8957900c5ece42627e8 | refs/heads/master | 2015-08-17T16:21:01.627000 | 2014-12-04T21:36:27 | 2014-12-04T21:36:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* @java.file.header */
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
package org.gridgain.examples;
import org.gridgain.examples.misc.client.memcache.*;
/**
* GridMemcacheRestExample multi-node self test.
*/
public class GridMemcacheRestExamplesMultiNodeSelfTest extends GridMemcacheRestExamplesSelfTest {
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
for (int i = 0; i < RMT_NODES_CNT; i++)
startGrid("memcache-rest-examples-" + i, MemcacheRestExampleNodeStartup.configuration());
}
}
| UTF-8 | Java | 844 | java | GridMemcacheRestExamplesMultiNodeSelfTest.java | Java | [] | null | [] | /* @java.file.header */
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
package org.gridgain.examples;
import org.gridgain.examples.misc.client.memcache.*;
/**
* GridMemcacheRestExample multi-node self test.
*/
public class GridMemcacheRestExamplesMultiNodeSelfTest extends GridMemcacheRestExamplesSelfTest {
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
for (int i = 0; i < RMT_NODES_CNT; i++)
startGrid("memcache-rest-examples-" + i, MemcacheRestExampleNodeStartup.configuration());
}
}
| 844 | 0.43128 | 0.430095 | 23 | 35.695652 | 32.459251 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 13 |
2801d92c5d99af1608387fa89ee85072117b2a2e | 10,419,590,684,615 | f3c979ce8aa52837cdbc8f536f279edcf29b32e1 | /src/main/java/com/xwj/handler/HandlerChain.java | 3cf853cee6bbf2c132ff60813b9bc399a5afc27d | [] | no_license | xuwenjin/xwj-test | https://github.com/xuwenjin/xwj-test | eb5e59da596251a89e652de80b58126c6982aae9 | e1e59ba6b7499729ec55d3d9319ccfe694ff55f7 | refs/heads/master | 2022-12-22T23:05:47.126000 | 2021-04-12T00:59:08 | 2021-04-12T00:59:08 | 141,364,757 | 2 | 3 | null | false | 2022-12-10T02:33:21 | 2018-07-18T01:30:56 | 2021-04-12T00:59:23 | 2022-12-10T02:33:18 | 296 | 2 | 2 | 4 | Java | false | false | package com.xwj.handler;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class HandlerChain implements AbstractHandler {
// 所有链(使用CopyOnWriteArrayList线程安全)
private List<AbstractHandler> handlerList = new CopyOnWriteArrayList<>();
// 链的索引(AtomicInteger原子性)
private AtomicInteger index = new AtomicInteger(0);
// 添加 case
public HandlerChain addHandler(AbstractHandler baseCase) {
handlerList.add(baseCase);
return this;
}
@Override
public void handle(String input, AbstractHandler baseCase) {
// 所有遍历完了,直接返回
if (index.get() == handlerList.size()) {
return;
}
// 获取当前链
AbstractHandler currentHandler = handlerList.get(index.get());
// 修改索引值,以便下次回调获取下个链,达到遍历效果
index.incrementAndGet();
// 调用当前链处理方法
currentHandler.handle(input, this);
}
} | UTF-8 | Java | 995 | java | HandlerChain.java | Java | [] | null | [] | package com.xwj.handler;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class HandlerChain implements AbstractHandler {
// 所有链(使用CopyOnWriteArrayList线程安全)
private List<AbstractHandler> handlerList = new CopyOnWriteArrayList<>();
// 链的索引(AtomicInteger原子性)
private AtomicInteger index = new AtomicInteger(0);
// 添加 case
public HandlerChain addHandler(AbstractHandler baseCase) {
handlerList.add(baseCase);
return this;
}
@Override
public void handle(String input, AbstractHandler baseCase) {
// 所有遍历完了,直接返回
if (index.get() == handlerList.size()) {
return;
}
// 获取当前链
AbstractHandler currentHandler = handlerList.get(index.get());
// 修改索引值,以便下次回调获取下个链,达到遍历效果
index.incrementAndGet();
// 调用当前链处理方法
currentHandler.handle(input, this);
}
} | 995 | 0.752613 | 0.751452 | 38 | 21.68421 | 22.24872 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.289474 | false | false | 13 |
2274cd389ffacc0256220ee701716e0c2b8c651e | 10,419,590,684,516 | 92152f422553f07ee27e63565fa574e6a1e03e35 | /app/src/main/java/com/behemoth/repeat/util/SharedPreference.java | 9a5357fa71e3850026273ef2cfad1033c0ff130d | [] | no_license | endorphin0710/repeat | https://github.com/endorphin0710/repeat | 3a66941c4935ea6233dc37e167604c2fb11cd2b2 | 05f0e2f456ed1e99518a7c1c39f038a57d4b0f06 | refs/heads/master | 2023-03-30T15:30:44.683000 | 2021-04-04T16:48:37 | 2021-04-04T16:48:37 | 289,325,572 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.behemoth.repeat.util;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreference {
private static volatile SharedPreference instance;
private final SharedPreferences sharedPreferences;
public static void init(Context ctx){
instance = new SharedPreference(ctx);
}
private SharedPreference(Context ctx){
sharedPreferences = ctx.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
}
public static SharedPreference getInstance(){
return instance;
}
public SharedPreference(Context ctx, String name){
this.sharedPreferences = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
}
public void putString(String key, String value){
this.sharedPreferences.edit().putString(key, value).apply();
}
public String getString(String key, String def){
return this.sharedPreferences.getString(key, def);
}
public void putBoolean(String key, boolean b){
this.sharedPreferences.edit().putBoolean(key, b).apply();
}
public boolean getBoolean(String key, boolean defaultValue){
return this.sharedPreferences.getBoolean(key, defaultValue);
}
public void setRefresh(String key, int value){
this.sharedPreferences.edit().putInt(key, value).commit();
int main = getRefresh(Constants.REFRESH_MAIN, 0);
int mark = getRefresh(Constants.REFRESH_MARK, 0);
int recents = getRefresh(Constants.REFRESH_RECENTS, 0);
if(main + mark + recents >= 3){
initializeRefresh();
}
}
public int getRefresh(String key, int def){
return this.sharedPreferences.getInt(key, def);
}
public void initializeRefresh(){
this.sharedPreferences.edit().putInt(Constants.DATA_CHANGED, 0).apply();
this.sharedPreferences.edit().putInt(Constants.REFRESH_MAIN, 0).apply();
this.sharedPreferences.edit().putInt(Constants.REFRESH_MARK, 0).apply();
this.sharedPreferences.edit().putInt(Constants.REFRESH_RECENTS, 0).apply();
}
public void onDataChanged(){
setRefresh(Constants.DATA_CHANGED, 1);
setRefresh(Constants.REFRESH_MAIN, 0);
setRefresh(Constants.REFRESH_MARK, 0);
setRefresh(Constants.REFRESH_RECENTS, 0);
}
public void resetAll(){
SharedPreference.getInstance().putString(Constants.LOGIN_TYPE, "");
SharedPreference.getInstance().putString(Constants.USER_ID, "");
SharedPreference.getInstance().putString(Constants.USER_NICKNAME, "");
setRefresh(Constants.DATA_CHANGED, 0);
setRefresh(Constants.REFRESH_MAIN, 0);
setRefresh(Constants.REFRESH_MARK, 0);
setRefresh(Constants.REFRESH_RECENTS, 0);
}
}
| UTF-8 | Java | 2,810 | java | SharedPreference.java | Java | [] | null | [] | package com.behemoth.repeat.util;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreference {
private static volatile SharedPreference instance;
private final SharedPreferences sharedPreferences;
public static void init(Context ctx){
instance = new SharedPreference(ctx);
}
private SharedPreference(Context ctx){
sharedPreferences = ctx.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
}
public static SharedPreference getInstance(){
return instance;
}
public SharedPreference(Context ctx, String name){
this.sharedPreferences = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
}
public void putString(String key, String value){
this.sharedPreferences.edit().putString(key, value).apply();
}
public String getString(String key, String def){
return this.sharedPreferences.getString(key, def);
}
public void putBoolean(String key, boolean b){
this.sharedPreferences.edit().putBoolean(key, b).apply();
}
public boolean getBoolean(String key, boolean defaultValue){
return this.sharedPreferences.getBoolean(key, defaultValue);
}
public void setRefresh(String key, int value){
this.sharedPreferences.edit().putInt(key, value).commit();
int main = getRefresh(Constants.REFRESH_MAIN, 0);
int mark = getRefresh(Constants.REFRESH_MARK, 0);
int recents = getRefresh(Constants.REFRESH_RECENTS, 0);
if(main + mark + recents >= 3){
initializeRefresh();
}
}
public int getRefresh(String key, int def){
return this.sharedPreferences.getInt(key, def);
}
public void initializeRefresh(){
this.sharedPreferences.edit().putInt(Constants.DATA_CHANGED, 0).apply();
this.sharedPreferences.edit().putInt(Constants.REFRESH_MAIN, 0).apply();
this.sharedPreferences.edit().putInt(Constants.REFRESH_MARK, 0).apply();
this.sharedPreferences.edit().putInt(Constants.REFRESH_RECENTS, 0).apply();
}
public void onDataChanged(){
setRefresh(Constants.DATA_CHANGED, 1);
setRefresh(Constants.REFRESH_MAIN, 0);
setRefresh(Constants.REFRESH_MARK, 0);
setRefresh(Constants.REFRESH_RECENTS, 0);
}
public void resetAll(){
SharedPreference.getInstance().putString(Constants.LOGIN_TYPE, "");
SharedPreference.getInstance().putString(Constants.USER_ID, "");
SharedPreference.getInstance().putString(Constants.USER_NICKNAME, "");
setRefresh(Constants.DATA_CHANGED, 0);
setRefresh(Constants.REFRESH_MAIN, 0);
setRefresh(Constants.REFRESH_MARK, 0);
setRefresh(Constants.REFRESH_RECENTS, 0);
}
}
| 2,810 | 0.685765 | 0.680071 | 81 | 33.691357 | 28.7817 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.82716 | false | false | 13 |
d8084d40c173b8c17670469c9650c99dace088d0 | 31,903,017,092,416 | c074c20b796ceedd6b5b231e85a76b81f7ff150a | /src/main/java/SpringBoot/Policy_Module_Pro_Max/repositories/RemedyRepository.java | 5389e171e062932bf1fe5fbd8e80d8f5c802e0bb | [] | no_license | the-stranded-alien/Policy_Module_SpringBoot_05 | https://github.com/the-stranded-alien/Policy_Module_SpringBoot_05 | a81b05b71c778321c4ad51a1e8433add4b0257cf | 37a2cdc8bf2b560ecc312e411acaf9b8d69ed8b0 | refs/heads/master | 2023-05-06T22:52:41.847000 | 2021-05-31T17:17:04 | 2021-05-31T17:17:04 | 372,548,031 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package SpringBoot.Policy_Module_Pro_Max.repositories;
import SpringBoot.Policy_Module_Pro_Max.models.Remedy;
import SpringBoot.Policy_Module_Pro_Max.models.Activity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDateTime;
import java.util.List;
public interface RemedyRepository extends JpaRepository<Remedy, Long> {
Remedy findByActivity(Activity activity);
Page<Remedy> findByActivity(Activity activity, Pageable pageable);
List<Remedy> findAllByStatusOrderByActionTimeAsc(Boolean status);
List<Remedy> findAllByStatusAndActionTimeBetween(Boolean status, LocalDateTime actionStartTime, LocalDateTime actionEndTime);
}
| UTF-8 | Java | 772 | java | RemedyRepository.java | Java | [] | null | [] | package SpringBoot.Policy_Module_Pro_Max.repositories;
import SpringBoot.Policy_Module_Pro_Max.models.Remedy;
import SpringBoot.Policy_Module_Pro_Max.models.Activity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDateTime;
import java.util.List;
public interface RemedyRepository extends JpaRepository<Remedy, Long> {
Remedy findByActivity(Activity activity);
Page<Remedy> findByActivity(Activity activity, Pageable pageable);
List<Remedy> findAllByStatusOrderByActionTimeAsc(Boolean status);
List<Remedy> findAllByStatusAndActionTimeBetween(Boolean status, LocalDateTime actionStartTime, LocalDateTime actionEndTime);
}
| 772 | 0.832902 | 0.832902 | 17 | 44.411766 | 32.730736 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.941176 | false | false | 13 |
60dba4f67a34fcc47107f64b586db24dff4cebdf | 33,775,622,861,144 | 74f1c10f8b731d4f868ffb4043ac650c7d462415 | /src/main/java/io/gjf/weibo/TopSearch.java | 33075d18f53b372e236abc5939b6b71321dd8d20 | [] | no_license | liangaolei/GoodNews | https://github.com/liangaolei/GoodNews | 5f72bae6408be0206c4306d6869cb74f046ea242 | 00acb86afdc7e4c791839e33b1517b6aa1fe0244 | refs/heads/master | 2020-07-29T19:52:27.741000 | 2019-08-31T14:49:05 | 2019-08-31T14:49:05 | 209,939,880 | 1 | 0 | null | true | 2019-09-21T06:58:06 | 2019-09-21T06:58:04 | 2019-08-31T14:49:57 | 2019-08-31T14:49:55 | 8 | 0 | 0 | 0 | null | false | false | package io.gjf.weibo;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
/**
* Create by GuoJF on 2019/8/31
*/
public class TopSearch {
public static ArrayList<TopSearchBean> getTopSearch(String urltext) throws Exception {
//获取主页
String url = urltext;
Connection connection = Jsoup.connect(url);
String header = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\n" +
"Accept-Encoding: gzip, deflate, br\n" +
"Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-HK;q=0.6\n" +
"Cache-Control: no-cache\n" +
"Connection: keep-alive\n" +
"Cookie: SINAGLOBAL=6179870341432.93.1533800092867; ALF=1589373543; SCF=AhxMlkEVRFl8jS_WUE3nWlro9IFd3MKb6bfqkTes2fn-lCrj4kqFcM7Bx0iS43uSKRmXmauSy55e8DVvFBbPWZo.; SUHB=0rrLqIyjpfCVoz; SUB=_2AkMqX9GOf8PxqwJRmP0RzmnlaYlzyQ_EieKcAyBVJRMxHRl-yT83qmETtRB6Ad__YRmvBlgXDZk3I_qoRN1aLYMz16nd; SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9WhDyHZjJmn_QafehlGZWhcK; UM_distinctid=16cbca0d65c3bc-0ba1924bf5cebd-e353165-1fa400-16cbca0d65da96; UOR=,,www.baidu.com; _s_tentry=www.baidu.com; Apache=9951297836890.924.1567250222150; ULV=1567250222159:23:3:2:9951297836890.924.1567250222150:1567247824657; WBStorage=f54cf4e4362237da|undefined\n" +
"Host: s.weibo.com\n" +
"Pragma: no-cache\n" +
"Referer: https://www.baidu.com/s?wd=%E5%BE%AE%E5%8D%9A%E7%83%AD%E6%90%9C&rsv_spt=1&rsv_iqid=0x9a79e95b000de2ea&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=&tn=baiduhome_pg&ch=&rsv_enter=1&rsv_dl=ib&inputT=11935\n" +
"Upgrade-Insecure-Requests: 1\n" +
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36";
for (String s : header.split("\n")) {
String[] value = s.split(":");
connection.header(value[0], value[1]);
}
Connection.Response response = connection.ignoreContentType(true).method(Connection.Method.GET).execute();
Document document = response.parse();
//System.out.println(document.body().html());
Elements topSearchNameList = document.getElementsByClass("td-02");
ArrayList<TopSearchBean> searchBeans = new ArrayList<>();
topSearchNameList.forEach((name) -> {
System.out.println(name);
});
topSearchNameList.forEach((name) -> {
System.out.println(name);
// System.out.println(name.getElementsByAttributeValueContaining("href","/").html());
if (!name.toString().contains("href_to")) {
if (!name.toString().contains("javascript:void(0)")) {
searchBeans.add(new TopSearchBean(name.text().split(" ")[0], "https://s.weibo.com" + name.toString().split("<a href=\"")[1].split("\" target=\"_blank\">")[0]));
}else {
searchBeans.add(new TopSearchBean(name.text().split(" ")[0], "https://s.weibo.com" + name.toString().split("<a href=\"")[1].split("\" href=\"javascript:void")[0]));
}
} else {
String s1 = name.toString().split("<a href_to=\"")[1];
System.out.println(s1);
String s2 = s1.split("\" href=\"javascript:void")[0];
System.out.println(s2);
searchBeans.add(new TopSearchBean(name.text().split(" ")[0], "https://s.weibo.com" + name.toString().split("<a href_to=\"")[1].split("\" href=\"javascript:void")[0]));
}
});
searchBeans.forEach(topSearchBean -> {
//System.out.println(topSearchBean.toString());
});
return searchBeans;
}
}
| UTF-8 | Java | 3,973 | java | TopSearch.java | Java | [
{
"context": "ts;\n\nimport java.util.ArrayList;\n\n/**\n * Create by GuoJF on 2019/8/31\n */\npublic class TopSearch {\n pub",
"end": 227,
"score": 0.9996566772460938,
"start": 222,
"tag": "USERNAME",
"value": "GuoJF"
},
{
"context": "951297836890.924.1567250222150; ULV=1567250222159:23:3:2:9951297836890.924.1567250222150:1567247824657; WB",
"end": 1399,
"score": 0.9125099182128906,
"start": 1393,
"tag": "IP_ADDRESS",
"value": "23:3:2"
}
] | null | [] | package io.gjf.weibo;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
/**
* Create by GuoJF on 2019/8/31
*/
public class TopSearch {
public static ArrayList<TopSearchBean> getTopSearch(String urltext) throws Exception {
//获取主页
String url = urltext;
Connection connection = Jsoup.connect(url);
String header = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\n" +
"Accept-Encoding: gzip, deflate, br\n" +
"Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-HK;q=0.6\n" +
"Cache-Control: no-cache\n" +
"Connection: keep-alive\n" +
"Cookie: SINAGLOBAL=6179870341432.93.1533800092867; ALF=1589373543; SCF=AhxMlkEVRFl8jS_WUE3nWlro9IFd3MKb6bfqkTes2fn-lCrj4kqFcM7Bx0iS43uSKRmXmauSy55e8DVvFBbPWZo.; SUHB=0rrLqIyjpfCVoz; SUB=_2AkMqX9GOf8PxqwJRmP0RzmnlaYlzyQ_EieKcAyBVJRMxHRl-yT83qmETtRB6Ad__YRmvBlgXDZk3I_qoRN1aLYMz16nd; SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9WhDyHZjJmn_QafehlGZWhcK; UM_distinctid=16cbca0d65c3bc-0ba1924bf5cebd-e353165-1fa400-16cbca0d65da96; UOR=,,www.baidu.com; _s_tentry=www.baidu.com; Apache=9951297836890.924.1567250222150; ULV=1567250222159:23:3:2:9951297836890.924.1567250222150:1567247824657; WBStorage=f54cf4e4362237da|undefined\n" +
"Host: s.weibo.com\n" +
"Pragma: no-cache\n" +
"Referer: https://www.baidu.com/s?wd=%E5%BE%AE%E5%8D%9A%E7%83%AD%E6%90%9C&rsv_spt=1&rsv_iqid=0x9a79e95b000de2ea&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=&tn=baiduhome_pg&ch=&rsv_enter=1&rsv_dl=ib&inputT=11935\n" +
"Upgrade-Insecure-Requests: 1\n" +
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36";
for (String s : header.split("\n")) {
String[] value = s.split(":");
connection.header(value[0], value[1]);
}
Connection.Response response = connection.ignoreContentType(true).method(Connection.Method.GET).execute();
Document document = response.parse();
//System.out.println(document.body().html());
Elements topSearchNameList = document.getElementsByClass("td-02");
ArrayList<TopSearchBean> searchBeans = new ArrayList<>();
topSearchNameList.forEach((name) -> {
System.out.println(name);
});
topSearchNameList.forEach((name) -> {
System.out.println(name);
// System.out.println(name.getElementsByAttributeValueContaining("href","/").html());
if (!name.toString().contains("href_to")) {
if (!name.toString().contains("javascript:void(0)")) {
searchBeans.add(new TopSearchBean(name.text().split(" ")[0], "https://s.weibo.com" + name.toString().split("<a href=\"")[1].split("\" target=\"_blank\">")[0]));
}else {
searchBeans.add(new TopSearchBean(name.text().split(" ")[0], "https://s.weibo.com" + name.toString().split("<a href=\"")[1].split("\" href=\"javascript:void")[0]));
}
} else {
String s1 = name.toString().split("<a href_to=\"")[1];
System.out.println(s1);
String s2 = s1.split("\" href=\"javascript:void")[0];
System.out.println(s2);
searchBeans.add(new TopSearchBean(name.text().split(" ")[0], "https://s.weibo.com" + name.toString().split("<a href_to=\"")[1].split("\" href=\"javascript:void")[0]));
}
});
searchBeans.forEach(topSearchBean -> {
//System.out.println(topSearchBean.toString());
});
return searchBeans;
}
}
| 3,973 | 0.619168 | 0.541236 | 104 | 37.125 | 74.61087 | 636 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.701923 | false | false | 13 |
1dcb4e101a5445aaabe259350aed30ce929f2657 | 33,852,932,268,801 | f784d8065ce1bd1a6031cce2b0307fcb6e0869f4 | /pertemuan12/exercise07/src/com/multiplatform/Person.java | 48ec72d5f0c926daaf4e95635d1ec08cbf87ba98 | [] | no_license | jeinecl/MP2020-S11710101 | https://github.com/jeinecl/MP2020-S11710101 | d1e3baef19239dac0d996ee6634773fadb73040e | 41bccaedb043cb0b14ee1b0681a5ea1ceeb7f3d1 | refs/heads/master | 2022-11-14T10:33:01.685000 | 2020-07-06T06:21:46 | 2020-07-06T06:21:46 | 269,558,464 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.multiplatform;
public class Person {
//fields
private String firstName;
private String lastName;
private int age;
//methods
public String getFirstName(){
return this.firstName;
}
public String getLastName(){
return this.lastName;
}
public int getAge(){
return this.age;
}
public String setFirstName(String firstName){
return this.firstName = firstName;
}
public String setLastName(String lastName){
return this.lastName = lastName;
}
public int setAge(int age){
return this.age = age;
}
public boolean isTeen(){
if(age > 12 && age < 20){
return true;
}
return false;
}
public String getFullName(){
if(firstName.isEmpty() && lastName.isEmpty()){
return "";
}
if(lastName.isEmpty()){
return this.firstName;
}
if(firstName.isEmpty()){
return this.lastName;
}
return firstName + " " + lastName;
}
}
| UTF-8 | Java | 1,071 | java | Person.java | Java | [] | null | [] | package com.multiplatform;
public class Person {
//fields
private String firstName;
private String lastName;
private int age;
//methods
public String getFirstName(){
return this.firstName;
}
public String getLastName(){
return this.lastName;
}
public int getAge(){
return this.age;
}
public String setFirstName(String firstName){
return this.firstName = firstName;
}
public String setLastName(String lastName){
return this.lastName = lastName;
}
public int setAge(int age){
return this.age = age;
}
public boolean isTeen(){
if(age > 12 && age < 20){
return true;
}
return false;
}
public String getFullName(){
if(firstName.isEmpty() && lastName.isEmpty()){
return "";
}
if(lastName.isEmpty()){
return this.firstName;
}
if(firstName.isEmpty()){
return this.lastName;
}
return firstName + " " + lastName;
}
}
| 1,071 | 0.557423 | 0.553688 | 46 | 22.282608 | 14.334002 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 13 |
f5d82074b2a72defcb0ace22fb6ab418a6ddef67 | 27,084,063,825,285 | 7092e4e2cc2eec5def9f85eb5d56eae8171b3809 | /Service-Manager/src/main/java/cn/cloudbot/servicemanager/service/rss/servicers/WechatService.java | 6953929382d693e5b0d8aff0786e9ed0ab7d239b | [] | no_license | CloudBotTeam/service-manager | https://github.com/CloudBotTeam/service-manager | 5ac951acf527b8552faf4c725b2c7c70984ded3f | 2fd9bc2fee906a6e2a3dd1eda5ac786974afcc35 | refs/heads/master | 2020-04-10T17:32:22.075000 | 2019-06-19T16:56:40 | 2019-06-19T16:56:40 | 161,176,971 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.cloudbot.servicemanager.service.rss.servicers;
import cn.cloudbot.common.Message.BotMessage.MessageSegmentType;
import cn.cloudbot.common.Message.BotMessage.RobotSendMessage;
import cn.cloudbot.common.Message.BotMessage.RobotSendMessageSegment;
import cn.cloudbot.common.Message.ServiceMessage.RobotRecvMessage;
import cn.cloudbot.common.Message2.RobotSendMessage2;
import cn.cloudbot.servicemanager.service.Servicer;
import cn.cloudbot.servicemanager.service.rss.service.ChannelService;
import cn.cloudbot.servicemanager.service.rss.pojo.ChannelItem;
import cn.cloudbot.servicemanager.service.rss.pojo.Rss;
import cn.cloudbot.servicemanager.service.rss.service.RedisRssService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.Scanner;
@Data
@Component("wechat")
public class WechatService extends Servicer<RobotSendMessage2> {
@Autowired
private ChannelService channelController;
@Autowired
private RedisRssService redisRssService;
private RobotSendMessage message;
// 公众号名称
private String account_name;
// 公众号及对应的 ID
private HashMap<String, String> accountID = new HashMap<>();
@Override
public String serviceName() {
return "wechat";
}
@Override
public boolean if_accept(RobotSendMessage2 data) {
// 是否被AT
//boolean ated = false;
boolean name_called = false;
for (RobotSendMessageSegment segment:
data.getRobotSendMessage().getMessage()) {
// if (segment.getType().equals(MessageSegmentType.AT)) {
// ated = true;
// }
// if (segment.getType().equals(MessageSegmentType.TEXT) && segment.getData().getText().contains(serviceName())) {
// name_called = true;
//
// Iterator iter = accountID.keySet().iterator();
// while (iter.hasNext()) {
// String name = iter.next().toString();
//
// if(segment.getData().getText().contains(name)){
// this.account_name = name;
// break;
// }
// }
// }
if (segment.getType().equals(MessageSegmentType.TEXT)) {
if(segment.getData().getText().contains("公众号") ||
segment.getData().getText().contains("推送") ||
segment.getData().getText().contains("漫画") ||
segment.getData().getText().contains("文章")) {
Iterator iter = accountID.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next().toString();
if(segment.getData().getText().contains(name)){
name_called = true;
this.account_name = name;
break;
}
}
}
}
}
return name_called;
}
@Override
public void running_logic() throws InterruptedException {
accountID.put("知乎日报", "zhihuribao");
accountID.put("机器之心", "almosthuman2014");
accountID.put("混子曰", "hey-stone");
accountID.put("游戏时光", "VGTIME2015");
accountID.put("机核", "gamecores");
List<String> St = new ArrayList<>();
St.add("说到这个,");
St.add("既然你们在讨论这个,那");
St.add("你们对这种东西感兴趣吗,那");
St.add("告诉你们一个秘密,");
List<String> Mid = new ArrayList<>();
Mid.add("我发现");
Mid.add("看起来");
Mid.add("听说");
Mid.add("你们知道吗,");
List<String> Ed = new ArrayList<>();
Ed.add("发新推送了:");
Ed.add("发了一些精彩的文章:");
Ed.add("活过来了:");
Ed.add("最近有了一些动作:");
while (true) {
RobotSendMessage2 message2 = this.get_data();
this.message = message2.getRobotSendMessage(); // 阻塞直到收到消息
Rss rss = channelController.getWechatById(accountID.get(account_name));
RobotRecvMessage robotRecvMessage = new RobotRecvMessage();
StringBuilder articles = new StringBuilder();
int StID = (int)(Math.random()*1000) % 4;
int MidID = (int)(Math.random()*1000) % 4;
int EdID = (int)(Math.random()*1000) % 4;
articles.append(St.get(StID) + Mid.get(MidID) + account_name + "公众号" + Ed.get(EdID) + "\n");
ArrayList<ChannelItem> items = rss.getChannel().getItems();
for (int i = 0; i < 3; i++) {
articles.append(items.get(i).getTitle() + '\n');
articles.append("阅读这篇文章-> " + items.get(i).getLink() + '\n' + '\n');
}
robotRecvMessage.setMessage(articles.toString());
sendProcessedDataSingle(robotRecvMessage, message2);
}
}
// public static void main(String [] args) {
// WechatService test = new WechatService();
// test.running_logic();
// }
}
| UTF-8 | Java | 5,444 | java | WechatService.java | Java | [
{
"context": "ruptedException {\n\n accountID.put(\"知乎日报\", \"zhihuribao\");\n accountID.put(\"机器之心\", \"almosthuman2014",
"end": 3306,
"score": 0.9890671372413635,
"start": 3296,
"tag": "USERNAME",
"value": "zhihuribao"
},
{
"context": "报\", \"zhihuribao\");\n accountID.put(\"机器之心\", \"almosthuman2014\");\n accountID.put(\"混子曰\", \"hey-stone\");\n",
"end": 3353,
"score": 0.8363043665885925,
"start": 3341,
"tag": "USERNAME",
"value": "almosthuman2"
},
{
"context": "\"almosthuman2014\");\n accountID.put(\"混子曰\", \"hey-stone\");\n accountID.put(\"游戏时光\", \"VGTIME2015\");\n ",
"end": 3399,
"score": 0.9512774348258972,
"start": 3390,
"tag": "USERNAME",
"value": "hey-stone"
}
] | null | [] | package cn.cloudbot.servicemanager.service.rss.servicers;
import cn.cloudbot.common.Message.BotMessage.MessageSegmentType;
import cn.cloudbot.common.Message.BotMessage.RobotSendMessage;
import cn.cloudbot.common.Message.BotMessage.RobotSendMessageSegment;
import cn.cloudbot.common.Message.ServiceMessage.RobotRecvMessage;
import cn.cloudbot.common.Message2.RobotSendMessage2;
import cn.cloudbot.servicemanager.service.Servicer;
import cn.cloudbot.servicemanager.service.rss.service.ChannelService;
import cn.cloudbot.servicemanager.service.rss.pojo.ChannelItem;
import cn.cloudbot.servicemanager.service.rss.pojo.Rss;
import cn.cloudbot.servicemanager.service.rss.service.RedisRssService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.Scanner;
@Data
@Component("wechat")
public class WechatService extends Servicer<RobotSendMessage2> {
@Autowired
private ChannelService channelController;
@Autowired
private RedisRssService redisRssService;
private RobotSendMessage message;
// 公众号名称
private String account_name;
// 公众号及对应的 ID
private HashMap<String, String> accountID = new HashMap<>();
@Override
public String serviceName() {
return "wechat";
}
@Override
public boolean if_accept(RobotSendMessage2 data) {
// 是否被AT
//boolean ated = false;
boolean name_called = false;
for (RobotSendMessageSegment segment:
data.getRobotSendMessage().getMessage()) {
// if (segment.getType().equals(MessageSegmentType.AT)) {
// ated = true;
// }
// if (segment.getType().equals(MessageSegmentType.TEXT) && segment.getData().getText().contains(serviceName())) {
// name_called = true;
//
// Iterator iter = accountID.keySet().iterator();
// while (iter.hasNext()) {
// String name = iter.next().toString();
//
// if(segment.getData().getText().contains(name)){
// this.account_name = name;
// break;
// }
// }
// }
if (segment.getType().equals(MessageSegmentType.TEXT)) {
if(segment.getData().getText().contains("公众号") ||
segment.getData().getText().contains("推送") ||
segment.getData().getText().contains("漫画") ||
segment.getData().getText().contains("文章")) {
Iterator iter = accountID.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next().toString();
if(segment.getData().getText().contains(name)){
name_called = true;
this.account_name = name;
break;
}
}
}
}
}
return name_called;
}
@Override
public void running_logic() throws InterruptedException {
accountID.put("知乎日报", "zhihuribao");
accountID.put("机器之心", "almosthuman2014");
accountID.put("混子曰", "hey-stone");
accountID.put("游戏时光", "VGTIME2015");
accountID.put("机核", "gamecores");
List<String> St = new ArrayList<>();
St.add("说到这个,");
St.add("既然你们在讨论这个,那");
St.add("你们对这种东西感兴趣吗,那");
St.add("告诉你们一个秘密,");
List<String> Mid = new ArrayList<>();
Mid.add("我发现");
Mid.add("看起来");
Mid.add("听说");
Mid.add("你们知道吗,");
List<String> Ed = new ArrayList<>();
Ed.add("发新推送了:");
Ed.add("发了一些精彩的文章:");
Ed.add("活过来了:");
Ed.add("最近有了一些动作:");
while (true) {
RobotSendMessage2 message2 = this.get_data();
this.message = message2.getRobotSendMessage(); // 阻塞直到收到消息
Rss rss = channelController.getWechatById(accountID.get(account_name));
RobotRecvMessage robotRecvMessage = new RobotRecvMessage();
StringBuilder articles = new StringBuilder();
int StID = (int)(Math.random()*1000) % 4;
int MidID = (int)(Math.random()*1000) % 4;
int EdID = (int)(Math.random()*1000) % 4;
articles.append(St.get(StID) + Mid.get(MidID) + account_name + "公众号" + Ed.get(EdID) + "\n");
ArrayList<ChannelItem> items = rss.getChannel().getItems();
for (int i = 0; i < 3; i++) {
articles.append(items.get(i).getTitle() + '\n');
articles.append("阅读这篇文章-> " + items.get(i).getLink() + '\n' + '\n');
}
robotRecvMessage.setMessage(articles.toString());
sendProcessedDataSingle(robotRecvMessage, message2);
}
}
// public static void main(String [] args) {
// WechatService test = new WechatService();
// test.running_logic();
// }
}
| 5,444 | 0.574167 | 0.567777 | 159 | 31.477987 | 26.929173 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.553459 | false | false | 13 |
a83da53da5e0de4929bb78c1b0327a0ea65889b0 | 34,067,680,632,841 | 9b65bd0315c24c3aa678755a72ce6420bf2d8607 | /java/com/yy/game/cloudns/object/Zone.java | 246a20704dc224150973dbde934dcbf815c4fc89 | [
"Apache-2.0"
] | permissive | Cloudxtreme/cloudns | https://github.com/Cloudxtreme/cloudns | 2f4b0800f81dc30983e7106aed9a1388684344ed | feda7fe2e2c25e143e18938cc0db7fcb5030eff8 | refs/heads/master | 2021-05-27T23:22:46.308000 | 2013-11-29T11:39:32 | 2013-11-29T11:39:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yy.game.cloudns.object;
import java.util.Date;
/**
*
*
* @author jason.he
* @date 2013-11-15
*/
public class Zone implements IResult {
private int id;
private String name;
private int status;
private Date ctime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getCtime() {
return ctime;
}
public void setCtime(Date ctime) {
this.ctime = ctime;
}
}
| UTF-8 | Java | 655 | java | Zone.java | Java | [
{
"context": "t;\n\nimport java.util.Date;\n\n/**\n * \n * \n * @author jason.he\n * @date 2013-11-15\n */\npublic class Zone impleme",
"end": 92,
"score": 0.7644277811050415,
"start": 84,
"tag": "NAME",
"value": "jason.he"
}
] | null | [] | package com.yy.game.cloudns.object;
import java.util.Date;
/**
*
*
* @author jason.he
* @date 2013-11-15
*/
public class Zone implements IResult {
private int id;
private String name;
private int status;
private Date ctime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getCtime() {
return ctime;
}
public void setCtime(Date ctime) {
this.ctime = ctime;
}
}
| 655 | 0.651908 | 0.639695 | 50 | 12.1 | 12.161003 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 13 |
228a2ca79814a1d9f43051f8a8dd8f3d3d0faa33 | 10,411,000,726,153 | f15459a6a56240cb40829bee4198e748d55043c7 | /src/gwt/html5/file/client/MultipleFileUpload.java | 38e2d4274b19d7c642707e5f148f4a098a3fde6a | [] | no_license | mguiral/GwtFileApi | https://github.com/mguiral/GwtFileApi | 4c0af4b65b58461c963cb8da18bb9100c491b391 | 522de7ef5865e1ee39f39a82b553027905ffba8d | refs/heads/master | 2016-09-01T17:54:26.971000 | 2013-03-16T23:08:43 | 2013-03-16T23:08:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gwt.html5.file.client;
import gwt.html5.file.dom.FileListElement;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.FileUpload;
public class MultipleFileUpload extends FileUpload{
public interface MultiFileSelectedHandler {
void onFileSelected(FileListElement fileList);
}
public MultipleFileUpload() {
super();
getElement().setAttribute("multiple", "");
}
public HandlerRegistration addChangeHandler(ChangeHandler handler) {
throw new UnsupportedOperationException(
"Please use addChangeHandler(MultiFileSelectedHandler handler) method instead");
}
public void addChangeHandler(final MultiFileSelectedHandler handler) {
if (handler == null)
throw new IllegalStateException("handler must not be null");
addDomHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
FileListElement fileList = getFileList(event.getNativeEvent());
handler.onFileSelected(fileList);
}
}, ChangeEvent.getType());
}
private native FileListElement getFileList(JavaScriptObject event)/*-{
return event.target.files;
}-*/;
}
| UTF-8 | Java | 1,298 | java | MultipleFileUpload.java | Java | [] | null | [] | package gwt.html5.file.client;
import gwt.html5.file.dom.FileListElement;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.FileUpload;
public class MultipleFileUpload extends FileUpload{
public interface MultiFileSelectedHandler {
void onFileSelected(FileListElement fileList);
}
public MultipleFileUpload() {
super();
getElement().setAttribute("multiple", "");
}
public HandlerRegistration addChangeHandler(ChangeHandler handler) {
throw new UnsupportedOperationException(
"Please use addChangeHandler(MultiFileSelectedHandler handler) method instead");
}
public void addChangeHandler(final MultiFileSelectedHandler handler) {
if (handler == null)
throw new IllegalStateException("handler must not be null");
addDomHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
FileListElement fileList = getFileList(event.getNativeEvent());
handler.onFileSelected(fileList);
}
}, ChangeEvent.getType());
}
private native FileListElement getFileList(JavaScriptObject event)/*-{
return event.target.files;
}-*/;
}
| 1,298 | 0.77812 | 0.776579 | 45 | 27.844444 | 25.800047 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.577778 | false | false | 13 |
fd91f048a709824927f31f9aecfd4dcfb411cb63 | 18,700,287,669,441 | 7cac66465ceafb8549494b13a573d1e98e6b2f49 | /src/main/java/fr/miligo/model/entities/emprunt/Reservation.java | d7b10f788f15bf2e3048679e04c5f4d41e67971f | [] | no_license | foued64/miligo | https://github.com/foued64/miligo | dc6fee7a86c2bc0e50358b26a54695bc517da19d | 402a74f9ac6faa22ad641d8c5b054b9ec9769b51 | refs/heads/master | 2020-12-03T07:58:21.454000 | 2017-06-25T14:31:54 | 2017-06-25T14:32:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.miligo.model.entities.emprunt;
import java.util.Date;
import javax.enterprise.context.Dependent;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import fr.miligo.common.AbstractEntity;
import fr.miligo.model.entities.vehicule.TypeVehicule;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.FieldDefaults;
@SuppressWarnings("serial")
@Entity
@Table(name = "RESERVATION")
@NoArgsConstructor
@ToString(of = {"numeroReservation", "etat", "dateReservation", "demandeur", "conducteur", "typeVehicule", "trajet", "empruntReservation"})
@FieldDefaults(level = AccessLevel.PRIVATE)
@Getter
@Setter
@Dependent
public class Reservation extends AbstractEntity {
@Column(name = "NUMERO_RESERVATION", nullable = false)
String numeroReservation;
@Column(name = "ETAT")
@Enumerated(EnumType.STRING)
EtatEnum etat;
@Column(name = "DATE_RESERVATION", nullable = false)
@Temporal(TemporalType.DATE)
Date dateReservation;
@ManyToOne
@JoinColumn(name = "ID_DEMANDEUR", nullable = false)
Client demandeur;
@ManyToOne
@JoinColumn(name = "ID_CONDUCTEUR", nullable = false)
Client conducteur;
@ManyToOne
@JoinColumn(name = "ID_TYPE_VEHICULE", nullable = false)
TypeVehicule typeVehicule;
@ManyToOne
@JoinColumn(name = "ID_TRAJET", nullable = false)
Trajet trajet;
@ManyToOne
@JoinColumn(name = "ID_EMPRUNT_RESERVATION")
EmpruntReservation empruntReservation;
}
| UTF-8 | Java | 1,756 | java | Reservation.java | Java | [] | null | [] | package fr.miligo.model.entities.emprunt;
import java.util.Date;
import javax.enterprise.context.Dependent;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import fr.miligo.common.AbstractEntity;
import fr.miligo.model.entities.vehicule.TypeVehicule;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.FieldDefaults;
@SuppressWarnings("serial")
@Entity
@Table(name = "RESERVATION")
@NoArgsConstructor
@ToString(of = {"numeroReservation", "etat", "dateReservation", "demandeur", "conducteur", "typeVehicule", "trajet", "empruntReservation"})
@FieldDefaults(level = AccessLevel.PRIVATE)
@Getter
@Setter
@Dependent
public class Reservation extends AbstractEntity {
@Column(name = "NUMERO_RESERVATION", nullable = false)
String numeroReservation;
@Column(name = "ETAT")
@Enumerated(EnumType.STRING)
EtatEnum etat;
@Column(name = "DATE_RESERVATION", nullable = false)
@Temporal(TemporalType.DATE)
Date dateReservation;
@ManyToOne
@JoinColumn(name = "ID_DEMANDEUR", nullable = false)
Client demandeur;
@ManyToOne
@JoinColumn(name = "ID_CONDUCTEUR", nullable = false)
Client conducteur;
@ManyToOne
@JoinColumn(name = "ID_TYPE_VEHICULE", nullable = false)
TypeVehicule typeVehicule;
@ManyToOne
@JoinColumn(name = "ID_TRAJET", nullable = false)
Trajet trajet;
@ManyToOne
@JoinColumn(name = "ID_EMPRUNT_RESERVATION")
EmpruntReservation empruntReservation;
}
| 1,756 | 0.787585 | 0.787585 | 66 | 25.60606 | 22.298172 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.969697 | false | false | 13 |
270b928e47d04e7ccbe7da49bbc759f7264cb190 | 23,570,780,526,396 | e0114429eb09792417c69a03487823ebcfcaca8f | /greenfoot/seats/JustForFun.java | 49a0867d9d65fe6d5d4b41a9320a1625f7ee491a | [] | no_license | DevinMui/greenfoot | https://github.com/DevinMui/greenfoot | 27792a856726bbcb154b0b119539dfcbfa570335 | a86ca0257df40f2be61742060ec842becd097949 | refs/heads/master | 2020-09-12T11:19:39.351000 | 2017-03-06T18:02:26 | 2017-03-06T18:02:26 | 66,098,283 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Write a description of interface JustForFun here.
*
* @author (your name)
* @version (a version number or a date)
*/
public interface JustForFun
{
// method signatures - implement the signature below in your own class. Make sure to
// match the parameter list and return type
public String myFavoriteActivity();
}
| UTF-8 | Java | 361 | java | JustForFun.java | Java | [] | null | [] | /**
* Write a description of interface JustForFun here.
*
* @author (your name)
* @version (a version number or a date)
*/
public interface JustForFun
{
// method signatures - implement the signature below in your own class. Make sure to
// match the parameter list and return type
public String myFavoriteActivity();
}
| 361 | 0.66205 | 0.66205 | 12 | 29.083334 | 27.849173 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.083333 | false | false | 13 |
d7e6364ae14e3d2e94bdec4f9af89f2cd996ea7c | 12,953,621,368,437 | e84de335411fa8a898a317390fba711d6dd2e335 | /app/src/main/java/com/example/android2/HistoryDao.java | fd83ed43a350526334769537c767f2210e274bf9 | [] | no_license | ruslankd/Android2 | https://github.com/ruslankd/Android2 | 6a4279bd8d20489c1ee9aa943e0c6a4e67169840 | 40363d53455d5e600effd3d0e2586ff0621a5464 | refs/heads/master | 2023-01-22T16:26:22.374000 | 2020-12-01T07:57:48 | 2020-12-01T07:57:48 | 310,500,562 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android2;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.util.List;
@Dao
public interface HistoryDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insertHistory(History history);
@Delete
void deleteHistory(History history);
@Query("select * from history")
List<History> getAllHistory();
@Query("select count() from history")
long getCountHistory();
@Query("DELETE FROM history WHERE id = :id")
void deleteHistoryById(long id);
}
| UTF-8 | Java | 625 | java | HistoryDao.java | Java | [] | null | [] | package com.example.android2;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.util.List;
@Dao
public interface HistoryDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insertHistory(History history);
@Delete
void deleteHistory(History history);
@Query("select * from history")
List<History> getAllHistory();
@Query("select count() from history")
long getCountHistory();
@Query("DELETE FROM history WHERE id = :id")
void deleteHistoryById(long id);
}
| 625 | 0.7328 | 0.7312 | 28 | 21.321428 | 17.312368 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 13 |
cdfaf68dccda80d57c523e12956d8adeeb93bad8 | 26,242,250,220,168 | e92dc520be74f043e4e7cdf5d7d7d04e4d812bbd | /cake/src/test/java/com/sophia/cake/service/impl/BasicServiceTest.java | 938e57dc2765dc950b591caf11f3238f5d0d5ed6 | [] | no_license | philosophy912/cake_category | https://github.com/philosophy912/cake_category | 3336071b36099a15a468f1e2c84bc0732e06e133 | da31c18d5cb1a1801bb2b791288fee87c91e0e27 | refs/heads/master | 2023-01-07T04:18:40.897000 | 2020-11-19T09:41:22 | 2020-11-19T09:41:22 | 242,880,357 | 0 | 0 | null | false | 2023-01-05T08:57:26 | 2020-02-25T01:18:14 | 2020-11-19T09:41:58 | 2023-01-05T08:57:26 | 2,244 | 0 | 0 | 23 | Java | false | false | package com.sophia.cake.service.impl;
import com.philosophy.base.common.Pair;
import com.philosophy.base.entity.EnvData;
import com.sophia.cake.entity.FormulaType;
import com.sophia.cake.entity.bo.EntityBo;
import com.sophia.cake.entity.bo.NameBo;
import com.sophia.cake.entity.vo.BVo;
import com.sophia.cake.entity.vo.BasicVo;
import com.sophia.cake.entity.vo.FormulaVo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author lizhe
* @date 2020/4/7 16:02
**/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
class BasicServiceTest {
@Resource
private BasicService service;
private String type = FormulaType.MATERIAL.getValue();
@Test
void queryBasic() {
List<BVo> bVos = service.queryBasic();
assertTrue(bVos.size() > 5);
}
@Test
void query() {
EntityBo entityBo = new EntityBo();
Pair<List<BasicVo>, EnvData> query = service.query(entityBo);
assertTrue(query.getFirst().size() > 5);
}
@Test
void queryName() {
NameBo nameBo = new NameBo();
nameBo.setName("蛋糕");
Pair<List<BasicVo>, EnvData> query = service.queryName(nameBo);
assertTrue(query.getFirst().size() > 2);
}
@Test
void add() {
BasicVo basicVo = new BasicVo();
basicVo.setName("测试");
basicVo.setCapacity(1f);
basicVo.setUnit("头");
FormulaVo formulaVo1 = new FormulaVo();
formulaVo1.setCount(12f);
formulaVo1.setType(type);
formulaVo1.setId(1);
FormulaVo formulaVo2 = new FormulaVo();
formulaVo2.setCount(100f);
formulaVo2.setType(type);
formulaVo2.setId(2);
Set<FormulaVo> formulaVos = new HashSet<>();
formulaVos.add(formulaVo1);
formulaVos.add(formulaVo2);
basicVo.setFormulas(formulaVos);
assertDoesNotThrow(() -> service.add(basicVo));
}
@Test
void delete() {
BasicVo basicVo = new BasicVo();
basicVo.setId(120);
assertThrows(RuntimeException.class, () -> service.delete(basicVo));
}
@Test
void update() {
EntityBo entityBo = new EntityBo();
BasicVo basicVo = service.query(entityBo).getFirst().get(0);
basicVo.getFormulas().forEach(formulaVo -> formulaVo.setCount(formulaVo.getCount() + 2));
basicVo.setName(basicVo.getName() + "修改");
assertDoesNotThrow(() -> service.update(basicVo));
}
} | UTF-8 | Java | 2,788 | java | BasicServiceTest.java | Java | [
{
"context": "rg.junit.jupiter.api.Assertions.*;\n\n/**\n * @author lizhe\n * @date 2020/4/7 16:02\n **/\n@RunWith(SpringRunne",
"end": 776,
"score": 0.9995090365409851,
"start": 771,
"tag": "USERNAME",
"value": "lizhe"
},
{
"context": "basicVo = new BasicVo();\n basicVo.setName(\"测试\");\n basicVo.setCapacity(1f);\n basic",
"end": 1641,
"score": 0.8812163472175598,
"start": 1639,
"tag": "NAME",
"value": "测试"
}
] | null | [] | package com.sophia.cake.service.impl;
import com.philosophy.base.common.Pair;
import com.philosophy.base.entity.EnvData;
import com.sophia.cake.entity.FormulaType;
import com.sophia.cake.entity.bo.EntityBo;
import com.sophia.cake.entity.bo.NameBo;
import com.sophia.cake.entity.vo.BVo;
import com.sophia.cake.entity.vo.BasicVo;
import com.sophia.cake.entity.vo.FormulaVo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author lizhe
* @date 2020/4/7 16:02
**/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
class BasicServiceTest {
@Resource
private BasicService service;
private String type = FormulaType.MATERIAL.getValue();
@Test
void queryBasic() {
List<BVo> bVos = service.queryBasic();
assertTrue(bVos.size() > 5);
}
@Test
void query() {
EntityBo entityBo = new EntityBo();
Pair<List<BasicVo>, EnvData> query = service.query(entityBo);
assertTrue(query.getFirst().size() > 5);
}
@Test
void queryName() {
NameBo nameBo = new NameBo();
nameBo.setName("蛋糕");
Pair<List<BasicVo>, EnvData> query = service.queryName(nameBo);
assertTrue(query.getFirst().size() > 2);
}
@Test
void add() {
BasicVo basicVo = new BasicVo();
basicVo.setName("测试");
basicVo.setCapacity(1f);
basicVo.setUnit("头");
FormulaVo formulaVo1 = new FormulaVo();
formulaVo1.setCount(12f);
formulaVo1.setType(type);
formulaVo1.setId(1);
FormulaVo formulaVo2 = new FormulaVo();
formulaVo2.setCount(100f);
formulaVo2.setType(type);
formulaVo2.setId(2);
Set<FormulaVo> formulaVos = new HashSet<>();
formulaVos.add(formulaVo1);
formulaVos.add(formulaVo2);
basicVo.setFormulas(formulaVos);
assertDoesNotThrow(() -> service.add(basicVo));
}
@Test
void delete() {
BasicVo basicVo = new BasicVo();
basicVo.setId(120);
assertThrows(RuntimeException.class, () -> service.delete(basicVo));
}
@Test
void update() {
EntityBo entityBo = new EntityBo();
BasicVo basicVo = service.query(entityBo).getFirst().get(0);
basicVo.getFormulas().forEach(formulaVo -> formulaVo.setCount(formulaVo.getCount() + 2));
basicVo.setName(basicVo.getName() + "修改");
assertDoesNotThrow(() -> service.update(basicVo));
}
} | 2,788 | 0.660058 | 0.645638 | 101 | 26.475248 | 21.268019 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.574257 | false | false | 13 |
b027216c1b2d0d5d70fb3a6792f92af61c7ac268 | 28,046,136,466,469 | 0af5b30a4ecdf2e160cec24ca429f2a6ec9f3d3d | /src/com/example/gooleplay/utils/QuiteClose.java | 1c46dce87808df4e2eec41ed735621fda3e98ca4 | [
"Apache-2.0"
] | permissive | Elloink/FGooglePlay | https://github.com/Elloink/FGooglePlay | 29c04806d3dfa70d9af1526040e28fe467571592 | 134c8c2e0e038795a905bcc70b7a40449d332c5d | refs/heads/master | 2021-06-01T07:57:10.908000 | 2016-07-27T04:46:05 | 2016-07-27T04:46:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.gooleplay.utils;
import java.io.Closeable;
import java.io.IOException;
public class QuiteClose {
public static void quiteClose(Closeable stream) {
if(stream == null) {
return;
}
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 313 | java | QuiteClose.java | Java | [] | null | [] | package com.example.gooleplay.utils;
import java.io.Closeable;
import java.io.IOException;
public class QuiteClose {
public static void quiteClose(Closeable stream) {
if(stream == null) {
return;
}
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 313 | 0.645367 | 0.645367 | 17 | 16.411764 | 14.212914 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.588235 | false | false | 13 |
fcb64d67a4ba1781a24d4809b45e21b76d9e36bf | 27,582,279,988,772 | 8bcfb27a41bc9c17c57a7f702418266f038507e1 | /src/main/java/com/ua/poc/chatservice/repository/ActiveChatsRepository.java | 208fd36a8eba00d2f42152c59dbcf0b4551dfb20 | [] | no_license | shankerraoc/chat-service | https://github.com/shankerraoc/chat-service | 0f5a1c20ed2a83a466f73042e7dfe73236f82ec0 | 93c902e3b99d4fcf83e7a3fb35db74bd19433bf8 | refs/heads/master | 2020-03-28T17:49:47.255000 | 2018-09-17T16:43:43 | 2018-09-17T16:43:43 | 148,826,093 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ua.poc.chatservice.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import com.ua.poc.chatservice.domain.ActiveChat;
public interface ActiveChatsRepository extends MongoRepository<ActiveChat, Integer>{
@Query("{id:?0 }")
public Optional<ActiveChat> findById(Integer id);
@Query("{ username : '?0' }")
public List<ActiveChat> findByUsername(String username);
}
| UTF-8 | Java | 543 | java | ActiveChatsRepository.java | Java | [] | null | [] | package com.ua.poc.chatservice.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import com.ua.poc.chatservice.domain.ActiveChat;
public interface ActiveChatsRepository extends MongoRepository<ActiveChat, Integer>{
@Query("{id:?0 }")
public Optional<ActiveChat> findById(Integer id);
@Query("{ username : '?0' }")
public List<ActiveChat> findByUsername(String username);
}
| 543 | 0.760589 | 0.756906 | 19 | 26.578947 | 26.766665 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.789474 | false | false | 13 |
c53876f7d0ac39f7e948b96842b9365b78d381ef | 7,275,674,607,903 | 5bcc7ba7ffa8b03720ed54a12c661c9cfd4e751d | /zkcore/src/main/java/edu/uw/zookeeper/protocol/proto/IAuthRequest.java | 718e42480bfa991ece177a80b99d0fed8d791fa9 | [
"Apache-2.0"
] | permissive | lisaglendenning/zookeeper-lite | https://github.com/lisaglendenning/zookeeper-lite | 2b1165038272a4b86d96674967df8c00247069cc | 2a9679ddb196b3f65d687d67d7ef534e162fe6d9 | refs/heads/master | 2020-05-17T12:13:13.230000 | 2015-07-02T21:53:50 | 2015-07-02T21:53:50 | 9,090,323 | 10 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.uw.zookeeper.protocol.proto;
import org.apache.zookeeper.proto.AuthPacket;
@Operational(value=OpCode.AUTH)
@OperationalXid(value=OpCodeXid.AUTH)
public class IAuthRequest extends IOpCodeXidRecord<AuthPacket> implements Records.Request {
public IAuthRequest() {
this(new AuthPacket());
}
public IAuthRequest(int type, String scheme, byte[] auth) {
this(new AuthPacket(type, scheme, auth));
}
public IAuthRequest(AuthPacket record) {
super(record);
}
public int getType() {
return record.getType();
}
public String getScheme() {
return record.getScheme();
}
public byte[] getAuth() {
return record.getAuth();
}
} | UTF-8 | Java | 734 | java | IAuthRequest.java | Java | [] | null | [] | package edu.uw.zookeeper.protocol.proto;
import org.apache.zookeeper.proto.AuthPacket;
@Operational(value=OpCode.AUTH)
@OperationalXid(value=OpCodeXid.AUTH)
public class IAuthRequest extends IOpCodeXidRecord<AuthPacket> implements Records.Request {
public IAuthRequest() {
this(new AuthPacket());
}
public IAuthRequest(int type, String scheme, byte[] auth) {
this(new AuthPacket(type, scheme, auth));
}
public IAuthRequest(AuthPacket record) {
super(record);
}
public int getType() {
return record.getType();
}
public String getScheme() {
return record.getScheme();
}
public byte[] getAuth() {
return record.getAuth();
}
} | 734 | 0.653951 | 0.653951 | 32 | 21.96875 | 21.74926 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 13 |
85dad6dc6ed64c84959b779fab7967dddae9cb88 | 12,137,577,605,746 | e20b971b387b2966f136f7fe102bcb4735765e4b | /Project-Code-Practice/JavaFx-Practice/Display-Image.java | d8a18d24ac7c6c5cb805e1eb3abff05b6ec149f8 | [
"MIT"
] | permissive | fsshakkhor/academic-codes | https://github.com/fsshakkhor/academic-codes | ddb96aa5427a22c1d6f413672b7fe9eb23daf14b | 89f20907853c0190e6078aa5742f445c352881c4 | refs/heads/master | 2021-01-19T21:00:14.359000 | 2019-09-17T10:15:36 | 2019-09-17T10:15:36 | 88,586,804 | 3 | 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 gopro;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Font;
import static java.awt.Font.CENTER_BASELINE;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.*;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.scene.*;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javax.imageio.ImageIO;
/**
*
* @author fsshakkhor
*/
public class GoPro extends Application {
private Desktop desktop = Desktop.getDesktop();
@Override public void start(Stage primaryStage) throws IOException {
primaryStage.setTitle("Some Kind of Application");
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("All Files", "*.*"));
File selectedFile = fileChooser.showOpenDialog(primaryStage);
if (selectedFile != null) {
BufferedImage image = ImageIO.read(selectedFile);
int height = image.getHeight();
int width = image.getWidth();
WritableImage wr = new WritableImage(width, height);
PixelWriter pw = wr.getPixelWriter();
for(int i = 0;i < width;i++){
for(int j = 0;j < height;j++){
pw.setArgb(i,j,image.getRGB(i, j));
}
}
System.out.println(height + " " + width);
StackPane root = new StackPane();
ImageView imView = new ImageView(wr);
root.getChildren().add(imView);
Scene scene = new Scene(root,1000,1000);
primaryStage.setScene(scene);
primaryStage.show();;
}
}
public static void main(String[] args) {
launch(args);
}
}
| UTF-8 | Java | 2,465 | java | Display-Image.java | Java | [
{
"context": ";\nimport javax.imageio.ImageIO;\n\n/**\n *\n * @author fsshakkhor\n */\npublic class GoPro extends Application {\n ",
"end": 1013,
"score": 0.9992967844009399,
"start": 1003,
"tag": "USERNAME",
"value": "fsshakkhor"
}
] | 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 gopro;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Font;
import static java.awt.Font.CENTER_BASELINE;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.*;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.scene.*;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javax.imageio.ImageIO;
/**
*
* @author fsshakkhor
*/
public class GoPro extends Application {
private Desktop desktop = Desktop.getDesktop();
@Override public void start(Stage primaryStage) throws IOException {
primaryStage.setTitle("Some Kind of Application");
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("All Files", "*.*"));
File selectedFile = fileChooser.showOpenDialog(primaryStage);
if (selectedFile != null) {
BufferedImage image = ImageIO.read(selectedFile);
int height = image.getHeight();
int width = image.getWidth();
WritableImage wr = new WritableImage(width, height);
PixelWriter pw = wr.getPixelWriter();
for(int i = 0;i < width;i++){
for(int j = 0;j < height;j++){
pw.setArgb(i,j,image.getRGB(i, j));
}
}
System.out.println(height + " " + width);
StackPane root = new StackPane();
ImageView imView = new ImageView(wr);
root.getChildren().add(imView);
Scene scene = new Scene(root,1000,1000);
primaryStage.setScene(scene);
primaryStage.show();;
}
}
public static void main(String[] args) {
launch(args);
}
}
| 2,465 | 0.655172 | 0.651116 | 78 | 30.602564 | 20.069967 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.769231 | false | false | 13 |
260f357de07c02fd24b8adf6282bc1a88b0b0a86 | 18,227,841,264,016 | 8246e4b189f27dd2c33ff87a88054c7297645c7f | /app/src/main/java/edu/therealbranik/therealflower/user/User.java | db916fe881e83506bc7ebe2732f60e487bd5f9bd | [
"MIT"
] | permissive | therealbranik/the-real-flower-android-app | https://github.com/therealbranik/the-real-flower-android-app | 1b06915c08ca50955ee987cc615b8748922ed807 | 5b03b071a96bb258643e676e2b49906448bd7649 | refs/heads/master | 2021-06-10T17:49:56.244000 | 2019-07-15T22:01:44 | 2019-07-15T22:01:44 | 183,476,996 | 0 | 0 | MIT | false | 2021-12-06T13:52:46 | 2019-04-25T17:05:02 | 2021-12-06T13:51:52 | 2021-12-06T13:52:43 | 1,337 | 0 | 0 | 5 | Java | false | false | package edu.therealbranik.therealflower.user;
import androidx.annotation.NonNull;
import com.google.firebase.firestore.Exclude;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.IgnoreExtraProperties;
@IgnoreExtraProperties
public class User {
@Exclude
public String id;
private String username;
private String fullName;
private String email;
private String phoneNumber;
private int points;
private FirebaseFirestore db;
public User () {
db = FirebaseFirestore.getInstance();
}
public User (String username, String fullName, String email, String phoneNumber) {
this.username = username;
this.fullName = fullName;
this.email = email;
this.phoneNumber = phoneNumber;
this.db = FirebaseFirestore.getInstance();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullNameame(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void addPoints (int points) {
if (this.points >= 0) {
this.points += points;
} else {
this.points = points;
}
}
public void subPoints (int points) {
if (this.points > points) {
this.points -= points;
} else {
this.points = 0;
}
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public void save () {
db.collection("users")
.add(this);
}
public <T extends User> T withId(@NonNull final String id) {
this.id = id;
return (T) this;
}
}
| UTF-8 | Java | 2,177 | java | User.java | Java | [
{
"context": "ail, String phoneNumber) {\n this.username = username;\n this.fullName = fullName;\n this.e",
"end": 695,
"score": 0.9940621256828308,
"start": 687,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String userna",
"end": 914,
"score": 0.5759508609771729,
"start": 906,
"tag": "USERNAME",
"value": "username"
},
{
"context": "sername(String username) {\n this.username = username;\n }\n\n public String getFullName() {\n ",
"end": 1002,
"score": 0.9265639185905457,
"start": 994,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | package edu.therealbranik.therealflower.user;
import androidx.annotation.NonNull;
import com.google.firebase.firestore.Exclude;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.IgnoreExtraProperties;
@IgnoreExtraProperties
public class User {
@Exclude
public String id;
private String username;
private String fullName;
private String email;
private String phoneNumber;
private int points;
private FirebaseFirestore db;
public User () {
db = FirebaseFirestore.getInstance();
}
public User (String username, String fullName, String email, String phoneNumber) {
this.username = username;
this.fullName = fullName;
this.email = email;
this.phoneNumber = phoneNumber;
this.db = FirebaseFirestore.getInstance();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullNameame(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void addPoints (int points) {
if (this.points >= 0) {
this.points += points;
} else {
this.points = points;
}
}
public void subPoints (int points) {
if (this.points > points) {
this.points -= points;
} else {
this.points = 0;
}
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public void save () {
db.collection("users")
.add(this);
}
public <T extends User> T withId(@NonNull final String id) {
this.id = id;
return (T) this;
}
}
| 2,177 | 0.604502 | 0.603583 | 101 | 20.554455 | 18.252615 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.376238 | false | false | 13 |
0b1ac753c29e084c28973680cc3bffdd94b28224 | 28,303,834,520,825 | cbb375fa7db0bb399a2b02a5bf8a8f9614379c88 | /com.yzj.ebs/src/com/yzj/ebs/database/dao/SealDao.java | 8b1d590900d73ee39f12f026d360f559f21ddf74 | [] | no_license | chaug2018/web | https://github.com/chaug2018/web | 6d4dbf00799705b5f37256ec5bc40fa5e97db12b | 42fd1b0516bbfaca28bf6f4db36325e96c95c56f | refs/heads/master | 2023-06-15T20:07:55.674000 | 2021-07-08T02:42:13 | 2021-07-08T02:42:13 | 383,981,149 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yzj.ebs.database.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.yzj.ebs.common.XDocProcException;
/**
* 创建于:2012-8-3<br>
* 版权所有(C) 2012 深圳市银之杰科技股份有限公司<br>
* 通用DAO,用于操作所有的表
*
* @author WangXue
* @version 1.0.0
*/
public class SealDao extends HibernateDaoSupport {
/**
* 执行本地分页查询Sql语句
*
* @param sql
* 本地Sql语句
* @return 运行结果
* @throws XDocProcException
* 当执行本地Sql语句失败时抛出异常
*/
public List<Object> findBySql(final String sql) throws XDocProcException {
try {
return (List<Object>) getHibernateTemplate().execute(
new HibernateCallback<Object>() {
public Object doInHibernate(Session session)
throws HibernateException {
Query query = session.createSQLQuery(sql);
return query.list();
}
});
} catch (DataAccessException e) {
throw new XDocProcException("执行本地Sql失败 Sql=" + sql, e);
}
}
/**
* 功能:执行Sql语言
*
* @param QuerySql
* Sql语句
* @return 运行结果
* @throws DaoException
*/
public Object ExecQuery(String QuerySql) throws XDocProcException {
final String sql;
sql = QuerySql;
try {
return getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
Query query = session.createQuery(sql);
return Integer.valueOf(query.executeUpdate());
}
});
} catch (DataAccessException e) {
throw new XDocProcException("执行Sql失败 Sql=" + sql, e);
}
}
} | UTF-8 | Java | 2,175 | java | SealDao.java | Java | [
{
"context": "圳市银之杰科技股份有限公司<br>\n * 通用DAO,用于操作所有的表\n * \n * @author WangXue\n * @version 1.0.0\n */\npublic class SealDao extend",
"end": 716,
"score": 0.9984254837036133,
"start": 709,
"tag": "NAME",
"value": "WangXue"
}
] | null | [] | package com.yzj.ebs.database.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.yzj.ebs.common.XDocProcException;
/**
* 创建于:2012-8-3<br>
* 版权所有(C) 2012 深圳市银之杰科技股份有限公司<br>
* 通用DAO,用于操作所有的表
*
* @author WangXue
* @version 1.0.0
*/
public class SealDao extends HibernateDaoSupport {
/**
* 执行本地分页查询Sql语句
*
* @param sql
* 本地Sql语句
* @return 运行结果
* @throws XDocProcException
* 当执行本地Sql语句失败时抛出异常
*/
public List<Object> findBySql(final String sql) throws XDocProcException {
try {
return (List<Object>) getHibernateTemplate().execute(
new HibernateCallback<Object>() {
public Object doInHibernate(Session session)
throws HibernateException {
Query query = session.createSQLQuery(sql);
return query.list();
}
});
} catch (DataAccessException e) {
throw new XDocProcException("执行本地Sql失败 Sql=" + sql, e);
}
}
/**
* 功能:执行Sql语言
*
* @param QuerySql
* Sql语句
* @return 运行结果
* @throws DaoException
*/
public Object ExecQuery(String QuerySql) throws XDocProcException {
final String sql;
sql = QuerySql;
try {
return getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
Query query = session.createQuery(sql);
return Integer.valueOf(query.executeUpdate());
}
});
} catch (DataAccessException e) {
throw new XDocProcException("执行Sql失败 Sql=" + sql, e);
}
}
} | 2,175 | 0.708646 | 0.701149 | 81 | 23.716049 | 20.306438 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.839506 | false | false | 13 |
4255ba46281cff814ad971a175ffed4c6ce8b59f | 4,724,464,092,938 | b42fd38fd3b0faac98a0c641847559858f742b22 | /HomeWAV/Source Code/Android App Version 2005007/sources/com/forasoft/homewavvisitor/dao/CreditDao_Impl.java | e8d9f564535e208a1bae37bd1aa970ea7ec4a6f9 | [] | no_license | zuiaixiaobai/twilio-prison-video-visitation | https://github.com/zuiaixiaobai/twilio-prison-video-visitation | c8b300be9001c8b846ac4d1c1a46b3a720ee4f8a | c172ba4679b14e28d1922847309c3a86388c9957 | refs/heads/main | 2023-04-20T18:14:11.035000 | 2021-05-14T13:47:39 | 2021-05-14T13:47:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.forasoft.homewavvisitor.dao;
import android.database.Cursor;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.RxRoom;
import androidx.room.SharedSQLiteStatement;
import androidx.sqlite.db.SupportSQLiteStatement;
import com.forasoft.homewavvisitor.dao.converters.LocalDateTimeConverter;
import com.forasoft.homewavvisitor.model.UploadWorker;
import com.forasoft.homewavvisitor.model.data.payment.Credit;
import com.microsoft.appcenter.ingestion.models.CommonProperties;
import io.reactivex.Flowable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public final class CreditDao_Impl implements CreditDao {
/* access modifiers changed from: private */
public final RoomDatabase __db;
private final EntityInsertionAdapter __insertionAdapterOfCredit;
/* access modifiers changed from: private */
public final LocalDateTimeConverter __localDateTimeConverter = new LocalDateTimeConverter();
private final SharedSQLiteStatement __preparedStmtOfDeleteAll;
public CreditDao_Impl(RoomDatabase roomDatabase) {
this.__db = roomDatabase;
this.__insertionAdapterOfCredit = new EntityInsertionAdapter<Credit>(roomDatabase) {
public String createQuery() {
return "INSERT OR ABORT INTO `credits`(`id`,`inmate_id`,`braintree_transaction_id`,`stripe_transaction_id`,`created`,`creator`,`notes`,`type`,`value`) VALUES (?,?,?,?,?,?,?,?,?)";
}
public void bind(SupportSQLiteStatement supportSQLiteStatement, Credit credit) {
if (credit.getId() == null) {
supportSQLiteStatement.bindNull(1);
} else {
supportSQLiteStatement.bindString(1, credit.getId());
}
if (credit.getInmate_id() == null) {
supportSQLiteStatement.bindNull(2);
} else {
supportSQLiteStatement.bindString(2, credit.getInmate_id());
}
if (credit.getBraintree_transaction_id() == null) {
supportSQLiteStatement.bindNull(3);
} else {
supportSQLiteStatement.bindString(3, credit.getBraintree_transaction_id());
}
if (credit.getStripe_transaction_id() == null) {
supportSQLiteStatement.bindNull(4);
} else {
supportSQLiteStatement.bindString(4, credit.getStripe_transaction_id());
}
Long fromLocalDateTime = CreditDao_Impl.this.__localDateTimeConverter.fromLocalDateTime(credit.getCreated());
if (fromLocalDateTime == null) {
supportSQLiteStatement.bindNull(5);
} else {
supportSQLiteStatement.bindLong(5, fromLocalDateTime.longValue());
}
if (credit.getCreator() == null) {
supportSQLiteStatement.bindNull(6);
} else {
supportSQLiteStatement.bindString(6, credit.getCreator());
}
if (credit.getNotes() == null) {
supportSQLiteStatement.bindNull(7);
} else {
supportSQLiteStatement.bindString(7, credit.getNotes());
}
if (credit.getType() == null) {
supportSQLiteStatement.bindNull(8);
} else {
supportSQLiteStatement.bindString(8, credit.getType());
}
if (credit.getValue() == null) {
supportSQLiteStatement.bindNull(9);
} else {
supportSQLiteStatement.bindString(9, credit.getValue());
}
}
};
this.__preparedStmtOfDeleteAll = new SharedSQLiteStatement(roomDatabase) {
public String createQuery() {
return "DELETE FROM credits";
}
};
}
public void saveCredit(Credit credit) {
this.__db.beginTransaction();
try {
this.__insertionAdapterOfCredit.insert(credit);
this.__db.setTransactionSuccessful();
} finally {
this.__db.endTransaction();
}
}
public void deleteAll() {
SupportSQLiteStatement acquire = this.__preparedStmtOfDeleteAll.acquire();
this.__db.beginTransaction();
try {
acquire.executeUpdateDelete();
this.__db.setTransactionSuccessful();
} finally {
this.__db.endTransaction();
this.__preparedStmtOfDeleteAll.release(acquire);
}
}
public Flowable<List<Credit>> getCreditsForInmate(String str) {
final RoomSQLiteQuery acquire = RoomSQLiteQuery.acquire("SELECT * FROM credits WHERE inmate_id = ?", 1);
if (str == null) {
acquire.bindNull(1);
} else {
acquire.bindString(1, str);
}
return RxRoom.createFlowable(this.__db, new String[]{"credits"}, new Callable<List<Credit>>() {
public List<Credit> call() throws Exception {
Long l;
Cursor query = CreditDao_Impl.this.__db.query(acquire);
try {
int columnIndexOrThrow = query.getColumnIndexOrThrow("id");
int columnIndexOrThrow2 = query.getColumnIndexOrThrow(UploadWorker.KEY_INMATE_ID);
int columnIndexOrThrow3 = query.getColumnIndexOrThrow("braintree_transaction_id");
int columnIndexOrThrow4 = query.getColumnIndexOrThrow("stripe_transaction_id");
int columnIndexOrThrow5 = query.getColumnIndexOrThrow("created");
int columnIndexOrThrow6 = query.getColumnIndexOrThrow("creator");
int columnIndexOrThrow7 = query.getColumnIndexOrThrow("notes");
int columnIndexOrThrow8 = query.getColumnIndexOrThrow("type");
int columnIndexOrThrow9 = query.getColumnIndexOrThrow(CommonProperties.VALUE);
ArrayList arrayList = new ArrayList(query.getCount());
while (query.moveToNext()) {
String string = query.getString(columnIndexOrThrow);
String string2 = query.getString(columnIndexOrThrow2);
String string3 = query.getString(columnIndexOrThrow3);
String string4 = query.getString(columnIndexOrThrow4);
if (query.isNull(columnIndexOrThrow5)) {
l = null;
} else {
l = Long.valueOf(query.getLong(columnIndexOrThrow5));
}
arrayList.add(new Credit(string, string2, string3, string4, CreditDao_Impl.this.__localDateTimeConverter.toLocalDateTime(l), query.getString(columnIndexOrThrow6), query.getString(columnIndexOrThrow7), query.getString(columnIndexOrThrow8), query.getString(columnIndexOrThrow9)));
}
return arrayList;
} finally {
query.close();
}
}
/* access modifiers changed from: protected */
public void finalize() {
acquire.release();
}
});
}
}
| UTF-8 | Java | 7,505 | java | CreditDao_Impl.java | Java | [] | null | [] | package com.forasoft.homewavvisitor.dao;
import android.database.Cursor;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.RxRoom;
import androidx.room.SharedSQLiteStatement;
import androidx.sqlite.db.SupportSQLiteStatement;
import com.forasoft.homewavvisitor.dao.converters.LocalDateTimeConverter;
import com.forasoft.homewavvisitor.model.UploadWorker;
import com.forasoft.homewavvisitor.model.data.payment.Credit;
import com.microsoft.appcenter.ingestion.models.CommonProperties;
import io.reactivex.Flowable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public final class CreditDao_Impl implements CreditDao {
/* access modifiers changed from: private */
public final RoomDatabase __db;
private final EntityInsertionAdapter __insertionAdapterOfCredit;
/* access modifiers changed from: private */
public final LocalDateTimeConverter __localDateTimeConverter = new LocalDateTimeConverter();
private final SharedSQLiteStatement __preparedStmtOfDeleteAll;
public CreditDao_Impl(RoomDatabase roomDatabase) {
this.__db = roomDatabase;
this.__insertionAdapterOfCredit = new EntityInsertionAdapter<Credit>(roomDatabase) {
public String createQuery() {
return "INSERT OR ABORT INTO `credits`(`id`,`inmate_id`,`braintree_transaction_id`,`stripe_transaction_id`,`created`,`creator`,`notes`,`type`,`value`) VALUES (?,?,?,?,?,?,?,?,?)";
}
public void bind(SupportSQLiteStatement supportSQLiteStatement, Credit credit) {
if (credit.getId() == null) {
supportSQLiteStatement.bindNull(1);
} else {
supportSQLiteStatement.bindString(1, credit.getId());
}
if (credit.getInmate_id() == null) {
supportSQLiteStatement.bindNull(2);
} else {
supportSQLiteStatement.bindString(2, credit.getInmate_id());
}
if (credit.getBraintree_transaction_id() == null) {
supportSQLiteStatement.bindNull(3);
} else {
supportSQLiteStatement.bindString(3, credit.getBraintree_transaction_id());
}
if (credit.getStripe_transaction_id() == null) {
supportSQLiteStatement.bindNull(4);
} else {
supportSQLiteStatement.bindString(4, credit.getStripe_transaction_id());
}
Long fromLocalDateTime = CreditDao_Impl.this.__localDateTimeConverter.fromLocalDateTime(credit.getCreated());
if (fromLocalDateTime == null) {
supportSQLiteStatement.bindNull(5);
} else {
supportSQLiteStatement.bindLong(5, fromLocalDateTime.longValue());
}
if (credit.getCreator() == null) {
supportSQLiteStatement.bindNull(6);
} else {
supportSQLiteStatement.bindString(6, credit.getCreator());
}
if (credit.getNotes() == null) {
supportSQLiteStatement.bindNull(7);
} else {
supportSQLiteStatement.bindString(7, credit.getNotes());
}
if (credit.getType() == null) {
supportSQLiteStatement.bindNull(8);
} else {
supportSQLiteStatement.bindString(8, credit.getType());
}
if (credit.getValue() == null) {
supportSQLiteStatement.bindNull(9);
} else {
supportSQLiteStatement.bindString(9, credit.getValue());
}
}
};
this.__preparedStmtOfDeleteAll = new SharedSQLiteStatement(roomDatabase) {
public String createQuery() {
return "DELETE FROM credits";
}
};
}
public void saveCredit(Credit credit) {
this.__db.beginTransaction();
try {
this.__insertionAdapterOfCredit.insert(credit);
this.__db.setTransactionSuccessful();
} finally {
this.__db.endTransaction();
}
}
public void deleteAll() {
SupportSQLiteStatement acquire = this.__preparedStmtOfDeleteAll.acquire();
this.__db.beginTransaction();
try {
acquire.executeUpdateDelete();
this.__db.setTransactionSuccessful();
} finally {
this.__db.endTransaction();
this.__preparedStmtOfDeleteAll.release(acquire);
}
}
public Flowable<List<Credit>> getCreditsForInmate(String str) {
final RoomSQLiteQuery acquire = RoomSQLiteQuery.acquire("SELECT * FROM credits WHERE inmate_id = ?", 1);
if (str == null) {
acquire.bindNull(1);
} else {
acquire.bindString(1, str);
}
return RxRoom.createFlowable(this.__db, new String[]{"credits"}, new Callable<List<Credit>>() {
public List<Credit> call() throws Exception {
Long l;
Cursor query = CreditDao_Impl.this.__db.query(acquire);
try {
int columnIndexOrThrow = query.getColumnIndexOrThrow("id");
int columnIndexOrThrow2 = query.getColumnIndexOrThrow(UploadWorker.KEY_INMATE_ID);
int columnIndexOrThrow3 = query.getColumnIndexOrThrow("braintree_transaction_id");
int columnIndexOrThrow4 = query.getColumnIndexOrThrow("stripe_transaction_id");
int columnIndexOrThrow5 = query.getColumnIndexOrThrow("created");
int columnIndexOrThrow6 = query.getColumnIndexOrThrow("creator");
int columnIndexOrThrow7 = query.getColumnIndexOrThrow("notes");
int columnIndexOrThrow8 = query.getColumnIndexOrThrow("type");
int columnIndexOrThrow9 = query.getColumnIndexOrThrow(CommonProperties.VALUE);
ArrayList arrayList = new ArrayList(query.getCount());
while (query.moveToNext()) {
String string = query.getString(columnIndexOrThrow);
String string2 = query.getString(columnIndexOrThrow2);
String string3 = query.getString(columnIndexOrThrow3);
String string4 = query.getString(columnIndexOrThrow4);
if (query.isNull(columnIndexOrThrow5)) {
l = null;
} else {
l = Long.valueOf(query.getLong(columnIndexOrThrow5));
}
arrayList.add(new Credit(string, string2, string3, string4, CreditDao_Impl.this.__localDateTimeConverter.toLocalDateTime(l), query.getString(columnIndexOrThrow6), query.getString(columnIndexOrThrow7), query.getString(columnIndexOrThrow8), query.getString(columnIndexOrThrow9)));
}
return arrayList;
} finally {
query.close();
}
}
/* access modifiers changed from: protected */
public void finalize() {
acquire.release();
}
});
}
}
| 7,505 | 0.584943 | 0.579081 | 158 | 46.5 | 37.01757 | 302 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.746835 | false | false | 13 |
19446dda77b1a9a3b147be67e7ee11b8d04b5b7a | 3,289,944,995,290 | ba56589290a5ebcbb2bf42b02fee7bdb06fd716c | /src/main/java/com/siren/config/SwaggerConfig.java | f08f90d88d5fb8c77450da623e9f2444a3691fcc | [] | no_license | Kicray/Siren | https://github.com/Kicray/Siren | ff742c9795cb083e550a6c11e99e4f28c3445b92 | 417cd4827a6d361ad30db0eaf668de88a4e7deb2 | refs/heads/master | 2022-07-26T13:18:23.195000 | 2022-06-25T02:31:15 | 2022-06-25T02:31:15 | 198,567,268 | 0 | 0 | null | false | 2021-04-26T19:25:16 | 2019-07-24T05:52:39 | 2019-08-12T10:48:03 | 2021-04-26T19:25:15 | 20 | 0 | 0 | 1 | Java | false | false | package com.siren.config;
import com.siren.properties.swagger.SwaggerProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: Aqr
* @Desc:
* @Date: 2019/7/25
*/
@Configuration("sirenSwaggerConfig")
@EnableSwagger2
public class SwaggerConfig implements Serializable {
private static final long serialVersionUID = -4308082312511684602L;
@Resource(name = "sirenSwaggerProperty")
private SwaggerProperty swaggerProperty;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes());
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title(swaggerProperty.getTitle())
//版本号
.version(swaggerProperty.getVersion())
//描述
.description(swaggerProperty.getDescription())
.termsOfServiceUrl(swaggerProperty.getTermsOfServiceUrl())
.build();
}
/**
* 设置全局认证的
* @return
*/
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList= new ArrayList();
apiKeyList.add(new ApiKey("x-auth-token", "x-auth-token", "header"));
return apiKeyList;
}
}
| UTF-8 | Java | 2,325 | java | SwaggerConfig.java | Java | [
{
"context": "ArrayList;\nimport java.util.List;\n\n/**\n * @Author: Aqr\n * @Desc:\n * @Date: 2019/7/25\n */\n@Configuration(",
"end": 823,
"score": 0.9996603727340698,
"start": 820,
"tag": "USERNAME",
"value": "Aqr"
}
] | null | [] | package com.siren.config;
import com.siren.properties.swagger.SwaggerProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: Aqr
* @Desc:
* @Date: 2019/7/25
*/
@Configuration("sirenSwaggerConfig")
@EnableSwagger2
public class SwaggerConfig implements Serializable {
private static final long serialVersionUID = -4308082312511684602L;
@Resource(name = "sirenSwaggerProperty")
private SwaggerProperty swaggerProperty;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes());
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title(swaggerProperty.getTitle())
//版本号
.version(swaggerProperty.getVersion())
//描述
.description(swaggerProperty.getDescription())
.termsOfServiceUrl(swaggerProperty.getTermsOfServiceUrl())
.build();
}
/**
* 设置全局认证的
* @return
*/
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList= new ArrayList();
apiKeyList.add(new ApiKey("x-auth-token", "x-auth-token", "header"));
return apiKeyList;
}
}
| 2,325 | 0.68652 | 0.673086 | 67 | 32.328358 | 22.56823 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.402985 | false | false | 13 |
af4d56e4f2349987b5e0e2cdc72c8ed9dcb89572 | 3,289,944,998,096 | bb784c0d77f5613d681a08ad82926d546f9d5bfc | /LeetCodePractice/src/LeetCode/Medium/RepeatedDNASequences.java | 043f9e117718a69ca42ad4f542e8ce015c1cb4d3 | [] | no_license | WinnieZhao84/MyPractice | https://github.com/WinnieZhao84/MyPractice | a18fe03e287aa5d045bfc7367652515e2c9be1ef | 95620deb4bd41c54541375d60c3db04e0b5b2855 | refs/heads/master | 2021-01-17T17:39:48.581000 | 2020-08-11T08:35:15 | 2020-08-11T08:35:15 | 61,250,293 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package LeetCode.Medium;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG".
* When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
*
* Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
*
* For example, Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",
* Return: ["AAAAACCCCC", "CCCCCAAAAA"].
* @author WinnieZhao
*
*/
public class RepeatedDNASequences {
public List<String> findRepeatedDnaSequences(String s) {
List<String> res = new ArrayList<>();
if (s == null || s.isEmpty()) {
return res;
}
Map<String, Integer> counts = new HashMap<>();
for (int i=0; i<=s.length() - 10; i++) {
String subStr = s.substring(i, i+10);
counts.put(subStr, counts.getOrDefault(subStr, 0) + 1);
}
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
String key = entry.getKey();
Integer count = entry.getValue();
if (count > 1) {
res.add(key);
}
}
return res;
}
/**
* So we have only 4 possible letters, and we can use as little bits as possible to store
* each character of our 10-letter string. We really need only 2 bits (bits, not bytes)
* for this. Specifically the solution uses the following coding:
* 0 = 00 (bits in binary number system) = 'A'
* 1 = 01 (bits in binary number system) = 'C'
* 2 = 10 (bits in binary number system) = 'G'
* 3 = 11 (bits in binary number system) = 'T'
*
* Note that since there 10 letters and each letter requires only 2 bits,
* we will need only 10 * 2= 20 bits to code the string (which is less then
* size of integer in java (as well as in all other popular languages),
* which is 4 bytes = 32 bits).
*
* For example, this is how "AACCTCCGGT" string will be coded:
* A A C C T C C G G T
* 00 00 01 01 11 01 01 10 10 11 = 00000101110101101011 (binary) = 23915 (decimal)
* @param s
* @return
*/
public List<String> findRepeatedDnaSequences_better(String s) {
Set<Integer> words = new HashSet<>();
Set<Integer> doubleWords = new HashSet<>();
List<String> rv = new ArrayList<>();
int[] map = new int[26];
//map['A' - 'A'] = 0;
map['C' - 'A'] = 1;
map['G' - 'A'] = 2;
map['T' - 'A'] = 3;
for(int i = 0; i < s.length() - 9; i++) {
int v = 0;
for(int j = i; j < i + 10; j++) {
char ch = s.charAt(j);
v <<= 2;
v = v | map[ch - 'A'];
}
/**
* doubleWords there to make sure when the pattern duplicated more than three times, we don't add it to the result again.
* Specifically, about !words.add(v) && doubleWords.add(v)
* (1)when the pattern occurs the 1st time, !words.add(v) return false, and && operator short-circuits
* doubleWords.add(v) (won't be evaluated).
* (2)when the pattern occurs the 2nd time, !words.add(v) return true, and doubleWords.add(v) return true.
* The pattern is added to the result.
* (3)when the pattern occurs more than three times, doubleWords.add(v) always return false.
*/
if(!words.add(v) && doubleWords.add(v)) {
rv.add(s.substring(i, i + 10));
}
}
return rv;
}
public static void main(String[] args) {
RepeatedDNASequences solution = new RepeatedDNASequences();
System.out.println(solution.findRepeatedDnaSequences_better("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"));
}
}
| UTF-8 | Java | 4,003 | java | RepeatedDNASequences.java | Java | [
{
"context": " Return: [\"AAAAACCCCC\", \"CCCCCAAAAA\"].\n\n * @author WinnieZhao\n *\n */\npublic class RepeatedDNASequences {\n\n p",
"end": 631,
"score": 0.9991640448570251,
"start": 621,
"tag": "NAME",
"value": "WinnieZhao"
}
] | null | [] | package LeetCode.Medium;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG".
* When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
*
* Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
*
* For example, Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",
* Return: ["AAAAACCCCC", "CCCCCAAAAA"].
* @author WinnieZhao
*
*/
public class RepeatedDNASequences {
public List<String> findRepeatedDnaSequences(String s) {
List<String> res = new ArrayList<>();
if (s == null || s.isEmpty()) {
return res;
}
Map<String, Integer> counts = new HashMap<>();
for (int i=0; i<=s.length() - 10; i++) {
String subStr = s.substring(i, i+10);
counts.put(subStr, counts.getOrDefault(subStr, 0) + 1);
}
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
String key = entry.getKey();
Integer count = entry.getValue();
if (count > 1) {
res.add(key);
}
}
return res;
}
/**
* So we have only 4 possible letters, and we can use as little bits as possible to store
* each character of our 10-letter string. We really need only 2 bits (bits, not bytes)
* for this. Specifically the solution uses the following coding:
* 0 = 00 (bits in binary number system) = 'A'
* 1 = 01 (bits in binary number system) = 'C'
* 2 = 10 (bits in binary number system) = 'G'
* 3 = 11 (bits in binary number system) = 'T'
*
* Note that since there 10 letters and each letter requires only 2 bits,
* we will need only 10 * 2= 20 bits to code the string (which is less then
* size of integer in java (as well as in all other popular languages),
* which is 4 bytes = 32 bits).
*
* For example, this is how "AACCTCCGGT" string will be coded:
* A A C C T C C G G T
* 00 00 01 01 11 01 01 10 10 11 = 00000101110101101011 (binary) = 23915 (decimal)
* @param s
* @return
*/
public List<String> findRepeatedDnaSequences_better(String s) {
Set<Integer> words = new HashSet<>();
Set<Integer> doubleWords = new HashSet<>();
List<String> rv = new ArrayList<>();
int[] map = new int[26];
//map['A' - 'A'] = 0;
map['C' - 'A'] = 1;
map['G' - 'A'] = 2;
map['T' - 'A'] = 3;
for(int i = 0; i < s.length() - 9; i++) {
int v = 0;
for(int j = i; j < i + 10; j++) {
char ch = s.charAt(j);
v <<= 2;
v = v | map[ch - 'A'];
}
/**
* doubleWords there to make sure when the pattern duplicated more than three times, we don't add it to the result again.
* Specifically, about !words.add(v) && doubleWords.add(v)
* (1)when the pattern occurs the 1st time, !words.add(v) return false, and && operator short-circuits
* doubleWords.add(v) (won't be evaluated).
* (2)when the pattern occurs the 2nd time, !words.add(v) return true, and doubleWords.add(v) return true.
* The pattern is added to the result.
* (3)when the pattern occurs more than three times, doubleWords.add(v) always return false.
*/
if(!words.add(v) && doubleWords.add(v)) {
rv.add(s.substring(i, i + 10));
}
}
return rv;
}
public static void main(String[] args) {
RepeatedDNASequences solution = new RepeatedDNASequences();
System.out.println(solution.findRepeatedDnaSequences_better("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"));
}
}
| 4,003 | 0.575568 | 0.550337 | 108 | 36.064816 | 32.152782 | 133 | false | false | 30 | 0.007494 | 0 | 0 | 0 | 0 | 0.62037 | false | false | 13 |
eb1c3a4d730f6af3b66f11f805c63b9276df0eb1 | 31,903,017,135,442 | 8678c0c4208c4351168e76f488420c7b6faa73d9 | /app/src/main/java/soursoft/secuenciauno/co/soursoft/ActivityMain.java | 6b606f6d30ab805d35f9d2f3c98850f62c171072 | [] | no_license | anfehernandez94/soursoft2 | https://github.com/anfehernandez94/soursoft2 | 8f5ebd569974f8cb795bb6a83d0c5c0a695e77e0 | 71a101a9bf8314be2e778111cff3556d50c0864d | refs/heads/master | 2021-01-20T22:11:40.126000 | 2016-06-26T19:33:45 | 2016-06-26T19:33:45 | 61,495,693 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package soursoft.secuenciauno.co.soursoft;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.design.widget.TabLayout;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.maps.MapFragment;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class ActivityMain extends Activity {
FragmentManager fragmentManager;
EditText etSearch;
ImageButton ibtnSearch;
public ArrayList<Client> listClients = new ArrayList<>();
// MapFragment fragmentMap;
FragmentCategoria fragmentCategoria = new FragmentCategoria();
FragmentMapa fragmentMapa = new FragmentMapa();
FragmentListCategoria fragmentListCategoria = new FragmentListCategoria();
FragmentClient fragmentClient = new FragmentClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ibtnSearch = (ImageButton)findViewById(R.id.ibtn_search);
etSearch = (EditText)findViewById(R.id.et_search);
// fragmentMap = MapFragment.newInstance();
fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.rl_app_bar_main, fragmentCategoria);
fragmentTransaction.add(R.id.rl_app_bar_main, fragmentMapa);
// fragmentTransaction.add(R.id.rl_app_bar_main, fragmentMap);
fragmentTransaction.add(R.id.rl_app_bar_main, fragmentListCategoria);
fragmentTransaction.add(R.id.rl_app_bar_main, fragmentClient);
fragmentTransaction.show(fragmentCategoria);
fragmentTransaction.hide(fragmentMapa);
// fragmentTransaction.hide(fragmentMap);
fragmentTransaction.hide(fragmentListCategoria);
fragmentTransaction.hide(fragmentClient);
fragmentTransaction.commit();
TabLayout tabLayout = (TabLayout) findViewById(R.id.appbartabs);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.addTab(tabLayout.newTab().setText("Categorias"));
tabLayout.addTab(tabLayout.newTab().setText("Mapa"));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(tab.getPosition() == 0) {
goToFragment(fragmentMapa, fragmentCategoria);
}else{
if(fragmentCategoria.isVisible())
goToFragment(fragmentCategoria, fragmentMapa);
else if(fragmentListCategoria.isVisible())
goToFragment(fragmentListCategoria, fragmentMapa);
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void goToFragment(Fragment hide, Fragment show) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.show(show);
fragmentTransaction.hide(hide);
fragmentTransaction.commit();
}
public void changeCategory(String categoria){
fragmentListCategoria.tvCategoria.setText(categoria);
// fragmentListCategoria.listClients = listClients;
goToFragment(fragmentCategoria, fragmentListCategoria);
}
public void changeClient(String client){
fragmentClient.tvClientName.setText(client);
goToFragment(fragmentListCategoria, fragmentClient);
}
@Override
public void onBackPressed() {
if (fragmentListCategoria.isVisible()) {
goToFragment(fragmentListCategoria, fragmentCategoria);
return;
}else if (fragmentClient.isVisible()) {
goToFragment(fragmentClient, fragmentCategoria);
return;
}
finish();
}
}
| UTF-8 | Java | 4,874 | java | ActivityMain.java | Java | [] | null | [] | package soursoft.secuenciauno.co.soursoft;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.design.widget.TabLayout;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.maps.MapFragment;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class ActivityMain extends Activity {
FragmentManager fragmentManager;
EditText etSearch;
ImageButton ibtnSearch;
public ArrayList<Client> listClients = new ArrayList<>();
// MapFragment fragmentMap;
FragmentCategoria fragmentCategoria = new FragmentCategoria();
FragmentMapa fragmentMapa = new FragmentMapa();
FragmentListCategoria fragmentListCategoria = new FragmentListCategoria();
FragmentClient fragmentClient = new FragmentClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ibtnSearch = (ImageButton)findViewById(R.id.ibtn_search);
etSearch = (EditText)findViewById(R.id.et_search);
// fragmentMap = MapFragment.newInstance();
fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.rl_app_bar_main, fragmentCategoria);
fragmentTransaction.add(R.id.rl_app_bar_main, fragmentMapa);
// fragmentTransaction.add(R.id.rl_app_bar_main, fragmentMap);
fragmentTransaction.add(R.id.rl_app_bar_main, fragmentListCategoria);
fragmentTransaction.add(R.id.rl_app_bar_main, fragmentClient);
fragmentTransaction.show(fragmentCategoria);
fragmentTransaction.hide(fragmentMapa);
// fragmentTransaction.hide(fragmentMap);
fragmentTransaction.hide(fragmentListCategoria);
fragmentTransaction.hide(fragmentClient);
fragmentTransaction.commit();
TabLayout tabLayout = (TabLayout) findViewById(R.id.appbartabs);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.addTab(tabLayout.newTab().setText("Categorias"));
tabLayout.addTab(tabLayout.newTab().setText("Mapa"));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(tab.getPosition() == 0) {
goToFragment(fragmentMapa, fragmentCategoria);
}else{
if(fragmentCategoria.isVisible())
goToFragment(fragmentCategoria, fragmentMapa);
else if(fragmentListCategoria.isVisible())
goToFragment(fragmentListCategoria, fragmentMapa);
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void goToFragment(Fragment hide, Fragment show) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.show(show);
fragmentTransaction.hide(hide);
fragmentTransaction.commit();
}
public void changeCategory(String categoria){
fragmentListCategoria.tvCategoria.setText(categoria);
// fragmentListCategoria.listClients = listClients;
goToFragment(fragmentCategoria, fragmentListCategoria);
}
public void changeClient(String client){
fragmentClient.tvClientName.setText(client);
goToFragment(fragmentListCategoria, fragmentClient);
}
@Override
public void onBackPressed() {
if (fragmentListCategoria.isVisible()) {
goToFragment(fragmentListCategoria, fragmentCategoria);
return;
}else if (fragmentClient.isVisible()) {
goToFragment(fragmentClient, fragmentCategoria);
return;
}
finish();
}
}
| 4,874 | 0.687731 | 0.687526 | 150 | 31.493334 | 25.860846 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.58 | false | false | 13 |
cbe7e3693cd0d6fea277d5f5a5a765bfd14307fe | 24,163,486,063,713 | 17aa85f28cc9b7d027cf12eb6130604248f5a8da | /src/giorgoskozindividualv2/db/jdbc/UserDAOImpl.java | b89745d91162fb61662a096ce98a3187f883d035 | [] | no_license | giorgoskoz/giorgoskoz-individual | https://github.com/giorgoskoz/giorgoskoz-individual | 325543f7162a13faf7b3b775f334437f7ada3a62 | 5b1c2dda492f00ab25067e1393dffe14379851c0 | refs/heads/master | 2020-04-15T19:26:17.821000 | 2019-01-18T05:57:09 | 2019-01-18T05:57:09 | 164,949,757 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package giorgoskozindividualv2.db.jdbc;
import giorgoskozindividualv2.MessengerException;
import giorgoskozindividualv2.dao.UserDAO;
import static giorgoskozindividualv2.db.jdbc.DatabaseHelper.fetchAllUserIdsUsernames;
import giorgoskozindividualv2.model.User;
import java.util.List;
import java.util.Map;
/**
*
* @author giorgoskoz
*/
public class UserDAOImpl implements UserDAO {
@Override
public int deleteUser(int userId){
String query = "DELETE FROM users WHERE user_id = ?";
return DatabaseHelper.updateUser(query, userId);
}
@Override
public int updateUserUsername(String username, int userId){
String query = "UPDATE users SET username = ? WHERE user_id = ?";
return DatabaseHelper.updateUser(query, username, userId);
}
@Override
public int updateUserPassword(String password, int userId){
String query = "UPDATE users SET password = ? WHERE user_id = ?";
return DatabaseHelper.updateUser(query, password, userId);
}
@Override
public int updateUserRole(int roleId, int userId){
String query = "UPDATE users SET role_id = ? WHERE user_id = ?";
return DatabaseHelper.updateUser(query, roleId, userId);
}
@Override
public int createUser(String name, String password, int roleId) throws MessengerException {
String query = "INSERT INTO `users` VALUES(default, ?, ?, ?, 0)";
return DatabaseHelper.insertNewUser(query, name, password, roleId);
}
@Override
public void update(User user) throws MessengerException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void delete(User user) throws MessengerException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public User getUserById(int id) throws MessengerException {
User user = DatabaseHelper.fetchUserOrNull("select * from users where user_id = ?", id);
if (user == null) {
throw new MessengerException("Invalid user id: " + id);
}
return user;
}
@Override
public User getUser(String username, String password) throws MessengerException {
User user = DatabaseHelper.fetchUserOrNull("select * from users where name = ? and password = ?", username, password);
if (user == null) {
throw new MessengerException("Invalid username / password");
}
return user;
}
@Override
public List<User> getAllUsers() throws MessengerException {
return DatabaseHelper.fetchUsers("select * from users");
}
@Override
public Map<Integer, String> getAllUserIdsAndUsernames() throws MessengerException {
return fetchAllUserIdsUsernames();
}
}
| UTF-8 | Java | 3,134 | java | UserDAOImpl.java | Java | [
{
"context": "til.List;\nimport java.util.Map;\n\n/**\n *\n * @author giorgoskoz\n */\npublic class UserDAOImpl implements UserDAO {",
"end": 521,
"score": 0.9996242523193359,
"start": 511,
"tag": "USERNAME",
"value": "giorgoskoz"
}
] | 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 giorgoskozindividualv2.db.jdbc;
import giorgoskozindividualv2.MessengerException;
import giorgoskozindividualv2.dao.UserDAO;
import static giorgoskozindividualv2.db.jdbc.DatabaseHelper.fetchAllUserIdsUsernames;
import giorgoskozindividualv2.model.User;
import java.util.List;
import java.util.Map;
/**
*
* @author giorgoskoz
*/
public class UserDAOImpl implements UserDAO {
@Override
public int deleteUser(int userId){
String query = "DELETE FROM users WHERE user_id = ?";
return DatabaseHelper.updateUser(query, userId);
}
@Override
public int updateUserUsername(String username, int userId){
String query = "UPDATE users SET username = ? WHERE user_id = ?";
return DatabaseHelper.updateUser(query, username, userId);
}
@Override
public int updateUserPassword(String password, int userId){
String query = "UPDATE users SET password = ? WHERE user_id = ?";
return DatabaseHelper.updateUser(query, password, userId);
}
@Override
public int updateUserRole(int roleId, int userId){
String query = "UPDATE users SET role_id = ? WHERE user_id = ?";
return DatabaseHelper.updateUser(query, roleId, userId);
}
@Override
public int createUser(String name, String password, int roleId) throws MessengerException {
String query = "INSERT INTO `users` VALUES(default, ?, ?, ?, 0)";
return DatabaseHelper.insertNewUser(query, name, password, roleId);
}
@Override
public void update(User user) throws MessengerException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void delete(User user) throws MessengerException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public User getUserById(int id) throws MessengerException {
User user = DatabaseHelper.fetchUserOrNull("select * from users where user_id = ?", id);
if (user == null) {
throw new MessengerException("Invalid user id: " + id);
}
return user;
}
@Override
public User getUser(String username, String password) throws MessengerException {
User user = DatabaseHelper.fetchUserOrNull("select * from users where name = ? and password = ?", username, password);
if (user == null) {
throw new MessengerException("Invalid username / password");
}
return user;
}
@Override
public List<User> getAllUsers() throws MessengerException {
return DatabaseHelper.fetchUsers("select * from users");
}
@Override
public Map<Integer, String> getAllUserIdsAndUsernames() throws MessengerException {
return fetchAllUserIdsUsernames();
}
}
| 3,134 | 0.682833 | 0.680919 | 89 | 34.213482 | 34.294975 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.651685 | false | false | 13 |
f6bf8be632cf870b0946536e1fe53aa59c636704 | 5,317,169,512,768 | deb4ee900b978e4c93aa8789ff3c234ec6257c6a | /src/main/java/com/snrtqi/buy/pojo/OrderitemCustom.java | fbf4dedcd2bb133ef1db008d11e8edbcc3b7cc2f | [] | no_license | SnrtQi/buy | https://github.com/SnrtQi/buy | 9ec10fffb8a0a65dab6b7412060675effd8a640a | 929e811a96d897fc7f459dc3c66be6110f5997a6 | refs/heads/master | 2017-12-29T10:05:08.716000 | 2016-12-14T05:13:34 | 2016-12-14T05:13:34 | 81,542,671 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.snrtqi.buy.pojo;
/**
* 订单条目的扩展类
* Created by Gumo on 2016/11/12.
*/
public class OrderitemCustom extends Orderitem {
// 图书信息扩展类
private BookCustom bookCustom;
public BookCustom getBookCustom() {
return bookCustom;
}
public void setBookCustom(BookCustom bookCustom) {
this.bookCustom = bookCustom;
}
}
| UTF-8 | Java | 391 | java | OrderitemCustom.java | Java | [
{
"context": "om.snrtqi.buy.pojo;\n\n/**\n * 订单条目的扩展类\n * Created by Gumo on 2016/11/12.\n */\npublic class OrderitemCustom e",
"end": 64,
"score": 0.9637848734855652,
"start": 60,
"tag": "USERNAME",
"value": "Gumo"
}
] | null | [] | package com.snrtqi.buy.pojo;
/**
* 订单条目的扩展类
* Created by Gumo on 2016/11/12.
*/
public class OrderitemCustom extends Orderitem {
// 图书信息扩展类
private BookCustom bookCustom;
public BookCustom getBookCustom() {
return bookCustom;
}
public void setBookCustom(BookCustom bookCustom) {
this.bookCustom = bookCustom;
}
}
| 391 | 0.67036 | 0.648199 | 19 | 18 | 17.879715 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.210526 | false | false | 13 |
cc6175c17ae02cf0bbdb553d50bea99ab2b5be21 | 23,124,103,953,894 | 51bcd5f81f8ed19edd137866183fbdfb2abfa3c8 | /src/main/java/com/era/easyretail/validators/exceptions/UsersValidatorsExceptions.java | a0a3a74be9dd5efd8a1ecb9dc8e12a7b72deeb3a | [] | no_license | davidtadeovargas/era_easyretail | https://github.com/davidtadeovargas/era_easyretail | 60edeb7c30468e596662e127c396a3d93948426b | 2e19a1859c115bfa6574b2133e6a62ec9ed92d3e | refs/heads/master | 2023-01-27T23:34:31.676000 | 2020-11-24T04:42:46 | 2020-11-24T04:42:46 | 245,110,215 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.era.easyretail.validators.exceptions;
public class UsersValidatorsExceptions {
private static UsersValidatorsExceptions UsersValidatorsExceptions;
public static UsersValidatorsExceptions getSigleton(){
if(UsersValidatorsExceptions==null){UsersValidatorsExceptions = new UsersValidatorsExceptions();}return UsersValidatorsExceptions;
}
public Exception getModelExistsException(){
return new Exception("El registro ya existe");
}
public Exception getCustomVaidationNotPassedException(){
return new Exception("El registro no paso las validaciones");
}
public Exception getModelNotExistsException(){
return new Exception("El registro no existe");
}
public Exception getCodeException(){
return new Exception("Falta espeficiar codigo");
}
public Exception getCortException(){
return new Exception("Falta espeficiar Cort");
}
public Exception getDisccountException(){
return new Exception("Falta espeficiar Disccount");
}
public Exception getM52Exception(){
return new Exception("Falta espeficiar M52");
}
public Exception getPasswordException(){
return new Exception("Falta espeficiar Password");
}
public Exception getUserOfsalesOfPointException(){
return new Exception("Falta espeficiar UserOfsalesOfPoint");
}
} | UTF-8 | Java | 1,366 | java | UsersValidatorsExceptions.java | Java | [] | null | [] | package com.era.easyretail.validators.exceptions;
public class UsersValidatorsExceptions {
private static UsersValidatorsExceptions UsersValidatorsExceptions;
public static UsersValidatorsExceptions getSigleton(){
if(UsersValidatorsExceptions==null){UsersValidatorsExceptions = new UsersValidatorsExceptions();}return UsersValidatorsExceptions;
}
public Exception getModelExistsException(){
return new Exception("El registro ya existe");
}
public Exception getCustomVaidationNotPassedException(){
return new Exception("El registro no paso las validaciones");
}
public Exception getModelNotExistsException(){
return new Exception("El registro no existe");
}
public Exception getCodeException(){
return new Exception("Falta espeficiar codigo");
}
public Exception getCortException(){
return new Exception("Falta espeficiar Cort");
}
public Exception getDisccountException(){
return new Exception("Falta espeficiar Disccount");
}
public Exception getM52Exception(){
return new Exception("Falta espeficiar M52");
}
public Exception getPasswordException(){
return new Exception("Falta espeficiar Password");
}
public Exception getUserOfsalesOfPointException(){
return new Exception("Falta espeficiar UserOfsalesOfPoint");
}
} | 1,366 | 0.739385 | 0.736457 | 47 | 28.085106 | 30.235832 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.276596 | false | false | 13 |
17b98c3c3eaa8c6ee8ba5d81b2aecc2498fff6fd | 22,041,772,210,658 | 97fe3429ff14fd4af896a68d2a31ed9dec7c9c59 | /src/admin/Voterlogin.java | 92497fe68f9ee42d0c3fb6da2e75a838a92fc1fe | [] | no_license | saurabhdubeycs/online-voting-system | https://github.com/saurabhdubeycs/online-voting-system | dd4e6541d3314172f2e1131a8f2b7320b4666f99 | c48818dedff56e238d32c69abc5b65d56b8b1682 | refs/heads/master | 2022-12-04T01:01:49.861000 | 2020-08-10T04:29:59 | 2020-08-10T04:29:59 | 286,373,577 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package admin;
import admin.Action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Voterlogin extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user_name=request.getParameter("user_name");
String password=request.getParameter("password");
String status="0";
Action o1= new Action();
o1.setUser_name(user_name);
o1.setPassword(password);
o1.setStatus(status);
if(o1.voterlogin(user_name, password,status))
{
HttpSession session=request.getSession();
session.setAttribute("name", user_name);
response.sendRedirect("../voting.jsp");
o1.updatedata("voter"," WHERE password="+password+""," status="+1+"");
}
else
{
response.sendRedirect("../admin/voterlogin.jsp");
}
}
}
| UTF-8 | Java | 1,232 | java | Voterlogin.java | Java | [
{
"context": "\t\t\n\t\to1.setUser_name(user_name);\n\t\to1.setPassword(password);\n\t\to1.setStatus(status);\n\t\t\n\t\tif(o1.voterlogin(u",
"end": 836,
"score": 0.9947636127471924,
"start": 828,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "sp\");\n\t\t\to1.updatedata(\"voter\",\" WHERE password=\"+password+\"\",\" status=\"+1+\"\");\n\t\t\t\n\t\t }\n\t\t else\n\t\t {\n\t\t\t",
"end": 1115,
"score": 0.9210662245750427,
"start": 1107,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package admin;
import admin.Action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Voterlogin extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user_name=request.getParameter("user_name");
String password=request.getParameter("password");
String status="0";
Action o1= new Action();
o1.setUser_name(user_name);
o1.setPassword(<PASSWORD>);
o1.setStatus(status);
if(o1.voterlogin(user_name, password,status))
{
HttpSession session=request.getSession();
session.setAttribute("name", user_name);
response.sendRedirect("../voting.jsp");
o1.updatedata("voter"," WHERE password="+<PASSWORD>+""," status="+1+"");
}
else
{
response.sendRedirect("../admin/voterlogin.jsp");
}
}
}
| 1,236 | 0.719156 | 0.711851 | 52 | 22.692308 | 21.42028 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.961538 | false | false | 13 |
c63eace37e9a428d79265250d80b3ba81bac2289 | 7,146,825,632,825 | a642b269ef664f3271d473cc00ecb4e0b77a0544 | /common-lang/src/main/java/com/xc/common/lang/able/Decoratable.java | e4cd29ff9135b3545080469bf116e7f9bd66ee9c | [] | no_license | taiyangchen/common | https://github.com/taiyangchen/common | 237b9f76e80f2cdf4ac2a2f4b8bd50e6648b5d52 | 435076f2ae4621d8c632dfd3b6d74035af5a94c2 | refs/heads/master | 2017-11-01T13:42:26.917000 | 2016-07-06T15:52:43 | 2016-07-06T15:52:43 | 62,551,740 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (C) 2015 Baidu, Inc. All Rights Reserved.
*/
package com.xc.common.lang.able;
/**
* 装饰用
*
* @author <a href="mailto:xuchen06@baidu.com">xuc</a>
* @version create on 2015-6-17 下午4:04:20
*/
public interface Decoratable<T> {
T get();
void set(T t);
}
| UTF-8 | Java | 312 | java | Decoratable.java | Java | [
{
"context": ";\r\n\r\n/**\r\n * 装饰用\r\n * \r\n * @author <a href=\"mailto:xuchen06@baidu.com\">xuc</a>\r\n * @version create on 2015-6-17 下午4:04:",
"end": 165,
"score": 0.9999250769615173,
"start": 147,
"tag": "EMAIL",
"value": "xuchen06@baidu.com"
},
{
"context": " \r\n * @author <a href=\"mailto:xuchen06@baidu.com\">xuc</a>\r\n * @version create on 2015-6-17 下午4:04:20\r\n ",
"end": 170,
"score": 0.9978479146957397,
"start": 167,
"tag": "USERNAME",
"value": "xuc"
}
] | null | [] | /**
* Copyright (C) 2015 Baidu, Inc. All Rights Reserved.
*/
package com.xc.common.lang.able;
/**
* 装饰用
*
* @author <a href="mailto:<EMAIL>">xuc</a>
* @version create on 2015-6-17 下午4:04:20
*/
public interface Decoratable<T> {
T get();
void set(T t);
}
| 301 | 0.576159 | 0.516556 | 18 | 14.777778 | 18.62661 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 13 |
c37ac0d0a4be0388ad8b7b51530efb172734318f | 9,603,546,901,100 | acc85b3337de39c227c71a98b52bd389bf11a945 | /src/Scoreboard.java | f600ddfce217fb4cc6004fefd7f9eddf52436c98 | [] | no_license | StefanWG/CompsciFinalProject | https://github.com/StefanWG/CompsciFinalProject | d3d905dbeca09e517924bba85cc912c59416c517 | 5db25920c2d69637e1936562e2e0123bad52ebc2 | refs/heads/master | 2022-06-07T06:58:58.861000 | 2020-05-04T21:16:49 | 2020-05-04T21:16:49 | 252,615,643 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* The Scoreboard class stores all the information about the state the game is in.
* It also is responsible for updating the game state given specific results.
**/
import java.util.ArrayList;
public class Scoreboard {
//tracks outs
int outs;
//this array is what keeps track of who is one what base
boolean[] bases = new boolean[3];
//these track hits and runs for both teams
int homeRuns;
int awayRuns;
int awayHits;
int homeHits;
//counting in half innings (so 18 innings total), Each time 3 outs ar hit this advances
int halfInning;
//how many inning we want to play
int maxInnings;
//the two teams to play
Team homeTeam;
Team awayTeam;
//to keep track of the number of runs in each inning
ArrayList<Integer> homeRunsInning = new ArrayList<>();
ArrayList<Integer> awayRunsInning = new ArrayList<>();
//the audio file and thread that plays hit audio
Audio hitball = new Audio("AudioFiles/hitball.wav");
Thread hitballThread = new Thread(hitball);
//constructor
public Scoreboard(int maxInnings, Team homeTeam, Team awayTeam) {
//initializing the variable using inputs from constructor or initializing to 0
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
this.outs = 0;
this.homeRuns = 0;
this.awayRuns = 0;
//initialized to 1 since we are starting in the first half inning
this.halfInning = 1;
this.maxInnings = maxInnings;
//initializing the bases to false since no one is on base and the game hasn't started.
for (int i = 0; i < this.bases.length; i++) {
bases[i] = false;
}
//initialization of complex data structures to avoid null pointers
awayRunsInning.add(0);
hitballThread.start();
}
/**this method adds runs to the totals based on which half inning we are in
*
* @param numRuns
*/
private void addRuns(int numRuns) {
//tells us which inning we are in.
int inning = (halfInning - 1) / 2;
//this is the home team
if (this.halfInning % 2 == 0) {
//adds RBIs to this player based on how many runs he drove in
this.homeTeam.lineup[homeTeam.lineupPos%9].RBIs += numRuns;
//adds runs to the home team total
this.homeRuns += numRuns;
//finds total number of runs scored in this inning
int runs = this.homeRunsInning.get(inning);
this.homeRunsInning.remove(inning);
this.homeRunsInning.add(runs + numRuns);
}
//this is the away team
//essentially same code as above but all being added to away teams totals and players
else {
//adds RBIs to this player based on how many runs he drove in
this.awayTeam.lineup[awayTeam.lineupPos%9].RBIs += numRuns;
//adds runs to the home team total
this.awayRuns += numRuns;
//finds total number of runs scored in this inning
int runs = this.awayRunsInning.get(inning);
this.awayRunsInning.remove(inning);
this.awayRunsInning.add(runs + numRuns);
}
}
/** This method updates the bases and adds runs for when a single is hit
*
*/
private void Single() {
//find initial state of bases
boolean first = this.bases[0];
boolean second = this.bases[1];
boolean third = this.bases[2];
//send person at third home
if (third) {
addRuns(1);
this.bases[2] = false;
}
//send person at second to third
if (second) {
this.bases[1] = false;
this.bases[2] = true;
}
//send person at first to second
if (first) {
//send them to second
this.bases[1] = true;
//not clearing first base because it was a single and hitter will
//now occupy first, hence first is still occupied
}
this.bases[0] = true; //send person to first base
//adding the hit to the total for thee respective teams hits
if (halfInning % 2 == 1) {
awayHits += 1;
} else {
homeHits += 1;
}
}
/** This method updates the bases and adds runs for when a double is hit
*
*/
private void Double() {
//find initial state of bases
boolean first = this.bases[0];
boolean second = this.bases[1];
boolean third = this.bases[2];
//Add run for if runners are on 2nd and 2rd
if (second) addRuns(1);
if (third) addRuns(1);
//Clear Bases
this.bases[1] = false;
this.bases[2] = false;
//send first to third
if (first) {
this.bases[0] = false;
this.bases[2] = true;
}
//make second base occupied since a double was hit
this.bases[1] = true;
//adding the hit to the total for thee respective teams hits
if (halfInning % 2 == 1) {
awayHits += 1;
} else {
homeHits += 1;
}
}
/** This method updates the bases and adds runs for when a triple is hit
*
*/
private void Triple() {
//very similar to home run. clears all bases and adds run accordingly
//however at the end, third base gets occupied.
//however, no guarantee of one scoring like HR, so we take one away from the tally
//to count for this
HomeRun();
//compensation for extra run from HR
addRuns(-1);
//make third base occupied and first and second empty
this.bases[0] = false;
this.bases[1] = false;
this.bases[2] = true;
}
/** This method updates adds runs for when a home run is hit
*
*/
private void HomeRun() {
//starts at one since at least one run scores from HR
int numBases = 1;
//checking how many people are on base and for each person on each base, adding to numruns
//will add numRuns to total since all of thm score after a home run.
for (int i = 0; i < this.bases.length; i++) {
boolean result = this.bases[i];
if (result) {
numBases++;
}
//empty all the bases
this.bases[i] = false;
}
//adding runs to the total
addRuns(numBases);
//adding the hit to the total for thee respective teams hits
if (halfInning % 2 == 1) {
awayHits += 1;
} else {
homeHits += 1;
}
}
/** This method updates the bases and adds runs for when a walk is hit
*
*/
private void Walk() {
//here runs only score if bases are loaded
boolean first = this.bases[0];
boolean second = this.bases[1];
boolean third = this.bases[2];
//if bases are loaded add a run and keep bases loaded
if (first && second && third) {
addRuns(1);
}
//if first is empty, just fill first
if (!first) {
this.bases[0] = true;
}
//otherwise first is full
else {
//first is full but second empty
if (!second) {
this.bases[1] = true;
}
//first and second are full
else {
if (!third) {
this.bases[2] = true;
}
//otherwise all three are full and this has been accounted for at the beginning
}
}
}
/**
* this method combines the single/double/etc. methods into one method.
*/
public void updateBases(int n, boolean human) {
if (human) hitball.play();
switch (n) {
//out
case 0:
this.outs++;
break;
//single
case 1:
Single();
break;
//double
case 2:
Double();
break;
//triple
case 3:
Triple();
break;
//HR
case 4:
HomeRun();
break;
//Walk
case 5:
Walk();
break;
}
}
/** This method advances the inning (resets bases, adds the counter for which inning we are in)
*
*/
public void newInning() {
//resets outs
this.outs = 0;
//makes all the bases empty by making them false
for (int i = 0; i < this.bases.length; i++) {
bases[i] = false;
}
//adds one to the half inning..progressing the game to the next inning
this.halfInning++;
//adds a 0 to signify the start of a new inning.
if (halfInning % 2 == 1) {
awayRunsInning.add(0);
} else {
homeRunsInning.add(0);
}
}
/**to String method to print out thee scoreboard in the terminal and also to display.
*
* @return
*/
public String toString() {
String str;
String i = (halfInning / 2) + " ";
if (halfInning % 2 == 1) i += "<";
else i += ">";
str = "Away: " + awayRuns + "Home: " + homeRuns + "Inning: " + i + "Outs: " + outs + "\n";
str += bases[0] + " " + bases[1] + " " + bases[2] + "\n";
return str;
}
} | UTF-8 | Java | 9,528 | java | Scoreboard.java | Java | [] | null | [] | /**
* The Scoreboard class stores all the information about the state the game is in.
* It also is responsible for updating the game state given specific results.
**/
import java.util.ArrayList;
public class Scoreboard {
//tracks outs
int outs;
//this array is what keeps track of who is one what base
boolean[] bases = new boolean[3];
//these track hits and runs for both teams
int homeRuns;
int awayRuns;
int awayHits;
int homeHits;
//counting in half innings (so 18 innings total), Each time 3 outs ar hit this advances
int halfInning;
//how many inning we want to play
int maxInnings;
//the two teams to play
Team homeTeam;
Team awayTeam;
//to keep track of the number of runs in each inning
ArrayList<Integer> homeRunsInning = new ArrayList<>();
ArrayList<Integer> awayRunsInning = new ArrayList<>();
//the audio file and thread that plays hit audio
Audio hitball = new Audio("AudioFiles/hitball.wav");
Thread hitballThread = new Thread(hitball);
//constructor
public Scoreboard(int maxInnings, Team homeTeam, Team awayTeam) {
//initializing the variable using inputs from constructor or initializing to 0
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
this.outs = 0;
this.homeRuns = 0;
this.awayRuns = 0;
//initialized to 1 since we are starting in the first half inning
this.halfInning = 1;
this.maxInnings = maxInnings;
//initializing the bases to false since no one is on base and the game hasn't started.
for (int i = 0; i < this.bases.length; i++) {
bases[i] = false;
}
//initialization of complex data structures to avoid null pointers
awayRunsInning.add(0);
hitballThread.start();
}
/**this method adds runs to the totals based on which half inning we are in
*
* @param numRuns
*/
private void addRuns(int numRuns) {
//tells us which inning we are in.
int inning = (halfInning - 1) / 2;
//this is the home team
if (this.halfInning % 2 == 0) {
//adds RBIs to this player based on how many runs he drove in
this.homeTeam.lineup[homeTeam.lineupPos%9].RBIs += numRuns;
//adds runs to the home team total
this.homeRuns += numRuns;
//finds total number of runs scored in this inning
int runs = this.homeRunsInning.get(inning);
this.homeRunsInning.remove(inning);
this.homeRunsInning.add(runs + numRuns);
}
//this is the away team
//essentially same code as above but all being added to away teams totals and players
else {
//adds RBIs to this player based on how many runs he drove in
this.awayTeam.lineup[awayTeam.lineupPos%9].RBIs += numRuns;
//adds runs to the home team total
this.awayRuns += numRuns;
//finds total number of runs scored in this inning
int runs = this.awayRunsInning.get(inning);
this.awayRunsInning.remove(inning);
this.awayRunsInning.add(runs + numRuns);
}
}
/** This method updates the bases and adds runs for when a single is hit
*
*/
private void Single() {
//find initial state of bases
boolean first = this.bases[0];
boolean second = this.bases[1];
boolean third = this.bases[2];
//send person at third home
if (third) {
addRuns(1);
this.bases[2] = false;
}
//send person at second to third
if (second) {
this.bases[1] = false;
this.bases[2] = true;
}
//send person at first to second
if (first) {
//send them to second
this.bases[1] = true;
//not clearing first base because it was a single and hitter will
//now occupy first, hence first is still occupied
}
this.bases[0] = true; //send person to first base
//adding the hit to the total for thee respective teams hits
if (halfInning % 2 == 1) {
awayHits += 1;
} else {
homeHits += 1;
}
}
/** This method updates the bases and adds runs for when a double is hit
*
*/
private void Double() {
//find initial state of bases
boolean first = this.bases[0];
boolean second = this.bases[1];
boolean third = this.bases[2];
//Add run for if runners are on 2nd and 2rd
if (second) addRuns(1);
if (third) addRuns(1);
//Clear Bases
this.bases[1] = false;
this.bases[2] = false;
//send first to third
if (first) {
this.bases[0] = false;
this.bases[2] = true;
}
//make second base occupied since a double was hit
this.bases[1] = true;
//adding the hit to the total for thee respective teams hits
if (halfInning % 2 == 1) {
awayHits += 1;
} else {
homeHits += 1;
}
}
/** This method updates the bases and adds runs for when a triple is hit
*
*/
private void Triple() {
//very similar to home run. clears all bases and adds run accordingly
//however at the end, third base gets occupied.
//however, no guarantee of one scoring like HR, so we take one away from the tally
//to count for this
HomeRun();
//compensation for extra run from HR
addRuns(-1);
//make third base occupied and first and second empty
this.bases[0] = false;
this.bases[1] = false;
this.bases[2] = true;
}
/** This method updates adds runs for when a home run is hit
*
*/
private void HomeRun() {
//starts at one since at least one run scores from HR
int numBases = 1;
//checking how many people are on base and for each person on each base, adding to numruns
//will add numRuns to total since all of thm score after a home run.
for (int i = 0; i < this.bases.length; i++) {
boolean result = this.bases[i];
if (result) {
numBases++;
}
//empty all the bases
this.bases[i] = false;
}
//adding runs to the total
addRuns(numBases);
//adding the hit to the total for thee respective teams hits
if (halfInning % 2 == 1) {
awayHits += 1;
} else {
homeHits += 1;
}
}
/** This method updates the bases and adds runs for when a walk is hit
*
*/
private void Walk() {
//here runs only score if bases are loaded
boolean first = this.bases[0];
boolean second = this.bases[1];
boolean third = this.bases[2];
//if bases are loaded add a run and keep bases loaded
if (first && second && third) {
addRuns(1);
}
//if first is empty, just fill first
if (!first) {
this.bases[0] = true;
}
//otherwise first is full
else {
//first is full but second empty
if (!second) {
this.bases[1] = true;
}
//first and second are full
else {
if (!third) {
this.bases[2] = true;
}
//otherwise all three are full and this has been accounted for at the beginning
}
}
}
/**
* this method combines the single/double/etc. methods into one method.
*/
public void updateBases(int n, boolean human) {
if (human) hitball.play();
switch (n) {
//out
case 0:
this.outs++;
break;
//single
case 1:
Single();
break;
//double
case 2:
Double();
break;
//triple
case 3:
Triple();
break;
//HR
case 4:
HomeRun();
break;
//Walk
case 5:
Walk();
break;
}
}
/** This method advances the inning (resets bases, adds the counter for which inning we are in)
*
*/
public void newInning() {
//resets outs
this.outs = 0;
//makes all the bases empty by making them false
for (int i = 0; i < this.bases.length; i++) {
bases[i] = false;
}
//adds one to the half inning..progressing the game to the next inning
this.halfInning++;
//adds a 0 to signify the start of a new inning.
if (halfInning % 2 == 1) {
awayRunsInning.add(0);
} else {
homeRunsInning.add(0);
}
}
/**to String method to print out thee scoreboard in the terminal and also to display.
*
* @return
*/
public String toString() {
String str;
String i = (halfInning / 2) + " ";
if (halfInning % 2 == 1) i += "<";
else i += ">";
str = "Away: " + awayRuns + "Home: " + homeRuns + "Inning: " + i + "Outs: " + outs + "\n";
str += bases[0] + " " + bases[1] + " " + bases[2] + "\n";
return str;
}
} | 9,528 | 0.537993 | 0.529282 | 294 | 31.411564 | 23.295732 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.408163 | false | false | 13 |
49a40359146d82db2e511ec84697a97b26b33444 | 9,388,798,538,890 | eec855242c55274a3cec4c1578fd671fa7b8709a | /src/nl/pa3bmg/pi4j/lora/model/GPSPosition.java | e26be68b9013f29057d539e4a2bf13f0cad00da0 | [] | no_license | Hey-Jobs/ReceiveLora | https://github.com/Hey-Jobs/ReceiveLora | b004754fba93d2a5479ee989433e9354a566c31f | 958844b0635e22c8d3d7779d6043014667c56ed4 | refs/heads/master | 2023-03-16T05:55:40.805000 | 2018-07-15T09:38:33 | 2018-07-15T09:38:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nl.pa3bmg.pi4j.lora.model;
public class GPSPosition {
public float time = 0.0f;
public float lat = 0.0f;
public float lon = 0.0f;
public boolean fixed = false;
public int quality = 0;
public float dir = 0.0f;
public float altitude = 0.0f;
public float velocity = 0.0f;
public void updatefix() {
fixed = quality > 0;
}
public String toString() {
return String.format("POSITION: lat: %f, lon: %f, time: %f, Q: %d, dir: %f, alt: %f, vel: %f", lat, lon, time, quality, dir, altitude, velocity);
}
}
| UTF-8 | Java | 524 | java | GPSPosition.java | Java | [] | null | [] | package nl.pa3bmg.pi4j.lora.model;
public class GPSPosition {
public float time = 0.0f;
public float lat = 0.0f;
public float lon = 0.0f;
public boolean fixed = false;
public int quality = 0;
public float dir = 0.0f;
public float altitude = 0.0f;
public float velocity = 0.0f;
public void updatefix() {
fixed = quality > 0;
}
public String toString() {
return String.format("POSITION: lat: %f, lon: %f, time: %f, Q: %d, dir: %f, alt: %f, vel: %f", lat, lon, time, quality, dir, altitude, velocity);
}
}
| 524 | 0.656489 | 0.625954 | 20 | 25.200001 | 30.386839 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.1 | false | false | 13 |
25d6e904d76e9bc03f2a4d2a1d5dcbbcc5224d95 | 1,434,519,110,608 | bf38aaa4671284032003dfaf54974e544c7b74f9 | /Lab.1/src/lab1/Bai5.java | abe8fec92780de9209931cd896627d1f86c4d91e | [] | no_license | Makeets/TTM_Tin12A1 | https://github.com/Makeets/TTM_Tin12A1 | d4364a5762b23eed55305b945cafc0c43d094cf7 | 208482064245c57be8b579da9d61e540cabb8fb0 | refs/heads/main | 2023-08-11T08:46:21.412000 | 2021-09-24T00:38:47 | 2021-09-24T00:38:47 | 409,514,515 | 0 | 1 | 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 lab1;
import java.util.Scanner;
/**
*
* @author ADMIN
*/
public class Bai5 {
int n;
public int getN() {
return n;
}
void nhap() {
boolean check = false;
Scanner sc = new Scanner(System.in);
do {
try {
System.out.println("Nhap vao n:");
n = Integer.parseInt(sc.nextLine());
check = true;
} catch (java.lang.NumberFormatException e) {
System.out.println("hay nhap dung kieu du lieu" + e.toString());
check = false;
}
} while (check == false);
}
float tinhTong1(int a) {
float tong1 = 0;
for (int i = 1; i <= a; i++) {
tong1 += 1.0 / i;
}
return tong1;
}
float tinhTong2(int a) {
float tong2 = 0;
int giaithua = 1;
for (int i = 1; i <= a; i++) {
giaithua *= i;
tong2 += 1.0 / giaithua;
}
return tong2;
}
void menu() {
System.out.println("1 Nhap vao so nguyen duong n");
System.out.println("2 Tinh tong :1+....+1/n");
System.out.println("3 Tinh tong :1+....+1/n!");
}
public static void main(String[] args) {
Bai5 bai5 = new Bai5();
int n = 0;
Scanner sc = new Scanner(System.in);
do {
boolean check = false;
do {
bai5.menu();
try {
System.out.println("Nhap vao lua chon :");
n = Integer.parseInt(sc.nextLine());
check = true;
} catch (java.lang.NumberFormatException e) {
System.out.println("hay nhap dung kieu du lieu" + e.toString());
check = false;
}
} while (check == false);
switch (n) {
case 1: {
bai5.nhap();
break;
}
case 2: {
if (bai5.getN() == 0) {
System.out.println("ban chua nhap n!hoac ban de n =0");
} else {
System.out.println("Tong 1+...1/" + n + " la:" + bai5.tinhTong1(bai5.getN()));
}
break;
}
case 3: {
if (bai5.getN() == 0) {
System.out.println("ban chua nhap n!hoac ban de n =0");
} else {
System.out.println("Tong 1+...1/" + n + "! la:" + bai5.tinhTong2(bai5.getN()));
}
break;
}
case 0: {
break;
}
default: {
System.out.println("Khong co lua chon cua ban ");
break;
}
}
} while (n != 0);
}
}
| UTF-8 | Java | 3,250 | java | Bai5.java | Java | [
{
"context": "\r\nimport java.util.Scanner;\r\n\r\n/**\r\n *\r\n * @author ADMIN\r\n */\r\npublic class Bai5 {\r\n\r\n int n;\r\n\r\n publ",
"end": 261,
"score": 0.6927539706230164,
"start": 256,
"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 lab1;
import java.util.Scanner;
/**
*
* @author ADMIN
*/
public class Bai5 {
int n;
public int getN() {
return n;
}
void nhap() {
boolean check = false;
Scanner sc = new Scanner(System.in);
do {
try {
System.out.println("Nhap vao n:");
n = Integer.parseInt(sc.nextLine());
check = true;
} catch (java.lang.NumberFormatException e) {
System.out.println("hay nhap dung kieu du lieu" + e.toString());
check = false;
}
} while (check == false);
}
float tinhTong1(int a) {
float tong1 = 0;
for (int i = 1; i <= a; i++) {
tong1 += 1.0 / i;
}
return tong1;
}
float tinhTong2(int a) {
float tong2 = 0;
int giaithua = 1;
for (int i = 1; i <= a; i++) {
giaithua *= i;
tong2 += 1.0 / giaithua;
}
return tong2;
}
void menu() {
System.out.println("1 Nhap vao so nguyen duong n");
System.out.println("2 Tinh tong :1+....+1/n");
System.out.println("3 Tinh tong :1+....+1/n!");
}
public static void main(String[] args) {
Bai5 bai5 = new Bai5();
int n = 0;
Scanner sc = new Scanner(System.in);
do {
boolean check = false;
do {
bai5.menu();
try {
System.out.println("Nhap vao lua chon :");
n = Integer.parseInt(sc.nextLine());
check = true;
} catch (java.lang.NumberFormatException e) {
System.out.println("hay nhap dung kieu du lieu" + e.toString());
check = false;
}
} while (check == false);
switch (n) {
case 1: {
bai5.nhap();
break;
}
case 2: {
if (bai5.getN() == 0) {
System.out.println("ban chua nhap n!hoac ban de n =0");
} else {
System.out.println("Tong 1+...1/" + n + " la:" + bai5.tinhTong1(bai5.getN()));
}
break;
}
case 3: {
if (bai5.getN() == 0) {
System.out.println("ban chua nhap n!hoac ban de n =0");
} else {
System.out.println("Tong 1+...1/" + n + "! la:" + bai5.tinhTong2(bai5.getN()));
}
break;
}
case 0: {
break;
}
default: {
System.out.println("Khong co lua chon cua ban ");
break;
}
}
} while (n != 0);
}
}
| 3,250 | 0.393538 | 0.377231 | 110 | 27.545454 | 22.496721 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481818 | false | false | 13 |
51334fb52d8620be67d4cc9a9ab70194e5766aae | 16,870,631,573,077 | 5cace9553f36c5d87af70354657c9ccce4c40dc6 | /src/main/java/com/admin/admin/Repository/CategoryQuestionCompositeRepository.java | cb9eef81164216f37e2cea2e9e5d646cf6f53014 | [] | no_license | sweta235/Admin | https://github.com/sweta235/Admin | 4ccc00e3ed6874dcbc061e7fbb85385e0b3b6737 | 65c6a44b61c6afbbe7c4b30226b095ffc0f4b3b0 | refs/heads/master | 2021-05-09T22:38:03.529000 | 2018-01-24T11:50:41 | 2018-01-24T11:50:41 | 118,758,035 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.admin.admin.Repository;
import com.admin.admin.Entity.CategoryQuestion;
import com.admin.admin.Entity.CategoryQuestionComposite;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface CategoryQuestionCompositeRepository extends CrudRepository<CategoryQuestion,CategoryQuestionComposite> {
public List<CategoryQuestion> findAllByCategoryQuestionCompositeCategoryId(String categoryId);
}
| UTF-8 | Java | 449 | java | CategoryQuestionCompositeRepository.java | Java | [] | null | [] | package com.admin.admin.Repository;
import com.admin.admin.Entity.CategoryQuestion;
import com.admin.admin.Entity.CategoryQuestionComposite;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface CategoryQuestionCompositeRepository extends CrudRepository<CategoryQuestion,CategoryQuestionComposite> {
public List<CategoryQuestion> findAllByCategoryQuestionCompositeCategoryId(String categoryId);
}
| 449 | 0.86637 | 0.86637 | 11 | 39.81818 | 39.570004 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 13 |
8a916c6a1cfd63d2d73271ecd70470f21e16bf39 | 26,207,890,466,539 | e2075c55341b2d576fadc2cde328de3afb0801d3 | /app/src/main/java/com/zt/inspection/view/fragment/HistoryFragment.java | 7a953719a981b3ae9ff8be764385da92c8ce15b3 | [] | no_license | MrCuiWenQiang/Inspection | https://github.com/MrCuiWenQiang/Inspection | 09512dd193e0bcb48738423f9e31e39e05b1b74b | 546c533bf56df51c130e52f1fd3e84616a6073bb | refs/heads/master | 2022-12-08T05:19:34.339000 | 2020-08-31T06:55:11 | 2020-08-31T06:55:11 | 262,462,238 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zt.inspection.view.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import com.qmuiteam.qmui.widget.QMUITabSegment;
import com.zt.inspection.R;
import com.zt.inspection.view.adapter.MainPageAdapter;
import java.util.ArrayList;
import cn.faker.repaymodel.fragment.BaseViewPagerFragment;
/**
* 因逻辑简单 不再使用mvp
*/
public class HistoryFragment extends BaseViewPagerFragment {
private ViewPager mContentViewPager;
private QMUITabSegment mTabSegment;
private ImageView im_icon;
public static HistoryFragment newInstance() {
Bundle args = new Bundle();
HistoryFragment fragment = new HistoryFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public int getLayoutId() {
return R.layout.fg_history;
}
@Override
public void initview(View v) {
mContentViewPager = v.findViewById(R.id.contentViewPager);
mTabSegment = v.findViewById(R.id.tabs);
im_icon = v.findViewById(R.id.im_icon);
mTabSegment.setDefaultNormalColor(ContextCompat.getColor(getContext(), R.color.passw_changing));
mTabSegment.setDefaultSelectedColor(ContextCompat.getColor(getContext(), R.color.blue_5));
mTabSegment.setHasIndicator(true);
mTabSegment.setIndicatorPosition(false);
mTabSegment.setIndicatorWidthAdjustContent(true);
}
@Override
public void initData(Bundle savedInstanceState) {
mTabSegment.addTab(new QMUITabSegment.Tab("案件历史"));
mTabSegment.addTab(new QMUITabSegment.Tab("巡检历史"));
ArrayList<Fragment> fragments = new ArrayList<>();
fragments.add(HistoryWorkFragment.newInstance());
fragments.add(HistoryRouteFragment.newInstance());
MainPageAdapter pageAdapter = new MainPageAdapter(getChildFragmentManager(), fragments);
mContentViewPager.setAdapter(pageAdapter);
mTabSegment.setupWithViewPager(mContentViewPager, false);
mTabSegment.notifyDataChanged();
mContentViewPager.setCurrentItem(0);
mContentViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
int n = i+1;
if (n==1){
im_icon.setImageResource(R.mipmap.workicc);
}else {
im_icon.setImageResource(R.mipmap.routrww);
}
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
}
}
| UTF-8 | Java | 2,874 | java | HistoryFragment.java | Java | [] | null | [] | package com.zt.inspection.view.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import com.qmuiteam.qmui.widget.QMUITabSegment;
import com.zt.inspection.R;
import com.zt.inspection.view.adapter.MainPageAdapter;
import java.util.ArrayList;
import cn.faker.repaymodel.fragment.BaseViewPagerFragment;
/**
* 因逻辑简单 不再使用mvp
*/
public class HistoryFragment extends BaseViewPagerFragment {
private ViewPager mContentViewPager;
private QMUITabSegment mTabSegment;
private ImageView im_icon;
public static HistoryFragment newInstance() {
Bundle args = new Bundle();
HistoryFragment fragment = new HistoryFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public int getLayoutId() {
return R.layout.fg_history;
}
@Override
public void initview(View v) {
mContentViewPager = v.findViewById(R.id.contentViewPager);
mTabSegment = v.findViewById(R.id.tabs);
im_icon = v.findViewById(R.id.im_icon);
mTabSegment.setDefaultNormalColor(ContextCompat.getColor(getContext(), R.color.passw_changing));
mTabSegment.setDefaultSelectedColor(ContextCompat.getColor(getContext(), R.color.blue_5));
mTabSegment.setHasIndicator(true);
mTabSegment.setIndicatorPosition(false);
mTabSegment.setIndicatorWidthAdjustContent(true);
}
@Override
public void initData(Bundle savedInstanceState) {
mTabSegment.addTab(new QMUITabSegment.Tab("案件历史"));
mTabSegment.addTab(new QMUITabSegment.Tab("巡检历史"));
ArrayList<Fragment> fragments = new ArrayList<>();
fragments.add(HistoryWorkFragment.newInstance());
fragments.add(HistoryRouteFragment.newInstance());
MainPageAdapter pageAdapter = new MainPageAdapter(getChildFragmentManager(), fragments);
mContentViewPager.setAdapter(pageAdapter);
mTabSegment.setupWithViewPager(mContentViewPager, false);
mTabSegment.notifyDataChanged();
mContentViewPager.setCurrentItem(0);
mContentViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
int n = i+1;
if (n==1){
im_icon.setImageResource(R.mipmap.workicc);
}else {
im_icon.setImageResource(R.mipmap.routrww);
}
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
}
}
| 2,874 | 0.673592 | 0.670775 | 88 | 31.272728 | 25.913197 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 13 |
bf63be9c175a3590b6f0685c288a3156a9e48e97 | 25,615,184,989,869 | 754ce53f10d018154fc161137a33a8cacfb4d902 | /LogSystemOpen/test/receive/ActiveMqConfigReceiver.java | f1272600a47fa2d238a832af34e35a2a6871c7c6 | [] | no_license | 13612177032/AutoLogSystem | https://github.com/13612177032/AutoLogSystem | 8bb9532a20b6e97604536963aa25770efde28847 | 9156e5e59801130698b78647742da1d37278039c | refs/heads/master | 2016-09-01T16:38:28.623000 | 2016-03-18T10:16:27 | 2016-03-18T10:16:27 | 54,189,356 | 8 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package receive;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import com.chale.logsystem.bean.ActiveMQConfigBean;
import com.chale.logsystem.util.PropertiesUtil;
public class ActiveMqConfigReceiver {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
new MqReceiverThread().start();;
}
static class MqReceiverThread extends Thread{
private static final String MQ_URL = PropertiesUtil.getProperties("url");
private static final String MQ_USER = PropertiesUtil.getProperties("user",ActiveMQConnection.DEFAULT_USER);
private static final String MQ_PASSWORD = PropertiesUtil.getProperties("password",ActiveMQConnection.DEFAULT_PASSWORD);
private static final String QUEUENAME=PropertiesUtil.getProperties("queuename");
// ConnectionFactory 锛氳繛鎺ュ伐鍘傦紝JMS 鐢ㄥ畠鍒涘缓杩炴帴 , 鏋勯�燙onnectionFactory瀹炰緥瀵硅薄锛屾澶勯噰鐢ˋctiveMq鐨勫疄鐜癹ar
private ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
MQ_USER,
MQ_PASSWORD,
MQ_URL);
public void run(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
receiveAndExecute();
}
public void receiveAndExecute() {
// Connection 锛欽MS 瀹㈡埛绔埌JMS Provider 鐨勮繛鎺�
Connection connection = null;
// Session锛� 涓�涓彂閫佹垨鎺ユ敹娑堟伅鐨勭嚎绋�
Session session;
// Destination 锛氭秷鎭殑鐩殑鍦�;娑堟伅鍙戦�佺粰璋�.
Destination destination;
// 娑堣垂鑰咃紝娑堟伅鎺ユ敹鑰�
MessageConsumer consumer;
try {
// 鏋勯�犱粠宸ュ巶寰楀埌杩炴帴瀵硅薄
connection = connectionFactory.createConnection();
// 鍚姩
connection.start();
// 鑾峰彇鎿嶄綔杩炴帴
session = connection.createSession(Boolean.FALSE,
Session.AUTO_ACKNOWLEDGE);
// 鑾峰彇session娉ㄦ剰鍙傛暟鍊紉ingbo.xu-queue鏄竴涓湇鍔″櫒鐨剄ueue锛岄』鍦ㄥ湪ActiveMq鐨刢onsole閰嶇疆
destination = session.createQueue(QUEUENAME);
consumer = session.createConsumer(destination);
while (true) {
//璁剧疆鎺ユ敹鑰呮帴鏀舵秷鎭殑鏃堕棿锛屼负浜嗕究浜庢祴璇曪紝杩欓噷璋佸畾涓�100s
Object obj = consumer.receive();
if(obj instanceof ObjectMessage){
ObjectMessage message = (ObjectMessage) obj;
if (null != message) {
try {
ActiveMQConfigBean bean = (ActiveMQConfigBean)message.getObject();
if(bean.getCode()!=null&&!bean.getCode().equals("")){
ActiveMqReceiver receiver = new ActiveMqReceiver();
receiver.process(bean);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != connection)
connection.close();
} catch (Throwable ignore) {
}
}
}
}
}
| UTF-8 | Java | 3,979 | java | ActiveMqConfigReceiver.java | Java | [] | null | [] | package receive;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import com.chale.logsystem.bean.ActiveMQConfigBean;
import com.chale.logsystem.util.PropertiesUtil;
public class ActiveMqConfigReceiver {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
new MqReceiverThread().start();;
}
static class MqReceiverThread extends Thread{
private static final String MQ_URL = PropertiesUtil.getProperties("url");
private static final String MQ_USER = PropertiesUtil.getProperties("user",ActiveMQConnection.DEFAULT_USER);
private static final String MQ_PASSWORD = PropertiesUtil.getProperties("password",ActiveMQConnection.DEFAULT_PASSWORD);
private static final String QUEUENAME=PropertiesUtil.getProperties("queuename");
// ConnectionFactory 锛氳繛鎺ュ伐鍘傦紝JMS 鐢ㄥ畠鍒涘缓杩炴帴 , 鏋勯�燙onnectionFactory瀹炰緥瀵硅薄锛屾澶勯噰鐢ˋctiveMq鐨勫疄鐜癹ar
private ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
MQ_USER,
MQ_PASSWORD,
MQ_URL);
public void run(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
receiveAndExecute();
}
public void receiveAndExecute() {
// Connection 锛欽MS 瀹㈡埛绔埌JMS Provider 鐨勮繛鎺�
Connection connection = null;
// Session锛� 涓�涓彂閫佹垨鎺ユ敹娑堟伅鐨勭嚎绋�
Session session;
// Destination 锛氭秷鎭殑鐩殑鍦�;娑堟伅鍙戦�佺粰璋�.
Destination destination;
// 娑堣垂鑰咃紝娑堟伅鎺ユ敹鑰�
MessageConsumer consumer;
try {
// 鏋勯�犱粠宸ュ巶寰楀埌杩炴帴瀵硅薄
connection = connectionFactory.createConnection();
// 鍚姩
connection.start();
// 鑾峰彇鎿嶄綔杩炴帴
session = connection.createSession(Boolean.FALSE,
Session.AUTO_ACKNOWLEDGE);
// 鑾峰彇session娉ㄦ剰鍙傛暟鍊紉ingbo.xu-queue鏄竴涓湇鍔″櫒鐨剄ueue锛岄』鍦ㄥ湪ActiveMq鐨刢onsole閰嶇疆
destination = session.createQueue(QUEUENAME);
consumer = session.createConsumer(destination);
while (true) {
//璁剧疆鎺ユ敹鑰呮帴鏀舵秷鎭殑鏃堕棿锛屼负浜嗕究浜庢祴璇曪紝杩欓噷璋佸畾涓�100s
Object obj = consumer.receive();
if(obj instanceof ObjectMessage){
ObjectMessage message = (ObjectMessage) obj;
if (null != message) {
try {
ActiveMQConfigBean bean = (ActiveMQConfigBean)message.getObject();
if(bean.getCode()!=null&&!bean.getCode().equals("")){
ActiveMqReceiver receiver = new ActiveMqReceiver();
receiver.process(bean);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != connection)
connection.close();
} catch (Throwable ignore) {
}
}
}
}
}
| 3,979 | 0.616292 | 0.613483 | 125 | 26.48 | 24.810192 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.536 | false | false | 13 |
6484c76fa708b0b65c0d13e22aef344170d447b7 | 4,733,053,994,935 | 635f8b5c1db0c9349b8283b690ad4b818c2159c4 | /src/main/java/com/dogacoder/www/linkedlist/ReverseLinkedListKNodes.java | 9592db75618a8677eda4593b9738a56cafd9766a | [] | no_license | akumariiit/coding-problems-java | https://github.com/akumariiit/coding-problems-java | 406eebca6e38de62e34c9a66761ad17158f8dba1 | 56deb2978a6b5ca16a7ba259462850aa25ec4265 | refs/heads/master | 2020-12-31T23:57:29.359000 | 2020-07-06T18:39:36 | 2020-07-06T18:39:36 | 239,086,717 | 0 | 0 | null | false | 2020-10-13T19:22:04 | 2020-02-08T07:25:11 | 2020-07-06T18:39:45 | 2020-10-13T19:22:03 | 269 | 0 | 0 | 1 | Java | false | false | package com.dogacoder.www.linkedlist;
import org.junit.Test;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
/**
*
*/
public class ReverseLinkedListKNodes {
public LinkedList.Node reverse(LinkedList.Node node, int k) {
LinkedList.Node prev = null;
LinkedList.Node current = node;
LinkedList.Node next = null;
int count = 1;
while (current != null && count <= k) {
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
if (next != null) {
node.next = reverse(next, k);
}
return prev;
}
@Test
public void testReverseKNodes() {
LinkedList llist = new LinkedList();
/* Constructed Linked List is 1->2->3->4->5->6->
7->8->8->9->null */
llist.push(9);
llist.push(8);
llist.push(7);
llist.push(6);
llist.push(5);
llist.push(4);
llist.push(3);
llist.push(2);
llist.push(1);
System.out.println("Given Linked List");
llist.printList();
llist.head = reverse(llist.head, 3);
System.out.println("Reversed list");
llist.printList();
}
}
| UTF-8 | Java | 1,269 | java | ReverseLinkedListKNodes.java | Java | [] | null | [] | package com.dogacoder.www.linkedlist;
import org.junit.Test;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
/**
*
*/
public class ReverseLinkedListKNodes {
public LinkedList.Node reverse(LinkedList.Node node, int k) {
LinkedList.Node prev = null;
LinkedList.Node current = node;
LinkedList.Node next = null;
int count = 1;
while (current != null && count <= k) {
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
if (next != null) {
node.next = reverse(next, k);
}
return prev;
}
@Test
public void testReverseKNodes() {
LinkedList llist = new LinkedList();
/* Constructed Linked List is 1->2->3->4->5->6->
7->8->8->9->null */
llist.push(9);
llist.push(8);
llist.push(7);
llist.push(6);
llist.push(5);
llist.push(4);
llist.push(3);
llist.push(2);
llist.push(1);
System.out.println("Given Linked List");
llist.printList();
llist.head = reverse(llist.head, 3);
System.out.println("Reversed list");
llist.printList();
}
}
| 1,269 | 0.528763 | 0.512214 | 53 | 22.943396 | 16.871786 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.603774 | false | false | 13 |
17ab36149951317012707e16a09a8663b4b1069c | 2,559,800,546,450 | d6cd58a40d97451e7c68264439f396a551b64bd4 | /app/controllers/WorkingDayController.java | 75349d65326f8dbb3dcc8231bc77c40c3f1eca8c | [] | no_license | ror4/ProjetStage | https://github.com/ror4/ProjetStage | 255268e9d6c7a7eb5a3aefea124f1e06ca8caa0e | 74accc3efe35988ad73f3b448d07d5e8e57782bc | refs/heads/master | 2021-01-12T09:45:11.851000 | 2016-12-16T11:13:50 | 2016-12-16T11:13:50 | 76,238,030 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controllers;
import models.Collaborator;
import models.WorkingDay;
import services.CollaboServices;
import services.ICollaboServices;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Formation on 14/12/2016.
*/
public class WorkingDayController {
}
| UTF-8 | Java | 284 | java | WorkingDayController.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Formation on 14/12/2016.\n */\npublic class WorkingDayControl",
"end": 223,
"score": 0.9558656215667725,
"start": 214,
"tag": "USERNAME",
"value": "Formation"
}
] | null | [] | package controllers;
import models.Collaborator;
import models.WorkingDay;
import services.CollaboServices;
import services.ICollaboServices;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Formation on 14/12/2016.
*/
public class WorkingDayController {
}
| 284 | 0.785211 | 0.757042 | 17 | 15.647058 | 14.564022 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 13 |
af83ea62c104facaa72c37f2d5c9b6fddf4f4e3d | 20,409,684,618,400 | 2a767506f8de5d365e2d44be36e5495a0ab95a88 | /davmoslav_aplikacija_2/davmoslav_aplikacija_2-ejb/src/java/org/foi/nwtis/davmoslav/ejb/Portfelj.java | 1a00276023a612bc83a023bc55c6fdf15fab58ca | [] | no_license | davor-moslavac/NWTiS_projekt | https://github.com/davor-moslavac/NWTiS_projekt | 7324b277b6c139fca91b9129b8a47e943aa6a7e9 | e277efaf7b434397e52137abaae452d76b727d81 | refs/heads/master | 2016-09-03T03:51:45.461000 | 2015-02-26T13:18:52 | 2015-02-26T13:18:52 | 31,367,864 | 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 org.foi.nwtis.davmoslav.ejb;
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.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
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 Davor
*/
@Entity
@Table(name = "PORTFELJ")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Portfelj.findAll", query = "SELECT p FROM Portfelj p"),
@NamedQuery(name = "Portfelj.findById", query = "SELECT p FROM Portfelj p WHERE p.id = :id"),
@NamedQuery(name = "Portfelj.findByNaziv", query = "SELECT p FROM Portfelj p WHERE p.naziv = :naziv")})
public class Portfelj implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "NAZIV")
private String naziv;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "portfeljId")
private List<PortfeljKorisnika> portfeljKorisnikaList;
@JoinColumn(name = "KORISNIK_ID", referencedColumnName = "ID")
@ManyToOne(optional = false)
private Korisnik korisnikId;
public Portfelj() {
}
public Portfelj(Integer id) {
this.id = id;
}
public Portfelj(Integer id, String naziv) {
this.id = id;
this.naziv = naziv;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
@XmlTransient
public List<PortfeljKorisnika> getPortfeljKorisnikaList() {
return portfeljKorisnikaList;
}
public void setPortfeljKorisnikaList(List<PortfeljKorisnika> portfeljKorisnikaList) {
this.portfeljKorisnikaList = portfeljKorisnikaList;
}
public Korisnik getKorisnikId() {
return korisnikId;
}
public void setKorisnikId(Korisnik korisnikId) {
this.korisnikId = korisnikId;
}
@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 Portfelj)) {
return false;
}
Portfelj other = (Portfelj) 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 "org.foi.nwtis.davmoslav.ejb.Portfelj[ id=" + id + " ]";
}
}
| UTF-8 | Java | 3,551 | java | Portfelj.java | Java | [
{
"context": "l.bind.annotation.XmlTransient;\n\n/**\n *\n * @author Davor\n */\n@Entity\n@Table(name = \"PORTFELJ\")\n@XmlRootEle",
"end": 947,
"score": 0.9980846643447876,
"start": 942,
"tag": "NAME",
"value": "Davor"
}
] | 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 org.foi.nwtis.davmoslav.ejb;
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.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
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 Davor
*/
@Entity
@Table(name = "PORTFELJ")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Portfelj.findAll", query = "SELECT p FROM Portfelj p"),
@NamedQuery(name = "Portfelj.findById", query = "SELECT p FROM Portfelj p WHERE p.id = :id"),
@NamedQuery(name = "Portfelj.findByNaziv", query = "SELECT p FROM Portfelj p WHERE p.naziv = :naziv")})
public class Portfelj implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "NAZIV")
private String naziv;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "portfeljId")
private List<PortfeljKorisnika> portfeljKorisnikaList;
@JoinColumn(name = "KORISNIK_ID", referencedColumnName = "ID")
@ManyToOne(optional = false)
private Korisnik korisnikId;
public Portfelj() {
}
public Portfelj(Integer id) {
this.id = id;
}
public Portfelj(Integer id, String naziv) {
this.id = id;
this.naziv = naziv;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
@XmlTransient
public List<PortfeljKorisnika> getPortfeljKorisnikaList() {
return portfeljKorisnikaList;
}
public void setPortfeljKorisnikaList(List<PortfeljKorisnika> portfeljKorisnikaList) {
this.portfeljKorisnikaList = portfeljKorisnikaList;
}
public Korisnik getKorisnikId() {
return korisnikId;
}
public void setKorisnikId(Korisnik korisnikId) {
this.korisnikId = korisnikId;
}
@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 Portfelj)) {
return false;
}
Portfelj other = (Portfelj) 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 "org.foi.nwtis.davmoslav.ejb.Portfelj[ id=" + id + " ]";
}
}
| 3,551 | 0.668262 | 0.666291 | 128 | 26.742188 | 23.826929 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.453125 | false | false | 13 |
6f19c6194a8f947ea50473b7191858961b324b39 | 1,692,217,121,565 | 12aa6ac1e7a91223e43206416effe8073ec05c17 | /leetcode_75.java | e1a311437148880ab07a15f4aa4a1a7e78adfbb2 | [] | no_license | georgesha/leetcode_problems | https://github.com/georgesha/leetcode_problems | b01a3c083b9e1cfcd96931480c429777be102a02 | 23cb01c47c62b96dda153da2159de4a73655da73 | refs/heads/master | 2020-03-28T01:53:38.223000 | 2019-04-20T01:53:47 | 2019-04-20T01:53:47 | 147,530,927 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution {
public void sortColors(int[] nums) {
if (nums.length == 0) {
return;
}
int slow = 0, fast = 0;
for (int i = 0; i <= 2; i++) {
while (slow < nums.length && fast < nums.length) {
if (slow > fast) {
fast = slow;
}
if (nums[fast] == i) {
int tmp = nums[slow];
nums[slow] = nums[fast];
nums[fast] = tmp;
slow++;
}
fast++;
}
fast = slow;
}
}
}
| UTF-8 | Java | 493 | java | leetcode_75.java | Java | [] | null | [] | class Solution {
public void sortColors(int[] nums) {
if (nums.length == 0) {
return;
}
int slow = 0, fast = 0;
for (int i = 0; i <= 2; i++) {
while (slow < nums.length && fast < nums.length) {
if (slow > fast) {
fast = slow;
}
if (nums[fast] == i) {
int tmp = nums[slow];
nums[slow] = nums[fast];
nums[fast] = tmp;
slow++;
}
fast++;
}
fast = slow;
}
}
}
| 493 | 0.409736 | 0.399594 | 23 | 20.434782 | 13.2364 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false | 13 |
dc559e206d69415648cb2ef3eefb08514cd13df9 | 2,972,117,419,627 | d01471cd980de05e7a22db7da129dd08c8288fba | /java/finalExam/BookCatalog.java | 495f04995372063f7e5bbe31b503c68193a0d080 | [] | no_license | ZiyuZhao19/CIT590-Course-Material | https://github.com/ZiyuZhao19/CIT590-Course-Material | c3d899af8b26d7f6bd61c6e938711e62db5f9e91 | af5d083509eb6c0fbaeb9800676a238ae2699e3f | refs/heads/master | 2021-01-06T10:24:23.812000 | 2020-03-26T01:20:05 | 2020-03-26T01:20:05 | 241,295,094 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package book;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import book.file.BookFileReader;
/**
* Represents a catalog of books.
* Code: <Y6T5R4>
* @author <zzhao19>
*
*/
public class BookCatalog {
/**
* Internal map for storing books.
*/
private Map<String, Book> bookMap;
/**
* Creates a book catalog and initializes the internal map for storing books.
*/
public BookCatalog() {
this.bookMap = new TreeMap<String, Book>();
}
/**
* Gets internal book map.
* @return book map
*/
public Map<String, Book> getBookMap() {
// TODO Implement method
return bookMap;
}
/**
* Adds the given book to the internal map.
* Uses book title as key and book itself as value. If title is null, doesn't add book.
* @param book to add
*/
public void addBook(Book book) {
// TODO Implement method
if (book.getTitle() != null) {
bookMap.put(book.getTitle(), book);
}
}
/**
* Gets the book associated with the given title.
* Returns null if the book doesn't exist in the catalog.
* @param title of book
* @return book
*/
public Book getBookByTitle(String title) {
// TODO Implement method
return bookMap.get(title);
}
/**
* Gets the book associated with the given author.
* Returns null if the book doesn't exist in the catalog.
* @param author of book
* @return book
*/
public Book getBookByAuthor(String author) {
// TODO Implement method
for (Map.Entry<String, Book> entry : this.bookMap.entrySet()) {
if (entry.getValue().getAuthor().equals(author)) {
return entry.getValue();
}
}
return null;
}
public static void main(String[] args) {
//create instance of book catalog
BookCatalog bookCatalog = new BookCatalog();
//load book files
List<String> warAndPeace = BookFileReader.parseFile("src/war_and_peace.txt");
List<String> siddhartha = BookFileReader.parseFile("src/siddhartha.txt");
//create books with lists above
Book warAndPeaceBook = new Book(warAndPeace);
Book siddharthaBook = new Book(siddhartha);
//add books to catalog
bookCatalog.addBook(warAndPeaceBook);
bookCatalog.addBook(siddharthaBook);
//get titles
System.out.println("\nGET TITLES");
String warAndPeaceBookTitle = warAndPeaceBook.getTitle();
System.out.println(warAndPeaceBookTitle);
String siddharthaBookTitle = siddharthaBook.getTitle();
System.out.println(siddharthaBookTitle);
//get authors
System.out.println("\nGET AUTHORS");
String warAndPeaceBookAuthor = warAndPeaceBook.getAuthor();
System.out.println(warAndPeaceBookAuthor);
String siddharthaBookAuthor = siddharthaBook.getAuthor();
System.out.println(siddharthaBookAuthor);
//get books by title
System.out.println("\nGET BOOKS BY TITLE");
System.out.println(bookCatalog.getBookByTitle("War and Peace"));
System.out.println(bookCatalog.getBookByTitle("Siddhartha"));
//get books by author
System.out.println("\nGET BOOKS BY AUTHOR");
System.out.println(bookCatalog.getBookByAuthor("Leo Tolstoy"));
System.out.println(bookCatalog.getBookByAuthor("Hermann Hesse"));
//get total word count
System.out.println("\nTOTAL WORD COUNTS");
System.out.println(bookCatalog.getBookByTitle("War and Peace").getTotalWordCount());
System.out.println(bookCatalog.getBookByTitle("Siddhartha").getTotalWordCount());
//get unique word count
System.out.println("\nUNIQUE WORD COUNTS");
System.out.println(bookCatalog.getBookByTitle("War and Peace").getUniqueWordCount());
System.out.println(bookCatalog.getBookByTitle("Siddhartha").getUniqueWordCount());
//get word count for specific word
System.out.println("\nWORD COUNT FOR SPECIFIC WORDS");
System.out.println("'love' in War and Peace: "
+ bookCatalog.getBookByTitle("War and Peace").getSpecificWordCount("love"));
System.out.println("'hate' in Siddhartha: "
+ bookCatalog.getBookByTitle("Siddhartha").getSpecificWordCount("hate"));
/*
* EXTRA CREDIT BELOW!
*/
//get first lines
System.out.println("\nFIRST LINES");
for (String line : bookCatalog.getBookByAuthor("Leo Tolstoy").getFirstLines()) {
System.out.println(line);
}
//get first 5 lines
for (String line : bookCatalog.getBookByAuthor("Hermann Hesse").getFirstLines(5)) {
System.out.println(line);
}
}
}
| UTF-8 | Java | 4,319 | java | BookCatalog.java | Java | [
{
"context": "a catalog of books.\n * Code: <Y6T5R4>\n * @author <zzhao19>\n *\n */\npublic class BookCatalog {\n\n\t/**\n\t * Inte",
"end": 195,
"score": 0.9995303153991699,
"start": 188,
"tag": "USERNAME",
"value": "zzhao19"
},
{
"context": "\t\tSystem.out.println(bookCatalog.getBookByAuthor(\"Leo Tolstoy\"));\n\t\tSystem.out.println(bookCatalog.getBookByAut",
"end": 3036,
"score": 0.9998586773872375,
"start": 3025,
"tag": "NAME",
"value": "Leo Tolstoy"
},
{
"context": "\t\tSystem.out.println(bookCatalog.getBookByAuthor(\"Hermann Hesse\"));\n\t\t\n\t\t//get total word count\n\t\tSystem.out.prin",
"end": 3104,
"score": 0.9998751878738403,
"start": 3091,
"tag": "NAME",
"value": "Hermann Hesse"
},
{
"context": "\t\tfor (String line : bookCatalog.getBookByAuthor(\"Leo Tolstoy\").getFirstLines()) {\n\t\t\tSystem.out.println(line);",
"end": 4115,
"score": 0.999736487865448,
"start": 4104,
"tag": "NAME",
"value": "Leo Tolstoy"
},
{
"context": "\t\tfor (String line : bookCatalog.getBookByAuthor(\"Hermann Hesse\").getFirstLines(5)) {\n\t\t\tSystem.out.println(line)",
"end": 4255,
"score": 0.9997531771659851,
"start": 4242,
"tag": "NAME",
"value": "Hermann Hesse"
}
] | null | [] | package book;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import book.file.BookFileReader;
/**
* Represents a catalog of books.
* Code: <Y6T5R4>
* @author <zzhao19>
*
*/
public class BookCatalog {
/**
* Internal map for storing books.
*/
private Map<String, Book> bookMap;
/**
* Creates a book catalog and initializes the internal map for storing books.
*/
public BookCatalog() {
this.bookMap = new TreeMap<String, Book>();
}
/**
* Gets internal book map.
* @return book map
*/
public Map<String, Book> getBookMap() {
// TODO Implement method
return bookMap;
}
/**
* Adds the given book to the internal map.
* Uses book title as key and book itself as value. If title is null, doesn't add book.
* @param book to add
*/
public void addBook(Book book) {
// TODO Implement method
if (book.getTitle() != null) {
bookMap.put(book.getTitle(), book);
}
}
/**
* Gets the book associated with the given title.
* Returns null if the book doesn't exist in the catalog.
* @param title of book
* @return book
*/
public Book getBookByTitle(String title) {
// TODO Implement method
return bookMap.get(title);
}
/**
* Gets the book associated with the given author.
* Returns null if the book doesn't exist in the catalog.
* @param author of book
* @return book
*/
public Book getBookByAuthor(String author) {
// TODO Implement method
for (Map.Entry<String, Book> entry : this.bookMap.entrySet()) {
if (entry.getValue().getAuthor().equals(author)) {
return entry.getValue();
}
}
return null;
}
public static void main(String[] args) {
//create instance of book catalog
BookCatalog bookCatalog = new BookCatalog();
//load book files
List<String> warAndPeace = BookFileReader.parseFile("src/war_and_peace.txt");
List<String> siddhartha = BookFileReader.parseFile("src/siddhartha.txt");
//create books with lists above
Book warAndPeaceBook = new Book(warAndPeace);
Book siddharthaBook = new Book(siddhartha);
//add books to catalog
bookCatalog.addBook(warAndPeaceBook);
bookCatalog.addBook(siddharthaBook);
//get titles
System.out.println("\nGET TITLES");
String warAndPeaceBookTitle = warAndPeaceBook.getTitle();
System.out.println(warAndPeaceBookTitle);
String siddharthaBookTitle = siddharthaBook.getTitle();
System.out.println(siddharthaBookTitle);
//get authors
System.out.println("\nGET AUTHORS");
String warAndPeaceBookAuthor = warAndPeaceBook.getAuthor();
System.out.println(warAndPeaceBookAuthor);
String siddharthaBookAuthor = siddharthaBook.getAuthor();
System.out.println(siddharthaBookAuthor);
//get books by title
System.out.println("\nGET BOOKS BY TITLE");
System.out.println(bookCatalog.getBookByTitle("War and Peace"));
System.out.println(bookCatalog.getBookByTitle("Siddhartha"));
//get books by author
System.out.println("\nGET BOOKS BY AUTHOR");
System.out.println(bookCatalog.getBookByAuthor("<NAME>"));
System.out.println(bookCatalog.getBookByAuthor("<NAME>"));
//get total word count
System.out.println("\nTOTAL WORD COUNTS");
System.out.println(bookCatalog.getBookByTitle("War and Peace").getTotalWordCount());
System.out.println(bookCatalog.getBookByTitle("Siddhartha").getTotalWordCount());
//get unique word count
System.out.println("\nUNIQUE WORD COUNTS");
System.out.println(bookCatalog.getBookByTitle("War and Peace").getUniqueWordCount());
System.out.println(bookCatalog.getBookByTitle("Siddhartha").getUniqueWordCount());
//get word count for specific word
System.out.println("\nWORD COUNT FOR SPECIFIC WORDS");
System.out.println("'love' in War and Peace: "
+ bookCatalog.getBookByTitle("War and Peace").getSpecificWordCount("love"));
System.out.println("'hate' in Siddhartha: "
+ bookCatalog.getBookByTitle("Siddhartha").getSpecificWordCount("hate"));
/*
* EXTRA CREDIT BELOW!
*/
//get first lines
System.out.println("\nFIRST LINES");
for (String line : bookCatalog.getBookByAuthor("<NAME>").getFirstLines()) {
System.out.println(line);
}
//get first 5 lines
for (String line : bookCatalog.getBookByAuthor("<NAME>").getFirstLines(5)) {
System.out.println(line);
}
}
}
| 4,295 | 0.709423 | 0.707803 | 150 | 27.793333 | 24.94268 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.873333 | false | false | 13 |
a17d8a1928cb0e1a860b8b83ef1d47dbd82c22f9 | 5,497,558,188,199 | c53ccc2313e6b75c82d46ada60f082e23176fd40 | /Realtime_QA_Site/src/main/java/neu/edu/realtime/web/AnswerSubmitController.java | a1405807ffbb005240110d423d8cbf66b942a0cf | [] | no_license | ZihanZhang/Forum-Website | https://github.com/ZihanZhang/Forum-Website | a9008ee78f27cf23edd50683dff48bf772453a6a | 5d4902aca32bc708375e18bb01187fa02f2f8f8d | refs/heads/master | 2020-05-25T03:47:17.534000 | 2018-12-20T21:16:00 | 2018-12-20T21:16:00 | 84,908,502 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package neu.edu.realtime.web;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import neu.edu.realtime.domain.Answer;
import neu.edu.realtime.domain.Question;
import neu.edu.realtime.domain.Role;
import neu.edu.realtime.domain.User;
import neu.edu.realtime.service.AnswerService;
import neu.edu.realtime.service.QuestionService;
import neu.edu.realtime.service.RoleService;
import neu.edu.realtime.service.UserService;
@Controller
@RequestMapping("/submission")
public class AnswerSubmitController {
@Autowired
private QuestionService questionService;
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private AnswerService answerService;
@RequestMapping(method=RequestMethod.POST)
public String submitPro(Model model,@RequestParam("questionid")int questionid,@ModelAttribute("answer")Answer answer,BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "home-page";
}
UserDetails userdetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User curuser = userService.query(userdetails.getUsername());
curuser.setExp(curuser.getExp()+30);
userService.userUpdate(curuser);
answer.setQuestion(questionService.query(questionid));
answerService.addAnswer(answer);
model.addAttribute("curuser",curuser);
model.addAttribute("answerList",answerService.listAnswer());
model.addAttribute("questionList", questionService.listQuestion());
return "home-page";
}
@RequestMapping(method=RequestMethod.GET)
public String getHomepage(){
return "test";
}
}
| UTF-8 | Java | 2,180 | java | AnswerSubmitController.java | Java | [] | null | [] | package neu.edu.realtime.web;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import neu.edu.realtime.domain.Answer;
import neu.edu.realtime.domain.Question;
import neu.edu.realtime.domain.Role;
import neu.edu.realtime.domain.User;
import neu.edu.realtime.service.AnswerService;
import neu.edu.realtime.service.QuestionService;
import neu.edu.realtime.service.RoleService;
import neu.edu.realtime.service.UserService;
@Controller
@RequestMapping("/submission")
public class AnswerSubmitController {
@Autowired
private QuestionService questionService;
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private AnswerService answerService;
@RequestMapping(method=RequestMethod.POST)
public String submitPro(Model model,@RequestParam("questionid")int questionid,@ModelAttribute("answer")Answer answer,BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "home-page";
}
UserDetails userdetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User curuser = userService.query(userdetails.getUsername());
curuser.setExp(curuser.getExp()+30);
userService.userUpdate(curuser);
answer.setQuestion(questionService.query(questionid));
answerService.addAnswer(answer);
model.addAttribute("curuser",curuser);
model.addAttribute("answerList",answerService.listAnswer());
model.addAttribute("questionList", questionService.listQuestion());
return "home-page";
}
@RequestMapping(method=RequestMethod.GET)
public String getHomepage(){
return "test";
}
}
| 2,180 | 0.811927 | 0.811009 | 65 | 32.53846 | 28.172041 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.476923 | false | false | 13 |
c6929a53fec0bd5adae708f47458e4c8ec7cf6e6 | 19,774,029,431,240 | ab593d8453f3f44456f52537397d58b392947cb9 | /FragReplace/app/src/main/java/com/example/user/fragreplace/MainActivity.java | bb791508a00e92a89a44385ba32bc6c666df0afc | [] | no_license | shahd2/android-apps | https://github.com/shahd2/android-apps | 930edc14f443cc4d155be24cf32d53c07743cc71 | 8872db66ff5e9cb9c4271630415585a325c983ab | refs/heads/master | 2022-12-18T13:13:04.037000 | 2020-09-22T06:21:16 | 2020-09-22T06:21:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.user.fragreplace;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.newUser);
LoginFragment loginFragment = new LoginFragment();
final RegFragment regFragment = new RegFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragReplce,loginFragment);
fragmentTransaction.commit();
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//fragmentTransaction.replace(R.id.fragReplce,regFragment);
//fragmentTransaction.commit();
FragmentManager fragmentManager1 = getSupportFragmentManager();
FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmentTransaction1.replace(R.id.fragReplce,regFragment);
fragmentTransaction1.commit();
}
});
}
}
| UTF-8 | Java | 1,537 | java | MainActivity.java | Java | [] | null | [] | package com.example.user.fragreplace;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.newUser);
LoginFragment loginFragment = new LoginFragment();
final RegFragment regFragment = new RegFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragReplce,loginFragment);
fragmentTransaction.commit();
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//fragmentTransaction.replace(R.id.fragReplce,regFragment);
//fragmentTransaction.commit();
FragmentManager fragmentManager1 = getSupportFragmentManager();
FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmentTransaction1.replace(R.id.fragReplce,regFragment);
fragmentTransaction1.commit();
}
});
}
}
| 1,537 | 0.707222 | 0.702017 | 35 | 42.914288 | 25.309933 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.771429 | false | false | 13 |
25840c6417bb8b96d9736b71b67e8a67d080e8a2 | 22,754,736,762,821 | 979f79fb5e354d19c7f3c9aea3d0ea6cee01cbaf | /src/ar/edu/unq/po2/tpIntegrador/Icalculador.java | a2b63f3153d20c5d7b765835dcbb6c0c8070481c | [] | no_license | pablov1993/patternDesign | https://github.com/pablov1993/patternDesign | dacd96cc7099deb068cb6c3b47263548a8aa2083 | 560395b407aeb67235dc5bbedc4f7c7555a3050e | refs/heads/main | 2023-02-02T18:10:30.452000 | 2020-12-15T15:54:03 | 2020-12-15T15:54:03 | 321,714,979 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ar.edu.unq.po2.tpIntegrador;
public interface Icalculador {
public Tipo calcularTipo(Muestra muestra);
public boolean hayEmpate(Muestra muestra, Integer score);
}
| UTF-8 | Java | 181 | java | Icalculador.java | Java | [] | null | [] | package ar.edu.unq.po2.tpIntegrador;
public interface Icalculador {
public Tipo calcularTipo(Muestra muestra);
public boolean hayEmpate(Muestra muestra, Integer score);
}
| 181 | 0.773481 | 0.767956 | 11 | 15.454545 | 20.85606 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false | 13 |
cc9d66b79af8ed42cce3ab060d6977253a6fd538 | 695,784,710,532 | c6010ea43d7533eb1a4ee78faa6dab0da0dc9606 | /app/src/main/java/com/cctv/xiqu/android/CityActivity.java | 6ffbbf8e36610469c03e1d45b3d3d0a867deea05 | [] | no_license | 30962088/c11_as | https://github.com/30962088/c11_as | 4a101940adce30a7bdc802db1497dfce59bc872f | c4c152aace91aaf980e85c07291740c46bd66d0c | refs/heads/master | 2021-01-13T00:37:31.549000 | 2016-01-10T08:16:20 | 2016-01-10T08:16:20 | 49,358,888 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cctv.xiqu.android;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.cctv.xiqu.android.fragment.network.GetProvinceCityRequest;
import com.cctv.xiqu.android.fragment.network.BaseClient.RequestHandler;
import com.cctv.xiqu.android.fragment.network.GetProvinceCityRequest.Params;
import com.cctv.xiqu.android.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class CityActivity extends BaseActivity implements BDLocationListener {
private static final long serialVersionUID = 1L;
private String provincecity;
private TextView city;
private View confirmBtn;
public LocationClient mLocationClient = null;
public BDLocationListener myListener;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_mycity);
city = (TextView) findViewById(R.id.city);
findViewById(R.id.back).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
confirmBtn = findViewById(R.id.confirm);
confirmBtn.setEnabled(false);
confirmBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("city", provincecity);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener(this);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mLocationClient.stop();
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
mLocationClient.start();
}
@Override
public void onReceiveLocation(BDLocation location) {
GetProvinceCityRequest request = new GetProvinceCityRequest(this,
new Params(location.getLongitude(), location.getLatitude()));
request.request(new RequestHandler() {
@Override
public void onSuccess(Object object) {
GetProvinceCityRequest.Result result = (GetProvinceCityRequest.Result) object;
provincecity = result.getProvincecity();
confirmBtn.setEnabled(true);
city.setText("您当前所在城市:" + provincecity);
mLocationClient.stop();
}
@Override
public void onComplete() {
// TODO Auto-generated method stub
}
@Override
public void onError(int error, String msg) {
// TODO Auto-generated method stub
}
});
}
} | UTF-8 | Java | 2,684 | java | CityActivity.java | Java | [] | null | [] | package com.cctv.xiqu.android;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.cctv.xiqu.android.fragment.network.GetProvinceCityRequest;
import com.cctv.xiqu.android.fragment.network.BaseClient.RequestHandler;
import com.cctv.xiqu.android.fragment.network.GetProvinceCityRequest.Params;
import com.cctv.xiqu.android.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class CityActivity extends BaseActivity implements BDLocationListener {
private static final long serialVersionUID = 1L;
private String provincecity;
private TextView city;
private View confirmBtn;
public LocationClient mLocationClient = null;
public BDLocationListener myListener;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_mycity);
city = (TextView) findViewById(R.id.city);
findViewById(R.id.back).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
confirmBtn = findViewById(R.id.confirm);
confirmBtn.setEnabled(false);
confirmBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("city", provincecity);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener(this);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mLocationClient.stop();
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
mLocationClient.start();
}
@Override
public void onReceiveLocation(BDLocation location) {
GetProvinceCityRequest request = new GetProvinceCityRequest(this,
new Params(location.getLongitude(), location.getLatitude()));
request.request(new RequestHandler() {
@Override
public void onSuccess(Object object) {
GetProvinceCityRequest.Result result = (GetProvinceCityRequest.Result) object;
provincecity = result.getProvincecity();
confirmBtn.setEnabled(true);
city.setText("您当前所在城市:" + provincecity);
mLocationClient.stop();
}
@Override
public void onComplete() {
// TODO Auto-generated method stub
}
@Override
public void onError(int error, String msg) {
// TODO Auto-generated method stub
}
});
}
} | 2,684 | 0.742879 | 0.741754 | 112 | 22.830357 | 22.078144 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.946429 | false | false | 13 |
dbd2174e43c8f8e787f795e26f5cc25679f6d1db | 5,823,975,662,111 | 37dda06d548abf24a1e5c415e7bdd498c73f6454 | /Week2/src/lab02helloworldDecoupled/HelloWorldDecoupled.java | 0168510b13a0bc2d26a2bb35d67ce76730d46e04 | [] | no_license | vdiasf01-DSP16/exercises | https://github.com/vdiasf01-DSP16/exercises | 1902c8ccf7c6f3ca70963cd561e7310aaa604985 | ee602e11a4590ccf4747454d0c3372209d02a36d | refs/heads/master | 2021-01-10T02:10:33.111000 | 2016-04-11T19:47:06 | 2016-04-11T19:47:06 | 49,325,994 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lab02helloworldDecoupled;
/**
* Main class to print the message.
*
* @author Vasco
*
*/
public class HelloWorldDecoupled {
/**
* Main method.
*
* @param args
*/
public static void main(String[] args) {
// Instantiate the renderer
StandardOutMessageRenderer mr = new StandardOutMessageRenderer();
// Instantiate the message provider
HelloWorldMessageProvider mp = new HelloWorldMessageProvider();
// Pass into the rendered the message provider
mr.setMessageProvider(mp);
// Render the message to STDOUT.
mr.render();
}
}
| UTF-8 | Java | 576 | java | HelloWorldDecoupled.java | Java | [
{
"context": " * Main class to print the message.\n * \n * @author Vasco\n *\n */\npublic class HelloWorldDecoupled {\n\n\t/**\n\t",
"end": 95,
"score": 0.9996447563171387,
"start": 90,
"tag": "NAME",
"value": "Vasco"
}
] | null | [] | package lab02helloworldDecoupled;
/**
* Main class to print the message.
*
* @author Vasco
*
*/
public class HelloWorldDecoupled {
/**
* Main method.
*
* @param args
*/
public static void main(String[] args) {
// Instantiate the renderer
StandardOutMessageRenderer mr = new StandardOutMessageRenderer();
// Instantiate the message provider
HelloWorldMessageProvider mp = new HelloWorldMessageProvider();
// Pass into the rendered the message provider
mr.setMessageProvider(mp);
// Render the message to STDOUT.
mr.render();
}
}
| 576 | 0.696181 | 0.692708 | 29 | 18.862068 | 19.641132 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.241379 | false | false | 13 |
eacc9765208e21568dfab2ec1e144c82269beb9d | 10,617,159,164,804 | 68c8f5fef17e6c24fdd52fee50b4ee552b447c52 | /src/main/java/ua/artcode/todo/service/MainService.java | 8b78ce632c6596b19e0b1f4c2142dcfccd3ea8b3 | [] | no_license | presly808/TodoApp | https://github.com/presly808/TodoApp | 241118f014e60b20e3134368b563e7e631609bc0 | df763cb8848a07e99c2e323aee24b1e40e424ea0 | refs/heads/master | 2021-08-30T06:01:01.021000 | 2017-12-16T09:49:44 | 2017-12-16T09:49:44 | 107,852,251 | 0 | 0 | null | false | 2017-12-16T09:30:12 | 2017-10-22T09:18:42 | 2017-10-22T09:19:11 | 2017-12-16T09:30:11 | 121 | 0 | 0 | 0 | Java | false | null | package ua.artcode.todo.service;
import ua.artcode.todo.model.Todo;
import java.util.List;
/**
* Created by serhii on 22.10.17.
*/
public interface MainService {
Todo create(Todo todo);
void initData();
List<Todo> getAll();
Todo find(int id);
}
| UTF-8 | Java | 272 | java | MainService.java | Java | [
{
"context": "l.Todo;\n\nimport java.util.List;\n\n/**\n * Created by serhii on 22.10.17.\n */\npublic interface MainService {\n\n",
"end": 118,
"score": 0.9986662864685059,
"start": 112,
"tag": "USERNAME",
"value": "serhii"
}
] | null | [] | package ua.artcode.todo.service;
import ua.artcode.todo.model.Todo;
import java.util.List;
/**
* Created by serhii on 22.10.17.
*/
public interface MainService {
Todo create(Todo todo);
void initData();
List<Todo> getAll();
Todo find(int id);
}
| 272 | 0.658088 | 0.636029 | 21 | 11.952381 | 13.55931 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 13 |
3c7868cfe5ee6bc5b7a7a42ff927633e1fd1125b | 33,311,766,353,602 | 9b46ea18b3f282e2df77c6abc6a3c30b56f8c264 | /Leetcode/src/main/java/com/ls/leetcode/Main.java | f7c860dd4736e30640637de2968a23ad353aaa72 | [] | no_license | lsc1993/Leetcode-Java | https://github.com/lsc1993/Leetcode-Java | bc707ca8d7294fbbb1aacdb18a2c95cf904b90d4 | 7bc359f203a31b7615b0960f9030711155d4e06d | refs/heads/master | 2023-04-27T10:04:52.033000 | 2023-04-18T14:15:51 | 2023-04-18T14:15:51 | 150,354,569 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ls.leetcode;
public class Main {
public static void main(String[] args) {
//TwoSum.testTwoSum();
//AddTwoNumbers.testAddTwoNumbers();
//LongestSubstringWithoutRepeatingCharacters.testLengthOfLongestSubstring();
System.out.println(System.getenv("ANDROID_HOME"));
}
}
| UTF-8 | Java | 320 | java | Main.java | Java | [] | null | [] | package com.ls.leetcode;
public class Main {
public static void main(String[] args) {
//TwoSum.testTwoSum();
//AddTwoNumbers.testAddTwoNumbers();
//LongestSubstringWithoutRepeatingCharacters.testLengthOfLongestSubstring();
System.out.println(System.getenv("ANDROID_HOME"));
}
}
| 320 | 0.6875 | 0.6875 | 11 | 28.09091 | 26.067934 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 13 |
688f6e574949fcf1ea24002f820dae3d024210c6 | 19,713,899,900,106 | 7946802c181ae17862ea7df59eddd56bd6399860 | /src/com/ipartek/formacion/appjava/prueba/Prueba1.java | a79119d9b9cc1642733a59086ce91106baee9775 | [] | no_license | ibolano/Appjava | https://github.com/ibolano/Appjava | 6b150d2eab9f54b1958d40d0c42272efd446dd16 | 1f2b2903e18d0ec022fda5fdcd4688a203599ddd | refs/heads/master | 2021-01-21T01:44:54.113000 | 2016-06-24T11:01:39 | 2016-06-24T11:01:39 | 61,877,977 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ipartek.formacion.appjava.prueba;
public class Prueba1 {
}
| UTF-8 | Java | 78 | java | Prueba1.java | Java | [] | null | [] | package com.ipartek.formacion.appjava.prueba;
public class Prueba1 {
}
| 78 | 0.730769 | 0.717949 | 5 | 13.6 | 17.805616 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 13 |
a3821dd655529e19b19957e80e0981b8058c245c | 33,200,097,205,806 | 136ac66d3909803cd0d50407ac0e4dd441c08801 | /src/main/java/com/zju/cst/simplefitserver/service/UserService.java | f15efb0403444767f42f0b49baf34d75d95f6fb0 | [] | no_license | neilHyh/simple-fit-server | https://github.com/neilHyh/simple-fit-server | 07d128ae03a77af3461eb778ad6b7a648f737437 | 89420815dd8dc38df628a3d4ea21cf977c3a3de5 | refs/heads/master | 2020-04-08T18:57:07.768000 | 2018-11-29T10:08:10 | 2018-11-29T10:08:10 | 159,631,873 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zju.cst.simplefitserver.service;
import com.zju.cst.simplefitserver.model.InfoUser;
public interface UserService {
public InfoUser getUserInfoByName(String name);
int insertSelective(InfoUser record);
int updateByPrimaryKeySelective(InfoUser record);
}
| UTF-8 | Java | 283 | java | UserService.java | Java | [] | null | [] | package com.zju.cst.simplefitserver.service;
import com.zju.cst.simplefitserver.model.InfoUser;
public interface UserService {
public InfoUser getUserInfoByName(String name);
int insertSelective(InfoUser record);
int updateByPrimaryKeySelective(InfoUser record);
}
| 283 | 0.791519 | 0.791519 | 13 | 20.76923 | 22.905001 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 13 |
b5d02b67d5f1d79d12ffbd6e01d77512a6e3d350 | 15,925,738,746,382 | d4b5fd4791553fe8c39bdbbf45206c49a2156d7e | /javase1201/src/com/bittech/fun/IUtil.java | 166eb2d5224ba1f8577d2ccde983471c6f7b05ac | [] | no_license | Vicxl/Java | https://github.com/Vicxl/Java | 6d26e7565f4917709a42fb41e2ccb9676368d466 | a221696a0387a80144e104ce45c3c12355f46f13 | refs/heads/master | 2020-04-09T17:55:33.724000 | 2018-12-05T09:40:16 | 2018-12-05T09:40:16 | 160,486,574 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bittech.fun;
/**
* Author: secondriver
* Created: 2018/12/1
*/
@FunctionalInterface
public interface IUtil {
String convert(int value);
public static void main(String[] args) {
//方法引用:类的静态方法引用
IUtil iUtil = String::valueOf;
System.out.println(iUtil.convert(1));
System.out.println(iUtil.convert(2));
}
}
| UTF-8 | Java | 436 | java | IUtil.java | Java | [
{
"context": "package com.bittech.fun;\n\n/**\n * Author: secondriver\n * Created: 2018/12/1\n */\n@FunctionalInterface\npu",
"end": 52,
"score": 0.9994473457336426,
"start": 41,
"tag": "USERNAME",
"value": "secondriver"
}
] | null | [] | package com.bittech.fun;
/**
* Author: secondriver
* Created: 2018/12/1
*/
@FunctionalInterface
public interface IUtil {
String convert(int value);
public static void main(String[] args) {
//方法引用:类的静态方法引用
IUtil iUtil = String::valueOf;
System.out.println(iUtil.convert(1));
System.out.println(iUtil.convert(2));
}
}
| 436 | 0.570732 | 0.548781 | 22 | 17.636364 | 14.809535 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227273 | false | false | 13 |
2ef77758f417aca592ce6a75f115fdbdcb923ac5 | 24,026,047,064,115 | 9d9c48034112db0f1d93b10c1bfda684f6753bb0 | /Hero_Traits/src/main/java/net/sf/anathema/hero/traits/model/state/NullTraitStateMap.java | 4bd1d0231578b52235821143b7445f5a88e018af | [] | no_license | tienelle/anathema_3e | https://github.com/tienelle/anathema_3e | 804690e37492e77dad041dc6996bdc44755b038e | fd1f0a95e40a5e8b8ca93d0dd8b32fd1239a6787 | refs/heads/master | 2020-12-11T06:15:32.858000 | 2016-08-31T11:02:38 | 2016-08-31T11:02:38 | 66,630,488 | 0 | 1 | null | true | 2016-08-26T08:25:03 | 2016-08-26T08:25:03 | 2016-08-10T06:51:28 | 2016-04-10T05:14:23 | 50,230 | 0 | 0 | 0 | null | null | null | package net.sf.anathema.hero.traits.model.state;
import net.sf.anathema.hero.traits.model.Trait;
import net.sf.anathema.hero.traits.model.TraitType;
public class NullTraitStateMap implements TraitStateMap {
@Override
public TraitState getState(Trait trait) {
return new NullTraitState();
}
@Override
public TraitState getState(TraitType trait) {
return new NullTraitState();
}
} | UTF-8 | Java | 401 | java | NullTraitStateMap.java | Java | [] | null | [] | package net.sf.anathema.hero.traits.model.state;
import net.sf.anathema.hero.traits.model.Trait;
import net.sf.anathema.hero.traits.model.TraitType;
public class NullTraitStateMap implements TraitStateMap {
@Override
public TraitState getState(Trait trait) {
return new NullTraitState();
}
@Override
public TraitState getState(TraitType trait) {
return new NullTraitState();
}
} | 401 | 0.765586 | 0.765586 | 16 | 24.125 | 21.53159 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 13 |
32ce29e7e857e669d9ee7393b9ceb3d9bd97b629 | 11,828,339,962,925 | eb5f5353f49ee558e497e5caded1f60f32f536b5 | /java/util/concurrent/locks/ReentrantReadWriteLock.java | 3c1a6ab72d7d61c93e58bfec8e9d7a0adb318cd1 | [] | no_license | mohitrajvardhan17/java1.8.0_151 | https://github.com/mohitrajvardhan17/java1.8.0_151 | 6fc53e15354d88b53bd248c260c954807d612118 | 6eeab0c0fd20be34db653f4778f8828068c50c92 | refs/heads/master | 2020-03-18T09:44:14.769000 | 2018-05-23T14:28:24 | 2018-05-23T14:28:24 | 134,578,186 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package java.util.concurrent.locks;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import sun.misc.Unsafe;
public class ReentrantReadWriteLock
implements ReadWriteLock, Serializable
{
private static final long serialVersionUID = -6992448646407690164L;
private final ReadLock readerLock = new ReadLock(this);
private final WriteLock writerLock = new WriteLock(this);
final Sync sync = paramBoolean ? new FairSync() : new NonfairSync();
private static final Unsafe UNSAFE;
private static final long TID_OFFSET;
public ReentrantReadWriteLock()
{
this(false);
}
public ReentrantReadWriteLock(boolean paramBoolean) {}
public WriteLock writeLock()
{
return writerLock;
}
public ReadLock readLock()
{
return readerLock;
}
public final boolean isFair()
{
return sync instanceof FairSync;
}
protected Thread getOwner()
{
return sync.getOwner();
}
public int getReadLockCount()
{
return sync.getReadLockCount();
}
public boolean isWriteLocked()
{
return sync.isWriteLocked();
}
public boolean isWriteLockedByCurrentThread()
{
return sync.isHeldExclusively();
}
public int getWriteHoldCount()
{
return sync.getWriteHoldCount();
}
public int getReadHoldCount()
{
return sync.getReadHoldCount();
}
protected Collection<Thread> getQueuedWriterThreads()
{
return sync.getExclusiveQueuedThreads();
}
protected Collection<Thread> getQueuedReaderThreads()
{
return sync.getSharedQueuedThreads();
}
public final boolean hasQueuedThreads()
{
return sync.hasQueuedThreads();
}
public final boolean hasQueuedThread(Thread paramThread)
{
return sync.isQueued(paramThread);
}
public final int getQueueLength()
{
return sync.getQueueLength();
}
protected Collection<Thread> getQueuedThreads()
{
return sync.getQueuedThreads();
}
public boolean hasWaiters(Condition paramCondition)
{
if (paramCondition == null) {
throw new NullPointerException();
}
if (!(paramCondition instanceof AbstractQueuedSynchronizer.ConditionObject)) {
throw new IllegalArgumentException("not owner");
}
return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)paramCondition);
}
public int getWaitQueueLength(Condition paramCondition)
{
if (paramCondition == null) {
throw new NullPointerException();
}
if (!(paramCondition instanceof AbstractQueuedSynchronizer.ConditionObject)) {
throw new IllegalArgumentException("not owner");
}
return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)paramCondition);
}
protected Collection<Thread> getWaitingThreads(Condition paramCondition)
{
if (paramCondition == null) {
throw new NullPointerException();
}
if (!(paramCondition instanceof AbstractQueuedSynchronizer.ConditionObject)) {
throw new IllegalArgumentException("not owner");
}
return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)paramCondition);
}
public String toString()
{
int i = sync.getCount();
int j = Sync.exclusiveCount(i);
int k = Sync.sharedCount(i);
return super.toString() + "[Write locks = " + j + ", Read locks = " + k + "]";
}
static final long getThreadId(Thread paramThread)
{
return UNSAFE.getLongVolatile(paramThread, TID_OFFSET);
}
static
{
try
{
UNSAFE = Unsafe.getUnsafe();
Class localClass = Thread.class;
TID_OFFSET = UNSAFE.objectFieldOffset(localClass.getDeclaredField("tid"));
}
catch (Exception localException)
{
throw new Error(localException);
}
}
static final class FairSync
extends ReentrantReadWriteLock.Sync
{
private static final long serialVersionUID = -2274990926593161451L;
FairSync() {}
final boolean writerShouldBlock()
{
return hasQueuedPredecessors();
}
final boolean readerShouldBlock()
{
return hasQueuedPredecessors();
}
}
static final class NonfairSync
extends ReentrantReadWriteLock.Sync
{
private static final long serialVersionUID = -8159625535654395037L;
NonfairSync() {}
final boolean writerShouldBlock()
{
return false;
}
final boolean readerShouldBlock()
{
return apparentlyFirstQueuedIsExclusive();
}
}
public static class ReadLock
implements Lock, Serializable
{
private static final long serialVersionUID = -5992448646407690164L;
private final ReentrantReadWriteLock.Sync sync;
protected ReadLock(ReentrantReadWriteLock paramReentrantReadWriteLock)
{
sync = sync;
}
public void lock()
{
sync.acquireShared(1);
}
public void lockInterruptibly()
throws InterruptedException
{
sync.acquireSharedInterruptibly(1);
}
public boolean tryLock()
{
return sync.tryReadLock();
}
public boolean tryLock(long paramLong, TimeUnit paramTimeUnit)
throws InterruptedException
{
return sync.tryAcquireSharedNanos(1, paramTimeUnit.toNanos(paramLong));
}
public void unlock()
{
sync.releaseShared(1);
}
public Condition newCondition()
{
throw new UnsupportedOperationException();
}
public String toString()
{
int i = sync.getReadLockCount();
return super.toString() + "[Read locks = " + i + "]";
}
}
static abstract class Sync
extends AbstractQueuedSynchronizer
{
private static final long serialVersionUID = 6317671515068378041L;
static final int SHARED_SHIFT = 16;
static final int SHARED_UNIT = 65536;
static final int MAX_COUNT = 65535;
static final int EXCLUSIVE_MASK = 65535;
private transient ThreadLocalHoldCounter readHolds = new ThreadLocalHoldCounter();
private transient HoldCounter cachedHoldCounter;
private transient Thread firstReader = null;
private transient int firstReaderHoldCount;
static int sharedCount(int paramInt)
{
return paramInt >>> 16;
}
static int exclusiveCount(int paramInt)
{
return paramInt & 0xFFFF;
}
Sync()
{
setState(getState());
}
abstract boolean readerShouldBlock();
abstract boolean writerShouldBlock();
protected final boolean tryRelease(int paramInt)
{
if (!isHeldExclusively()) {
throw new IllegalMonitorStateException();
}
int i = getState() - paramInt;
boolean bool = exclusiveCount(i) == 0;
if (bool) {
setExclusiveOwnerThread(null);
}
setState(i);
return bool;
}
protected final boolean tryAcquire(int paramInt)
{
Thread localThread = Thread.currentThread();
int i = getState();
int j = exclusiveCount(i);
if (i != 0)
{
if ((j == 0) || (localThread != getExclusiveOwnerThread())) {
return false;
}
if (j + exclusiveCount(paramInt) > 65535) {
throw new Error("Maximum lock count exceeded");
}
setState(i + paramInt);
return true;
}
if ((writerShouldBlock()) || (!compareAndSetState(i, i + paramInt))) {
return false;
}
setExclusiveOwnerThread(localThread);
return true;
}
protected final boolean tryReleaseShared(int paramInt)
{
Thread localThread = Thread.currentThread();
int j;
if (firstReader == localThread)
{
if (firstReaderHoldCount == 1) {
firstReader = null;
} else {
firstReaderHoldCount -= 1;
}
}
else
{
HoldCounter localHoldCounter = cachedHoldCounter;
if ((localHoldCounter == null) || (tid != ReentrantReadWriteLock.getThreadId(localThread))) {
localHoldCounter = (HoldCounter)readHolds.get();
}
j = count;
if (j <= 1)
{
readHolds.remove();
if (j <= 0) {
throw unmatchedUnlockException();
}
}
count -= 1;
}
for (;;)
{
int i = getState();
j = i - 65536;
if (compareAndSetState(i, j)) {
return j == 0;
}
}
}
private IllegalMonitorStateException unmatchedUnlockException()
{
return new IllegalMonitorStateException("attempt to unlock read lock, not locked by current thread");
}
protected final int tryAcquireShared(int paramInt)
{
Thread localThread = Thread.currentThread();
int i = getState();
if ((exclusiveCount(i) != 0) && (getExclusiveOwnerThread() != localThread)) {
return -1;
}
int j = sharedCount(i);
if ((!readerShouldBlock()) && (j < 65535) && (compareAndSetState(i, i + 65536)))
{
if (j == 0)
{
firstReader = localThread;
firstReaderHoldCount = 1;
}
else if (firstReader == localThread)
{
firstReaderHoldCount += 1;
}
else
{
HoldCounter localHoldCounter = cachedHoldCounter;
if ((localHoldCounter == null) || (tid != ReentrantReadWriteLock.getThreadId(localThread))) {
cachedHoldCounter = (localHoldCounter = (HoldCounter)readHolds.get());
} else if (count == 0) {
readHolds.set(localHoldCounter);
}
count += 1;
}
return 1;
}
return fullTryAcquireShared(localThread);
}
final int fullTryAcquireShared(Thread paramThread)
{
HoldCounter localHoldCounter = null;
for (;;)
{
int i = getState();
if (exclusiveCount(i) != 0)
{
if (getExclusiveOwnerThread() != paramThread) {
return -1;
}
}
else if ((readerShouldBlock()) && (firstReader != paramThread))
{
if (localHoldCounter == null)
{
localHoldCounter = cachedHoldCounter;
if ((localHoldCounter == null) || (tid != ReentrantReadWriteLock.getThreadId(paramThread)))
{
localHoldCounter = (HoldCounter)readHolds.get();
if (count == 0) {
readHolds.remove();
}
}
}
if (count == 0) {
return -1;
}
}
if (sharedCount(i) == 65535) {
throw new Error("Maximum lock count exceeded");
}
if (compareAndSetState(i, i + 65536))
{
if (sharedCount(i) == 0)
{
firstReader = paramThread;
firstReaderHoldCount = 1;
}
else if (firstReader == paramThread)
{
firstReaderHoldCount += 1;
}
else
{
if (localHoldCounter == null) {
localHoldCounter = cachedHoldCounter;
}
if ((localHoldCounter == null) || (tid != ReentrantReadWriteLock.getThreadId(paramThread))) {
localHoldCounter = (HoldCounter)readHolds.get();
} else if (count == 0) {
readHolds.set(localHoldCounter);
}
count += 1;
cachedHoldCounter = localHoldCounter;
}
return 1;
}
}
}
final boolean tryWriteLock()
{
Thread localThread = Thread.currentThread();
int i = getState();
if (i != 0)
{
int j = exclusiveCount(i);
if ((j == 0) || (localThread != getExclusiveOwnerThread())) {
return false;
}
if (j == 65535) {
throw new Error("Maximum lock count exceeded");
}
}
if (!compareAndSetState(i, i + 1)) {
return false;
}
setExclusiveOwnerThread(localThread);
return true;
}
final boolean tryReadLock()
{
Thread localThread = Thread.currentThread();
for (;;)
{
int i = getState();
if ((exclusiveCount(i) != 0) && (getExclusiveOwnerThread() != localThread)) {
return false;
}
int j = sharedCount(i);
if (j == 65535) {
throw new Error("Maximum lock count exceeded");
}
if (compareAndSetState(i, i + 65536))
{
if (j == 0)
{
firstReader = localThread;
firstReaderHoldCount = 1;
}
else if (firstReader == localThread)
{
firstReaderHoldCount += 1;
}
else
{
HoldCounter localHoldCounter = cachedHoldCounter;
if ((localHoldCounter == null) || (tid != ReentrantReadWriteLock.getThreadId(localThread))) {
cachedHoldCounter = (localHoldCounter = (HoldCounter)readHolds.get());
} else if (count == 0) {
readHolds.set(localHoldCounter);
}
count += 1;
}
return true;
}
}
}
protected final boolean isHeldExclusively()
{
return getExclusiveOwnerThread() == Thread.currentThread();
}
final AbstractQueuedSynchronizer.ConditionObject newCondition()
{
return new AbstractQueuedSynchronizer.ConditionObject(this);
}
final Thread getOwner()
{
return exclusiveCount(getState()) == 0 ? null : getExclusiveOwnerThread();
}
final int getReadLockCount()
{
return sharedCount(getState());
}
final boolean isWriteLocked()
{
return exclusiveCount(getState()) != 0;
}
final int getWriteHoldCount()
{
return isHeldExclusively() ? exclusiveCount(getState()) : 0;
}
final int getReadHoldCount()
{
if (getReadLockCount() == 0) {
return 0;
}
Thread localThread = Thread.currentThread();
if (firstReader == localThread) {
return firstReaderHoldCount;
}
HoldCounter localHoldCounter = cachedHoldCounter;
if ((localHoldCounter != null) && (tid == ReentrantReadWriteLock.getThreadId(localThread))) {
return count;
}
int i = readHolds.get()).count;
if (i == 0) {
readHolds.remove();
}
return i;
}
private void readObject(ObjectInputStream paramObjectInputStream)
throws IOException, ClassNotFoundException
{
paramObjectInputStream.defaultReadObject();
readHolds = new ThreadLocalHoldCounter();
setState(0);
}
final int getCount()
{
return getState();
}
static final class HoldCounter
{
int count = 0;
final long tid = ReentrantReadWriteLock.getThreadId(Thread.currentThread());
HoldCounter() {}
}
static final class ThreadLocalHoldCounter
extends ThreadLocal<ReentrantReadWriteLock.Sync.HoldCounter>
{
ThreadLocalHoldCounter() {}
public ReentrantReadWriteLock.Sync.HoldCounter initialValue()
{
return new ReentrantReadWriteLock.Sync.HoldCounter();
}
}
}
public static class WriteLock
implements Lock, Serializable
{
private static final long serialVersionUID = -4992448646407690164L;
private final ReentrantReadWriteLock.Sync sync;
protected WriteLock(ReentrantReadWriteLock paramReentrantReadWriteLock)
{
sync = sync;
}
public void lock()
{
sync.acquire(1);
}
public void lockInterruptibly()
throws InterruptedException
{
sync.acquireInterruptibly(1);
}
public boolean tryLock()
{
return sync.tryWriteLock();
}
public boolean tryLock(long paramLong, TimeUnit paramTimeUnit)
throws InterruptedException
{
return sync.tryAcquireNanos(1, paramTimeUnit.toNanos(paramLong));
}
public void unlock()
{
sync.release(1);
}
public Condition newCondition()
{
return sync.newCondition();
}
public String toString()
{
Thread localThread = sync.getOwner();
return super.toString() + (localThread == null ? "[Unlocked]" : new StringBuilder().append("[Locked by thread ").append(localThread.getName()).append("]").toString());
}
public boolean isHeldByCurrentThread()
{
return sync.isHeldExclusively();
}
public int getHoldCount()
{
return sync.getWriteHoldCount();
}
}
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\java\util\concurrent\locks\ReentrantReadWriteLock.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 16,882 | java | ReentrantReadWriteLock.java | Java | [] | null | [] | package java.util.concurrent.locks;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import sun.misc.Unsafe;
public class ReentrantReadWriteLock
implements ReadWriteLock, Serializable
{
private static final long serialVersionUID = -6992448646407690164L;
private final ReadLock readerLock = new ReadLock(this);
private final WriteLock writerLock = new WriteLock(this);
final Sync sync = paramBoolean ? new FairSync() : new NonfairSync();
private static final Unsafe UNSAFE;
private static final long TID_OFFSET;
public ReentrantReadWriteLock()
{
this(false);
}
public ReentrantReadWriteLock(boolean paramBoolean) {}
public WriteLock writeLock()
{
return writerLock;
}
public ReadLock readLock()
{
return readerLock;
}
public final boolean isFair()
{
return sync instanceof FairSync;
}
protected Thread getOwner()
{
return sync.getOwner();
}
public int getReadLockCount()
{
return sync.getReadLockCount();
}
public boolean isWriteLocked()
{
return sync.isWriteLocked();
}
public boolean isWriteLockedByCurrentThread()
{
return sync.isHeldExclusively();
}
public int getWriteHoldCount()
{
return sync.getWriteHoldCount();
}
public int getReadHoldCount()
{
return sync.getReadHoldCount();
}
protected Collection<Thread> getQueuedWriterThreads()
{
return sync.getExclusiveQueuedThreads();
}
protected Collection<Thread> getQueuedReaderThreads()
{
return sync.getSharedQueuedThreads();
}
public final boolean hasQueuedThreads()
{
return sync.hasQueuedThreads();
}
public final boolean hasQueuedThread(Thread paramThread)
{
return sync.isQueued(paramThread);
}
public final int getQueueLength()
{
return sync.getQueueLength();
}
protected Collection<Thread> getQueuedThreads()
{
return sync.getQueuedThreads();
}
public boolean hasWaiters(Condition paramCondition)
{
if (paramCondition == null) {
throw new NullPointerException();
}
if (!(paramCondition instanceof AbstractQueuedSynchronizer.ConditionObject)) {
throw new IllegalArgumentException("not owner");
}
return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)paramCondition);
}
public int getWaitQueueLength(Condition paramCondition)
{
if (paramCondition == null) {
throw new NullPointerException();
}
if (!(paramCondition instanceof AbstractQueuedSynchronizer.ConditionObject)) {
throw new IllegalArgumentException("not owner");
}
return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)paramCondition);
}
protected Collection<Thread> getWaitingThreads(Condition paramCondition)
{
if (paramCondition == null) {
throw new NullPointerException();
}
if (!(paramCondition instanceof AbstractQueuedSynchronizer.ConditionObject)) {
throw new IllegalArgumentException("not owner");
}
return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)paramCondition);
}
public String toString()
{
int i = sync.getCount();
int j = Sync.exclusiveCount(i);
int k = Sync.sharedCount(i);
return super.toString() + "[Write locks = " + j + ", Read locks = " + k + "]";
}
static final long getThreadId(Thread paramThread)
{
return UNSAFE.getLongVolatile(paramThread, TID_OFFSET);
}
static
{
try
{
UNSAFE = Unsafe.getUnsafe();
Class localClass = Thread.class;
TID_OFFSET = UNSAFE.objectFieldOffset(localClass.getDeclaredField("tid"));
}
catch (Exception localException)
{
throw new Error(localException);
}
}
static final class FairSync
extends ReentrantReadWriteLock.Sync
{
private static final long serialVersionUID = -2274990926593161451L;
FairSync() {}
final boolean writerShouldBlock()
{
return hasQueuedPredecessors();
}
final boolean readerShouldBlock()
{
return hasQueuedPredecessors();
}
}
static final class NonfairSync
extends ReentrantReadWriteLock.Sync
{
private static final long serialVersionUID = -8159625535654395037L;
NonfairSync() {}
final boolean writerShouldBlock()
{
return false;
}
final boolean readerShouldBlock()
{
return apparentlyFirstQueuedIsExclusive();
}
}
public static class ReadLock
implements Lock, Serializable
{
private static final long serialVersionUID = -5992448646407690164L;
private final ReentrantReadWriteLock.Sync sync;
protected ReadLock(ReentrantReadWriteLock paramReentrantReadWriteLock)
{
sync = sync;
}
public void lock()
{
sync.acquireShared(1);
}
public void lockInterruptibly()
throws InterruptedException
{
sync.acquireSharedInterruptibly(1);
}
public boolean tryLock()
{
return sync.tryReadLock();
}
public boolean tryLock(long paramLong, TimeUnit paramTimeUnit)
throws InterruptedException
{
return sync.tryAcquireSharedNanos(1, paramTimeUnit.toNanos(paramLong));
}
public void unlock()
{
sync.releaseShared(1);
}
public Condition newCondition()
{
throw new UnsupportedOperationException();
}
public String toString()
{
int i = sync.getReadLockCount();
return super.toString() + "[Read locks = " + i + "]";
}
}
static abstract class Sync
extends AbstractQueuedSynchronizer
{
private static final long serialVersionUID = 6317671515068378041L;
static final int SHARED_SHIFT = 16;
static final int SHARED_UNIT = 65536;
static final int MAX_COUNT = 65535;
static final int EXCLUSIVE_MASK = 65535;
private transient ThreadLocalHoldCounter readHolds = new ThreadLocalHoldCounter();
private transient HoldCounter cachedHoldCounter;
private transient Thread firstReader = null;
private transient int firstReaderHoldCount;
static int sharedCount(int paramInt)
{
return paramInt >>> 16;
}
static int exclusiveCount(int paramInt)
{
return paramInt & 0xFFFF;
}
Sync()
{
setState(getState());
}
abstract boolean readerShouldBlock();
abstract boolean writerShouldBlock();
protected final boolean tryRelease(int paramInt)
{
if (!isHeldExclusively()) {
throw new IllegalMonitorStateException();
}
int i = getState() - paramInt;
boolean bool = exclusiveCount(i) == 0;
if (bool) {
setExclusiveOwnerThread(null);
}
setState(i);
return bool;
}
protected final boolean tryAcquire(int paramInt)
{
Thread localThread = Thread.currentThread();
int i = getState();
int j = exclusiveCount(i);
if (i != 0)
{
if ((j == 0) || (localThread != getExclusiveOwnerThread())) {
return false;
}
if (j + exclusiveCount(paramInt) > 65535) {
throw new Error("Maximum lock count exceeded");
}
setState(i + paramInt);
return true;
}
if ((writerShouldBlock()) || (!compareAndSetState(i, i + paramInt))) {
return false;
}
setExclusiveOwnerThread(localThread);
return true;
}
protected final boolean tryReleaseShared(int paramInt)
{
Thread localThread = Thread.currentThread();
int j;
if (firstReader == localThread)
{
if (firstReaderHoldCount == 1) {
firstReader = null;
} else {
firstReaderHoldCount -= 1;
}
}
else
{
HoldCounter localHoldCounter = cachedHoldCounter;
if ((localHoldCounter == null) || (tid != ReentrantReadWriteLock.getThreadId(localThread))) {
localHoldCounter = (HoldCounter)readHolds.get();
}
j = count;
if (j <= 1)
{
readHolds.remove();
if (j <= 0) {
throw unmatchedUnlockException();
}
}
count -= 1;
}
for (;;)
{
int i = getState();
j = i - 65536;
if (compareAndSetState(i, j)) {
return j == 0;
}
}
}
private IllegalMonitorStateException unmatchedUnlockException()
{
return new IllegalMonitorStateException("attempt to unlock read lock, not locked by current thread");
}
protected final int tryAcquireShared(int paramInt)
{
Thread localThread = Thread.currentThread();
int i = getState();
if ((exclusiveCount(i) != 0) && (getExclusiveOwnerThread() != localThread)) {
return -1;
}
int j = sharedCount(i);
if ((!readerShouldBlock()) && (j < 65535) && (compareAndSetState(i, i + 65536)))
{
if (j == 0)
{
firstReader = localThread;
firstReaderHoldCount = 1;
}
else if (firstReader == localThread)
{
firstReaderHoldCount += 1;
}
else
{
HoldCounter localHoldCounter = cachedHoldCounter;
if ((localHoldCounter == null) || (tid != ReentrantReadWriteLock.getThreadId(localThread))) {
cachedHoldCounter = (localHoldCounter = (HoldCounter)readHolds.get());
} else if (count == 0) {
readHolds.set(localHoldCounter);
}
count += 1;
}
return 1;
}
return fullTryAcquireShared(localThread);
}
final int fullTryAcquireShared(Thread paramThread)
{
HoldCounter localHoldCounter = null;
for (;;)
{
int i = getState();
if (exclusiveCount(i) != 0)
{
if (getExclusiveOwnerThread() != paramThread) {
return -1;
}
}
else if ((readerShouldBlock()) && (firstReader != paramThread))
{
if (localHoldCounter == null)
{
localHoldCounter = cachedHoldCounter;
if ((localHoldCounter == null) || (tid != ReentrantReadWriteLock.getThreadId(paramThread)))
{
localHoldCounter = (HoldCounter)readHolds.get();
if (count == 0) {
readHolds.remove();
}
}
}
if (count == 0) {
return -1;
}
}
if (sharedCount(i) == 65535) {
throw new Error("Maximum lock count exceeded");
}
if (compareAndSetState(i, i + 65536))
{
if (sharedCount(i) == 0)
{
firstReader = paramThread;
firstReaderHoldCount = 1;
}
else if (firstReader == paramThread)
{
firstReaderHoldCount += 1;
}
else
{
if (localHoldCounter == null) {
localHoldCounter = cachedHoldCounter;
}
if ((localHoldCounter == null) || (tid != ReentrantReadWriteLock.getThreadId(paramThread))) {
localHoldCounter = (HoldCounter)readHolds.get();
} else if (count == 0) {
readHolds.set(localHoldCounter);
}
count += 1;
cachedHoldCounter = localHoldCounter;
}
return 1;
}
}
}
final boolean tryWriteLock()
{
Thread localThread = Thread.currentThread();
int i = getState();
if (i != 0)
{
int j = exclusiveCount(i);
if ((j == 0) || (localThread != getExclusiveOwnerThread())) {
return false;
}
if (j == 65535) {
throw new Error("Maximum lock count exceeded");
}
}
if (!compareAndSetState(i, i + 1)) {
return false;
}
setExclusiveOwnerThread(localThread);
return true;
}
final boolean tryReadLock()
{
Thread localThread = Thread.currentThread();
for (;;)
{
int i = getState();
if ((exclusiveCount(i) != 0) && (getExclusiveOwnerThread() != localThread)) {
return false;
}
int j = sharedCount(i);
if (j == 65535) {
throw new Error("Maximum lock count exceeded");
}
if (compareAndSetState(i, i + 65536))
{
if (j == 0)
{
firstReader = localThread;
firstReaderHoldCount = 1;
}
else if (firstReader == localThread)
{
firstReaderHoldCount += 1;
}
else
{
HoldCounter localHoldCounter = cachedHoldCounter;
if ((localHoldCounter == null) || (tid != ReentrantReadWriteLock.getThreadId(localThread))) {
cachedHoldCounter = (localHoldCounter = (HoldCounter)readHolds.get());
} else if (count == 0) {
readHolds.set(localHoldCounter);
}
count += 1;
}
return true;
}
}
}
protected final boolean isHeldExclusively()
{
return getExclusiveOwnerThread() == Thread.currentThread();
}
final AbstractQueuedSynchronizer.ConditionObject newCondition()
{
return new AbstractQueuedSynchronizer.ConditionObject(this);
}
final Thread getOwner()
{
return exclusiveCount(getState()) == 0 ? null : getExclusiveOwnerThread();
}
final int getReadLockCount()
{
return sharedCount(getState());
}
final boolean isWriteLocked()
{
return exclusiveCount(getState()) != 0;
}
final int getWriteHoldCount()
{
return isHeldExclusively() ? exclusiveCount(getState()) : 0;
}
final int getReadHoldCount()
{
if (getReadLockCount() == 0) {
return 0;
}
Thread localThread = Thread.currentThread();
if (firstReader == localThread) {
return firstReaderHoldCount;
}
HoldCounter localHoldCounter = cachedHoldCounter;
if ((localHoldCounter != null) && (tid == ReentrantReadWriteLock.getThreadId(localThread))) {
return count;
}
int i = readHolds.get()).count;
if (i == 0) {
readHolds.remove();
}
return i;
}
private void readObject(ObjectInputStream paramObjectInputStream)
throws IOException, ClassNotFoundException
{
paramObjectInputStream.defaultReadObject();
readHolds = new ThreadLocalHoldCounter();
setState(0);
}
final int getCount()
{
return getState();
}
static final class HoldCounter
{
int count = 0;
final long tid = ReentrantReadWriteLock.getThreadId(Thread.currentThread());
HoldCounter() {}
}
static final class ThreadLocalHoldCounter
extends ThreadLocal<ReentrantReadWriteLock.Sync.HoldCounter>
{
ThreadLocalHoldCounter() {}
public ReentrantReadWriteLock.Sync.HoldCounter initialValue()
{
return new ReentrantReadWriteLock.Sync.HoldCounter();
}
}
}
public static class WriteLock
implements Lock, Serializable
{
private static final long serialVersionUID = -4992448646407690164L;
private final ReentrantReadWriteLock.Sync sync;
protected WriteLock(ReentrantReadWriteLock paramReentrantReadWriteLock)
{
sync = sync;
}
public void lock()
{
sync.acquire(1);
}
public void lockInterruptibly()
throws InterruptedException
{
sync.acquireInterruptibly(1);
}
public boolean tryLock()
{
return sync.tryWriteLock();
}
public boolean tryLock(long paramLong, TimeUnit paramTimeUnit)
throws InterruptedException
{
return sync.tryAcquireNanos(1, paramTimeUnit.toNanos(paramLong));
}
public void unlock()
{
sync.release(1);
}
public Condition newCondition()
{
return sync.newCondition();
}
public String toString()
{
Thread localThread = sync.getOwner();
return super.toString() + (localThread == null ? "[Unlocked]" : new StringBuilder().append("[Locked by thread ").append(localThread.getName()).append("]").toString());
}
public boolean isHeldByCurrentThread()
{
return sync.isHeldExclusively();
}
public int getHoldCount()
{
return sync.getWriteHoldCount();
}
}
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\java\util\concurrent\locks\ReentrantReadWriteLock.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/ | 16,882 | 0.600462 | 0.585831 | 663 | 24.464556 | 24.082466 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.349925 | false | false | 13 |
70d69c2a94096b0c05aec03f8892bb1b360f43c1 | 7,241,314,886,875 | 483d554a63f97df14c45f18996ae448a0e5f8ab7 | /src/main/java/com/almasb/compression/CompressionMain.java | 8f816b4a5e8ebce4bb2f0e713db711abbeb71dc0 | [
"MIT"
] | permissive | AlmasB/FXTutorials | https://github.com/AlmasB/FXTutorials | 5ff5d212d4f89ceb874c07fa302896cd6e4eff70 | e17583ceee30392878ffc41abe09d861f915dae0 | refs/heads/master | 2023-08-20T11:49:11.060000 | 2023-01-08T16:30:18 | 2023-01-08T16:30:18 | 30,721,087 | 497 | 480 | null | false | 2017-04-04T16:13:59 | 2015-02-12T20:04:28 | 2017-03-05T16:40:07 | 2017-04-04T16:13:59 | 21,298 | 51 | 66 | 0 | Java | null | null | package com.almasb.compression;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
/**
* @author Almas Baimagambetov (almaslvl@gmail.com)
*/
public class CompressionMain extends Application {
@Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(createContent()));
stage.show();
}
private Parent createContent() {
StackPane root = new StackPane();
root.setPrefSize(800, 600);
Button btn = new Button("Press");
btn.setOnAction(e -> {
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
File file = fileChooser.showOpenDialog(null);
if (file != null) {
try {
Compressor compressor = new SimpleCompressor();
byte[] original = Files.readAllBytes(file.toPath());
byte[] compressed = compressor.compress(original);
System.out.println("Original size: " + original.length);
System.out.println("Compressed size: " + compressed.length);
byte[] decompressed = compressor.decompress(compressed);
System.out.println(Arrays.equals(original, decompressed));
} catch (IOException e2) {
e2.printStackTrace();
}
}
});
root.getChildren().add(btn);
return root;
}
public static void main(String[] args) throws Exception {
launch(args);
}
}
| UTF-8 | Java | 1,921 | java | CompressionMain.java | Java | [
{
"context": "le.Paths;\nimport java.util.Arrays;\n\n/**\n * @author Almas Baimagambetov (almaslvl@gmail.com)\n */\npublic class Compression",
"end": 427,
"score": 0.9998936653137207,
"start": 408,
"tag": "NAME",
"value": "Almas Baimagambetov"
},
{
"context": "util.Arrays;\n\n/**\n * @author Almas Baimagambetov (almaslvl@gmail.com)\n */\npublic class CompressionMain extends Applica",
"end": 447,
"score": 0.9999300241470337,
"start": 429,
"tag": "EMAIL",
"value": "almaslvl@gmail.com"
}
] | null | [] | package com.almasb.compression;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
/**
* @author <NAME> (<EMAIL>)
*/
public class CompressionMain extends Application {
@Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(createContent()));
stage.show();
}
private Parent createContent() {
StackPane root = new StackPane();
root.setPrefSize(800, 600);
Button btn = new Button("Press");
btn.setOnAction(e -> {
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
File file = fileChooser.showOpenDialog(null);
if (file != null) {
try {
Compressor compressor = new SimpleCompressor();
byte[] original = Files.readAllBytes(file.toPath());
byte[] compressed = compressor.compress(original);
System.out.println("Original size: " + original.length);
System.out.println("Compressed size: " + compressed.length);
byte[] decompressed = compressor.decompress(compressed);
System.out.println(Arrays.equals(original, decompressed));
} catch (IOException e2) {
e2.printStackTrace();
}
}
});
root.getChildren().add(btn);
return root;
}
public static void main(String[] args) throws Exception {
launch(args);
}
}
| 1,897 | 0.61114 | 0.606976 | 68 | 27.25 | 24.983746 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.514706 | false | false | 13 |
02c854f040bd5e5c8c4095b73dca049fc4a1e06f | 15,272,903,732,979 | f6d271f0c93bf5a1f93553ed665d1415f254b330 | /app/src/main/java/com/onelio/connectu/Helpers/AnimTransHelper.java | fdd2531c2e1f784ff5327b1cdd99c8aac447498e | [
"Apache-2.0"
] | permissive | ecomaikgolf/ConnectU | https://github.com/ecomaikgolf/ConnectU | 0210a7a393d60f8d8b566a6efa692183185ca71d | 0cad52ca611a23060781870742696069168173d8 | refs/heads/master | 2020-09-17T00:34:18.019000 | 2019-11-25T11:39:09 | 2019-11-25T11:39:09 | 223,933,830 | 1 | 0 | Apache-2.0 | true | 2019-11-25T11:35:24 | 2019-11-25T11:35:23 | 2019-11-18T19:21:30 | 2018-09-21T09:27:17 | 4,746 | 0 | 0 | 0 | null | false | false | package com.onelio.connectu.Helpers;
import android.app.ActivityOptions;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import com.onelio.connectu.R;
public class AnimTransHelper {
public static Bundle circleSlideUp(Context context, View v) {
Bundle optsBundle;
ActivityOptions opts = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int left = 0, top = 0;
int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
opts = ActivityOptions.makeClipRevealAnimation(v, left, top, width, height);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Below L, we use a scale up animation
opts =
ActivityOptions.makeScaleUpAnimation(
v, 0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
// On L devices, we use the device default slide-up transition.
// On L MR1 devices, we use a custom version of the slide-up transition which
// doesn't have the delay present in the device default.
opts = ActivityOptions.makeCustomAnimation(context, R.anim.task_open_enter, R.anim.no_anim);
}
optsBundle = opts != null ? opts.toBundle() : null;
return optsBundle;
}
}
| UTF-8 | Java | 1,343 | java | AnimTransHelper.java | Java | [] | null | [] | package com.onelio.connectu.Helpers;
import android.app.ActivityOptions;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import com.onelio.connectu.R;
public class AnimTransHelper {
public static Bundle circleSlideUp(Context context, View v) {
Bundle optsBundle;
ActivityOptions opts = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int left = 0, top = 0;
int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
opts = ActivityOptions.makeClipRevealAnimation(v, left, top, width, height);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Below L, we use a scale up animation
opts =
ActivityOptions.makeScaleUpAnimation(
v, 0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
// On L devices, we use the device default slide-up transition.
// On L MR1 devices, we use a custom version of the slide-up transition which
// doesn't have the delay present in the device default.
opts = ActivityOptions.makeCustomAnimation(context, R.anim.task_open_enter, R.anim.no_anim);
}
optsBundle = opts != null ? opts.toBundle() : null;
return optsBundle;
}
}
| 1,343 | 0.69248 | 0.688012 | 33 | 39.696968 | 27.608173 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.969697 | false | false | 13 |
590042130a7367ab9202942014a0b9efdc34de3b | 19,834,159,003,036 | 749a000094019cdeee9c33656de396b1217dbab9 | /src/main/java/com/wutsi/ferari/domain/ProductType.java | 6b8513f7431f049d2f2e0495bacd5156304a28eb | [
"MIT"
] | permissive | wutsi/wutsi-shopping-service | https://github.com/wutsi/wutsi-shopping-service | 7725f1e95bdba5a0fca3ef915daaa1c7d587ffeb | 8a77c033dc5d0a2f1aaa06f938ccf0dd6db02fc9 | refs/heads/master | 2018-08-29T19:18:56.305000 | 2018-06-20T23:54:12 | 2018-06-20T23:54:12 | 134,849,710 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wutsi.ferari.domain;
import com.wutsi.commons.domain.ActiveAware;
import com.wutsi.commons.domain.Persistent;
import com.wutsi.commons.enums.TransportationMode;
import com.wutsi.profile.domain.Merchant;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Getter
@Setter
@Entity
@ToString
@Table(name="T_PRODUCT_TYPE")
public class ProductType extends Persistent implements ActiveAware {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String description;
@Enumerated(EnumType.STRING)
@Column(name="transportation_mode")
private TransportationMode transportationMode;
@ManyToOne
@JoinColumn(name="merchant_fk")
private Merchant merchant;
private boolean active;
}
| UTF-8 | Java | 1,154 | java | ProductType.java | Java | [] | null | [] | package com.wutsi.ferari.domain;
import com.wutsi.commons.domain.ActiveAware;
import com.wutsi.commons.domain.Persistent;
import com.wutsi.commons.enums.TransportationMode;
import com.wutsi.profile.domain.Merchant;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Getter
@Setter
@Entity
@ToString
@Table(name="T_PRODUCT_TYPE")
public class ProductType extends Persistent implements ActiveAware {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String description;
@Enumerated(EnumType.STRING)
@Column(name="transportation_mode")
private TransportationMode transportationMode;
@ManyToOne
@JoinColumn(name="merchant_fk")
private Merchant merchant;
private boolean active;
}
| 1,154 | 0.795494 | 0.795494 | 44 | 25.227272 | 17.102449 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 13 |
e0a23d3b56fdd1205c043c2ebd19f53b5dd43915 | 6,640,019,481,536 | 9e54476b8f16533412d57f86d1d07b86ade9325d | /src/main/java/com/hfy/example/bean/Tasks.java | 8c3be414b1aac449427bc740a9ca9cee20fdbd6d | [] | no_license | luoyexiaohe/MySpringboot_190329 | https://github.com/luoyexiaohe/MySpringboot_190329 | e2069f87be2807bd2e5b5c64d124e857843111da | 4ede3ab7e8443bcb5936622464479ac20fd86aee | refs/heads/master | 2020-05-03T14:45:00.317000 | 2019-03-31T12:40:15 | 2019-03-31T12:40:15 | 178,686,303 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hfy.example.bean;
import java.util.Date;
public class Tasks {
private Integer id;
private String distributorName;
private Integer distributorId;
private String executantName;
private Integer executantId;
private String taskDescribe;
private Integer finishedMark;
private String remark;
private Date startTime;
private Date endTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDistributorName() {
return distributorName;
}
public void setDistributorName(String distributorName) {
this.distributorName = distributorName == null ? null : distributorName.trim();
}
public Integer getDistributorId() {
return distributorId;
}
public void setDistributorId(Integer distributorId) {
this.distributorId = distributorId;
}
public String getExecutantName() {
return executantName;
}
public void setExecutantName(String executantName) {
this.executantName = executantName == null ? null : executantName.trim();
}
public Integer getExecutantId() {
return executantId;
}
public void setExecutantId(Integer executantId) {
this.executantId = executantId;
}
public String getTaskDescribe() {
return taskDescribe;
}
public void setTaskDescribe(String taskDescribe) {
this.taskDescribe = taskDescribe == null ? null : taskDescribe.trim();
}
public Integer getFinishedMark() {
return finishedMark;
}
public void setFinishedMark(Integer finishedMark) {
this.finishedMark = finishedMark;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
} | UTF-8 | Java | 2,202 | java | Tasks.java | Java | [] | null | [] | package com.hfy.example.bean;
import java.util.Date;
public class Tasks {
private Integer id;
private String distributorName;
private Integer distributorId;
private String executantName;
private Integer executantId;
private String taskDescribe;
private Integer finishedMark;
private String remark;
private Date startTime;
private Date endTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDistributorName() {
return distributorName;
}
public void setDistributorName(String distributorName) {
this.distributorName = distributorName == null ? null : distributorName.trim();
}
public Integer getDistributorId() {
return distributorId;
}
public void setDistributorId(Integer distributorId) {
this.distributorId = distributorId;
}
public String getExecutantName() {
return executantName;
}
public void setExecutantName(String executantName) {
this.executantName = executantName == null ? null : executantName.trim();
}
public Integer getExecutantId() {
return executantId;
}
public void setExecutantId(Integer executantId) {
this.executantId = executantId;
}
public String getTaskDescribe() {
return taskDescribe;
}
public void setTaskDescribe(String taskDescribe) {
this.taskDescribe = taskDescribe == null ? null : taskDescribe.trim();
}
public Integer getFinishedMark() {
return finishedMark;
}
public void setFinishedMark(Integer finishedMark) {
this.finishedMark = finishedMark;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
} | 2,202 | 0.645777 | 0.645777 | 105 | 19.980953 | 20.904764 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304762 | false | false | 13 |
1b73b36e0b8ada008789b0f4f3b06c590c86a06c | 3,590,592,693,051 | 3bfbb897a34dc5778db92be8bcf3d8a895ecba67 | /src/builder/tasks/Task.java | b35dbc08a0a66bb423c0d0524e072bccb83227f1 | [] | no_license | Naifff/patterns | https://github.com/Naifff/patterns | fb02b28e0b5c9b15cfde83a43acf1c8213e33e9e | 85c758f710fa3b072eede13b316862a4eaea77ac | refs/heads/master | 2020-03-26T23:17:01.828000 | 2018-08-21T11:50:25 | 2018-08-21T11:50:25 | 145,526,666 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package builder.tasks;
import builder.components.*;
public class Task {
private final Type type;
private final Lifetime lifetime;
private final Responsible responsible;
private final State state;
public Task(Type type, Lifetime lifetime, Responsible responsible,
State state) {
this.type = type;
this.lifetime = lifetime;
this.responsible = responsible;
this.state = state;
this.state.setTask(this);
}
public Type getType() {
return type;
}
public Lifetime getLifetime() {
return lifetime;
}
public Responsible getResponsible() {
return responsible;
}
public State getState() {
return state;
}
}
| UTF-8 | Java | 747 | java | Task.java | Java | [] | null | [] | package builder.tasks;
import builder.components.*;
public class Task {
private final Type type;
private final Lifetime lifetime;
private final Responsible responsible;
private final State state;
public Task(Type type, Lifetime lifetime, Responsible responsible,
State state) {
this.type = type;
this.lifetime = lifetime;
this.responsible = responsible;
this.state = state;
this.state.setTask(this);
}
public Type getType() {
return type;
}
public Lifetime getLifetime() {
return lifetime;
}
public Responsible getResponsible() {
return responsible;
}
public State getState() {
return state;
}
}
| 747 | 0.619813 | 0.619813 | 35 | 20.342857 | 16.466316 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.514286 | false | false | 13 |
90869a994c58802cd09ae307265e93d751e728be | 18,116,172,085,562 | 909effd8a17ee16471e5f11f15b3473dce0f2638 | /src/main/java/com/my/files/CopyZipFile.java | 8e995e163164fd420ba810d6c0471219905aafa3 | [
"Apache-2.0"
] | permissive | Nelphalem/exercise | https://github.com/Nelphalem/exercise | 6dbf5b306ec2c271ae4d51a6daa23d95c141f31f | 8ce8773b5cef43abce576447acde8f234fad14b4 | refs/heads/development | 2020-01-27T22:52:42.213000 | 2015-07-15T09:08:12 | 2015-07-15T09:08:12 | 27,412,320 | 0 | 1 | null | false | 2015-01-26T08:20:26 | 2014-12-02T03:02:26 | 2014-12-24T03:55:00 | 2015-01-02T05:39:42 | 264 | 0 | 1 | 1 | Java | null | null | package com.my.files;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
public class CopyZipFile {
// OK
private static String saveTmp(InputStream in, String fileName) throws IOException {
OutputStream outputStream = null;
try {
File file = new File("D:\\local\\esb\\data\\rcs_tmp\\" + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[200];
int i = 0;
while ((i = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, i);
}
return file.getPath();
} finally {
if (outputStream != null)
outputStream.close();
}
}
// Not sure why failed ... maybe some error while convert to string
private static String saveTmp2(InputStream in, String fileName) throws IOException {
BufferedWriter writer = null;
BufferedReader reader = null;
try {
File file = new File("D:\\local\\esb\\data\\rcs_tmp\\" + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
writer = new BufferedWriter(new FileWriter(file));
reader = new BufferedReader(new InputStreamReader(in));
String lineString = null;
while ((lineString = reader.readLine()) != null) {
writer.write(lineString);
System.out.println(lineString);
writer.newLine();
}
return file.getPath();
} finally {
if (writer != null)
writer.close();
if (reader != null)
reader.close();
}
}
private static String saveTmp3(InputStream in, String fileName) throws IOException {
OutputStream outputStream = null;
try {
File file = new File("D:\\local\\esb\\data\\rcs_tmp\\" + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[200];
while (in.read(buffer) != -1) {
outputStream.write(buffer);
}
return file.getPath();
} finally {
if (outputStream != null)
outputStream.close();
}
}
private static String saveTmp4(InputStream in, String fileName) throws IOException {
OutputStream outputStream = null;
try {
File file = new File("D:\\local\\esb\\data\\rcs_tmp\\" + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[200];
while (in.read(buffer) != -1) {
String string = Arrays.toString(buffer);
System.out.println(Arrays.toString(buffer));
outputStream.write(getBytes(string));
}
return file.getPath();
} finally {
if (outputStream != null)
outputStream.close();
}
}
private static byte[] getBytes(String s) throws IOException {
if (s == null || !s.endsWith("]") || !s.startsWith("["))
throw new IOException();
String buffString = s.substring(1, s.length() - 1);
String[] buffStrings = buffString.split(",");
byte[] buffer = new byte[buffStrings.length];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = Byte.valueOf(buffStrings[i].trim());
}
// System.out.print(Arrays.toString(buffStrings));
return buffer;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
InputStream inputStream = new FileInputStream(
"d:\\local\\esb\\data\\rcsdata\\ds21\\RCSKnowledgeItem\\1.zip");
saveTmp4(inputStream, "1.txt.zip");
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
| UTF-8 | Java | 3,847 | java | CopyZipFile.java | Java | [] | null | [] | package com.my.files;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
public class CopyZipFile {
// OK
private static String saveTmp(InputStream in, String fileName) throws IOException {
OutputStream outputStream = null;
try {
File file = new File("D:\\local\\esb\\data\\rcs_tmp\\" + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[200];
int i = 0;
while ((i = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, i);
}
return file.getPath();
} finally {
if (outputStream != null)
outputStream.close();
}
}
// Not sure why failed ... maybe some error while convert to string
private static String saveTmp2(InputStream in, String fileName) throws IOException {
BufferedWriter writer = null;
BufferedReader reader = null;
try {
File file = new File("D:\\local\\esb\\data\\rcs_tmp\\" + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
writer = new BufferedWriter(new FileWriter(file));
reader = new BufferedReader(new InputStreamReader(in));
String lineString = null;
while ((lineString = reader.readLine()) != null) {
writer.write(lineString);
System.out.println(lineString);
writer.newLine();
}
return file.getPath();
} finally {
if (writer != null)
writer.close();
if (reader != null)
reader.close();
}
}
private static String saveTmp3(InputStream in, String fileName) throws IOException {
OutputStream outputStream = null;
try {
File file = new File("D:\\local\\esb\\data\\rcs_tmp\\" + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[200];
while (in.read(buffer) != -1) {
outputStream.write(buffer);
}
return file.getPath();
} finally {
if (outputStream != null)
outputStream.close();
}
}
private static String saveTmp4(InputStream in, String fileName) throws IOException {
OutputStream outputStream = null;
try {
File file = new File("D:\\local\\esb\\data\\rcs_tmp\\" + fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[200];
while (in.read(buffer) != -1) {
String string = Arrays.toString(buffer);
System.out.println(Arrays.toString(buffer));
outputStream.write(getBytes(string));
}
return file.getPath();
} finally {
if (outputStream != null)
outputStream.close();
}
}
private static byte[] getBytes(String s) throws IOException {
if (s == null || !s.endsWith("]") || !s.startsWith("["))
throw new IOException();
String buffString = s.substring(1, s.length() - 1);
String[] buffStrings = buffString.split(",");
byte[] buffer = new byte[buffStrings.length];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = Byte.valueOf(buffStrings[i].trim());
}
// System.out.print(Arrays.toString(buffStrings));
return buffer;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
InputStream inputStream = new FileInputStream(
"d:\\local\\esb\\data\\rcsdata\\ds21\\RCSKnowledgeItem\\1.zip");
saveTmp4(inputStream, "1.txt.zip");
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
| 3,847 | 0.672472 | 0.665973 | 134 | 27.708956 | 21.207161 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.671642 | false | false | 13 |
819d2eadd288d6892b1fdf7b1c1024e08d74934a | 31,370,441,165,452 | eea5f46ed94db90cb66c645d8b4d95b1fc7d9c2d | /app/src/main/java/com/voler/person/app/home/MainActivity.java | 0f51246ea0a0b2cbe146a03e76587d976050ecfc | [] | no_license | voler-JHL/PersonalAPP | https://github.com/voler-JHL/PersonalAPP | f28ed23c8ea2204ef74deab6b91fd7249076afc2 | 0525dbffca5960c62c2f62d210951e9b202eebea | refs/heads/master | 2021-01-20T16:54:44.478000 | 2017-10-28T05:19:34 | 2017-10-28T05:19:34 | 90,855,799 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.voler.person.app.home;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.voler.annotation.FieldInject;
import com.voler.person.app.R;
import com.voler.person.app.bean.Person;
import com.voler.person.app.bean.Student;
import com.voler.person.app.inject.InjectActivity;
import com.voler.person.app.lock.LockService;
import com.voler.person.app.widget.RTLProgressBar;
import com.voler.person.app.widget.RatingBarView;
import com.voler.person.http.Api;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import okhttp3.ResponseBody;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
public class MainActivity extends AppCompatActivity {
@FieldInject
String name;
@FieldInject
String age;
@FieldInject
String getName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
RTLProgressBar rtlProgressBar = (RTLProgressBar) findViewById(R.id.pb);
// tv.setText(stringFromJNI());
long l = 1495603459000l;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzzz");
String dateString = formatter.format(l);
tv.setText(dateString);
Intent intent = new Intent(this, InjectActivity.class);
intent.putExtra("string","这是由MainActivity传来的字符串");
intent.putExtra("number",52054843);
intent.putExtra("chars",new char[]{'v','o','l','e','r',' ','m','e','a','n','s',' ','l','o','v','e','r'});
intent.putExtra("obj",new Person("Voler",false));
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Loof",69));
students.add(new Student("Fool",25));
intent.putParcelableArrayListExtra("studentList",students);
// startActivity(intent);
startService(new Intent(this, LockService.class));
// toggleFlowEntrance(this,SplashActivityAlias.class);
Calendar calendar = Calendar.getInstance();
int today = calendar.get(Calendar.DAY_OF_YEAR);
Toast.makeText(this,today+"", Toast.LENGTH_SHORT).show();
//
RatingBarView viewById = (RatingBarView) findViewById(R.id.rb_view);
// viewById.setStar(3,false);
viewById.setOnRatingListener(new RatingBarView.OnRatingListener() {
@Override
public void onRating(Object bindObject, int RatingScore) {
Toast.makeText(MainActivity.this, String.valueOf(RatingScore), Toast.LENGTH_SHORT).show();
}
});
rtlProgressBar.setMax(300);
rtlProgressBar.toProgress(290);
Api.getComApi()
.getSplashAdv()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new Action1<ResponseBody>() {
@Override
public void call(ResponseBody s) {
try {
Log.e("-----", s.string());
} catch (IOException e) {
e.printStackTrace();
}
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
// try {
// new FUtil().find(PriImpl.class);
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
// finish();
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
// public native String stringFromJNI();
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
}
| UTF-8 | Java | 4,416 | java | MainActivity.java | Java | [
{
"context": ",'r'});\n intent.putExtra(\"obj\",new Person(\"Voler\",false));\n ArrayList<Student> students = n",
"end": 1911,
"score": 0.9913734197616577,
"start": 1906,
"tag": "NAME",
"value": "Voler"
},
{
"context": " ArrayList<>();\n students.add(new Student(\"Loof\",69));\n students.add(new Student(\"Fool\",25",
"end": 2017,
"score": 0.9995622038841248,
"start": 2013,
"tag": "NAME",
"value": "Loof"
},
{
"context": "nt(\"Loof\",69));\n students.add(new Student(\"Fool\",25));\n intent.putParcelableArrayListExtra",
"end": 2063,
"score": 0.9997453689575195,
"start": 2059,
"tag": "NAME",
"value": "Fool"
}
] | null | [] | package com.voler.person.app.home;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.voler.annotation.FieldInject;
import com.voler.person.app.R;
import com.voler.person.app.bean.Person;
import com.voler.person.app.bean.Student;
import com.voler.person.app.inject.InjectActivity;
import com.voler.person.app.lock.LockService;
import com.voler.person.app.widget.RTLProgressBar;
import com.voler.person.app.widget.RatingBarView;
import com.voler.person.http.Api;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import okhttp3.ResponseBody;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
public class MainActivity extends AppCompatActivity {
@FieldInject
String name;
@FieldInject
String age;
@FieldInject
String getName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
RTLProgressBar rtlProgressBar = (RTLProgressBar) findViewById(R.id.pb);
// tv.setText(stringFromJNI());
long l = 1495603459000l;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzzz");
String dateString = formatter.format(l);
tv.setText(dateString);
Intent intent = new Intent(this, InjectActivity.class);
intent.putExtra("string","这是由MainActivity传来的字符串");
intent.putExtra("number",52054843);
intent.putExtra("chars",new char[]{'v','o','l','e','r',' ','m','e','a','n','s',' ','l','o','v','e','r'});
intent.putExtra("obj",new Person("Voler",false));
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Loof",69));
students.add(new Student("Fool",25));
intent.putParcelableArrayListExtra("studentList",students);
// startActivity(intent);
startService(new Intent(this, LockService.class));
// toggleFlowEntrance(this,SplashActivityAlias.class);
Calendar calendar = Calendar.getInstance();
int today = calendar.get(Calendar.DAY_OF_YEAR);
Toast.makeText(this,today+"", Toast.LENGTH_SHORT).show();
//
RatingBarView viewById = (RatingBarView) findViewById(R.id.rb_view);
// viewById.setStar(3,false);
viewById.setOnRatingListener(new RatingBarView.OnRatingListener() {
@Override
public void onRating(Object bindObject, int RatingScore) {
Toast.makeText(MainActivity.this, String.valueOf(RatingScore), Toast.LENGTH_SHORT).show();
}
});
rtlProgressBar.setMax(300);
rtlProgressBar.toProgress(290);
Api.getComApi()
.getSplashAdv()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new Action1<ResponseBody>() {
@Override
public void call(ResponseBody s) {
try {
Log.e("-----", s.string());
} catch (IOException e) {
e.printStackTrace();
}
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
// try {
// new FUtil().find(PriImpl.class);
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// }
// finish();
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
// public native String stringFromJNI();
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
}
| 4,416 | 0.613006 | 0.604593 | 125 | 34.183998 | 23.535635 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.824 | false | false | 13 |
d5c1750caf27b6630808a6cde0c0ca7184256c6c | 23,699,629,585,752 | 0a8fdcb389ec52a7335c85cb905fe74cda2dae74 | /src/com/spoj/impl/CowTreats.java | 07aa44bac534e030663d3b189e31481a7a154141 | [] | no_license | hp-rohitsharma/SPOJ_solutions | https://github.com/hp-rohitsharma/SPOJ_solutions | 3bdcb9d7ccc335f19ab6d15578426d425e1addd4 | 98c68be83c75664705eba2a311190d1ad2df0fc3 | refs/heads/master | 2020-04-29T02:07:13.415000 | 2019-05-16T09:34:42 | 2019-05-16T09:34:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.spoj.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CowTreats {
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line = stdin.readLine();
int[] input = new int[Integer.parseInt(line)];
int index = 0;
while ((line = stdin.readLine()) != null) {
input[index++] = Integer.parseInt(line);
if(index == input.length) {
break;
}
}
int[][] memory = new int[2001][2001];
System.out.println(dp(0, input.length - 1, input, 1, memory));
}
private static int dp(int start, int end, int[] input, int day, int[][] memory) {
if (memory[start][end] != 0) {
return memory[start][end];
}
if (start == end) {
return day * input[start];
}
memory[start][end] = Math.max(dp(start + 1, end, input, day + 1, memory) + day * input[start],
dp(start, end - 1, input, day + 1, memory) + day * input[end]);
return memory[start][end];
}
}
| UTF-8 | Java | 1,047 | java | CowTreats.java | Java | [] | null | [] | package com.spoj.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CowTreats {
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line = stdin.readLine();
int[] input = new int[Integer.parseInt(line)];
int index = 0;
while ((line = stdin.readLine()) != null) {
input[index++] = Integer.parseInt(line);
if(index == input.length) {
break;
}
}
int[][] memory = new int[2001][2001];
System.out.println(dp(0, input.length - 1, input, 1, memory));
}
private static int dp(int start, int end, int[] input, int day, int[][] memory) {
if (memory[start][end] != 0) {
return memory[start][end];
}
if (start == end) {
return day * input[start];
}
memory[start][end] = Math.max(dp(start + 1, end, input, day + 1, memory) + day * input[start],
dp(start, end - 1, input, day + 1, memory) + day * input[end]);
return memory[start][end];
}
}
| 1,047 | 0.643744 | 0.627507 | 41 | 24.536585 | 25.820295 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.195122 | false | false | 13 |
c27ea413f823a5a630c275a5ea0572078ec3b7a2 | 23,699,629,585,389 | a0e2058ed4d98e1f60ff25e0f5cacb7665c2b872 | /src/main/java/am/test/model/MaleSurname.java | 7bb163cc0ff4ad50555464fc5d07c83168437f1d | [] | no_license | MherMg/vaadin_with_parser | https://github.com/MherMg/vaadin_with_parser | 45cecddb99fd6bfba938d32d73d43ca7187c5990 | 193699d2a778bad66436436076670f2fb50aa92b | refs/heads/master | 2023-01-14T14:48:15.259000 | 2020-11-12T14:00:21 | 2020-11-12T14:00:21 | 312,290,445 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package am.test.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/**
* Created by
* Mher Petrosyan
* Email mher13.02.94@gmail.ru
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "male_surname")
public class MaleSurname {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String surname;
}
| UTF-8 | Java | 435 | java | MaleSurname.java | Java | [
{
"context": "\nimport javax.persistence.*;\n\n/**\n * Created by\n * Mher Petrosyan\n * Email mher13.02.94@gmail.ru\n */\n@Data\n@AllArgs",
"end": 176,
"score": 0.9998977780342102,
"start": 162,
"tag": "NAME",
"value": "Mher Petrosyan"
},
{
"context": "e.*;\n\n/**\n * Created by\n * Mher Petrosyan\n * Email mher13.02.94@gmail.ru\n */\n@Data\n@AllArgsConstructor\n@NoArgsConstructor\n",
"end": 207,
"score": 0.999925971031189,
"start": 186,
"tag": "EMAIL",
"value": "mher13.02.94@gmail.ru"
}
] | null | [] | package am.test.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/**
* Created by
* <NAME>
* Email <EMAIL>
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "male_surname")
public class MaleSurname {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String surname;
}
| 413 | 0.737931 | 0.724138 | 26 | 15.730769 | 13.423738 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.269231 | false | false | 13 |
f826cc2322fdc153fa49ac370de5009a8abd5de9 | 19,799,799,272,121 | e0b9a25c9b06c0969a0d29e909852575616c556d | /src/test/java/com/_5values/jndistub/LightweightJNDIContextFactoryTest.java | 7ae34ab41d947ccbad5b6e5ee9601969fe556d64 | [
"MIT"
] | permissive | stuartblair/jndistub | https://github.com/stuartblair/jndistub | 733cd4f582ab60411d941d385dec0b6f83df9170 | 211d5e1e1aa81ed0acc22e563722a06c767ecae7 | refs/heads/master | 2020-05-09T16:21:07.457000 | 2011-12-20T00:43:38 | 2011-12-20T00:43:38 | 2,998,954 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com._5values.jndistub;
import static org.junit.Assert.*;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com._5values.jndistub.LightweightJNDIContextFactory;
import org.jmock.Expectations;
import org.jmock.Mockery;
public class LightweightJNDIContextFactoryTest {
private LightweightJNDIContextFactory lightweightJNDIContextFactory;
private Context context;
@After
public void tearDown() throws Exception {
context = null;
}
@Test
public void shouldReturnTheSameContextAcrossDifferentInstances() throws NamingException {
LightweightJNDIContextFactory.setContext(providedContext());
LightweightJNDIContextFactory first = new LightweightJNDIContextFactory();
LightweightJNDIContextFactory second = new LightweightJNDIContextFactory();
assertSame(first.getInitialContext(dummyEnvironment()), second.getInitialContext(dummyEnvironment()));
}
private Context providedContext() {
if (context == null) {
Mockery factory = new Mockery();
context = factory.mock(Context.class);
}
return context;
}
private Hashtable<?, ?> dummyEnvironment() {
return null;
}
}
| UTF-8 | Java | 1,382 | java | LightweightJNDIContextFactoryTest.java | Java | [] | null | [] | package com._5values.jndistub;
import static org.junit.Assert.*;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com._5values.jndistub.LightweightJNDIContextFactory;
import org.jmock.Expectations;
import org.jmock.Mockery;
public class LightweightJNDIContextFactoryTest {
private LightweightJNDIContextFactory lightweightJNDIContextFactory;
private Context context;
@After
public void tearDown() throws Exception {
context = null;
}
@Test
public void shouldReturnTheSameContextAcrossDifferentInstances() throws NamingException {
LightweightJNDIContextFactory.setContext(providedContext());
LightweightJNDIContextFactory first = new LightweightJNDIContextFactory();
LightweightJNDIContextFactory second = new LightweightJNDIContextFactory();
assertSame(first.getInitialContext(dummyEnvironment()), second.getInitialContext(dummyEnvironment()));
}
private Context providedContext() {
if (context == null) {
Mockery factory = new Mockery();
context = factory.mock(Context.class);
}
return context;
}
private Hashtable<?, ?> dummyEnvironment() {
return null;
}
}
| 1,382 | 0.728654 | 0.727207 | 49 | 27.204082 | 27.327925 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55102 | false | false | 13 |
837944f9f96d69d1fb96e81e9cb27848bf41ed9c | 17,231,408,827,195 | b905fbc16a3e4c1765ce4b4eb270d017e6b4b5d2 | /HRMS/HRMS-Domain/src/main/java/com/csipl/hrms/model/organisation/Project.java | 691c61826a34e6b9737d78083cebfb26a807d4b9 | [] | no_license | ravindra2017bangalore/FabHR | https://github.com/ravindra2017bangalore/FabHR | 76ed00741be81b6219b565bb38c4c4a68a364dc1 | c77e5d4c99d5e9bdb042efea5e30fa25e7e0561e | refs/heads/master | 2021-07-03T22:56:55.877000 | 2019-03-11T15:13:02 | 2019-03-11T15:13:02 | 175,022,830 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.csipl.hrms.model.organisation;
import java.io.Serializable;
import javax.persistence.*;
import com.csipl.hrms.model.BaseModel;
import java.util.Date;
/**
* The persistent class for the Project database table.
*
*/
@Entity
@NamedQuery(name="Project.findAll", query="SELECT p FROM Project p")
public class Project extends BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long projectId;
private String allowModi;
private Long branchId;
@Temporal(TemporalType.TIMESTAMP)
private Date dateUpdate;
private String projectName;
//bi-directional many-to-one association to Department
@ManyToOne
@JoinColumn(name="departmentId")
private Department department;
//bi-directional many-to-one association to Client
@ManyToOne
@JoinColumn(name="clientId")
private Client client;
//bi-directional many-to-one association to Company
/*@ManyToOne
@JoinColumn(name="companyId")
private Company company;
*/
public Project() {
}
public Long getProjectId() {
return this.projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public String getAllowModi() {
return this.allowModi;
}
public void setAllowModi(String allowModi) {
this.allowModi = allowModi;
}
public Long getBranchId() {
return this.branchId;
}
public void setBranchId(Long branchId) {
this.branchId = branchId;
}
public Date getDateUpdate() {
return this.dateUpdate;
}
public void setDateUpdate(Date dateUpdate) {
this.dateUpdate = dateUpdate;
}
public String getProjectName() {
return this.projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public Department getDepartment() {
return this.department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Client getClient() {
return this.client;
}
public void setClient(Client client) {
this.client = client;
}
/*public Company getCompany() {
return this.company;
}
public void setCompany(Company company) {
this.company = company;
}*/
} | UTF-8 | Java | 2,295 | java | Project.java | Java | [] | null | [] | package com.csipl.hrms.model.organisation;
import java.io.Serializable;
import javax.persistence.*;
import com.csipl.hrms.model.BaseModel;
import java.util.Date;
/**
* The persistent class for the Project database table.
*
*/
@Entity
@NamedQuery(name="Project.findAll", query="SELECT p FROM Project p")
public class Project extends BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long projectId;
private String allowModi;
private Long branchId;
@Temporal(TemporalType.TIMESTAMP)
private Date dateUpdate;
private String projectName;
//bi-directional many-to-one association to Department
@ManyToOne
@JoinColumn(name="departmentId")
private Department department;
//bi-directional many-to-one association to Client
@ManyToOne
@JoinColumn(name="clientId")
private Client client;
//bi-directional many-to-one association to Company
/*@ManyToOne
@JoinColumn(name="companyId")
private Company company;
*/
public Project() {
}
public Long getProjectId() {
return this.projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public String getAllowModi() {
return this.allowModi;
}
public void setAllowModi(String allowModi) {
this.allowModi = allowModi;
}
public Long getBranchId() {
return this.branchId;
}
public void setBranchId(Long branchId) {
this.branchId = branchId;
}
public Date getDateUpdate() {
return this.dateUpdate;
}
public void setDateUpdate(Date dateUpdate) {
this.dateUpdate = dateUpdate;
}
public String getProjectName() {
return this.projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public Department getDepartment() {
return this.department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Client getClient() {
return this.client;
}
public void setClient(Client client) {
this.client = client;
}
/*public Company getCompany() {
return this.company;
}
public void setCompany(Company company) {
this.company = company;
}*/
} | 2,295 | 0.705447 | 0.705011 | 116 | 17.801723 | 18.174072 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.017241 | false | false | 13 |
b552d1d2dcc990e7c4fc730488c238b71d34e8be | 16,750,372,495,582 | 00540cdf1c7f901f9fe4ae7ba2e42d4e375e5667 | /src/main/java/com/test/jenseny/chapter02/PublishSubject.java | f886aa0806e3a87f59d078c3fb5465cbb9b402ca | [] | no_license | jenseny/rx-test | https://github.com/jenseny/rx-test | 4ecfd47d0322abb1058a1bc47647d85c9032bcd6 | b6269a821d4463248a9e9f25105e7e5178dfb7d5 | refs/heads/master | 2021-01-20T04:21:31.347000 | 2017-04-28T10:23:50 | 2017-04-28T10:23:50 | 89,677,584 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.test.jenseny.chapter02;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Action0;
/**
* Created by riven on 4/28/17.
*/
public class PublishSubject {
public static void main(String[] args) {
final rx.subjects.PublishSubject<String> publishSubject = rx.subjects.PublishSubject.create();
publishSubject.subscribe(new Observer<String>() {
public void onCompleted() {
System.out.println("completed");
}
public void onError(Throwable throwable) {
}
public void onNext(String s) {
System.out.println("res:"+s);
}
});
Observable.create(new Observable.OnSubscribe<Integer>() {
public void call(Subscriber<? super Integer> subscriber) {
subscriber.onCompleted();
}
}).doOnCompleted(new Action0() {
public void call() {
publishSubject.onNext("over");
}
}).subscribe();
}
}
| UTF-8 | Java | 1,062 | java | PublishSubject.java | Java | [
{
"context": "r;\nimport rx.functions.Action0;\n\n/**\n * Created by riven on 4/28/17.\n */\n\npublic class PublishSubject",
"end": 148,
"score": 0.9743536710739136,
"start": 148,
"tag": "USERNAME",
"value": ""
},
{
"context": ";\nimport rx.functions.Action0;\n\n/**\n * Created by riven on 4/28/17.\n */\n\npublic class PublishSubject {\n\n ",
"end": 154,
"score": 0.9915328621864319,
"start": 149,
"tag": "USERNAME",
"value": "riven"
}
] | null | [] | package com.test.jenseny.chapter02;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Action0;
/**
* Created by riven on 4/28/17.
*/
public class PublishSubject {
public static void main(String[] args) {
final rx.subjects.PublishSubject<String> publishSubject = rx.subjects.PublishSubject.create();
publishSubject.subscribe(new Observer<String>() {
public void onCompleted() {
System.out.println("completed");
}
public void onError(Throwable throwable) {
}
public void onNext(String s) {
System.out.println("res:"+s);
}
});
Observable.create(new Observable.OnSubscribe<Integer>() {
public void call(Subscriber<? super Integer> subscriber) {
subscriber.onCompleted();
}
}).doOnCompleted(new Action0() {
public void call() {
publishSubject.onNext("over");
}
}).subscribe();
}
}
| 1,062 | 0.573446 | 0.564972 | 42 | 24.285715 | 23.647497 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 13 |
8897b48251c5921832fb4a16dab38c73e439556d | 11,424,613,052,407 | 8497caca5d7eaeabffe04c0b9d0fd9195208a14c | /src/main/java/com/divergentsl/cms_springboot/repository/AdminRepository.java | a65acfb2a418e92676cda8cac211ca1b20fb2fca | [] | no_license | Sarwesh-divergentsoftlab/cms-spring-security | https://github.com/Sarwesh-divergentsoftlab/cms-spring-security | ea485420a15e7af5f0fd0836042fcc23d8a95207 | 2af87614b563b5eee87e4cd0da64ffbaf989c97a | refs/heads/master | 2023-05-21T00:48:45.958000 | 2021-06-11T11:20:37 | 2021-06-11T11:20:37 | 375,348,837 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.divergentsl.cms_springboot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.divergentsl.cms_springboot.model.LoginAdmin;
public interface AdminRepository extends JpaRepository<LoginAdmin, String> {
LoginAdmin findByUsername(String username);
}
| UTF-8 | Java | 299 | java | AdminRepository.java | Java | [] | null | [] | package com.divergentsl.cms_springboot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.divergentsl.cms_springboot.model.LoginAdmin;
public interface AdminRepository extends JpaRepository<LoginAdmin, String> {
LoginAdmin findByUsername(String username);
}
| 299 | 0.83612 | 0.83612 | 10 | 28.9 | 29.642706 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 13 |
af27b6453e2510b78c5ffdf79d95dfe7c85b19b1 | 19,035,295,106,472 | 0e424fa61add58aeea53bc0eab3cad364441c252 | /Java_Programming/Innerclasses/App1/Flavour2Demo.java | 1191ee46661c609b7a58d9122ce5e0901f7544f5 | [] | no_license | Vijay-Ky/Rooman_JSD_MAY_5TO9_BATCH | https://github.com/Vijay-Ky/Rooman_JSD_MAY_5TO9_BATCH | 7255bb4d493bf46b677086cbaa14ab61927ce74b | 5fe57a9bd5122389ccba6b0f2044fecc5dd71e95 | refs/heads/master | 2020-05-26T12:55:45.911000 | 2019-07-02T18:13:25 | 2019-07-02T18:13:25 | 188,238,770 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Flavor2Demo
{
// An anonymous class that implements Hello interface
static Hello h = new Hello()
{
public void show()
{
System.out.println("i am in anonymous class");
}
};
public static void main(String[] args)
{
h.show();
}
}
interface Hello
{
void show();
}
| UTF-8 | Java | 313 | java | Flavour2Demo.java | Java | [] | null | [] | class Flavor2Demo
{
// An anonymous class that implements Hello interface
static Hello h = new Hello()
{
public void show()
{
System.out.println("i am in anonymous class");
}
};
public static void main(String[] args)
{
h.show();
}
}
interface Hello
{
void show();
}
| 313 | 0.594249 | 0.591054 | 22 | 13.181818 | 16.179775 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.545455 | false | false | 13 |
0340f2de3340c9bef12394cc5af7a28c1217604c | 30,640,296,691,004 | dc713783b4910f816a10e6da05bf23c8f45528ce | /OnlineForum2/src/daoInterfaces/ReviewDao.java | e482cb18ee9acd201858478a348aa8f169f91f04 | [] | no_license | Ning2018/OnlineForum2 | https://github.com/Ning2018/OnlineForum2 | c293bc2ca763e836cc4c26004320b244d694e3d4 | 4b105103642100d3bb265b1e9c3ad4b8b16fc493 | refs/heads/master | 2020-04-03T11:53:18.242000 | 2018-10-29T15:25:59 | 2018-10-29T15:25:59 | 155,234,655 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package daoInterfaces;
import java.util.List;
import entity.Review;
public interface ReviewDao {
public void save(Review review);
public List<Review> query(String hql, Object...params);
}
| UTF-8 | Java | 196 | java | ReviewDao.java | Java | [] | null | [] | package daoInterfaces;
import java.util.List;
import entity.Review;
public interface ReviewDao {
public void save(Review review);
public List<Review> query(String hql, Object...params);
}
| 196 | 0.755102 | 0.755102 | 12 | 15.333333 | 17.317301 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 13 |
0333be35acf382302b2ce917e81a0a6db4870eee | 2,851,858,288,194 | 4e1e5e2518e2d9e43fe35b245cd9680b8a88ec32 | /src/java/com/yitong/app/service/system/LoginService.java | 1afddf7a506cbcb6234fffdb057dc97c4140d366 | [] | no_license | MoonLuckSir/MoonRepository | https://github.com/MoonLuckSir/MoonRepository | df0592f2f43bb04bcfa4cdbd0f02582f2743604c | 12ad3b4dcbcbc639d90e11366dbd81ab8ba2c172 | refs/heads/master | 2021-01-12T15:41:00.492000 | 2016-10-25T01:56:00 | 2016-10-25T01:56:00 | 71,849,484 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yitong.app.service.system;
import java.util.List;
import java.util.Map;
import com.yitong.commons.service.BaseService;
public class LoginService extends BaseService {
/**
* 加载系统所有菜单
*
* @return
*/
public List findAllMenus() {
return this.findList("MenuInfo.findAll", null);
}
/**
* 加载用户菜单
*
* @return
*/
public List findMenuByUserId(Map params) {
return this.findList("MenuInfo.findMenuByUserId", params);
}
/**
* 加载报表菜单
*
* @param params
* @return
*/
public List findReportMenus(Map params) {
return this.findList("ReportInfo.queryReportMenu", params);
}
/**
* 修改密码
*
* @param user
* @return
*/
public boolean updatePwd(Map user) {
return this.update("UserInfo.updateById", user);
}
}
| UTF-8 | Java | 814 | java | LoginService.java | Java | [] | null | [] | package com.yitong.app.service.system;
import java.util.List;
import java.util.Map;
import com.yitong.commons.service.BaseService;
public class LoginService extends BaseService {
/**
* 加载系统所有菜单
*
* @return
*/
public List findAllMenus() {
return this.findList("MenuInfo.findAll", null);
}
/**
* 加载用户菜单
*
* @return
*/
public List findMenuByUserId(Map params) {
return this.findList("MenuInfo.findMenuByUserId", params);
}
/**
* 加载报表菜单
*
* @param params
* @return
*/
public List findReportMenus(Map params) {
return this.findList("ReportInfo.queryReportMenu", params);
}
/**
* 修改密码
*
* @param user
* @return
*/
public boolean updatePwd(Map user) {
return this.update("UserInfo.updateById", user);
}
}
| 814 | 0.663185 | 0.663185 | 47 | 15.297873 | 18.077745 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.06383 | false | false | 13 |
f23e622c4aaa4a052256559bb060ed5d89fe185c | 16,793,322,141,212 | 2378438b43c9f23493ecb57becd3c71d2b00000b | /tp2/src/com/company/modelo/terreno/Mapa.java | 25c124a13ee924fe13df8263ade4356fe7b3b54a | [] | no_license | martinstd96/algoritmos3-7507 | https://github.com/martinstd96/algoritmos3-7507 | e695367f3fe4f4679881cc93343e3479a0854de0 | 532e735a15bb4b2dc3922e84254f979d81e05185 | refs/heads/master | 2020-03-27T16:51:59.812000 | 2018-12-21T01:33:19 | 2018-12-21T01:33:19 | 146,811,525 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company.modelo.terreno;
import com.company.excepciones.CasilleroLlenoException;
import com.company.excepciones.CasilleroNoExistenteException;
import com.company.excepciones.MapaLlenoException;
import com.company.modelo.Posicionable;
import com.company.modelo.unidades.Unidad;
public class Mapa {
private static Integer numeroDeCasillerosHorizontales = 25;
private static Integer numeroDeCasillerosVerticales = 25;
private static Mapa instancia = new Mapa();
private Casillero[][] casilleros;
private Mapa() {
casilleros = new Casillero[numeroDeCasillerosVerticales][numeroDeCasillerosHorizontales];
for(Integer i = 0; i < numeroDeCasillerosVerticales; i++){
for(Integer j = 0; j < numeroDeCasillerosHorizontales; j++){
casilleros[i][j] = new Casillero();
}
}
}
public void ubicar(Posicionable posicionable, Integer posicionHorizontal, Integer posicionVertical) throws CasilleroNoExistenteException, CasilleroLlenoException {
Casillero destino = obtenerCasillero(posicionHorizontal, posicionVertical);
destino.agregarPosicionable(posicionable);
}
public Boolean estaOcupado(Integer posicionHorizontal, Integer posicionVertical) {
try {
Casillero casilleroAConsultar = obtenerCasillero(posicionHorizontal, posicionVertical);
return casilleroAConsultar.estaOcupado();
} catch (CasilleroNoExistenteException e) {
return true;
}
}
/*Listo*/
protected Casillero obtenerCasillero(Integer posicionHorizontal, Integer posicionVertical) throws CasilleroNoExistenteException {
if(!esParteDelMapa(posicionHorizontal, posicionVertical)){
throw new CasilleroNoExistenteException("Error al intentar obtener casillero: El casillero " + posicionHorizontal + ", " + posicionVertical + "esta fuera del mapa.");
}
return casilleros[posicionHorizontal][posicionVertical];
}
private Boolean esParteDelMapa(Integer posicionHorizontal, Integer posicionVertical){
return (posicionHorizontal >= 0 && posicionHorizontal < numeroDeCasillerosHorizontales && posicionVertical >= 0 && posicionVertical < numeroDeCasillerosVerticales);
}
public static Mapa getMapa(){
if (instancia == null){
instancia = new Mapa();
}
return instancia;
}
public void colocarEnCasilleroLibreMasCercano(Unidad nuevaUnidad, Integer posicionHorizontal, Integer posicionVertical) throws MapaLlenoException, CasilleroNoExistenteException, CasilleroLlenoException {
Reptador reptador = new Reptador(posicionHorizontal, posicionVertical);
Boolean encontrado = false;
while(! encontrado){
encontrado = reptador.buscar();
}
reptador.ubicarUnidad(nuevaUnidad);
}
public Posicionable conseguirOcupante(Integer posicionHorizontal, Integer posicionVertical ) throws CasilleroNoExistenteException {
Casillero contenedor = obtenerCasillero(posicionHorizontal, posicionVertical);
return contenedor.obtenerPosicionable();
}
public void destruir(){
instancia = null;
}
public Integer obtenerTamanio(){
return (this.numeroDeCasillerosHorizontales * this.numeroDeCasillerosVerticales);
}
public void quitar(Integer posicionHorizontal, Integer posicionVertical) throws CasilleroNoExistenteException {
Casillero aModificar = obtenerCasillero(posicionHorizontal,posicionVertical);
aModificar.quitarPosicionable();
}
}
| UTF-8 | Java | 3,604 | java | Mapa.java | Java | [] | null | [] | package com.company.modelo.terreno;
import com.company.excepciones.CasilleroLlenoException;
import com.company.excepciones.CasilleroNoExistenteException;
import com.company.excepciones.MapaLlenoException;
import com.company.modelo.Posicionable;
import com.company.modelo.unidades.Unidad;
public class Mapa {
private static Integer numeroDeCasillerosHorizontales = 25;
private static Integer numeroDeCasillerosVerticales = 25;
private static Mapa instancia = new Mapa();
private Casillero[][] casilleros;
private Mapa() {
casilleros = new Casillero[numeroDeCasillerosVerticales][numeroDeCasillerosHorizontales];
for(Integer i = 0; i < numeroDeCasillerosVerticales; i++){
for(Integer j = 0; j < numeroDeCasillerosHorizontales; j++){
casilleros[i][j] = new Casillero();
}
}
}
public void ubicar(Posicionable posicionable, Integer posicionHorizontal, Integer posicionVertical) throws CasilleroNoExistenteException, CasilleroLlenoException {
Casillero destino = obtenerCasillero(posicionHorizontal, posicionVertical);
destino.agregarPosicionable(posicionable);
}
public Boolean estaOcupado(Integer posicionHorizontal, Integer posicionVertical) {
try {
Casillero casilleroAConsultar = obtenerCasillero(posicionHorizontal, posicionVertical);
return casilleroAConsultar.estaOcupado();
} catch (CasilleroNoExistenteException e) {
return true;
}
}
/*Listo*/
protected Casillero obtenerCasillero(Integer posicionHorizontal, Integer posicionVertical) throws CasilleroNoExistenteException {
if(!esParteDelMapa(posicionHorizontal, posicionVertical)){
throw new CasilleroNoExistenteException("Error al intentar obtener casillero: El casillero " + posicionHorizontal + ", " + posicionVertical + "esta fuera del mapa.");
}
return casilleros[posicionHorizontal][posicionVertical];
}
private Boolean esParteDelMapa(Integer posicionHorizontal, Integer posicionVertical){
return (posicionHorizontal >= 0 && posicionHorizontal < numeroDeCasillerosHorizontales && posicionVertical >= 0 && posicionVertical < numeroDeCasillerosVerticales);
}
public static Mapa getMapa(){
if (instancia == null){
instancia = new Mapa();
}
return instancia;
}
public void colocarEnCasilleroLibreMasCercano(Unidad nuevaUnidad, Integer posicionHorizontal, Integer posicionVertical) throws MapaLlenoException, CasilleroNoExistenteException, CasilleroLlenoException {
Reptador reptador = new Reptador(posicionHorizontal, posicionVertical);
Boolean encontrado = false;
while(! encontrado){
encontrado = reptador.buscar();
}
reptador.ubicarUnidad(nuevaUnidad);
}
public Posicionable conseguirOcupante(Integer posicionHorizontal, Integer posicionVertical ) throws CasilleroNoExistenteException {
Casillero contenedor = obtenerCasillero(posicionHorizontal, posicionVertical);
return contenedor.obtenerPosicionable();
}
public void destruir(){
instancia = null;
}
public Integer obtenerTamanio(){
return (this.numeroDeCasillerosHorizontales * this.numeroDeCasillerosVerticales);
}
public void quitar(Integer posicionHorizontal, Integer posicionVertical) throws CasilleroNoExistenteException {
Casillero aModificar = obtenerCasillero(posicionHorizontal,posicionVertical);
aModificar.quitarPosicionable();
}
}
| 3,604 | 0.728912 | 0.726693 | 89 | 39.494381 | 45.559475 | 207 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617977 | false | false | 13 |
0d3bbf74e52e2a4446969b6e30641faa5b379b07 | 11,673,721,124,856 | 3484c80653b84664bf956c30797c2a13daa60f2b | /src/main/java/com/example/demo/service/UserRegisterService.java | a5341b4d8e5021d9c971032091900188610ccec4 | [] | no_license | shaozige/deviceManager | https://github.com/shaozige/deviceManager | f34f75bd331a2ce548928a2e35a99b6ffa358a90 | 7dd313ddaa23cb611878015f4840bdf282fa23a4 | refs/heads/master | 2020-03-26T04:33:57.662000 | 2018-08-13T00:10:38 | 2018-08-13T00:10:38 | 144,509,998 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.service;
import com.example.demo.domain.UserRegister;
import com.example.demo.response.CommonResponse;
import com.example.demo.response.UserRegisterResponse;
import com.example.demo.response.UserRegistersResponse;
public interface UserRegisterService {
UserRegistersResponse selectAllByStatus(int status);
UserRegisterResponse selectByPhone(String phone);
UserRegister getByPhone(String phone);
CommonResponse insert(UserRegister userRegister);
CommonResponse updateStatusByPhone(UserRegister userRegister);
}
| UTF-8 | Java | 563 | java | UserRegisterService.java | Java | [] | null | [] | package com.example.demo.service;
import com.example.demo.domain.UserRegister;
import com.example.demo.response.CommonResponse;
import com.example.demo.response.UserRegisterResponse;
import com.example.demo.response.UserRegistersResponse;
public interface UserRegisterService {
UserRegistersResponse selectAllByStatus(int status);
UserRegisterResponse selectByPhone(String phone);
UserRegister getByPhone(String phone);
CommonResponse insert(UserRegister userRegister);
CommonResponse updateStatusByPhone(UserRegister userRegister);
}
| 563 | 0.824156 | 0.824156 | 20 | 27.15 | 25.344181 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
0f3af56411642939e6b73e0c07923fd2d73c94a8 | 28,192,165,356,514 | 3ba1176df2d9dfdce034841cd6213aa9673a0f3b | /src/java/main/vektah/rust/RustFileType.java | 49c56728ca07d32ab3701e7a6026186d9359b309 | [
"BSD-2-Clause"
] | permissive | AndrewTamm/idea-rust | https://github.com/AndrewTamm/idea-rust | a15360706592ff385b64171a41e877f333bef593 | 98440867b10dc03004818de0f9f6b55f275c7d2c | refs/heads/master | 2021-01-21T09:49:42.417000 | 2015-07-26T15:45:20 | 2015-07-26T15:45:20 | 34,121,383 | 2 | 0 | null | true | 2015-04-17T14:33:07 | 2015-04-17T14:33:06 | 2015-04-16T05:27:44 | 2015-03-19T22:02:53 | 1,975 | 0 | 0 | 0 | null | null | null | package vektah.rust;
import com.intellij.openapi.fileTypes.LanguageFileType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import vektah.rust.i18n.RustBundle;
import javax.swing.*;
public class RustFileType extends LanguageFileType {
public static final RustFileType INSTANCE = new RustFileType();
private RustFileType() {
super(RustLanguage.INSTANCE);
}
@NotNull
@Override
public String getName() {
return RustBundle.message("file.type.name.rust");
}
@NotNull
@Override
public String getDescription() {
return RustBundle.message("file.type.description.rust");
}
@NotNull
@Override
public String getDefaultExtension() {
return "rs";
}
@Nullable
@Override
public Icon getIcon() {
return RustIcons.ICON_RUST_16;
}
}
| UTF-8 | Java | 790 | java | RustFileType.java | Java | [] | null | [] | package vektah.rust;
import com.intellij.openapi.fileTypes.LanguageFileType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import vektah.rust.i18n.RustBundle;
import javax.swing.*;
public class RustFileType extends LanguageFileType {
public static final RustFileType INSTANCE = new RustFileType();
private RustFileType() {
super(RustLanguage.INSTANCE);
}
@NotNull
@Override
public String getName() {
return RustBundle.message("file.type.name.rust");
}
@NotNull
@Override
public String getDescription() {
return RustBundle.message("file.type.description.rust");
}
@NotNull
@Override
public String getDefaultExtension() {
return "rs";
}
@Nullable
@Override
public Icon getIcon() {
return RustIcons.ICON_RUST_16;
}
}
| 790 | 0.758228 | 0.753165 | 40 | 18.75 | 19.100719 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.025 | false | false | 13 |
235a687d2762aaf7d834d99c0ec6ce6a9f0acd4f | 9,216,999,864,782 | 746512cfb3387189bd2468de5716cf42a0b24954 | /src/proxy/TestAOP.java | a533346226131746ea4ee3006fa280fcacbe46d6 | [] | no_license | qiang231/IOFile1 | https://github.com/qiang231/IOFile1 | af73e991131d061dfdd2f87c7acc73f7dc46d5d9 | fcc128258bc8b678e724686e61a3bf027ad07831 | refs/heads/master | 2020-04-08T12:25:04.754000 | 2018-11-27T14:14:51 | 2018-11-27T14:14:51 | 159,346,657 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Human1{
void info();
void fly();
}
class Superman1 implements Human1{
@Override
public void info() {
System.out.println("我是超人");
}
@Override
public void fly() {
System.out.println("I can fly!");
}
}
class HumanUntil1{
public void method1(){
System.out.println("=======方法一======");
}
public void method2(){
System.out.println("=======方法二=======");
}
}
class MyInvocationHandler2 implements InvocationHandler{
Object obj;
public void setObj(Object obj){
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
HumanUntil1 h1 = new HumanUntil1();
h1.method1();
Object returnValue = method.invoke(obj,args);
h1.method2();
return returnValue;
}
}
//动态的创建一个代理类
class Myproxy1{
public static Object getProxyInstance(Object obj){
MyInvocationHandler2 handler2 = new MyInvocationHandler2();
handler2.setObj(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler2);
}
}
public class TestAOP {
public static void main(String[] args) {
Superman1 s1 = new Superman1();
Object obj = Myproxy1.getProxyInstance(s1);
Human1 hu = (Human1)obj;
hu.info();
System.out.println();
hu.fly();
System.out.println();
NikeClothFactory nike = new NikeClothFactory();
ClothFactory factory = (ClothFactory)Myproxy1.getProxyInstance(nike);
factory.productCloth();
}
}
| GB18030 | Java | 1,801 | java | TestAOP.java | Java | [] | null | [] | package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Human1{
void info();
void fly();
}
class Superman1 implements Human1{
@Override
public void info() {
System.out.println("我是超人");
}
@Override
public void fly() {
System.out.println("I can fly!");
}
}
class HumanUntil1{
public void method1(){
System.out.println("=======方法一======");
}
public void method2(){
System.out.println("=======方法二=======");
}
}
class MyInvocationHandler2 implements InvocationHandler{
Object obj;
public void setObj(Object obj){
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
HumanUntil1 h1 = new HumanUntil1();
h1.method1();
Object returnValue = method.invoke(obj,args);
h1.method2();
return returnValue;
}
}
//动态的创建一个代理类
class Myproxy1{
public static Object getProxyInstance(Object obj){
MyInvocationHandler2 handler2 = new MyInvocationHandler2();
handler2.setObj(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler2);
}
}
public class TestAOP {
public static void main(String[] args) {
Superman1 s1 = new Superman1();
Object obj = Myproxy1.getProxyInstance(s1);
Human1 hu = (Human1)obj;
hu.info();
System.out.println();
hu.fly();
System.out.println();
NikeClothFactory nike = new NikeClothFactory();
ClothFactory factory = (ClothFactory)Myproxy1.getProxyInstance(nike);
factory.productCloth();
}
}
| 1,801 | 0.628766 | 0.612848 | 77 | 21.844156 | 22.628029 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 13 |
7808a9a8f243da71b646a29464ac6ca3e13fccba | 26,671,746,911,579 | 20bff72fe0d1c7c1e9bbc3170a92eaa358393832 | /src/Driver.java | 4946e0bd8ef00908cb5f10aaee02c58b11e38265 | [] | no_license | harveylallave/ADVANDBMP1 | https://github.com/harveylallave/ADVANDBMP1 | a8da08263a088a9cc39b1ad24532cb16eecf7a3a | a48f1f2568e30200b0d98b708c927e0f29c46f23 | refs/heads/master | 2021-07-15T14:24:13.204000 | 2017-10-22T20:53:52 | 2017-10-22T20:53:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
//import javafx.scene.input.KeyCombination;
public class Driver extends Application {
Scene home;
Button button;
TableView<ArrayList<String>> table;
BorderPane mainPane = new BorderPane();
Label queryNum = new Label(),
query = new Label();
Button optimizeButton;
ChoiceBox<String> queryChoiceBox;
Connection conn;
private LineChart graphArea;
private XYChart.Series dataSeries1;
private int nQueryExec = 1;
private TextField input,
input_2;
private ToggleGroup queryTypeToggleGroup;
@SuppressWarnings("unchecked")
public void start(Stage primaryStage) throws Exception {
conn = getConnection();
deleteAllIndex();
initMainScreen();
home = new Scene(mainPane, 1000, 600);
home.getStylesheets().add("View/Style.css");
primaryStage.setTitle("ADVANDB - MP1");
primaryStage.setOnCloseRequest(e -> terminateProgram());
primaryStage.setScene(home);
primaryStage.show();
}
public void initMainScreen() {
mainPane.getChildren().remove(mainPane.getCenter());
mainPane.setTop(initTopBar());
mainPane.setCenter(initCenterVBox());
mainPane.setRight(initRightVBox());
}
public MenuBar initTopBar() {
//Initializing menu items
Menu refreshIndex = new Menu(),
optimization = new Menu(),
exit = new Menu();
Label refreshLabelMenu = new Label("Refresh"),
optimizationLabelMenu = new Label("Optimization");
refreshLabelMenu.setOnMouseClicked(e -> deleteAllIndex());
optimizationLabelMenu.setOnMouseClicked(e -> {
Stage myDialog = new Stage();
myDialog.initModality(Modality.WINDOW_MODAL);
GridPane optimizePane = new GridPane();
optimizePane.setVgap(20);
optimizePane.setHgap(25);
optimizePane.setAlignment(Pos.CENTER);
Scene dialogScene = new Scene(optimizePane, 800, 400);
ChoiceBox optimizationType = new ChoiceBox<>();
optimizationType.getItems().addAll("Create Indexes");
optimizePane.add(new Label("Method"), 0, 0);
optimizePane.add(optimizationType, 1, 0);
optimizationType.getSelectionModel().selectedIndexProperty().addListener((observableValue, number, number2) -> {
switch ((Integer) number2) {
case 0: indexOptimization(optimizePane);
break;
}
});
myDialog.setTitle("Query Optimization");
dialogScene.getStylesheets().add("View/Style.css");
myDialog.setScene(dialogScene);
myDialog.show();
});
refreshIndex.setGraphic(refreshLabelMenu);
optimization.setGraphic(optimizationLabelMenu);
optimizationLabelMenu = new Label("Exit");
exit.setGraphic(optimizationLabelMenu);
optimizationLabelMenu.setOnMouseClicked(e -> terminateProgram());
MenuBar menuBar = new MenuBar();
menuBar.getMenus().addAll(refreshIndex, optimization, exit);
return menuBar;
}
public void indexOptimization(GridPane optimizePane){
ChoiceBox tableChoiceBox = new ChoiceBox<>();
ChoiceBox attrChoiceBox = new ChoiceBox<>();
optimizeButton = new Button("Optimize");
optimizeButton.setDisable(true);
optimizeButton.setOnAction(e -> {
Statement st = null;
String query = "create index i" +attrChoiceBox.getSelectionModel().getSelectedItem().toString() + " on " +
tableChoiceBox.getSelectionModel().getSelectedItem().toString()+ "(" +
attrChoiceBox.getSelectionModel().getSelectedItem().toString() + ") ";
try{
st = conn.createStatement();
st.executeUpdate(query);
st.close();
System.out.println("Added new index: i" + attrChoiceBox.getSelectionModel().getSelectedItem().toString());
} catch (SQLException e2) {
System.out.println("SQLException: " + e2.getMessage());
System.out.println("SQLState: " + e2.getSQLState());
System.out.println("VendorError: " + e2.getErrorCode());
}
});
tableChoiceBox.getItems().addAll("book", "book_author", "book_loans", "borrower", "library_branch", "publisher");
tableChoiceBox.getSelectionModel().selectedIndexProperty().addListener((observableValue, number, number2) -> {
optimizeButton.setDisable(true);
attrChoiceBox.getItems().clear();
switch ((Integer) number2) {
case 0: attrChoiceBox.getItems().addAll("BookID", "Title", "PublisherName");
break;
case 1: attrChoiceBox.getItems().addAll("BookID", "AuthorLastName", "AuthorFirstName");
break;
case 2: attrChoiceBox.getItems().addAll("BookID", "BranchID", "CardNo", "DateOut", "DueDate", "DateReturned");
break;
case 3: attrChoiceBox.getItems().addAll("CardNo", "BorrowerLName", "BorrowerFName", "Address", "Phone");
break;
case 4: attrChoiceBox.getItems().addAll("BranchID", "BranchName", "BranchAddress");
break;
case 5: attrChoiceBox.getItems().addAll("PublisherName", "Address", "Phone");
break;
}
attrChoiceBox.getSelectionModel().selectedIndexProperty().addListener((observableValue1,
oldNum,
newNum) ->
optimizeButton.setDisable(false));
});
optimizePane.add(new Label("Table"), 0, 1);
optimizePane.add(tableChoiceBox, 1, 1);
optimizePane.add(new Label("Attribute"), 0, 2);
optimizePane.add(attrChoiceBox, 1, 2);
optimizePane.add(optimizeButton, 1, 3);
}
public VBox initRightVBox() {
VBox mainVBox = new VBox(15);
mainVBox.setAlignment(Pos.TOP_CENTER);
mainVBox.setPadding(new Insets(10, 0, 0, 0));
button = new Button("Edit Query");
button.getStyleClass().add("rightVBoxButton");
button.setMinWidth(150);
button.wrapTextProperty().setValue(true);
button.setOnAction(event -> {
Label label = new Label(queryChoiceBox.getValue().toString());
label.getStyleClass().add("editQueryLabel");
VBox subVBox = new VBox(10);
subVBox.getStyleClass().add("subVBox");
subVBox.getChildren().add(label);
System.out.println("\nEDIT QUERY: " + queryChoiceBox.getValue());
button = new Button("Update Query");
button.setMinWidth(150);
mainVBox.getChildren().add(subVBox);
VBox editQueryVBox;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
switch (queryChoiceBox.getSelectionModel().getSelectedItem().toString()) {
case "1. All books published by Doubleday":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("Doubleday");
editQueryVBox.getChildren().addAll(new Label("SELECT Title, PublisherName \n" +
"FROM book \n" +
"WHERE PublisherName like \n'%"), input,
new Label("%'\n ORDER BY PublisherName;"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery1((VBox) mainPane.getCenter(), input.getText());
});
break;
case "2. Number of books loaned in 2017":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("2017");
editQueryVBox.getChildren().addAll(new Label("SELECT COUNT(*) AS NoBooksBor\n" +
"FROM book_loans\n" +
"WHERE YEAR(DateOut) = "), input);
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery2((VBox) mainPane.getCenter(), input.getText());
});
break;
case "3. All borrowers who have borrowed at most 2 books":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("0");
input_2 = new TextField("2");
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Normal") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) AS BorrowerName, COUNT(*) as NoBooksBor\n" +
"FROM borrower BO, book_loans BL\n" +
"WHERE BO.CardNo = BL.CardNo\n" +
"GROUP BY BorrowerName\n" +
"HAVING NoBooksBor >= ": queryToggleString.equals("Join") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) as BorrowerName , COUNT(*) as NoBooksBor\n" +
"\tFROM borrower BO join book_loans BL on BO.CardNo = BL.CardNo\n" +
"\tGROUP BY BorrowerName\n" +
"HAVING NoBooksBor >= ": /*SubQuery*/
"SELECT CONCAT(BorrowerLName, \", \", BorrowerFName) as BorrowerName, BO2.NoBooksBor\n" +
"\tFROM borrower, (SELECT BL.CardNo, COUNT(CardNo) as NoBooksBor\n" +
"\tFROM book_loans BL\n" +
"\tGROUP BY BL.CardNo\n" +
"\tHAVING COUNT(CardNo) >= "), input,
new Label(queryToggleString.equals("Normal") ?
" and NoBooksBor <= ": queryToggleString.equals("Join") ?
" and NoBooksBor <= " : /*SubQuery*/
" 0 and COUNT(CardNo) <= "), input_2,
new Label(queryToggleString.equals("Normal") ?
"ORDER BY 2 DESC, 1;\n" : queryToggleString.equals("Join") ?
"ORDER BY 2 DESC, 1;" : /*SubQuery*/
"ORDER BY 1) as BO2\n" +
"WHERE borrower.CardNo = BO2.CardNo\n" +
"ORDER BY 2 DESC;"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery3((VBox) mainPane.getCenter(), input.getText(), input_2.getText());
});
break;
case "4. All books written by Burningpeak, Loni":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("Burningpeak");
input_2 = new TextField("Loni");
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Normal") ?
"SELECT B.Title, B.PublisherName, CONCAT(BA.AuthorLastName, '. ', BA.AuthorFirstName) as Author\n" +
"FROM book B, (SELECT * \n" +
" FROM book_authors\n" +
" WHERE AuthorLastName LIKE '%" : queryToggleString.equals("Join") ?
"SELECT B.Title, B.PublisherName, CONCAT(BA.AuthorLastName, '. ', BA.AuthorFirstName) as Author\n" +
"FROM book B join (SELECT * \n" +
" FROM book_authors\n" +
" WHERE AuthorLastName LIKE '%" : /*Subquery*/
"SELECT B.Title, B.PublisherName, \n" +
"\t\tCONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as Author\n" +
"\t\tFROM book B, (SELECT * \n" +
"\t\t FROM book_authors\n" +
"\t\t WHERE AuthorLastName LIKE '%"), input,
new Label(queryToggleString.equals("Normal") ?
"%' and AuthorFirstName LIKE '%" : queryToggleString.equals("Join") ?
"%' and AuthorFirstName LIKE '%" : "%' and AuthorFirstName LIKE '%"), input_2,
new Label(queryToggleString.equals("Normal") ?
"%') as BA\n" +
"WHERE BA.BookID = B.BookID\n" +
"ORDER BY 1;\n" : queryToggleString.equals("Join") ?
"%' ) as BA on BA.BookID = B.BookID\n" +
"ORDER BY 1;" : /*Subquery*/
"%' ) as BA\n" +
"WHERE BA.BookID = B.BookID\n" +
"ORDER BY 1;"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery4((VBox) mainPane.getCenter(), input.getText(), input_2.getText());
});
break;
case "5. All books which were never loaned out (nobody borrowed them)":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Normal") ?
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLName, \", \", " +
"BA.AuthorFName) as AuthorName, B.PublisherName\n" +
"FROM book B, book_authors BA\n" +
"WHERE B.BookID NOT IN (SELECT BookID\n" +
" FROM book_loans)\n" +
" and B.BookID = BA.BookID" +
"GROUP BY B.BookID\n" +
"ORDER BY 3, 2;\n" : queryToggleString.equals("Join") ?
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, B.PublisherName\n" +
"\tFROM book B inner join book_authors BA on \n" +
"\tB.BookID NOT IN (SELECT BookID\n" +
"\tFROM book_loans) and B.BookID = BA.BookID" : /*Subquery*/
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, B.PublisherName\n" +
"\t\tFROM book B inner join book_authors BA on \n" +
"\t\tB.BookID NOT IN (SELECT BookID\n" +
"\tFROM book_loans) and B.BookID = BA.BookID;"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery5((VBox) mainPane.getCenter());
});
break;
case "6. All borrowers who have loaned books in their own branch":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("Burningpeak");
input_2 = new TextField("Loni");
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Normal") ?
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) as " +
"BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO, book_loans BL, library_branch LB\n" +
"WHERE BO.CardNo IN (SELECT CardNo \n" +
" FROM book_loans) AND BO.Address = LB.BranchAddress AND BL.BranchID = LB.BranchID\n" +
"GROUP BY BorrowerName\n" +
"ORDER BY 2;\n" : queryToggleString.equals("Join") ?
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, \", \", BO.BorrowerFName) " +
"as BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO join book_loans BL on BO.CardNo IN (SELECT CardNo \n" +
"FROM book_loans) join library_branch LB on BO.Address = " +
"LB.BranchAddress and BL.BranchID = LB.BranchID\n" : /*Subquery*/
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) " +
"as BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO, book_loans BL, library_branch LB\n" +
"WHERE BO.CardNo IN (SELECT CardNo \n" +
" FROM book_loans) AND BO.Address = LB.BranchAddress AND BL.BranchID = LB.BranchID"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery6((VBox) mainPane.getCenter());
});
break;
case "7. First 100 book loans that were returned exactly on their due date":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("100");
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Normal") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) AS BorrowerName, " +
"BL.BookID, B.Title, CONCAT(BA.AuthorLastName, ', ', " +
"BA.AuthorFirstName) as AuthorName, BL.DueDate, BL.DateReturned\n" +
"FROM book B, book_authors BA, book_loans BL, borrower BO\n" +
"WHERE B.BookID = BA.BookID AND BA.BookID = BL.BookID AND " +
"BL.CardNo AND BL.DueDate = BL.DateReturned\n" +
"LIMIT 0, " : queryToggleString.equals("Join") ?
"SELECT CONCAT(BO.BorrowerFName, \", \" , BO.BorrowerLName) AS " +
"BorrowerName, BL.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", " +
"BA.AuthorFirstName) as AuthorName, BL.DueDate, BL.DateReturned\n" +
"FROM book B join book_authors BA on B.BookID = BA.BookID join book_loans " +
"BL on BA.BookID = BL.BookID join borrower BO on BL.DueDate = BL.DateReturned\n" +
"LIMIT 0, " : /*Subquery*/
"SELECT O.BorrowerName, A.AuthorName, D.BookID, D.DueDate, D.DateReturned\n" +
"FROM (SELECT BL.BookID, BL.DateReturned, BL.DueDate, BL.CardNo\n" +
" FROM book_loans BL\n" +
" WHERE BL.DateReturned = BL.DueDate) AS D, (SELECT BA.BookID, " +
" CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName\n" +
" FROM book_authors BA) as A, (SELECT B.BookID, B.Title\n" +
" FROM book B) as B, (SELECT BO.CardNo, " +
" CONCAT(BO.BorrowerFName, \", \" , BO.BorrowerLName) AS BorrowerName\n" +
" FROM borrower BO) as O\n" +
"WHERE D.BookID = A.BookID AND B.BookID = D.BookID AND O.CardNo = D.CardNo \n" +
"LIMIT 0, "), input);
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery7((VBox) mainPane.getCenter(), input.getText());
});
break;
case "8. Most popular title (most loaned out title) for each branch":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Join") ?
"SELECT BL.BranchID, LB.BranchName, BL.BookID, BL.NoTimesLoaned, " +
"B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, " +
"P.PublisherName, P.Address AS PublisherAddress\n" +
"FROM book B join book_authors BA on B.BookID = BA.BookID join library_branch " +
"LB join publisher P on B.PublisherName = P.PublisherName join " +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned FROM book_loans " +
"GROUP BY BranchID, BookID) AS BL on BL.BranchID = LB.BranchID and BL.BookID = B.BookID\n" +
"join (SELECT TEMP.BranchID, MAX(TEMP.NoTimesLoaned) AS NoTimesLoaned FROM\n" +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned FROM BOOK_LOANS GROUP BY " +
"BranchID, BookID) AS TEMP GROUP BY TEMP.BranchID) AS C on BL.BranchID = " +
"C.BranchID AND BL.NoTimesLoaned = C.NoTimesLoaned\n" +
"GROUP BY BL.BranchID\n" +
"ORDER BY 2, 5;" : /*Normal & subquery*/
"SELECT BL.BranchID, LB.BranchName, BL.BookID, BL.NoTimesLoaned, " +
"B.Title, CONCAT(BA.AuthorLastName, ', ', BA.AuthorFirstName) as " +
"AuthorName, P.PublisherName, P.Address AS PublisherAddress\n" +
"FROM book B, book_authors BA, library_branch LB, publisher P, " +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned\n" +
"FROM book_loans\n" +
"GROUP BY BranchID, BookID) AS BL,\n" +
"(SELECT TEMP.BranchID,\n" +
"MAX(TEMP.NoTimesLoaned)\n" +
"AS NoTimesLoaned\n" +
"FROM\n" +
"(SELECT BranchID, BookID,\n" +
"COUNT(*) AS NoTimesLoaned\n" +
"FROM BOOK_LOANS\n" +
"GROUP BY BranchID, BookID) AS TEMP\n" +
"GROUP BY TEMP.BranchID) AS C\n" +
"WHERE\n" +
"BL.BranchID = C.BranchID AND\n" +
"BL.NoTimesLoaned = C.NoTimesLoaned AND\n" +
"BL.BranchID = LB.BranchID AND\n" +
"BL.BookID = B.BookID AND\n" +
"B.BookID = BA.BookID AND\n" +
"B.PublisherName = P.PublisherName\n" +
"GROUP BY BL.BranchID\n" +
"ORDER BY 2, 5;\n"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery8((VBox) mainPane.getCenter());
});
break;
}
});
queryTypeToggleGroup = new ToggleGroup();
RadioButton normal = new RadioButton("Normal");
normal.setToggleGroup(queryTypeToggleGroup);
normal.setUserData("Normal");
normal.setSelected(true);
RadioButton join = new RadioButton("Join");
join.setToggleGroup(queryTypeToggleGroup);
join.setUserData("Join");
RadioButton subquery = new RadioButton("Subquery");
subquery.setToggleGroup(queryTypeToggleGroup);
subquery.setUserData("Subquery");
queryTypeToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
@Override
public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) {
System.out.println(new_toggle.getUserData().toString());
switch (new_toggle.getUserData().toString()) {
case "Normal": /* normal queries */
break;
case "Join":
break;
case "Subquery":
break;
}
}
});
VBox radioButtonVBox = new VBox(5);
radioButtonVBox.setPadding(new Insets(0, 10, 0, 10));
radioButtonVBox.getChildren().addAll(normal, join, subquery);
mainVBox.getChildren().addAll(radioButtonVBox, new Separator(Orientation.HORIZONTAL), button);
mainVBox.setMinWidth(200);
mainVBox.setMaxWidth(500);
return mainVBox;
}
public VBox initCenterVBox() {
VBox vBox = new VBox();
HBox hBox;
vBox.getStyleClass().add("vBoxCenter");
Pane field = new Pane();
field.setId("centerPane");
if (conn == null) {
vBox.getChildren().add(new Label("Unable to connect to the database, check getConnection()"));
} else {
ImageView queryIcon = new ImageView("View/Images/queryIcon.png");
queryIcon.setFitHeight(25);
queryIcon.setFitWidth(25);
queryIcon.setPreserveRatio(true);
queryChoiceBox = new ChoiceBox<>();
queryChoiceBox.getItems().addAll("",
"1. All books published by Doubleday",
"2. Number of books loaned in 2017",
"3. All borrowers who have borrowed at most 2 books",
"4. All books written by Burningpeak, Loni",
"5. All books which were never loaned out (nobody borrowed them)",
"6. All borrowers who have loaned books in their own branch",
"7. First 100 book loans that were returned exactly on their due date",
"8. Most popular title (most loaned out title) for each branch");
queryChoiceBox.setValue("");
queryChoiceBox.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
restartProfiling();
queryNum.setText("Query #" + number2);
query.setText(queryChoiceBox.getItems().get((Integer) number2));
graphArea.getData().clear();
dataSeries1 = new XYChart.Series();
graphArea.getData().add(dataSeries1);
nQueryExec = 1;
if (vBox.getChildren().get(2) instanceof TableView)
vBox.getChildren().remove(2);
table = new TableView<>();
switch ((Integer) number2) {
case 0:
break;
case 1:
updateTableQuery1(vBox, "Doubleday");
break;
case 2:
updateTableQuery2(vBox, "2017");
break;
case 3:
updateTableQuery3(vBox, "0", "2");
break;
case 4:
updateTableQuery4(vBox, "Burningpeak", "Loni");
break;
case 5:
updateTableQuery5(vBox);
break;
case 6:
updateTableQuery6(vBox);
break;
case 7:
updateTableQuery7(vBox, "100");
break;
case 8:
updateTableQuery8(vBox);
break;
default:
System.out.println("Query choice box selection model not in the range");
}
System.out.println("\n" + queryChoiceBox.getItems().get((Integer) number2));
}
});
queryNum.setText("Query #" + 0);
queryNum.getStyleClass().add("headerText");
queryNum.setAlignment(Pos.BASELINE_LEFT);
hBox = new HBox(10);
hBox.setAlignment(Pos.CENTER);
Button button = new Button("Run");
hBox.getChildren().addAll(queryIcon, queryChoiceBox, button);
vBox.getChildren().add(0, queryNum);
vBox.getChildren().add(1, hBox);
button.setOnAction(e -> {
refreshTable();
nQueryExec += 1;
String queryNumText = queryNum.getText();
VBox tempvBox = new VBox();
tempvBox.getChildren().addAll(new Label());
tempvBox.getChildren().addAll(new Label());
table = new TableView<>();
switch (queryNumText.charAt(queryNumText.length() - 1)) {
case '0':
break;
case '1':
updateTableQuery1(tempvBox, "Doubleday");
break;
case '2':
updateTableQuery2(tempvBox, "2017");
break;
case '3':
updateTableQuery3(tempvBox, "0", "2");
break;
case '4':
updateTableQuery4(tempvBox, "Burningpeak", "Loni");
break;
case '5':
updateTableQuery5(tempvBox);
break;
case '6':
updateTableQuery6(tempvBox);
break;
case '7':
updateTableQuery7(tempvBox, "100");
break;
case '8':
updateTableQuery8(tempvBox);
break;
default:
System.out.println("Repeating Query #" + queryNumText.charAt(queryNumText.length() - 1));
}
});
NumberAxis xAxis = new NumberAxis();
xAxis.setLabel("Execution Number");
NumberAxis yAxis = new NumberAxis();
yAxis.setLabel("Time Processed");
graphArea = new LineChart(xAxis, yAxis);
graphArea.setId("graphArea");
graphArea.setLegendVisible(false);
vBox.getChildren().add(graphArea);
}
return vBox;
}
// Irrelevant query to refresh stored table
private void refreshTable() {
Statement st = null;
ResultSet rs = null;
String query = "SELECT * FROM Book B";
System.out.println("\n\n ... \n\n");
nQueryExec += 1;
try {
st = conn.createStatement();
rs = st.executeQuery(query);
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
}
private void restartProfiling() {
Statement st = null;
try {
st = conn.createStatement();
st.executeQuery(" SET @@profiling = 0;");
st.executeQuery("SET @@profiling_history_size = 0;");
st.executeQuery("SET @@profiling_history_size = 100;");
st.executeQuery("SET @@profiling = 1;");
st.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}
}
private BigDecimal getQueryProcessTime(int i) {
Statement st = null;
ResultSet rs = null;
BigDecimal time = BigDecimal.valueOf(0);
try {
st = conn.createStatement();
rs = st.executeQuery("SHOW PROFILES ");
int row = 1;
while (rs.next()) {
System.out.println("Line #: " + i + " || Row #:" + row +
" || Time: " + rs.getFloat("Duration"));
if (row == i)
time = rs.getBigDecimal("Duration");
row++;
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return time;
}
// Update table queries
private void updateTableQuery1(VBox vBox, String filterName) {
TableColumn<ArrayList<String>, String> titleCol = new TableColumn<>("Title");
titleCol.setMinWidth(100);
titleCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> pubNameCol = new TableColumn<>("PublisherName");
pubNameCol.setMinWidth(100);
pubNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
table.setItems(getQuery1(filterName));
table.getColumns().addAll(titleCol, pubNameCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
vBox.getChildren().add(2, table);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
}
private void updateTableQuery2(VBox vBox, String filterNum) {
TableColumn<ArrayList<String>, String> noBooksBorCol = new TableColumn<>("NoBooksBor");
noBooksBorCol.setMinWidth(100);
noBooksBorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
table.setItems(getQuery2(filterNum));
table.getColumns().addAll(noBooksBorCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery3(VBox vBox, String filter1, String filter2) {
TableColumn<ArrayList<String>, String> nameCol = new TableColumn<>("BorrowerName");
nameCol.setMinWidth(100);
nameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
//Starting Point Column
TableColumn<ArrayList<String>, String> noBooksBorCol = new TableColumn<>("NoBooksBor");
noBooksBorCol.setMinWidth(100);
noBooksBorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
table.setItems(getQuery3(filter1, filter2));
table.getColumns().addAll(nameCol, noBooksBorCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery4(VBox vBox, String filter1, String filter2) {
TableColumn<ArrayList<String>, String> titleCol = new TableColumn<>("Title");
titleCol.setMinWidth(100);
titleCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> pubNameCol = new TableColumn<>("PublisherName");
pubNameCol.setMinWidth(100);
pubNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
TableColumn<ArrayList<String>, String> authorCol = new TableColumn<>("Author");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(2));
});
table.setItems(getQuery4(filter1, filter2));
table.getColumns().addAll(titleCol, pubNameCol, authorCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
System.out.println((nQueryExec - nQueryExec/2) + " || " + processTime);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery5(VBox vBox) {
TableColumn<ArrayList<String>, String> bookIdCol = new TableColumn<>("BookID");
bookIdCol.setMinWidth(100);
bookIdCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> titleCol = new TableColumn<>("Title");
titleCol.setMinWidth(100);
titleCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
TableColumn<ArrayList<String>, String> authorCol = new TableColumn<>("AuthorName");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(2));
});
TableColumn<ArrayList<String>, String> pubCol = new TableColumn<>("PublisherName");
pubCol.setMinWidth(100);
pubCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(3));
});
table.setItems(getQuery5());
table.getColumns().addAll(bookIdCol, titleCol, authorCol, pubCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery6(VBox vBox) {
TableColumn<ArrayList<String>, String> cardNoCol = new TableColumn<>("CardNo");
cardNoCol.setMinWidth(100);
cardNoCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> borrowerNameCol = new TableColumn<>("BorrowerName");
borrowerNameCol.setMinWidth(100);
borrowerNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
TableColumn<ArrayList<String>, String> branchIdCol = new TableColumn<>("BranchID");
branchIdCol.setMinWidth(100);
branchIdCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(2));
});
//Starting Point Column
TableColumn<ArrayList<String>, String> branchNameCol = new TableColumn<>("BranchName");
branchNameCol.setMinWidth(100);
branchNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(3));
});
TableColumn<ArrayList<String>, String> branchAddressCol = new TableColumn<>("BranchAddress");
branchAddressCol.setMinWidth(100);
branchAddressCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(4));
});
table.setItems(getQuery6());
table.getColumns().addAll(cardNoCol, borrowerNameCol, branchIdCol, branchNameCol, branchAddressCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery7(VBox vBox, String filter) {
TableColumn<ArrayList<String>, String> nameCol = new TableColumn<>("BorrowerName");
nameCol.setMinWidth(100);
nameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> idCol = new TableColumn<>("BookID");
idCol.setMinWidth(100);
idCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
TableColumn<ArrayList<String>, String> titleCol = new TableColumn<>("Title");
titleCol.setMinWidth(100);
titleCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(2));
});
TableColumn<ArrayList<String>, String> authorCol = new TableColumn<>("AuthorName");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(3));
});
TableColumn<ArrayList<String>, String> dueDateCol = new TableColumn<>("DueDate");
dueDateCol.setMinWidth(100);
dueDateCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(4));
});
TableColumn<ArrayList<String>, String> dateReturnedCol = new TableColumn<>("DateReturned");
dateReturnedCol.setMinWidth(100);
dateReturnedCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(5));
});
table.setItems(getQuery7(filter));
table.getColumns().addAll(nameCol, idCol, titleCol, authorCol, dueDateCol, dateReturnedCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery8(VBox vBox) {
TableColumn<ArrayList<String>, String> idCol = new TableColumn<>("BranchID");
idCol.setMinWidth(100);
idCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> branchNameCol = new TableColumn<>("BranchName");
branchNameCol.setMinWidth(100);
branchNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
TableColumn<ArrayList<String>, String> bookIdCol = new TableColumn<>("BookID");
bookIdCol.setMinWidth(100);
bookIdCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(2));
});
TableColumn<ArrayList<String>, String> noTimesLoanedCol = new TableColumn<>("NoTimesLoaned");
noTimesLoanedCol.setMinWidth(100);
noTimesLoanedCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(3));
});
TableColumn<ArrayList<String>, String> titleCol = new TableColumn<>("Title");
titleCol.setMinWidth(100);
titleCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(4));
});
TableColumn<ArrayList<String>, String> authorCol = new TableColumn<>("AuthorName");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(5));
});
TableColumn<ArrayList<String>, String> publisherNameCol = new TableColumn<>("PublisherName");
publisherNameCol.setMinWidth(100);
publisherNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(6));
});
TableColumn<ArrayList<String>, String> publisherAddressCol = new TableColumn<>("PublisherAddress");
publisherAddressCol.setMinWidth(100);
publisherAddressCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(7));
});
table.setItems(getQuery8());
table.getColumns().addAll(idCol, branchNameCol, bookIdCol, noTimesLoanedCol, titleCol, authorCol, publisherNameCol, publisherAddressCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
// Get queries
public ObservableList<ArrayList<String>> getQuery1(String filterName) {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String query = "SELECT Title, PublisherName\n" +
"FROM book\n" +
"WHERE PublisherName like '%" + filterName + "%'\n" +
"ORDER BY PublisherName;\n";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getString("Title"));
rowData.add(rs.getString("PublisherName"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery2(String filterNum) {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String query = "SELECT COUNT(*) AS NoBooksBor\n" +
"FROM book_loans\n" +
"WHERE YEAR(DateOut) = " + filterNum;
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getString("NoBooksBor"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery3(String f1, String f2) {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Normal") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) AS BorrowerName, COUNT(*) as NoBooksBor\n" +
"FROM borrower BO, book_loans BL\n" +
"WHERE BO.CardNo = BL.CardNo\n" +
"GROUP BY BorrowerName\n" +
"HAVING NoBooksBor >= " + f1 + " and NoBooksBor <= " + f2 + "\n" +
"ORDER BY 2 DESC, 1;\n" : queryToggleString.equals("Join") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) as BorrowerName , COUNT(*) as NoBooksBor\n" +
"\tFROM borrower BO join book_loans BL on BO.CardNo = BL.CardNo\n" +
"\tGROUP BY BorrowerName\n" +
"HAVING NoBooksBor >= " + f1 + " and NoBooksBor <= " + f2 + "\n" +
"\tORDER BY 2 DESC, 1;" : /*SubQuery*/
"SELECT CONCAT(BorrowerLName, \", \", BorrowerFName) as BorrowerName, BO2.NoBooksBor\n" +
"\tFROM borrower, (SELECT BL.CardNo, COUNT(CardNo) as NoBooksBor\n" +
"\t\t\t\t\tFROM book_loans BL\n" +
"\t\t\t\t\tGROUP BY BL.CardNo\n" +
"\t\t\t\t\tHAVING COUNT(CardNo) >= " + f1 + " and COUNT(CardNo) <= " + f2 + "\n" +
"\t\t\t\t\tORDER BY 1) as BO2\n" +
"WHERE borrower.CardNo = BO2.CardNo\n" +
"\tORDER BY 2 DESC;";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getString("BorrowerName"));
rowData.add(rs.getString("NoBooksBor"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery4(String f1, String f2) {
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Normal") ?
"SELECT B.Title, B.PublisherName, CONCAT(BA.AuthorLastName, '. ', BA.AuthorFirstName) as Author\n" +
"FROM book B, (SELECT * \n" +
" FROM book_authors\n" +
" WHERE AuthorLastName LIKE '%" + f1 + "%' and " +
" AuthorFirstName LIKE '%" + f2 + "%') as BA\n" +
"WHERE BA.BookID = B.BookID\n" +
"ORDER BY 1;\n" : queryToggleString.equals("Join") ?
"SELECT B.Title, B.PublisherName, CONCAT(BA.AuthorLastName, '. ', BA.AuthorFirstName) as Author\n" +
"FROM book B join (SELECT * \n" +
" FROM book_authors\n" +
" WHERE AuthorLastName LIKE '%" + f1 + "%' and " +
" AuthorFirstName LIKE '%" + f2 + "%' ) as BA on BA.BookID = B.BookID\n" +
"ORDER BY 1;" : /*Subquery*/
"SELECT B.Title, B.PublisherName, \n" +
"\t\tCONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as Author\n" +
"\t\tFROM book B, (SELECT * \n" +
"\t\t FROM book_authors\n" +
"\t\t WHERE AuthorLastName LIKE '%" + f1 + "%' and AuthorFirstName LIKE '%" + f2 + "%' ) as BA\n" +
"\t\tWHERE BA.BookID = B.BookID\n" +
"\t\tORDER BY 1;";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getString("Title"));
rowData.add(rs.getString("PublisherName"));
rowData.add(rs.getString("Author"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery5() {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Normal") ?
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, B.PublisherName\n" +
"FROM book B, book_authors BA\n" +
"WHERE B.BookID NOT IN (SELECT BookID\n" +
" FROM book_loans) and B.BookID = BA.BookID\n" +
"GROUP BY B.BookID\n" +
"ORDER BY 3, 2;" : queryToggleString.equals("Join") ?
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, B.PublisherName\n" +
"\tFROM book B inner join book_authors BA on \n" +
"\tB.BookID NOT IN (SELECT BookID\n" +
"\tFROM book_loans) and B.BookID = BA.BookID" : /*Subquery*/
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, B.PublisherName\n" +
"\t\tFROM book B inner join book_authors BA on \n" +
"\t\tB.BookID NOT IN (SELECT BookID\n" +
"\tFROM book_loans) and B.BookID = BA.BookID;";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getInt("BookID") + "");
rowData.add(rs.getString("Title"));
rowData.add(rs.getString("AuthorName"));
rowData.add(rs.getString("PublisherName"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery6() {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Normal") ?
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) as " +
"BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO, book_loans BL, library_branch LB\n" +
"WHERE BO.CardNo IN (SELECT CardNo \n" +
" FROM book_loans) AND BO.Address = LB.BranchAddress AND BL.BranchID = LB.BranchID\n" +
"GROUP BY BorrowerName\n" +
"ORDER BY 2;\n" : queryToggleString.equals("Join") ?
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, \", \", BO.BorrowerFName) " +
"as BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO join book_loans BL on BO.CardNo IN (SELECT CardNo \n" +
"FROM book_loans) join library_branch LB on BO.Address = " +
"LB.BranchAddress and BL.BranchID = LB.BranchID\n" : /*Subquery*/
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) " +
"as BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO, book_loans BL, library_branch LB\n" +
"WHERE BO.CardNo IN (SELECT CardNo \n" +
" FROM book_loans) AND BO.Address = LB.BranchAddress AND BL.BranchID = LB.BranchID";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getInt("CardNo") + "");
rowData.add(rs.getString("BorrowerName"));
rowData.add(rs.getInt("BranchID") + "");
rowData.add(rs.getString("BranchName"));
rowData.add(rs.getString("BranchAddress"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery7(String filter) {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Normal") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) AS BorrowerName, " +
"BL.BookID, B.Title, CONCAT(BA.AuthorLastName, ', ', " +
"BA.AuthorFirstName) as AuthorName, BL.DueDate, BL.DateReturned\n" +
"FROM book B, book_authors BA, book_loans BL, borrower BO\n" +
"WHERE B.BookID = BA.BookID AND BA.BookID = BL.BookID AND " +
"BL.CardNo AND BL.DueDate = BL.DateReturned\n" +
"LIMIT 0, " + filter : queryToggleString.equals("Join") ?
"SELECT CONCAT(BO.BorrowerFName, \", \" , BO.BorrowerLName) AS " +
"BorrowerName, BL.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", " +
"BA.AuthorFirstName) as AuthorName, BL.DueDate, BL.DateReturned\n" +
"FROM book B join book_authors BA on B.BookID = BA.BookID join book_loans " +
"BL on BA.BookID = BL.BookID join borrower BO on BL.DueDate = BL.DateReturned\n" +
"LIMIT 0, " + filter: /*Subquery*/
"SELECT O.BorrowerName, A.AuthorName, D.BookID, D.DueDate, D.DateReturned\n" +
"FROM (SELECT BL.BookID, BL.DateReturned, BL.DueDate, BL.CardNo\n" +
" FROM book_loans BL\n" +
" WHERE BL.DateReturned = BL.DueDate) AS D, (SELECT BA.BookID, " +
" CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName\n" +
" FROM book_authors BA) as A, (SELECT B.BookID, B.Title\n" +
" FROM book B) as B, (SELECT BO.CardNo, " +
" CONCAT(BO.BorrowerFName, \", \" , BO.BorrowerLName) AS BorrowerName\n" +
" FROM borrower BO) as O\n" +
"WHERE D.BookID = A.BookID AND B.BookID = D.BookID AND O.CardNo = D.CardNo \n" +
"LIMIT 0, " + filter;
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getString("BorrowerName"));
rowData.add(rs.getInt("BookID") + "");
rowData.add(rs.getString("Title"));
rowData.add(rs.getString("AuthorName"));
rowData.add(rs.getString("DueDate"));
rowData.add(rs.getString("DateReturned"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery8() {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Join") ?
"SELECT BL.BranchID, LB.BranchName, BL.BookID, BL.NoTimesLoaned, " +
"B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, " +
"P.PublisherName, P.Address AS PublisherAddress\n" +
"FROM book B join book_authors BA on B.BookID = BA.BookID join library_branch " +
"LB join publisher P on B.PublisherName = P.PublisherName join " +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned FROM book_loans " +
"GROUP BY BranchID, BookID) AS BL on BL.BranchID = LB.BranchID and BL.BookID = B.BookID\n" +
"join (SELECT TEMP.BranchID, MAX(TEMP.NoTimesLoaned) AS NoTimesLoaned FROM\n" +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned FROM BOOK_LOANS GROUP BY " +
"BranchID, BookID) AS TEMP GROUP BY TEMP.BranchID) AS C on BL.BranchID = " +
"C.BranchID AND BL.NoTimesLoaned = C.NoTimesLoaned\n" +
"GROUP BY BL.BranchID\n" +
"ORDER BY 2, 5;" : /*Normal & subquery*/
"SELECT BL.BranchID, LB.BranchName, BL.BookID, BL.NoTimesLoaned, " +
"B.Title, CONCAT(BA.AuthorLastName, ', ', BA.AuthorFirstName) as " +
"AuthorName, P.PublisherName, P.Address AS PublisherAddress\n" +
"FROM book B, book_authors BA, library_branch LB, publisher P, " +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned\n" +
"FROM book_loans\n" +
"GROUP BY BranchID, BookID) AS BL,\n" +
"(SELECT TEMP.BranchID,\n" +
"MAX(TEMP.NoTimesLoaned)\n" +
"AS NoTimesLoaned\n" +
"FROM\n" +
"(SELECT BranchID, BookID,\n" +
"COUNT(*) AS NoTimesLoaned\n" +
"FROM BOOK_LOANS\n" +
"GROUP BY BranchID, BookID) AS TEMP\n" +
"GROUP BY TEMP.BranchID) AS C\n" +
"WHERE\n" +
"BL.BranchID = C.BranchID AND\n" +
"BL.NoTimesLoaned = C.NoTimesLoaned AND\n" +
"BL.BranchID = LB.BranchID AND\n" +
"BL.BookID = B.BookID AND\n" +
"B.BookID = BA.BookID AND\n" +
"B.PublisherName = P.PublisherName\n" +
"GROUP BY BL.BranchID\n" +
"ORDER BY 2, 5;\n";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getInt("BranchID") + "");
rowData.add(rs.getString("BranchName"));
rowData.add(rs.getInt("BookID") + "");
rowData.add(rs.getInt("NoTimesLoaned") + "");
rowData.add(rs.getString("Title"));
rowData.add(rs.getString("AuthorName"));
rowData.add(rs.getString("PublisherName"));
rowData.add(rs.getString("PublisherAddress"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
private void deleteAllIndex() {
//Connection conn = getConnection(); called at the start
Statement st = null;
Statement st2 = null;
ResultSet rs = null;
String query = "SELECT DISTINCT\n" +
" TABLE_NAME,\n" +
" INDEX_NAME\n" +
"FROM INFORMATION_SCHEMA.STATISTICS\n" +
"WHERE TABLE_SCHEMA = 'mco1_db' AND INDEX_NAME != 'PRIMARY';";
try {
st = conn.createStatement();
st2 = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
query = "DROP INDEX " + rs.getString("INDEX_NAME") + " ON " + rs.getString("TABLE_NAME");
st2.executeUpdate(query);
System.out.println("Deleted index: " + rs.getString("INDEX_NAME"));
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
}
private void terminateProgram() {
if (conn != null)
try {
deleteAllIndex();
conn.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
}
System.out.println("\nProgram has been terminated.");
Platform.exit();
System.exit(0);
}
public Connection getConnection() {
Connection tempConn = null;
String driver = "com.mysql.jdbc.Driver";
String db = "mco1_db";
String url = "jdbc:mysql://localhost/" + db + "?useSSL=false";
String user = "root";
String pass = "1234";
try {
Class.forName(driver);
tempConn = DriverManager.getConnection(url, user, pass);
System.out.println("Connected to database : " + db);
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException");
}
return tempConn;
}
/* Filters the table *************************************/
// public EventHandler<KeyEvent> filterRoutesTable() {
// return new EventHandler<KeyEvent>() {
// @Override
// @SuppressWarnings("unchecked")
// public void handle(KeyEvent e) {
// ObservableList<Route> routes = FXCollections.observableArrayList();
//
// //Connection conn = getConnection(); called at the start
// Statement st = null;
// ResultSet rs = null;
// String query = new String(" ");
// TextField text = (TextField) e.getSource();
// if(userRider){
// query = "SELECT l.landmarkName as `Starting Point`, l2.landmarkName as `End Point`, r.mins as `Minutes`, r.fare as `Fare` " +
// "FROM landmarks l, landmarks l2, route r " +
// "WHERE `r`.pickupLoc = l.landmarkID AND r.dropoffLoc = l2.landmarkId " +
// "AND l.landmarkName LIKE '%" + startingTextField.getText() + "%'" +
// "AND l2.landmarkName LIKE '%" + endingTextField.getText() + "%'" +
// "AND r.mins LIKE '%" + minutesTextField.getText() + "%'" +
// "AND r.fare LIKE '%" + fareTextField.getText() + "%';";
// }
// else
// query = "SELECT l.landmarkName as `Starting Point`, l2.landmarkName as `End Point`, r.mins as `Minutes`, r.fare as `Fare` " +
// ", CONCAT(ri.firstName, \" \", ri.lastName) AS `Rider Name`, ri.rating AS `Rating` " +
// "FROM landmarks l, landmarks l2, route r, riderInfo ri, transaction t " +
// "WHERE r.pickupLoc = l.landmarkID AND r.dropoffLoc = l2.landmarkId AND " +
// "t.routeId = r.routeId AND ri.riderId = t.riderId AND t.driverId = 0 "+
// "AND l.landmarkName LIKE '%" + startingTextField.getText() + "%'" +
// "AND l2.landmarkName LIKE '%" + endingTextField.getText() + "%'" +
// "AND r.mins LIKE '%" + minutesTextField.getText() + "%'" +
// "AND r.fare LIKE '%" + fareTextField.getText() + "%'" +
// "AND CONCAT(ri.firstName, \" \", ri.lastName) LIKE '%" + riderTextField.getText() + "%'" +
// "AND ri.rating LIKE '%" + ratingTextField.getText() + "%'";
//
// try {
//
// st = conn.createStatement();
// rs = st.executeQuery(query);
//
// while(rs.next()){
// Route r = new Route(rs.getString("Starting Point"), rs.getString("End Point"),
// rs.getInt("Minutes"), rs.getInt("Fare"));
// if(!userRider){
// r.setRider(rs.getString("Rider Name"));
// r.setRating(rs.getString("Rating"));
// }
//
// routes.add(r);
// }
// st.close();
// rs.close();
// } catch (SQLException e2) {
// System.out.println("SQLException: " + e2.getMessage());
// System.out.println("SQLState: " + e2.getSQLState());
// System.out.println("VendorError: " + e2.getErrorCode());
// }
//
// //Starting Point Column
// TableColumn<Route, String> startingColumn= new TableColumn<>("Starting Point");
// startingColumn.setMinWidth(100);
// startingColumn.setCellValueFactory(new PropertyValueFactory<>("start"));
//
// //End Point Column
// TableColumn<Route, String> endColumn= new TableColumn<>("End Point");
// endColumn.setMinWidth(100);
// endColumn.setCellValueFactory(new PropertyValueFactory<>("end"));
//
// //Minutes Column
// TableColumn<Route, String> minutesColumn= new TableColumn<>("Minutes");
// minutesColumn.setMinWidth(75);
// minutesColumn.setCellValueFactory(new PropertyValueFactory<>("Minutes"));
//
// //Fare Column
// TableColumn<Route, String> fareColumn= new TableColumn<>("Fare");
// fareColumn.setMinWidth(75);
// fareColumn.setCellValueFactory(new PropertyValueFactory<>("fare"));
//
// if(userRider){
// filterVBox.getChildren().remove(routesTable);
// routesTable = new TableView<Route>();
// routesTable.setItems(routes);
// routesTable.getColumns().addAll(startingColumn, endColumn, minutesColumn, fareColumn);
// routesTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// filterVBox.getChildren().add(0, routesTable);
// }
//
// else {
// //Rider Info Column
// TableColumn<Route, String> riderInfoColumn= new TableColumn<>("Rider Name");
// riderInfoColumn.setMinWidth(75);
// riderInfoColumn.setCellValueFactory(new PropertyValueFactory<>("rider"));
//
// //Rating Column
// TableColumn<Route, String> ratingColumn= new TableColumn<>("Rating");
// ratingColumn.setMinWidth(75);
// ratingColumn.setCellValueFactory(new PropertyValueFactory<>("Rating"));
//
// filterVBox.getChildren().remove(driverTable);
// driverTable = new TableView<Route>();
// driverTable.setItems(routes);
// driverTable.getColumns().addAll(startingColumn, endColumn, minutesColumn, fareColumn, riderInfoColumn, ratingColumn);
// driverTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// filterVBox.getChildren().add(0, driverTable);
// }
// }
// };
// }
/*****************************************************************************************/
/* Numeric Validation Limit the characters to maxLength AND to ONLY DigitS *************************************/
// public EventHandler<KeyEvent> numeric_Validation(final Integer max_Length) {
// return new EventHandler<KeyEvent>() {
// @Override
// public void handle(KeyEvent e) {
// TextField txt_TextField = (TextField) e.getSource();
// if (max_Length > 0 && txt_TextField.getText().length() >= max_Length) {
// e.consume();
// }
// if(e.getCharacter().matches("[0-9.]")){
// if(txt_TextField.getText().contains(".") && e.getCharacter().matches("[.]")){
// e.consume();
// }else if(txt_TextField.getText().length() == 0 && e.getCharacter().matches("[.]")){
// e.consume();
// }
// }else{
// e.consume();
// }
// }
// };
// }
/*****************************************************************************************/
/* Letters Validation Limit the characters to maxLength AND to ONLY Letters *************************************/
// public EventHandler<KeyEvent> numOfLetters_Validation(final Integer max_Length) {
// return new EventHandler<KeyEvent>() {
// @Override
// public void handle(KeyEvent e) {
// TextField txt_TextField = (TextField) e.getSource();
// if (max_Length > 0 && txt_TextField.getText().length() >= max_Length) {
// e.consume();
// }
// if(!(e.getCharacter().matches("[A-Za-z]")))
// e.consume();
// }
// };
// }
/*****************************************************************************************/
} | UTF-8 | Java | 85,112 | java | Driver.java | Java | [
{
"context": "ak;\n\n case \"4. All books written by Burningpeak, Loni\":\n editQueryVBox = new V",
"end": 13460,
"score": 0.9153832197189331,
"start": 13449,
"tag": "NAME",
"value": "Burningpeak"
},
{
"context": " case \"4. All books written by Burningpeak, Loni\":\n editQueryVBox = new VBox(2)",
"end": 13466,
"score": 0.997949481010437,
"start": 13462,
"tag": "NAME",
"value": "Loni"
},
{
"context": "k\");\n input_2 = new TextField(\"Loni\");\n editQueryVBox.getChildren(",
"end": 13697,
"score": 0.9784929752349854,
"start": 13693,
"tag": "NAME",
"value": "Loni"
},
{
"context": "k\");\n input_2 = new TextField(\"Loni\");\n editQueryVBox.getChildren(",
"end": 19165,
"score": 0.6316701173782349,
"start": 19161,
"tag": "NAME",
"value": "Loni"
},
{
"context": "oks\",\n \"4. All books written by Burningpeak, Loni\",\n \"5. All books which were ne",
"end": 31552,
"score": 0.9947682619094849,
"start": 31535,
"tag": "NAME",
"value": "Burningpeak, Loni"
},
{
"context": " String user = \"root\";\n String pass = \"1234\";\n\n try {\n Class.forName(driver",
"end": 76276,
"score": 0.9993299841880798,
"start": 76272,
"tag": "PASSWORD",
"value": "1234"
}
] | null | [] | import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
//import javafx.scene.input.KeyCombination;
public class Driver extends Application {
Scene home;
Button button;
TableView<ArrayList<String>> table;
BorderPane mainPane = new BorderPane();
Label queryNum = new Label(),
query = new Label();
Button optimizeButton;
ChoiceBox<String> queryChoiceBox;
Connection conn;
private LineChart graphArea;
private XYChart.Series dataSeries1;
private int nQueryExec = 1;
private TextField input,
input_2;
private ToggleGroup queryTypeToggleGroup;
@SuppressWarnings("unchecked")
public void start(Stage primaryStage) throws Exception {
conn = getConnection();
deleteAllIndex();
initMainScreen();
home = new Scene(mainPane, 1000, 600);
home.getStylesheets().add("View/Style.css");
primaryStage.setTitle("ADVANDB - MP1");
primaryStage.setOnCloseRequest(e -> terminateProgram());
primaryStage.setScene(home);
primaryStage.show();
}
public void initMainScreen() {
mainPane.getChildren().remove(mainPane.getCenter());
mainPane.setTop(initTopBar());
mainPane.setCenter(initCenterVBox());
mainPane.setRight(initRightVBox());
}
public MenuBar initTopBar() {
//Initializing menu items
Menu refreshIndex = new Menu(),
optimization = new Menu(),
exit = new Menu();
Label refreshLabelMenu = new Label("Refresh"),
optimizationLabelMenu = new Label("Optimization");
refreshLabelMenu.setOnMouseClicked(e -> deleteAllIndex());
optimizationLabelMenu.setOnMouseClicked(e -> {
Stage myDialog = new Stage();
myDialog.initModality(Modality.WINDOW_MODAL);
GridPane optimizePane = new GridPane();
optimizePane.setVgap(20);
optimizePane.setHgap(25);
optimizePane.setAlignment(Pos.CENTER);
Scene dialogScene = new Scene(optimizePane, 800, 400);
ChoiceBox optimizationType = new ChoiceBox<>();
optimizationType.getItems().addAll("Create Indexes");
optimizePane.add(new Label("Method"), 0, 0);
optimizePane.add(optimizationType, 1, 0);
optimizationType.getSelectionModel().selectedIndexProperty().addListener((observableValue, number, number2) -> {
switch ((Integer) number2) {
case 0: indexOptimization(optimizePane);
break;
}
});
myDialog.setTitle("Query Optimization");
dialogScene.getStylesheets().add("View/Style.css");
myDialog.setScene(dialogScene);
myDialog.show();
});
refreshIndex.setGraphic(refreshLabelMenu);
optimization.setGraphic(optimizationLabelMenu);
optimizationLabelMenu = new Label("Exit");
exit.setGraphic(optimizationLabelMenu);
optimizationLabelMenu.setOnMouseClicked(e -> terminateProgram());
MenuBar menuBar = new MenuBar();
menuBar.getMenus().addAll(refreshIndex, optimization, exit);
return menuBar;
}
public void indexOptimization(GridPane optimizePane){
ChoiceBox tableChoiceBox = new ChoiceBox<>();
ChoiceBox attrChoiceBox = new ChoiceBox<>();
optimizeButton = new Button("Optimize");
optimizeButton.setDisable(true);
optimizeButton.setOnAction(e -> {
Statement st = null;
String query = "create index i" +attrChoiceBox.getSelectionModel().getSelectedItem().toString() + " on " +
tableChoiceBox.getSelectionModel().getSelectedItem().toString()+ "(" +
attrChoiceBox.getSelectionModel().getSelectedItem().toString() + ") ";
try{
st = conn.createStatement();
st.executeUpdate(query);
st.close();
System.out.println("Added new index: i" + attrChoiceBox.getSelectionModel().getSelectedItem().toString());
} catch (SQLException e2) {
System.out.println("SQLException: " + e2.getMessage());
System.out.println("SQLState: " + e2.getSQLState());
System.out.println("VendorError: " + e2.getErrorCode());
}
});
tableChoiceBox.getItems().addAll("book", "book_author", "book_loans", "borrower", "library_branch", "publisher");
tableChoiceBox.getSelectionModel().selectedIndexProperty().addListener((observableValue, number, number2) -> {
optimizeButton.setDisable(true);
attrChoiceBox.getItems().clear();
switch ((Integer) number2) {
case 0: attrChoiceBox.getItems().addAll("BookID", "Title", "PublisherName");
break;
case 1: attrChoiceBox.getItems().addAll("BookID", "AuthorLastName", "AuthorFirstName");
break;
case 2: attrChoiceBox.getItems().addAll("BookID", "BranchID", "CardNo", "DateOut", "DueDate", "DateReturned");
break;
case 3: attrChoiceBox.getItems().addAll("CardNo", "BorrowerLName", "BorrowerFName", "Address", "Phone");
break;
case 4: attrChoiceBox.getItems().addAll("BranchID", "BranchName", "BranchAddress");
break;
case 5: attrChoiceBox.getItems().addAll("PublisherName", "Address", "Phone");
break;
}
attrChoiceBox.getSelectionModel().selectedIndexProperty().addListener((observableValue1,
oldNum,
newNum) ->
optimizeButton.setDisable(false));
});
optimizePane.add(new Label("Table"), 0, 1);
optimizePane.add(tableChoiceBox, 1, 1);
optimizePane.add(new Label("Attribute"), 0, 2);
optimizePane.add(attrChoiceBox, 1, 2);
optimizePane.add(optimizeButton, 1, 3);
}
public VBox initRightVBox() {
VBox mainVBox = new VBox(15);
mainVBox.setAlignment(Pos.TOP_CENTER);
mainVBox.setPadding(new Insets(10, 0, 0, 0));
button = new Button("Edit Query");
button.getStyleClass().add("rightVBoxButton");
button.setMinWidth(150);
button.wrapTextProperty().setValue(true);
button.setOnAction(event -> {
Label label = new Label(queryChoiceBox.getValue().toString());
label.getStyleClass().add("editQueryLabel");
VBox subVBox = new VBox(10);
subVBox.getStyleClass().add("subVBox");
subVBox.getChildren().add(label);
System.out.println("\nEDIT QUERY: " + queryChoiceBox.getValue());
button = new Button("Update Query");
button.setMinWidth(150);
mainVBox.getChildren().add(subVBox);
VBox editQueryVBox;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
switch (queryChoiceBox.getSelectionModel().getSelectedItem().toString()) {
case "1. All books published by Doubleday":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("Doubleday");
editQueryVBox.getChildren().addAll(new Label("SELECT Title, PublisherName \n" +
"FROM book \n" +
"WHERE PublisherName like \n'%"), input,
new Label("%'\n ORDER BY PublisherName;"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery1((VBox) mainPane.getCenter(), input.getText());
});
break;
case "2. Number of books loaned in 2017":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("2017");
editQueryVBox.getChildren().addAll(new Label("SELECT COUNT(*) AS NoBooksBor\n" +
"FROM book_loans\n" +
"WHERE YEAR(DateOut) = "), input);
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery2((VBox) mainPane.getCenter(), input.getText());
});
break;
case "3. All borrowers who have borrowed at most 2 books":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("0");
input_2 = new TextField("2");
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Normal") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) AS BorrowerName, COUNT(*) as NoBooksBor\n" +
"FROM borrower BO, book_loans BL\n" +
"WHERE BO.CardNo = BL.CardNo\n" +
"GROUP BY BorrowerName\n" +
"HAVING NoBooksBor >= ": queryToggleString.equals("Join") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) as BorrowerName , COUNT(*) as NoBooksBor\n" +
"\tFROM borrower BO join book_loans BL on BO.CardNo = BL.CardNo\n" +
"\tGROUP BY BorrowerName\n" +
"HAVING NoBooksBor >= ": /*SubQuery*/
"SELECT CONCAT(BorrowerLName, \", \", BorrowerFName) as BorrowerName, BO2.NoBooksBor\n" +
"\tFROM borrower, (SELECT BL.CardNo, COUNT(CardNo) as NoBooksBor\n" +
"\tFROM book_loans BL\n" +
"\tGROUP BY BL.CardNo\n" +
"\tHAVING COUNT(CardNo) >= "), input,
new Label(queryToggleString.equals("Normal") ?
" and NoBooksBor <= ": queryToggleString.equals("Join") ?
" and NoBooksBor <= " : /*SubQuery*/
" 0 and COUNT(CardNo) <= "), input_2,
new Label(queryToggleString.equals("Normal") ?
"ORDER BY 2 DESC, 1;\n" : queryToggleString.equals("Join") ?
"ORDER BY 2 DESC, 1;" : /*SubQuery*/
"ORDER BY 1) as BO2\n" +
"WHERE borrower.CardNo = BO2.CardNo\n" +
"ORDER BY 2 DESC;"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery3((VBox) mainPane.getCenter(), input.getText(), input_2.getText());
});
break;
case "4. All books written by Burningpeak, Loni":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("Burningpeak");
input_2 = new TextField("Loni");
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Normal") ?
"SELECT B.Title, B.PublisherName, CONCAT(BA.AuthorLastName, '. ', BA.AuthorFirstName) as Author\n" +
"FROM book B, (SELECT * \n" +
" FROM book_authors\n" +
" WHERE AuthorLastName LIKE '%" : queryToggleString.equals("Join") ?
"SELECT B.Title, B.PublisherName, CONCAT(BA.AuthorLastName, '. ', BA.AuthorFirstName) as Author\n" +
"FROM book B join (SELECT * \n" +
" FROM book_authors\n" +
" WHERE AuthorLastName LIKE '%" : /*Subquery*/
"SELECT B.Title, B.PublisherName, \n" +
"\t\tCONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as Author\n" +
"\t\tFROM book B, (SELECT * \n" +
"\t\t FROM book_authors\n" +
"\t\t WHERE AuthorLastName LIKE '%"), input,
new Label(queryToggleString.equals("Normal") ?
"%' and AuthorFirstName LIKE '%" : queryToggleString.equals("Join") ?
"%' and AuthorFirstName LIKE '%" : "%' and AuthorFirstName LIKE '%"), input_2,
new Label(queryToggleString.equals("Normal") ?
"%') as BA\n" +
"WHERE BA.BookID = B.BookID\n" +
"ORDER BY 1;\n" : queryToggleString.equals("Join") ?
"%' ) as BA on BA.BookID = B.BookID\n" +
"ORDER BY 1;" : /*Subquery*/
"%' ) as BA\n" +
"WHERE BA.BookID = B.BookID\n" +
"ORDER BY 1;"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery4((VBox) mainPane.getCenter(), input.getText(), input_2.getText());
});
break;
case "5. All books which were never loaned out (nobody borrowed them)":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Normal") ?
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLName, \", \", " +
"BA.AuthorFName) as AuthorName, B.PublisherName\n" +
"FROM book B, book_authors BA\n" +
"WHERE B.BookID NOT IN (SELECT BookID\n" +
" FROM book_loans)\n" +
" and B.BookID = BA.BookID" +
"GROUP BY B.BookID\n" +
"ORDER BY 3, 2;\n" : queryToggleString.equals("Join") ?
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, B.PublisherName\n" +
"\tFROM book B inner join book_authors BA on \n" +
"\tB.BookID NOT IN (SELECT BookID\n" +
"\tFROM book_loans) and B.BookID = BA.BookID" : /*Subquery*/
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, B.PublisherName\n" +
"\t\tFROM book B inner join book_authors BA on \n" +
"\t\tB.BookID NOT IN (SELECT BookID\n" +
"\tFROM book_loans) and B.BookID = BA.BookID;"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery5((VBox) mainPane.getCenter());
});
break;
case "6. All borrowers who have loaned books in their own branch":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("Burningpeak");
input_2 = new TextField("Loni");
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Normal") ?
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) as " +
"BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO, book_loans BL, library_branch LB\n" +
"WHERE BO.CardNo IN (SELECT CardNo \n" +
" FROM book_loans) AND BO.Address = LB.BranchAddress AND BL.BranchID = LB.BranchID\n" +
"GROUP BY BorrowerName\n" +
"ORDER BY 2;\n" : queryToggleString.equals("Join") ?
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, \", \", BO.BorrowerFName) " +
"as BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO join book_loans BL on BO.CardNo IN (SELECT CardNo \n" +
"FROM book_loans) join library_branch LB on BO.Address = " +
"LB.BranchAddress and BL.BranchID = LB.BranchID\n" : /*Subquery*/
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) " +
"as BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO, book_loans BL, library_branch LB\n" +
"WHERE BO.CardNo IN (SELECT CardNo \n" +
" FROM book_loans) AND BO.Address = LB.BranchAddress AND BL.BranchID = LB.BranchID"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery6((VBox) mainPane.getCenter());
});
break;
case "7. First 100 book loans that were returned exactly on their due date":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
input = new TextField("100");
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Normal") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) AS BorrowerName, " +
"BL.BookID, B.Title, CONCAT(BA.AuthorLastName, ', ', " +
"BA.AuthorFirstName) as AuthorName, BL.DueDate, BL.DateReturned\n" +
"FROM book B, book_authors BA, book_loans BL, borrower BO\n" +
"WHERE B.BookID = BA.BookID AND BA.BookID = BL.BookID AND " +
"BL.CardNo AND BL.DueDate = BL.DateReturned\n" +
"LIMIT 0, " : queryToggleString.equals("Join") ?
"SELECT CONCAT(BO.BorrowerFName, \", \" , BO.BorrowerLName) AS " +
"BorrowerName, BL.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", " +
"BA.AuthorFirstName) as AuthorName, BL.DueDate, BL.DateReturned\n" +
"FROM book B join book_authors BA on B.BookID = BA.BookID join book_loans " +
"BL on BA.BookID = BL.BookID join borrower BO on BL.DueDate = BL.DateReturned\n" +
"LIMIT 0, " : /*Subquery*/
"SELECT O.BorrowerName, A.AuthorName, D.BookID, D.DueDate, D.DateReturned\n" +
"FROM (SELECT BL.BookID, BL.DateReturned, BL.DueDate, BL.CardNo\n" +
" FROM book_loans BL\n" +
" WHERE BL.DateReturned = BL.DueDate) AS D, (SELECT BA.BookID, " +
" CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName\n" +
" FROM book_authors BA) as A, (SELECT B.BookID, B.Title\n" +
" FROM book B) as B, (SELECT BO.CardNo, " +
" CONCAT(BO.BorrowerFName, \", \" , BO.BorrowerLName) AS BorrowerName\n" +
" FROM borrower BO) as O\n" +
"WHERE D.BookID = A.BookID AND B.BookID = D.BookID AND O.CardNo = D.CardNo \n" +
"LIMIT 0, "), input);
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery7((VBox) mainPane.getCenter(), input.getText());
});
break;
case "8. Most popular title (most loaned out title) for each branch":
editQueryVBox = new VBox(2);
editQueryVBox.setPadding(new Insets(0, 10, 0, 10));
editQueryVBox.getChildren().addAll(new Label(queryToggleString.equals("Join") ?
"SELECT BL.BranchID, LB.BranchName, BL.BookID, BL.NoTimesLoaned, " +
"B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, " +
"P.PublisherName, P.Address AS PublisherAddress\n" +
"FROM book B join book_authors BA on B.BookID = BA.BookID join library_branch " +
"LB join publisher P on B.PublisherName = P.PublisherName join " +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned FROM book_loans " +
"GROUP BY BranchID, BookID) AS BL on BL.BranchID = LB.BranchID and BL.BookID = B.BookID\n" +
"join (SELECT TEMP.BranchID, MAX(TEMP.NoTimesLoaned) AS NoTimesLoaned FROM\n" +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned FROM BOOK_LOANS GROUP BY " +
"BranchID, BookID) AS TEMP GROUP BY TEMP.BranchID) AS C on BL.BranchID = " +
"C.BranchID AND BL.NoTimesLoaned = C.NoTimesLoaned\n" +
"GROUP BY BL.BranchID\n" +
"ORDER BY 2, 5;" : /*Normal & subquery*/
"SELECT BL.BranchID, LB.BranchName, BL.BookID, BL.NoTimesLoaned, " +
"B.Title, CONCAT(BA.AuthorLastName, ', ', BA.AuthorFirstName) as " +
"AuthorName, P.PublisherName, P.Address AS PublisherAddress\n" +
"FROM book B, book_authors BA, library_branch LB, publisher P, " +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned\n" +
"FROM book_loans\n" +
"GROUP BY BranchID, BookID) AS BL,\n" +
"(SELECT TEMP.BranchID,\n" +
"MAX(TEMP.NoTimesLoaned)\n" +
"AS NoTimesLoaned\n" +
"FROM\n" +
"(SELECT BranchID, BookID,\n" +
"COUNT(*) AS NoTimesLoaned\n" +
"FROM BOOK_LOANS\n" +
"GROUP BY BranchID, BookID) AS TEMP\n" +
"GROUP BY TEMP.BranchID) AS C\n" +
"WHERE\n" +
"BL.BranchID = C.BranchID AND\n" +
"BL.NoTimesLoaned = C.NoTimesLoaned AND\n" +
"BL.BranchID = LB.BranchID AND\n" +
"BL.BookID = B.BookID AND\n" +
"B.BookID = BA.BookID AND\n" +
"B.PublisherName = P.PublisherName\n" +
"GROUP BY BL.BranchID\n" +
"ORDER BY 2, 5;\n"));
subVBox.getChildren().addAll(editQueryVBox, button);
button.setOnAction(event1 -> {
if (((VBox)mainPane.getCenter()).getChildren().get(2) instanceof TableView)
((VBox)mainPane.getCenter()).getChildren().remove(2);
table = new TableView<>();
mainVBox.getChildren().remove(3);
updateTableQuery8((VBox) mainPane.getCenter());
});
break;
}
});
queryTypeToggleGroup = new ToggleGroup();
RadioButton normal = new RadioButton("Normal");
normal.setToggleGroup(queryTypeToggleGroup);
normal.setUserData("Normal");
normal.setSelected(true);
RadioButton join = new RadioButton("Join");
join.setToggleGroup(queryTypeToggleGroup);
join.setUserData("Join");
RadioButton subquery = new RadioButton("Subquery");
subquery.setToggleGroup(queryTypeToggleGroup);
subquery.setUserData("Subquery");
queryTypeToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
@Override
public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) {
System.out.println(new_toggle.getUserData().toString());
switch (new_toggle.getUserData().toString()) {
case "Normal": /* normal queries */
break;
case "Join":
break;
case "Subquery":
break;
}
}
});
VBox radioButtonVBox = new VBox(5);
radioButtonVBox.setPadding(new Insets(0, 10, 0, 10));
radioButtonVBox.getChildren().addAll(normal, join, subquery);
mainVBox.getChildren().addAll(radioButtonVBox, new Separator(Orientation.HORIZONTAL), button);
mainVBox.setMinWidth(200);
mainVBox.setMaxWidth(500);
return mainVBox;
}
public VBox initCenterVBox() {
VBox vBox = new VBox();
HBox hBox;
vBox.getStyleClass().add("vBoxCenter");
Pane field = new Pane();
field.setId("centerPane");
if (conn == null) {
vBox.getChildren().add(new Label("Unable to connect to the database, check getConnection()"));
} else {
ImageView queryIcon = new ImageView("View/Images/queryIcon.png");
queryIcon.setFitHeight(25);
queryIcon.setFitWidth(25);
queryIcon.setPreserveRatio(true);
queryChoiceBox = new ChoiceBox<>();
queryChoiceBox.getItems().addAll("",
"1. All books published by Doubleday",
"2. Number of books loaned in 2017",
"3. All borrowers who have borrowed at most 2 books",
"4. All books written by <NAME>",
"5. All books which were never loaned out (nobody borrowed them)",
"6. All borrowers who have loaned books in their own branch",
"7. First 100 book loans that were returned exactly on their due date",
"8. Most popular title (most loaned out title) for each branch");
queryChoiceBox.setValue("");
queryChoiceBox.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
restartProfiling();
queryNum.setText("Query #" + number2);
query.setText(queryChoiceBox.getItems().get((Integer) number2));
graphArea.getData().clear();
dataSeries1 = new XYChart.Series();
graphArea.getData().add(dataSeries1);
nQueryExec = 1;
if (vBox.getChildren().get(2) instanceof TableView)
vBox.getChildren().remove(2);
table = new TableView<>();
switch ((Integer) number2) {
case 0:
break;
case 1:
updateTableQuery1(vBox, "Doubleday");
break;
case 2:
updateTableQuery2(vBox, "2017");
break;
case 3:
updateTableQuery3(vBox, "0", "2");
break;
case 4:
updateTableQuery4(vBox, "Burningpeak", "Loni");
break;
case 5:
updateTableQuery5(vBox);
break;
case 6:
updateTableQuery6(vBox);
break;
case 7:
updateTableQuery7(vBox, "100");
break;
case 8:
updateTableQuery8(vBox);
break;
default:
System.out.println("Query choice box selection model not in the range");
}
System.out.println("\n" + queryChoiceBox.getItems().get((Integer) number2));
}
});
queryNum.setText("Query #" + 0);
queryNum.getStyleClass().add("headerText");
queryNum.setAlignment(Pos.BASELINE_LEFT);
hBox = new HBox(10);
hBox.setAlignment(Pos.CENTER);
Button button = new Button("Run");
hBox.getChildren().addAll(queryIcon, queryChoiceBox, button);
vBox.getChildren().add(0, queryNum);
vBox.getChildren().add(1, hBox);
button.setOnAction(e -> {
refreshTable();
nQueryExec += 1;
String queryNumText = queryNum.getText();
VBox tempvBox = new VBox();
tempvBox.getChildren().addAll(new Label());
tempvBox.getChildren().addAll(new Label());
table = new TableView<>();
switch (queryNumText.charAt(queryNumText.length() - 1)) {
case '0':
break;
case '1':
updateTableQuery1(tempvBox, "Doubleday");
break;
case '2':
updateTableQuery2(tempvBox, "2017");
break;
case '3':
updateTableQuery3(tempvBox, "0", "2");
break;
case '4':
updateTableQuery4(tempvBox, "Burningpeak", "Loni");
break;
case '5':
updateTableQuery5(tempvBox);
break;
case '6':
updateTableQuery6(tempvBox);
break;
case '7':
updateTableQuery7(tempvBox, "100");
break;
case '8':
updateTableQuery8(tempvBox);
break;
default:
System.out.println("Repeating Query #" + queryNumText.charAt(queryNumText.length() - 1));
}
});
NumberAxis xAxis = new NumberAxis();
xAxis.setLabel("Execution Number");
NumberAxis yAxis = new NumberAxis();
yAxis.setLabel("Time Processed");
graphArea = new LineChart(xAxis, yAxis);
graphArea.setId("graphArea");
graphArea.setLegendVisible(false);
vBox.getChildren().add(graphArea);
}
return vBox;
}
// Irrelevant query to refresh stored table
private void refreshTable() {
Statement st = null;
ResultSet rs = null;
String query = "SELECT * FROM Book B";
System.out.println("\n\n ... \n\n");
nQueryExec += 1;
try {
st = conn.createStatement();
rs = st.executeQuery(query);
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
}
private void restartProfiling() {
Statement st = null;
try {
st = conn.createStatement();
st.executeQuery(" SET @@profiling = 0;");
st.executeQuery("SET @@profiling_history_size = 0;");
st.executeQuery("SET @@profiling_history_size = 100;");
st.executeQuery("SET @@profiling = 1;");
st.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}
}
private BigDecimal getQueryProcessTime(int i) {
Statement st = null;
ResultSet rs = null;
BigDecimal time = BigDecimal.valueOf(0);
try {
st = conn.createStatement();
rs = st.executeQuery("SHOW PROFILES ");
int row = 1;
while (rs.next()) {
System.out.println("Line #: " + i + " || Row #:" + row +
" || Time: " + rs.getFloat("Duration"));
if (row == i)
time = rs.getBigDecimal("Duration");
row++;
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return time;
}
// Update table queries
private void updateTableQuery1(VBox vBox, String filterName) {
TableColumn<ArrayList<String>, String> titleCol = new TableColumn<>("Title");
titleCol.setMinWidth(100);
titleCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> pubNameCol = new TableColumn<>("PublisherName");
pubNameCol.setMinWidth(100);
pubNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
table.setItems(getQuery1(filterName));
table.getColumns().addAll(titleCol, pubNameCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
vBox.getChildren().add(2, table);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
}
private void updateTableQuery2(VBox vBox, String filterNum) {
TableColumn<ArrayList<String>, String> noBooksBorCol = new TableColumn<>("NoBooksBor");
noBooksBorCol.setMinWidth(100);
noBooksBorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
table.setItems(getQuery2(filterNum));
table.getColumns().addAll(noBooksBorCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery3(VBox vBox, String filter1, String filter2) {
TableColumn<ArrayList<String>, String> nameCol = new TableColumn<>("BorrowerName");
nameCol.setMinWidth(100);
nameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
//Starting Point Column
TableColumn<ArrayList<String>, String> noBooksBorCol = new TableColumn<>("NoBooksBor");
noBooksBorCol.setMinWidth(100);
noBooksBorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
table.setItems(getQuery3(filter1, filter2));
table.getColumns().addAll(nameCol, noBooksBorCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery4(VBox vBox, String filter1, String filter2) {
TableColumn<ArrayList<String>, String> titleCol = new TableColumn<>("Title");
titleCol.setMinWidth(100);
titleCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> pubNameCol = new TableColumn<>("PublisherName");
pubNameCol.setMinWidth(100);
pubNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
TableColumn<ArrayList<String>, String> authorCol = new TableColumn<>("Author");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(2));
});
table.setItems(getQuery4(filter1, filter2));
table.getColumns().addAll(titleCol, pubNameCol, authorCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
System.out.println((nQueryExec - nQueryExec/2) + " || " + processTime);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery5(VBox vBox) {
TableColumn<ArrayList<String>, String> bookIdCol = new TableColumn<>("BookID");
bookIdCol.setMinWidth(100);
bookIdCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> titleCol = new TableColumn<>("Title");
titleCol.setMinWidth(100);
titleCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
TableColumn<ArrayList<String>, String> authorCol = new TableColumn<>("AuthorName");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(2));
});
TableColumn<ArrayList<String>, String> pubCol = new TableColumn<>("PublisherName");
pubCol.setMinWidth(100);
pubCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(3));
});
table.setItems(getQuery5());
table.getColumns().addAll(bookIdCol, titleCol, authorCol, pubCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery6(VBox vBox) {
TableColumn<ArrayList<String>, String> cardNoCol = new TableColumn<>("CardNo");
cardNoCol.setMinWidth(100);
cardNoCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> borrowerNameCol = new TableColumn<>("BorrowerName");
borrowerNameCol.setMinWidth(100);
borrowerNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
TableColumn<ArrayList<String>, String> branchIdCol = new TableColumn<>("BranchID");
branchIdCol.setMinWidth(100);
branchIdCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(2));
});
//Starting Point Column
TableColumn<ArrayList<String>, String> branchNameCol = new TableColumn<>("BranchName");
branchNameCol.setMinWidth(100);
branchNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(3));
});
TableColumn<ArrayList<String>, String> branchAddressCol = new TableColumn<>("BranchAddress");
branchAddressCol.setMinWidth(100);
branchAddressCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(4));
});
table.setItems(getQuery6());
table.getColumns().addAll(cardNoCol, borrowerNameCol, branchIdCol, branchNameCol, branchAddressCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery7(VBox vBox, String filter) {
TableColumn<ArrayList<String>, String> nameCol = new TableColumn<>("BorrowerName");
nameCol.setMinWidth(100);
nameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> idCol = new TableColumn<>("BookID");
idCol.setMinWidth(100);
idCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
TableColumn<ArrayList<String>, String> titleCol = new TableColumn<>("Title");
titleCol.setMinWidth(100);
titleCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(2));
});
TableColumn<ArrayList<String>, String> authorCol = new TableColumn<>("AuthorName");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(3));
});
TableColumn<ArrayList<String>, String> dueDateCol = new TableColumn<>("DueDate");
dueDateCol.setMinWidth(100);
dueDateCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(4));
});
TableColumn<ArrayList<String>, String> dateReturnedCol = new TableColumn<>("DateReturned");
dateReturnedCol.setMinWidth(100);
dateReturnedCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(5));
});
table.setItems(getQuery7(filter));
table.getColumns().addAll(nameCol, idCol, titleCol, authorCol, dueDateCol, dateReturnedCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
private void updateTableQuery8(VBox vBox) {
TableColumn<ArrayList<String>, String> idCol = new TableColumn<>("BranchID");
idCol.setMinWidth(100);
idCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(0));
});
TableColumn<ArrayList<String>, String> branchNameCol = new TableColumn<>("BranchName");
branchNameCol.setMinWidth(100);
branchNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(1));
});
TableColumn<ArrayList<String>, String> bookIdCol = new TableColumn<>("BookID");
bookIdCol.setMinWidth(100);
bookIdCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(2));
});
TableColumn<ArrayList<String>, String> noTimesLoanedCol = new TableColumn<>("NoTimesLoaned");
noTimesLoanedCol.setMinWidth(100);
noTimesLoanedCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(3));
});
TableColumn<ArrayList<String>, String> titleCol = new TableColumn<>("Title");
titleCol.setMinWidth(100);
titleCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(4));
});
TableColumn<ArrayList<String>, String> authorCol = new TableColumn<>("AuthorName");
authorCol.setMinWidth(100);
authorCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(5));
});
TableColumn<ArrayList<String>, String> publisherNameCol = new TableColumn<>("PublisherName");
publisherNameCol.setMinWidth(100);
publisherNameCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(6));
});
TableColumn<ArrayList<String>, String> publisherAddressCol = new TableColumn<>("PublisherAddress");
publisherAddressCol.setMinWidth(100);
publisherAddressCol.setCellValueFactory(param -> {
ArrayList<String> x = param.getValue();
return new SimpleStringProperty(x.get(7));
});
table.setItems(getQuery8());
table.getColumns().addAll(idCol, branchNameCol, bookIdCol, noTimesLoanedCol, titleCol, authorCol, publisherNameCol, publisherAddressCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
BigDecimal processTime = getQueryProcessTime(nQueryExec);
// clear current data
dataSeries1.getData().clear();
// add new data
dataSeries1.getData().add(new XYChart.Data(nQueryExec - nQueryExec/2, processTime));
vBox.getChildren().add(2, table);
}
// Get queries
public ObservableList<ArrayList<String>> getQuery1(String filterName) {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String query = "SELECT Title, PublisherName\n" +
"FROM book\n" +
"WHERE PublisherName like '%" + filterName + "%'\n" +
"ORDER BY PublisherName;\n";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getString("Title"));
rowData.add(rs.getString("PublisherName"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery2(String filterNum) {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String query = "SELECT COUNT(*) AS NoBooksBor\n" +
"FROM book_loans\n" +
"WHERE YEAR(DateOut) = " + filterNum;
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getString("NoBooksBor"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery3(String f1, String f2) {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Normal") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) AS BorrowerName, COUNT(*) as NoBooksBor\n" +
"FROM borrower BO, book_loans BL\n" +
"WHERE BO.CardNo = BL.CardNo\n" +
"GROUP BY BorrowerName\n" +
"HAVING NoBooksBor >= " + f1 + " and NoBooksBor <= " + f2 + "\n" +
"ORDER BY 2 DESC, 1;\n" : queryToggleString.equals("Join") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) as BorrowerName , COUNT(*) as NoBooksBor\n" +
"\tFROM borrower BO join book_loans BL on BO.CardNo = BL.CardNo\n" +
"\tGROUP BY BorrowerName\n" +
"HAVING NoBooksBor >= " + f1 + " and NoBooksBor <= " + f2 + "\n" +
"\tORDER BY 2 DESC, 1;" : /*SubQuery*/
"SELECT CONCAT(BorrowerLName, \", \", BorrowerFName) as BorrowerName, BO2.NoBooksBor\n" +
"\tFROM borrower, (SELECT BL.CardNo, COUNT(CardNo) as NoBooksBor\n" +
"\t\t\t\t\tFROM book_loans BL\n" +
"\t\t\t\t\tGROUP BY BL.CardNo\n" +
"\t\t\t\t\tHAVING COUNT(CardNo) >= " + f1 + " and COUNT(CardNo) <= " + f2 + "\n" +
"\t\t\t\t\tORDER BY 1) as BO2\n" +
"WHERE borrower.CardNo = BO2.CardNo\n" +
"\tORDER BY 2 DESC;";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getString("BorrowerName"));
rowData.add(rs.getString("NoBooksBor"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery4(String f1, String f2) {
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Normal") ?
"SELECT B.Title, B.PublisherName, CONCAT(BA.AuthorLastName, '. ', BA.AuthorFirstName) as Author\n" +
"FROM book B, (SELECT * \n" +
" FROM book_authors\n" +
" WHERE AuthorLastName LIKE '%" + f1 + "%' and " +
" AuthorFirstName LIKE '%" + f2 + "%') as BA\n" +
"WHERE BA.BookID = B.BookID\n" +
"ORDER BY 1;\n" : queryToggleString.equals("Join") ?
"SELECT B.Title, B.PublisherName, CONCAT(BA.AuthorLastName, '. ', BA.AuthorFirstName) as Author\n" +
"FROM book B join (SELECT * \n" +
" FROM book_authors\n" +
" WHERE AuthorLastName LIKE '%" + f1 + "%' and " +
" AuthorFirstName LIKE '%" + f2 + "%' ) as BA on BA.BookID = B.BookID\n" +
"ORDER BY 1;" : /*Subquery*/
"SELECT B.Title, B.PublisherName, \n" +
"\t\tCONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as Author\n" +
"\t\tFROM book B, (SELECT * \n" +
"\t\t FROM book_authors\n" +
"\t\t WHERE AuthorLastName LIKE '%" + f1 + "%' and AuthorFirstName LIKE '%" + f2 + "%' ) as BA\n" +
"\t\tWHERE BA.BookID = B.BookID\n" +
"\t\tORDER BY 1;";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getString("Title"));
rowData.add(rs.getString("PublisherName"));
rowData.add(rs.getString("Author"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery5() {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Normal") ?
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, B.PublisherName\n" +
"FROM book B, book_authors BA\n" +
"WHERE B.BookID NOT IN (SELECT BookID\n" +
" FROM book_loans) and B.BookID = BA.BookID\n" +
"GROUP BY B.BookID\n" +
"ORDER BY 3, 2;" : queryToggleString.equals("Join") ?
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, B.PublisherName\n" +
"\tFROM book B inner join book_authors BA on \n" +
"\tB.BookID NOT IN (SELECT BookID\n" +
"\tFROM book_loans) and B.BookID = BA.BookID" : /*Subquery*/
"SELECT B.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, B.PublisherName\n" +
"\t\tFROM book B inner join book_authors BA on \n" +
"\t\tB.BookID NOT IN (SELECT BookID\n" +
"\tFROM book_loans) and B.BookID = BA.BookID;";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getInt("BookID") + "");
rowData.add(rs.getString("Title"));
rowData.add(rs.getString("AuthorName"));
rowData.add(rs.getString("PublisherName"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery6() {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Normal") ?
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) as " +
"BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO, book_loans BL, library_branch LB\n" +
"WHERE BO.CardNo IN (SELECT CardNo \n" +
" FROM book_loans) AND BO.Address = LB.BranchAddress AND BL.BranchID = LB.BranchID\n" +
"GROUP BY BorrowerName\n" +
"ORDER BY 2;\n" : queryToggleString.equals("Join") ?
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, \", \", BO.BorrowerFName) " +
"as BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO join book_loans BL on BO.CardNo IN (SELECT CardNo \n" +
"FROM book_loans) join library_branch LB on BO.Address = " +
"LB.BranchAddress and BL.BranchID = LB.BranchID\n" : /*Subquery*/
"SELECT BO.CardNo, CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) " +
"as BorrowerName, LB.BranchID, LB.BranchName, LB.BranchAddress\n" +
"FROM borrower BO, book_loans BL, library_branch LB\n" +
"WHERE BO.CardNo IN (SELECT CardNo \n" +
" FROM book_loans) AND BO.Address = LB.BranchAddress AND BL.BranchID = LB.BranchID";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getInt("CardNo") + "");
rowData.add(rs.getString("BorrowerName"));
rowData.add(rs.getInt("BranchID") + "");
rowData.add(rs.getString("BranchName"));
rowData.add(rs.getString("BranchAddress"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery7(String filter) {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Normal") ?
"SELECT CONCAT(BO.BorrowerLName, ', ', BO.BorrowerFName) AS BorrowerName, " +
"BL.BookID, B.Title, CONCAT(BA.AuthorLastName, ', ', " +
"BA.AuthorFirstName) as AuthorName, BL.DueDate, BL.DateReturned\n" +
"FROM book B, book_authors BA, book_loans BL, borrower BO\n" +
"WHERE B.BookID = BA.BookID AND BA.BookID = BL.BookID AND " +
"BL.CardNo AND BL.DueDate = BL.DateReturned\n" +
"LIMIT 0, " + filter : queryToggleString.equals("Join") ?
"SELECT CONCAT(BO.BorrowerFName, \", \" , BO.BorrowerLName) AS " +
"BorrowerName, BL.BookID, B.Title, CONCAT(BA.AuthorLastName, \", \", " +
"BA.AuthorFirstName) as AuthorName, BL.DueDate, BL.DateReturned\n" +
"FROM book B join book_authors BA on B.BookID = BA.BookID join book_loans " +
"BL on BA.BookID = BL.BookID join borrower BO on BL.DueDate = BL.DateReturned\n" +
"LIMIT 0, " + filter: /*Subquery*/
"SELECT O.BorrowerName, A.AuthorName, D.BookID, D.DueDate, D.DateReturned\n" +
"FROM (SELECT BL.BookID, BL.DateReturned, BL.DueDate, BL.CardNo\n" +
" FROM book_loans BL\n" +
" WHERE BL.DateReturned = BL.DueDate) AS D, (SELECT BA.BookID, " +
" CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName\n" +
" FROM book_authors BA) as A, (SELECT B.BookID, B.Title\n" +
" FROM book B) as B, (SELECT BO.CardNo, " +
" CONCAT(BO.BorrowerFName, \", \" , BO.BorrowerLName) AS BorrowerName\n" +
" FROM borrower BO) as O\n" +
"WHERE D.BookID = A.BookID AND B.BookID = D.BookID AND O.CardNo = D.CardNo \n" +
"LIMIT 0, " + filter;
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getString("BorrowerName"));
rowData.add(rs.getInt("BookID") + "");
rowData.add(rs.getString("Title"));
rowData.add(rs.getString("AuthorName"));
rowData.add(rs.getString("DueDate"));
rowData.add(rs.getString("DateReturned"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
public ObservableList<ArrayList<String>> getQuery8() {
//Connection conn = getConnection(); called at the start
Statement st = null;
ResultSet rs = null;
String queryToggleString = queryTypeToggleGroup.getSelectedToggle().getUserData().toString();
String query = queryToggleString.equals("Join") ?
"SELECT BL.BranchID, LB.BranchName, BL.BookID, BL.NoTimesLoaned, " +
"B.Title, CONCAT(BA.AuthorLastName, \", \", BA.AuthorFirstName) as AuthorName, " +
"P.PublisherName, P.Address AS PublisherAddress\n" +
"FROM book B join book_authors BA on B.BookID = BA.BookID join library_branch " +
"LB join publisher P on B.PublisherName = P.PublisherName join " +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned FROM book_loans " +
"GROUP BY BranchID, BookID) AS BL on BL.BranchID = LB.BranchID and BL.BookID = B.BookID\n" +
"join (SELECT TEMP.BranchID, MAX(TEMP.NoTimesLoaned) AS NoTimesLoaned FROM\n" +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned FROM BOOK_LOANS GROUP BY " +
"BranchID, BookID) AS TEMP GROUP BY TEMP.BranchID) AS C on BL.BranchID = " +
"C.BranchID AND BL.NoTimesLoaned = C.NoTimesLoaned\n" +
"GROUP BY BL.BranchID\n" +
"ORDER BY 2, 5;" : /*Normal & subquery*/
"SELECT BL.BranchID, LB.BranchName, BL.BookID, BL.NoTimesLoaned, " +
"B.Title, CONCAT(BA.AuthorLastName, ', ', BA.AuthorFirstName) as " +
"AuthorName, P.PublisherName, P.Address AS PublisherAddress\n" +
"FROM book B, book_authors BA, library_branch LB, publisher P, " +
"(SELECT BranchID, BookID, COUNT(*) AS NoTimesLoaned\n" +
"FROM book_loans\n" +
"GROUP BY BranchID, BookID) AS BL,\n" +
"(SELECT TEMP.BranchID,\n" +
"MAX(TEMP.NoTimesLoaned)\n" +
"AS NoTimesLoaned\n" +
"FROM\n" +
"(SELECT BranchID, BookID,\n" +
"COUNT(*) AS NoTimesLoaned\n" +
"FROM BOOK_LOANS\n" +
"GROUP BY BranchID, BookID) AS TEMP\n" +
"GROUP BY TEMP.BranchID) AS C\n" +
"WHERE\n" +
"BL.BranchID = C.BranchID AND\n" +
"BL.NoTimesLoaned = C.NoTimesLoaned AND\n" +
"BL.BranchID = LB.BranchID AND\n" +
"BL.BookID = B.BookID AND\n" +
"B.BookID = BA.BookID AND\n" +
"B.PublisherName = P.PublisherName\n" +
"GROUP BY BL.BranchID\n" +
"ORDER BY 2, 5;\n";
ObservableList<ArrayList<String>> arrayList = FXCollections.observableArrayList();
try {
st = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
ArrayList<String> rowData = new ArrayList<>();
rowData.add(rs.getInt("BranchID") + "");
rowData.add(rs.getString("BranchName"));
rowData.add(rs.getInt("BookID") + "");
rowData.add(rs.getInt("NoTimesLoaned") + "");
rowData.add(rs.getString("Title"));
rowData.add(rs.getString("AuthorName"));
rowData.add(rs.getString("PublisherName"));
rowData.add(rs.getString("PublisherAddress"));
arrayList.add(rowData);
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
return arrayList;
}
private void deleteAllIndex() {
//Connection conn = getConnection(); called at the start
Statement st = null;
Statement st2 = null;
ResultSet rs = null;
String query = "SELECT DISTINCT\n" +
" TABLE_NAME,\n" +
" INDEX_NAME\n" +
"FROM INFORMATION_SCHEMA.STATISTICS\n" +
"WHERE TABLE_SCHEMA = 'mco1_db' AND INDEX_NAME != 'PRIMARY';";
try {
st = conn.createStatement();
st2 = conn.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
query = "DROP INDEX " + rs.getString("INDEX_NAME") + " ON " + rs.getString("TABLE_NAME");
st2.executeUpdate(query);
System.out.println("Deleted index: " + rs.getString("INDEX_NAME"));
}
st.close();
rs.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}// catch (ClassNotFoundException e){
}
private void terminateProgram() {
if (conn != null)
try {
deleteAllIndex();
conn.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
}
System.out.println("\nProgram has been terminated.");
Platform.exit();
System.exit(0);
}
public Connection getConnection() {
Connection tempConn = null;
String driver = "com.mysql.jdbc.Driver";
String db = "mco1_db";
String url = "jdbc:mysql://localhost/" + db + "?useSSL=false";
String user = "root";
String pass = "<PASSWORD>";
try {
Class.forName(driver);
tempConn = DriverManager.getConnection(url, user, pass);
System.out.println("Connected to database : " + db);
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException");
}
return tempConn;
}
/* Filters the table *************************************/
// public EventHandler<KeyEvent> filterRoutesTable() {
// return new EventHandler<KeyEvent>() {
// @Override
// @SuppressWarnings("unchecked")
// public void handle(KeyEvent e) {
// ObservableList<Route> routes = FXCollections.observableArrayList();
//
// //Connection conn = getConnection(); called at the start
// Statement st = null;
// ResultSet rs = null;
// String query = new String(" ");
// TextField text = (TextField) e.getSource();
// if(userRider){
// query = "SELECT l.landmarkName as `Starting Point`, l2.landmarkName as `End Point`, r.mins as `Minutes`, r.fare as `Fare` " +
// "FROM landmarks l, landmarks l2, route r " +
// "WHERE `r`.pickupLoc = l.landmarkID AND r.dropoffLoc = l2.landmarkId " +
// "AND l.landmarkName LIKE '%" + startingTextField.getText() + "%'" +
// "AND l2.landmarkName LIKE '%" + endingTextField.getText() + "%'" +
// "AND r.mins LIKE '%" + minutesTextField.getText() + "%'" +
// "AND r.fare LIKE '%" + fareTextField.getText() + "%';";
// }
// else
// query = "SELECT l.landmarkName as `Starting Point`, l2.landmarkName as `End Point`, r.mins as `Minutes`, r.fare as `Fare` " +
// ", CONCAT(ri.firstName, \" \", ri.lastName) AS `Rider Name`, ri.rating AS `Rating` " +
// "FROM landmarks l, landmarks l2, route r, riderInfo ri, transaction t " +
// "WHERE r.pickupLoc = l.landmarkID AND r.dropoffLoc = l2.landmarkId AND " +
// "t.routeId = r.routeId AND ri.riderId = t.riderId AND t.driverId = 0 "+
// "AND l.landmarkName LIKE '%" + startingTextField.getText() + "%'" +
// "AND l2.landmarkName LIKE '%" + endingTextField.getText() + "%'" +
// "AND r.mins LIKE '%" + minutesTextField.getText() + "%'" +
// "AND r.fare LIKE '%" + fareTextField.getText() + "%'" +
// "AND CONCAT(ri.firstName, \" \", ri.lastName) LIKE '%" + riderTextField.getText() + "%'" +
// "AND ri.rating LIKE '%" + ratingTextField.getText() + "%'";
//
// try {
//
// st = conn.createStatement();
// rs = st.executeQuery(query);
//
// while(rs.next()){
// Route r = new Route(rs.getString("Starting Point"), rs.getString("End Point"),
// rs.getInt("Minutes"), rs.getInt("Fare"));
// if(!userRider){
// r.setRider(rs.getString("Rider Name"));
// r.setRating(rs.getString("Rating"));
// }
//
// routes.add(r);
// }
// st.close();
// rs.close();
// } catch (SQLException e2) {
// System.out.println("SQLException: " + e2.getMessage());
// System.out.println("SQLState: " + e2.getSQLState());
// System.out.println("VendorError: " + e2.getErrorCode());
// }
//
// //Starting Point Column
// TableColumn<Route, String> startingColumn= new TableColumn<>("Starting Point");
// startingColumn.setMinWidth(100);
// startingColumn.setCellValueFactory(new PropertyValueFactory<>("start"));
//
// //End Point Column
// TableColumn<Route, String> endColumn= new TableColumn<>("End Point");
// endColumn.setMinWidth(100);
// endColumn.setCellValueFactory(new PropertyValueFactory<>("end"));
//
// //Minutes Column
// TableColumn<Route, String> minutesColumn= new TableColumn<>("Minutes");
// minutesColumn.setMinWidth(75);
// minutesColumn.setCellValueFactory(new PropertyValueFactory<>("Minutes"));
//
// //Fare Column
// TableColumn<Route, String> fareColumn= new TableColumn<>("Fare");
// fareColumn.setMinWidth(75);
// fareColumn.setCellValueFactory(new PropertyValueFactory<>("fare"));
//
// if(userRider){
// filterVBox.getChildren().remove(routesTable);
// routesTable = new TableView<Route>();
// routesTable.setItems(routes);
// routesTable.getColumns().addAll(startingColumn, endColumn, minutesColumn, fareColumn);
// routesTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// filterVBox.getChildren().add(0, routesTable);
// }
//
// else {
// //Rider Info Column
// TableColumn<Route, String> riderInfoColumn= new TableColumn<>("Rider Name");
// riderInfoColumn.setMinWidth(75);
// riderInfoColumn.setCellValueFactory(new PropertyValueFactory<>("rider"));
//
// //Rating Column
// TableColumn<Route, String> ratingColumn= new TableColumn<>("Rating");
// ratingColumn.setMinWidth(75);
// ratingColumn.setCellValueFactory(new PropertyValueFactory<>("Rating"));
//
// filterVBox.getChildren().remove(driverTable);
// driverTable = new TableView<Route>();
// driverTable.setItems(routes);
// driverTable.getColumns().addAll(startingColumn, endColumn, minutesColumn, fareColumn, riderInfoColumn, ratingColumn);
// driverTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// filterVBox.getChildren().add(0, driverTable);
// }
// }
// };
// }
/*****************************************************************************************/
/* Numeric Validation Limit the characters to maxLength AND to ONLY DigitS *************************************/
// public EventHandler<KeyEvent> numeric_Validation(final Integer max_Length) {
// return new EventHandler<KeyEvent>() {
// @Override
// public void handle(KeyEvent e) {
// TextField txt_TextField = (TextField) e.getSource();
// if (max_Length > 0 && txt_TextField.getText().length() >= max_Length) {
// e.consume();
// }
// if(e.getCharacter().matches("[0-9.]")){
// if(txt_TextField.getText().contains(".") && e.getCharacter().matches("[.]")){
// e.consume();
// }else if(txt_TextField.getText().length() == 0 && e.getCharacter().matches("[.]")){
// e.consume();
// }
// }else{
// e.consume();
// }
// }
// };
// }
/*****************************************************************************************/
/* Letters Validation Limit the characters to maxLength AND to ONLY Letters *************************************/
// public EventHandler<KeyEvent> numOfLetters_Validation(final Integer max_Length) {
// return new EventHandler<KeyEvent>() {
// @Override
// public void handle(KeyEvent e) {
// TextField txt_TextField = (TextField) e.getSource();
// if (max_Length > 0 && txt_TextField.getText().length() >= max_Length) {
// e.consume();
// }
// if(!(e.getCharacter().matches("[A-Za-z]")))
// e.consume();
// }
// };
// }
/*****************************************************************************************/
} | 85,107 | 0.509364 | 0.502315 | 1,724 | 48.369488 | 33.751255 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.860209 | false | false | 13 |
a1930b229d4223d7867a48b64c50a2dec2d89cb0 | 27,333,171,883,901 | c19f56d0f83a4d83d493811bf21410e726889b93 | /infobip-mobile-messaging-android-sdk/src/main/java/org/infobip/mobile/messaging/interactive/notification/InteractiveNotificationHandler.java | bc6f107903719ad6f52bde0edebb02372f3a2109 | [
"Apache-2.0"
] | permissive | infobip/mobile-messaging-sdk-android | https://github.com/infobip/mobile-messaging-sdk-android | 2592f364605303bbb3efd4155af600f0be67e925 | 8ae1b5442e8265ef42fec9cbee6b68c59e1b7587 | refs/heads/master | 2023-08-30T11:58:52.146000 | 2023-08-24T15:19:22 | 2023-08-24T15:19:22 | 56,227,769 | 50 | 19 | Apache-2.0 | false | 2022-05-04T20:04:26 | 2016-04-14T10:15:36 | 2022-04-04T19:26:20 | 2022-05-04T20:04:25 | 3,833 | 33 | 13 | 4 | Java | false | false | package org.infobip.mobile.messaging.interactive.notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.RemoteInput;
import org.infobip.mobile.messaging.Message;
import org.infobip.mobile.messaging.dal.bundle.MessageBundleMapper;
import org.infobip.mobile.messaging.interactive.MobileInteractiveImpl;
import org.infobip.mobile.messaging.interactive.NotificationAction;
import org.infobip.mobile.messaging.interactive.NotificationCategory;
import org.infobip.mobile.messaging.interactive.dal.bundle.NotificationActionBundleMapper;
import org.infobip.mobile.messaging.interactive.dal.bundle.NotificationCategoryBundleMapper;
import org.infobip.mobile.messaging.notification.BaseNotificationHandler;
import org.infobip.mobile.messaging.notification.NotificationHandler;
import static org.infobip.mobile.messaging.BroadcastParameter.EXTRA_MESSAGE;
import static org.infobip.mobile.messaging.BroadcastParameter.EXTRA_NOTIFICATION_ID;
import static org.infobip.mobile.messaging.BroadcastParameter.EXTRA_TAPPED_ACTION;
import static org.infobip.mobile.messaging.BroadcastParameter.EXTRA_TAPPED_CATEGORY;
import static org.infobip.mobile.messaging.BroadcastParameter.NOTIFICATION_NOT_DISPLAYED_ID;
public class InteractiveNotificationHandler implements NotificationHandler {
private final Context context;
private final BaseNotificationHandler baseNotificationHandler;
public InteractiveNotificationHandler(Context context) {
this.context = context;
this.baseNotificationHandler = new BaseNotificationHandler(context);
}
@Override
public int displayNotification(Message message) {
if (context == null) return NOTIFICATION_NOT_DISPLAYED_ID;
int notificationId = baseNotificationHandler.getNotificationId(message);
NotificationCompat.Builder builder = getNotificationBuilder(message, notificationId);
boolean displayed = baseNotificationHandler.displayNotification(builder, message, notificationId);
if (!displayed) return NOTIFICATION_NOT_DISPLAYED_ID;
return notificationId;
}
@Override
public void cancelAllNotifications() {
baseNotificationHandler.cancelAllNotifications();
}
private NotificationCompat.Builder getNotificationBuilder(Message message, int notificationId) {
NotificationCompat.Builder builder = baseNotificationHandler.createNotificationCompatBuilder(message);
if (builder == null) return null;
String category = message.getCategory();
NotificationCategory triggeredNotificationCategory = MobileInteractiveImpl.getInstance(context).getNotificationCategory(category);
setNotificationActions(builder, message, triggeredNotificationCategory, notificationId);
return builder;
}
private void setNotificationActions(NotificationCompat.Builder notificationBuilder,
Message message,
NotificationCategory triggeredNotificationCategory,
int notificationId) {
if (triggeredNotificationCategory == null) {
return;
}
NotificationAction[] notificationActions = triggeredNotificationCategory.getNotificationActions();
for (NotificationAction notificationAction : notificationActions) {
PendingIntent pendingIntent = createActionTapPendingIntent(message, triggeredNotificationCategory, notificationAction, notificationId);
notificationBuilder.addAction(createAndroidNotificationAction(notificationAction, pendingIntent));
}
}
@NonNull
private NotificationCompat.Action createAndroidNotificationAction(NotificationAction notificationAction, PendingIntent pendingIntent) {
NotificationCompat.Action.Builder builder = new NotificationCompat.Action.Builder(
notificationAction.getIcon(),
notificationActionTitle(context, notificationAction),
pendingIntent);
if (notificationAction.hasInput()) {
RemoteInput.Builder inputBuilder = new RemoteInput.Builder(notificationAction.getId());
String inputPlaceholderText = notificationActionInputPlaceholder(context, notificationAction);
if (inputPlaceholderText != null) {
inputBuilder.setLabel(inputPlaceholderText);
}
builder.addRemoteInput(inputBuilder.build());
}
return builder.build();
}
private static String notificationActionTitle(Context context, NotificationAction action) {
return action.getTitleResourceId() != 0 ? context.getString(action.getTitleResourceId()) : action.getTitleText();
}
private static String notificationActionInputPlaceholder(Context context, NotificationAction action) {
return action.getInputPlaceholderResourceId() != 0 ? context.getString(action.getInputPlaceholderResourceId()) : action.getInputPlaceholderText();
}
@SuppressWarnings("WrongConstant")
@NonNull
private PendingIntent createActionTapPendingIntent(Message message, NotificationCategory notificationCategory, NotificationAction notificationAction, int notificationId) {
Intent intent = new Intent(context, NotificationActionTapReceiver.class);
intent.setAction(message.getMessageId() + notificationAction.getId());
intent.putExtra(EXTRA_MESSAGE, MessageBundleMapper.messageToBundle(message));
intent.putExtra(EXTRA_TAPPED_ACTION, NotificationActionBundleMapper.notificationActionToBundle(notificationAction));
intent.putExtra(EXTRA_TAPPED_CATEGORY, NotificationCategoryBundleMapper.notificationCategoryToBundle(notificationCategory));
intent.putExtra(EXTRA_NOTIFICATION_ID, notificationId);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
flags = notificationAction.hasInput() ? flags | PendingIntent.FLAG_MUTABLE : flags | PendingIntent.FLAG_IMMUTABLE;
}
return PendingIntent.getBroadcast(context, notificationId, intent, flags);
}
}
| UTF-8 | Java | 6,308 | java | InteractiveNotificationHandler.java | Java | [] | null | [] | package org.infobip.mobile.messaging.interactive.notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.RemoteInput;
import org.infobip.mobile.messaging.Message;
import org.infobip.mobile.messaging.dal.bundle.MessageBundleMapper;
import org.infobip.mobile.messaging.interactive.MobileInteractiveImpl;
import org.infobip.mobile.messaging.interactive.NotificationAction;
import org.infobip.mobile.messaging.interactive.NotificationCategory;
import org.infobip.mobile.messaging.interactive.dal.bundle.NotificationActionBundleMapper;
import org.infobip.mobile.messaging.interactive.dal.bundle.NotificationCategoryBundleMapper;
import org.infobip.mobile.messaging.notification.BaseNotificationHandler;
import org.infobip.mobile.messaging.notification.NotificationHandler;
import static org.infobip.mobile.messaging.BroadcastParameter.EXTRA_MESSAGE;
import static org.infobip.mobile.messaging.BroadcastParameter.EXTRA_NOTIFICATION_ID;
import static org.infobip.mobile.messaging.BroadcastParameter.EXTRA_TAPPED_ACTION;
import static org.infobip.mobile.messaging.BroadcastParameter.EXTRA_TAPPED_CATEGORY;
import static org.infobip.mobile.messaging.BroadcastParameter.NOTIFICATION_NOT_DISPLAYED_ID;
public class InteractiveNotificationHandler implements NotificationHandler {
private final Context context;
private final BaseNotificationHandler baseNotificationHandler;
public InteractiveNotificationHandler(Context context) {
this.context = context;
this.baseNotificationHandler = new BaseNotificationHandler(context);
}
@Override
public int displayNotification(Message message) {
if (context == null) return NOTIFICATION_NOT_DISPLAYED_ID;
int notificationId = baseNotificationHandler.getNotificationId(message);
NotificationCompat.Builder builder = getNotificationBuilder(message, notificationId);
boolean displayed = baseNotificationHandler.displayNotification(builder, message, notificationId);
if (!displayed) return NOTIFICATION_NOT_DISPLAYED_ID;
return notificationId;
}
@Override
public void cancelAllNotifications() {
baseNotificationHandler.cancelAllNotifications();
}
private NotificationCompat.Builder getNotificationBuilder(Message message, int notificationId) {
NotificationCompat.Builder builder = baseNotificationHandler.createNotificationCompatBuilder(message);
if (builder == null) return null;
String category = message.getCategory();
NotificationCategory triggeredNotificationCategory = MobileInteractiveImpl.getInstance(context).getNotificationCategory(category);
setNotificationActions(builder, message, triggeredNotificationCategory, notificationId);
return builder;
}
private void setNotificationActions(NotificationCompat.Builder notificationBuilder,
Message message,
NotificationCategory triggeredNotificationCategory,
int notificationId) {
if (triggeredNotificationCategory == null) {
return;
}
NotificationAction[] notificationActions = triggeredNotificationCategory.getNotificationActions();
for (NotificationAction notificationAction : notificationActions) {
PendingIntent pendingIntent = createActionTapPendingIntent(message, triggeredNotificationCategory, notificationAction, notificationId);
notificationBuilder.addAction(createAndroidNotificationAction(notificationAction, pendingIntent));
}
}
@NonNull
private NotificationCompat.Action createAndroidNotificationAction(NotificationAction notificationAction, PendingIntent pendingIntent) {
NotificationCompat.Action.Builder builder = new NotificationCompat.Action.Builder(
notificationAction.getIcon(),
notificationActionTitle(context, notificationAction),
pendingIntent);
if (notificationAction.hasInput()) {
RemoteInput.Builder inputBuilder = new RemoteInput.Builder(notificationAction.getId());
String inputPlaceholderText = notificationActionInputPlaceholder(context, notificationAction);
if (inputPlaceholderText != null) {
inputBuilder.setLabel(inputPlaceholderText);
}
builder.addRemoteInput(inputBuilder.build());
}
return builder.build();
}
private static String notificationActionTitle(Context context, NotificationAction action) {
return action.getTitleResourceId() != 0 ? context.getString(action.getTitleResourceId()) : action.getTitleText();
}
private static String notificationActionInputPlaceholder(Context context, NotificationAction action) {
return action.getInputPlaceholderResourceId() != 0 ? context.getString(action.getInputPlaceholderResourceId()) : action.getInputPlaceholderText();
}
@SuppressWarnings("WrongConstant")
@NonNull
private PendingIntent createActionTapPendingIntent(Message message, NotificationCategory notificationCategory, NotificationAction notificationAction, int notificationId) {
Intent intent = new Intent(context, NotificationActionTapReceiver.class);
intent.setAction(message.getMessageId() + notificationAction.getId());
intent.putExtra(EXTRA_MESSAGE, MessageBundleMapper.messageToBundle(message));
intent.putExtra(EXTRA_TAPPED_ACTION, NotificationActionBundleMapper.notificationActionToBundle(notificationAction));
intent.putExtra(EXTRA_TAPPED_CATEGORY, NotificationCategoryBundleMapper.notificationCategoryToBundle(notificationCategory));
intent.putExtra(EXTRA_NOTIFICATION_ID, notificationId);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
flags = notificationAction.hasInput() ? flags | PendingIntent.FLAG_MUTABLE : flags | PendingIntent.FLAG_IMMUTABLE;
}
return PendingIntent.getBroadcast(context, notificationId, intent, flags);
}
}
| 6,308 | 0.761414 | 0.761097 | 124 | 49.870968 | 42.860985 | 175 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.758065 | false | false | 13 |
4fb2c808a3b2664c76d29e4c16583668c68d4f3f | 9,887,014,731,166 | d6807304922e9d9e3a2c3c168e83c67f1642d25f | /app/src/main/java/com/uni3000/uni3000/model/User.java | d4760f33e9149242d9bce99fff6c509cfa53271a | [] | no_license | Kyarie/Uni3000 | https://github.com/Kyarie/Uni3000 | bd09833d20b1f3285edf00ad768cb819d88064f3 | 8304c8aebff9ea3748dfd7891b3a80a3489866b9 | refs/heads/master | 2021-01-01T05:58:41.365000 | 2017-12-26T03:53:40 | 2017-12-26T03:53:40 | 97,292,650 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.uni3000.uni3000.model;
import android.content.Context;
import android.content.SharedPreferences;
import com.uni3000.uni3000.model.Interface.IUser;
public class User implements IUser {
private String username;
private int level;
//private Context context;
//create shared preference
private static final String PREFS_NAME="prefs";
public User(Context context) {
this.username = User.getCurrentUsername(context);
this.level = User.getCurrentUserLevel(context);
//this.context = context;
}
public String getUsername() {
return this.username;
}
public int getLevel() {
return this.level;
}
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
//set Shared Preference
public static void setCurrentUsername(Context context, String input) {
//SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putString("username_key", input);
editor.apply();
}
public static void setCurrentUserLevel(Context context, int input) {
//SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putInt("userLevel_key", input);
editor.apply();
}
//get Shared Preference
public static String getCurrentUsername(Context context){
//SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,0);
return getPrefs(context).getString("username_key", "default_username");
}
public static int getCurrentUserLevel(Context context){
//SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,0);
return getPrefs(context).getInt("userLevel_key", 1);
}
}
| UTF-8 | Java | 1,949 | java | User.java | Java | [] | null | [] | package com.uni3000.uni3000.model;
import android.content.Context;
import android.content.SharedPreferences;
import com.uni3000.uni3000.model.Interface.IUser;
public class User implements IUser {
private String username;
private int level;
//private Context context;
//create shared preference
private static final String PREFS_NAME="prefs";
public User(Context context) {
this.username = User.getCurrentUsername(context);
this.level = User.getCurrentUserLevel(context);
//this.context = context;
}
public String getUsername() {
return this.username;
}
public int getLevel() {
return this.level;
}
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
//set Shared Preference
public static void setCurrentUsername(Context context, String input) {
//SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putString("username_key", input);
editor.apply();
}
public static void setCurrentUserLevel(Context context, int input) {
//SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putInt("userLevel_key", input);
editor.apply();
}
//get Shared Preference
public static String getCurrentUsername(Context context){
//SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,0);
return getPrefs(context).getString("username_key", "default_username");
}
public static int getCurrentUserLevel(Context context){
//SharedPreferences settings = context.getSharedPreferences(PREFS_NAME,0);
return getPrefs(context).getInt("userLevel_key", 1);
}
}
| 1,949 | 0.699333 | 0.688558 | 59 | 32.033897 | 27.729912 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.627119 | false | false | 13 |
e1e769723171d042d124d7196716984dcf5246aa | 27,582,279,997,738 | 2e917b6f899114ab6a2773c0057bbbcb06dd0eb7 | /source/org/tigr/microarray/mev/cgh/CGHUtil/CGHUtility.java | 799f2b8f13dd7fd1bdef75a56bdf61762d2ad75f | [
"Artistic-2.0",
"Artistic-1.0"
] | permissive | SamGG/mev-tm4 | https://github.com/SamGG/mev-tm4 | 7d3e09b8bfccc8dd9928b0a945af2c465fb04a31 | 72daf1eaf13d32cc6de45871bce09f943f856621 | refs/heads/master | 2021-01-10T15:34:14.917000 | 2013-04-04T17:51:15 | 2013-04-04T17:51:15 | 49,742,784 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright (c) 1999-2005 The Institute for Genomic Research (TIGR).
* Copyright (c) 2005-2008, the Dana-Farber Cancer Institute (DFCI),
* J. Craig Venter Institute (JCVI) and the University of Washington.
* All rights reserved.
*******************************************************************************/
/*
* Utility.java
*
* Created on October 6, 2002, 12:22 AM
*/
package org.tigr.microarray.mev.cgh.CGHUtil;
import java.util.List;
import org.tigr.microarray.mev.TMEV;
/**
*
* @author Adam Margolin
* @author Raktim Sinha
*/
public class CGHUtility {
/** Creates a new instance of Utility */
public CGHUtility() {
}
public static String encap(String str){
return "'" + str + "'";
}
public static int convertStringToChrom(String strChrom, int species){
if(strChrom.endsWith("_random")){
strChrom = strChrom.substring(0, strChrom.length() - 7);
}
if("chr1".equalsIgnoreCase(strChrom) || "1".equalsIgnoreCase(strChrom)){
return 1;
}else if("chr2".equalsIgnoreCase(strChrom) || "2".equalsIgnoreCase(strChrom)){
return 2;
}else if("chr3".equalsIgnoreCase(strChrom) || "3".equalsIgnoreCase(strChrom)){
return 3;
}else if("chr4".equalsIgnoreCase(strChrom) || "4".equalsIgnoreCase(strChrom)){
return 4;
}else if("chr5".equalsIgnoreCase(strChrom) || "5".equalsIgnoreCase(strChrom)){
return 5;
}else if("chr6".equalsIgnoreCase(strChrom) || "6".equalsIgnoreCase(strChrom)){
return 6;
}else if("chr7".equalsIgnoreCase(strChrom) || "7".equalsIgnoreCase(strChrom)){
return 7;
}else if("chr8".equalsIgnoreCase(strChrom) || "8".equalsIgnoreCase(strChrom)){
return 8;
}else if("chr9".equalsIgnoreCase(strChrom) || "9".equalsIgnoreCase(strChrom)){
return 9;
}else if("chr10".equalsIgnoreCase(strChrom) || "10".equalsIgnoreCase(strChrom)){
return 10;
}else if("chr11".equalsIgnoreCase(strChrom) || "11".equalsIgnoreCase(strChrom)){
return 11;
}else if("chr12".equalsIgnoreCase(strChrom) || "12".equalsIgnoreCase(strChrom)){
return 12;
}else if("chr13".equalsIgnoreCase(strChrom) || "13".equalsIgnoreCase(strChrom)){
return 13;
}else if("chr14".equalsIgnoreCase(strChrom) || "14".equalsIgnoreCase(strChrom)){
return 14;
}else if("chr15".equalsIgnoreCase(strChrom) || "15".equalsIgnoreCase(strChrom)){
return 15;
}else if("chr16".equalsIgnoreCase(strChrom) || "16".equalsIgnoreCase(strChrom)){
return 16;
}else if("chr17".equalsIgnoreCase(strChrom) || "17".equalsIgnoreCase(strChrom)){
return 17;
}else if("chr18".equalsIgnoreCase(strChrom) || "18".equalsIgnoreCase(strChrom)){
return 18;
}else if("chr19".equalsIgnoreCase(strChrom) || "19".equalsIgnoreCase(strChrom)){
return 19;
}else if("chr20".equalsIgnoreCase(strChrom) || "20".equalsIgnoreCase(strChrom)){
return 20;
}else if("chr21".equalsIgnoreCase(strChrom) || "21".equalsIgnoreCase(strChrom)){
return 21;
}else if("chr22".equalsIgnoreCase(strChrom) || "22".equalsIgnoreCase(strChrom)){
return 22;
}else if("chrX".equalsIgnoreCase(strChrom) || "X".equalsIgnoreCase(strChrom)){
//return 23;
int chr = 0;
switch (species){
case TMEV.CGH_SPECIES_HS: {chr = 23; break;}
case TMEV.CGH_SPECIES_MM: {chr = 20; break;}
default: chr = -1; break;
}
return chr;
}else if("chrY".equalsIgnoreCase(strChrom) || "Y".equalsIgnoreCase(strChrom)){
//return 24;
int chr = 0;
switch (species){
case TMEV.CGH_SPECIES_HS: {chr = 24; break;}
case TMEV.CGH_SPECIES_MM: {chr = 21; break;}
default: chr = -2; break;
}
return chr;
}else{
//System.out.println("Util convert chrom, not found: " + strChrom);
return org.tigr.microarray.mev.cgh.CGHDataObj.CGHClone.NOT_FOUND;
}
}
private int XChrToSpecies(int species) {
int chr = 0;
switch (species){
case TMEV.CGH_SPECIES_HS: {chr = 23; break;}
case TMEV.CGH_SPECIES_MM: {chr = 20; break;}
default: chr = -1; break;
}
return chr;
}
public static String convertChromToString(int chrom, int species){
switch (species){
case TMEV.CGH_SPECIES_HS:
if(chrom < 23 && chrom > 0) return "chr" + chrom;
if(chrom == 23) return "chrX";
if(chrom == 24) return "chrY";
case TMEV.CGH_SPECIES_MM:
if(chrom < 20 && chrom > 0) return "chr" + chrom;
if(chrom == 20) return "chrX";
if(chrom == 21) return "chrY";
case TMEV.CGH_SPECIES_Undef:
return "chr" + chrom;
default:
System.out.println("Util convert chrom, not found index: " + chrom);
return "";
}
}
public static String convertChromToLongString(int chrom, int species){
switch (species){
case TMEV.CGH_SPECIES_HS:
if(chrom < 23 && chrom > 0) return "Chromosome " + chrom;
if(chrom == 23) return "Chromosome X";
if(chrom == 24) return "Chromosome Y";
case TMEV.CGH_SPECIES_MM:
if(chrom < 20 && chrom > 0) return "Chromosome " + chrom;
if(chrom == 20) return "Chromosome X";
if(chrom == 21) return "Chromosome Y";
case TMEV.CGH_SPECIES_Undef:
return "Chromosome " + chrom;
default:
System.out.println("Util convert chrom, not found index: " + chrom);
return "";
}
}
public static String createQueryString(List values){
String queryString = "(";
if(values == null || values.size() < 1){
return null;
}
queryString += encap(values.get(0).toString());
for(int i = 1; i < values.size(); i++){
queryString += ", " + encap(values.get(i).toString());
}
return queryString + ")";
}
public static String createIntegerQueryString(List values){
String queryString = "(";
if(values == null || values.size() < 1){
return null;
}
queryString += values.get(0);
for(int i = 1; i < values.size(); i++){
queryString += ", " + values.get(i);
}
return queryString + ")";
}
}
| UTF-8 | Java | 6,672 | java | CGHUtility.java | Java | [
{
"context": " org.tigr.microarray.mev.TMEV;\n\n/**\n *\n * @author Adam Margolin\n * @author Raktim Sinha\n */\n\npublic class CGHUtil",
"end": 610,
"score": 0.9997875690460205,
"start": 597,
"tag": "NAME",
"value": "Adam Margolin"
},
{
"context": "TMEV;\n\n/**\n *\n * @author Adam Margolin\n * @author Raktim Sinha\n */\n\npublic class CGHUtility {\n\n /** Creates a",
"end": 634,
"score": 0.9998591542243958,
"start": 622,
"tag": "NAME",
"value": "Raktim Sinha"
}
] | null | [] | /*******************************************************************************
* Copyright (c) 1999-2005 The Institute for Genomic Research (TIGR).
* Copyright (c) 2005-2008, the Dana-Farber Cancer Institute (DFCI),
* J. Craig Venter Institute (JCVI) and the University of Washington.
* All rights reserved.
*******************************************************************************/
/*
* Utility.java
*
* Created on October 6, 2002, 12:22 AM
*/
package org.tigr.microarray.mev.cgh.CGHUtil;
import java.util.List;
import org.tigr.microarray.mev.TMEV;
/**
*
* @author <NAME>
* @author <NAME>
*/
public class CGHUtility {
/** Creates a new instance of Utility */
public CGHUtility() {
}
public static String encap(String str){
return "'" + str + "'";
}
public static int convertStringToChrom(String strChrom, int species){
if(strChrom.endsWith("_random")){
strChrom = strChrom.substring(0, strChrom.length() - 7);
}
if("chr1".equalsIgnoreCase(strChrom) || "1".equalsIgnoreCase(strChrom)){
return 1;
}else if("chr2".equalsIgnoreCase(strChrom) || "2".equalsIgnoreCase(strChrom)){
return 2;
}else if("chr3".equalsIgnoreCase(strChrom) || "3".equalsIgnoreCase(strChrom)){
return 3;
}else if("chr4".equalsIgnoreCase(strChrom) || "4".equalsIgnoreCase(strChrom)){
return 4;
}else if("chr5".equalsIgnoreCase(strChrom) || "5".equalsIgnoreCase(strChrom)){
return 5;
}else if("chr6".equalsIgnoreCase(strChrom) || "6".equalsIgnoreCase(strChrom)){
return 6;
}else if("chr7".equalsIgnoreCase(strChrom) || "7".equalsIgnoreCase(strChrom)){
return 7;
}else if("chr8".equalsIgnoreCase(strChrom) || "8".equalsIgnoreCase(strChrom)){
return 8;
}else if("chr9".equalsIgnoreCase(strChrom) || "9".equalsIgnoreCase(strChrom)){
return 9;
}else if("chr10".equalsIgnoreCase(strChrom) || "10".equalsIgnoreCase(strChrom)){
return 10;
}else if("chr11".equalsIgnoreCase(strChrom) || "11".equalsIgnoreCase(strChrom)){
return 11;
}else if("chr12".equalsIgnoreCase(strChrom) || "12".equalsIgnoreCase(strChrom)){
return 12;
}else if("chr13".equalsIgnoreCase(strChrom) || "13".equalsIgnoreCase(strChrom)){
return 13;
}else if("chr14".equalsIgnoreCase(strChrom) || "14".equalsIgnoreCase(strChrom)){
return 14;
}else if("chr15".equalsIgnoreCase(strChrom) || "15".equalsIgnoreCase(strChrom)){
return 15;
}else if("chr16".equalsIgnoreCase(strChrom) || "16".equalsIgnoreCase(strChrom)){
return 16;
}else if("chr17".equalsIgnoreCase(strChrom) || "17".equalsIgnoreCase(strChrom)){
return 17;
}else if("chr18".equalsIgnoreCase(strChrom) || "18".equalsIgnoreCase(strChrom)){
return 18;
}else if("chr19".equalsIgnoreCase(strChrom) || "19".equalsIgnoreCase(strChrom)){
return 19;
}else if("chr20".equalsIgnoreCase(strChrom) || "20".equalsIgnoreCase(strChrom)){
return 20;
}else if("chr21".equalsIgnoreCase(strChrom) || "21".equalsIgnoreCase(strChrom)){
return 21;
}else if("chr22".equalsIgnoreCase(strChrom) || "22".equalsIgnoreCase(strChrom)){
return 22;
}else if("chrX".equalsIgnoreCase(strChrom) || "X".equalsIgnoreCase(strChrom)){
//return 23;
int chr = 0;
switch (species){
case TMEV.CGH_SPECIES_HS: {chr = 23; break;}
case TMEV.CGH_SPECIES_MM: {chr = 20; break;}
default: chr = -1; break;
}
return chr;
}else if("chrY".equalsIgnoreCase(strChrom) || "Y".equalsIgnoreCase(strChrom)){
//return 24;
int chr = 0;
switch (species){
case TMEV.CGH_SPECIES_HS: {chr = 24; break;}
case TMEV.CGH_SPECIES_MM: {chr = 21; break;}
default: chr = -2; break;
}
return chr;
}else{
//System.out.println("Util convert chrom, not found: " + strChrom);
return org.tigr.microarray.mev.cgh.CGHDataObj.CGHClone.NOT_FOUND;
}
}
private int XChrToSpecies(int species) {
int chr = 0;
switch (species){
case TMEV.CGH_SPECIES_HS: {chr = 23; break;}
case TMEV.CGH_SPECIES_MM: {chr = 20; break;}
default: chr = -1; break;
}
return chr;
}
public static String convertChromToString(int chrom, int species){
switch (species){
case TMEV.CGH_SPECIES_HS:
if(chrom < 23 && chrom > 0) return "chr" + chrom;
if(chrom == 23) return "chrX";
if(chrom == 24) return "chrY";
case TMEV.CGH_SPECIES_MM:
if(chrom < 20 && chrom > 0) return "chr" + chrom;
if(chrom == 20) return "chrX";
if(chrom == 21) return "chrY";
case TMEV.CGH_SPECIES_Undef:
return "chr" + chrom;
default:
System.out.println("Util convert chrom, not found index: " + chrom);
return "";
}
}
public static String convertChromToLongString(int chrom, int species){
switch (species){
case TMEV.CGH_SPECIES_HS:
if(chrom < 23 && chrom > 0) return "Chromosome " + chrom;
if(chrom == 23) return "Chromosome X";
if(chrom == 24) return "Chromosome Y";
case TMEV.CGH_SPECIES_MM:
if(chrom < 20 && chrom > 0) return "Chromosome " + chrom;
if(chrom == 20) return "Chromosome X";
if(chrom == 21) return "Chromosome Y";
case TMEV.CGH_SPECIES_Undef:
return "Chromosome " + chrom;
default:
System.out.println("Util convert chrom, not found index: " + chrom);
return "";
}
}
public static String createQueryString(List values){
String queryString = "(";
if(values == null || values.size() < 1){
return null;
}
queryString += encap(values.get(0).toString());
for(int i = 1; i < values.size(); i++){
queryString += ", " + encap(values.get(i).toString());
}
return queryString + ")";
}
public static String createIntegerQueryString(List values){
String queryString = "(";
if(values == null || values.size() < 1){
return null;
}
queryString += values.get(0);
for(int i = 1; i < values.size(); i++){
queryString += ", " + values.get(i);
}
return queryString + ")";
}
}
| 6,659 | 0.56295 | 0.534772 | 182 | 35.626373 | 28.70182 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.324176 | false | false | 13 |
3c5cfdabd12211c0eef3608fad26ced7e569664a | 29,068,338,717,015 | 77a3dd9050177af002363a7bc1b663cc5d6a95d2 | /friendlyReminder/src/main/java/com/friendlyreminder/application/person/UserController.java | 0d8b3b4271e008be4604df37e3c7dead1c50baf0 | [] | no_license | reusablebuffalo/csci4448_project | https://github.com/reusablebuffalo/csci4448_project | 7a8d46646347bfea17fd474441e742ea90e78c34 | b1af8e267d6ceac8cde3e5f9da4830a0fcdda4e3 | refs/heads/master | 2020-03-30T00:32:31.427000 | 2018-11-29T16:32:51 | 2018-11-29T16:32:51 | 150,529,531 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.friendlyreminder.application.person;
import com.friendlyreminder.application.HomeController;
import com.friendlyreminder.application.contactbook.ContactBook;
import com.friendlyreminder.application.contactbook.ContactBookRepository;
import com.friendlyreminder.application.event.CommunicationEvent;
import com.friendlyreminder.application.event.CommunicationEventRepository;
import com.friendlyreminder.application.sortstrategy.CommunicationEventSortingStrategy;
import com.friendlyreminder.application.sortstrategy.ContactListSortingStrategy;
import com.friendlyreminder.application.utility.CommunicationType;
import com.friendlyreminder.application.utility.RelativeImportance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
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.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* controller class that handles displaying all views for a logged-in user
* controller handles requests to add/update/delete {@link ContactBook}s,{@link Contact}s, {@link CommunicationEvent}s, and
* {@link com.friendlyreminder.application.sortstrategy.SortingStrategy}s
*/
@Controller
@RequestMapping(path = "/users")
public class UserController {
private final UserRepository userRepository;
private final ContactBookRepository contactBookRepository;
private final ContactRepository contactRepository;
private final CommunicationEventRepository communicationEventRepository;
@Autowired
public UserController(UserRepository userRepository,
ContactBookRepository contactBookRepository,
ContactRepository contactRepository,
CommunicationEventRepository communicationEventRepository) {
this.userRepository = userRepository;
this.contactBookRepository = contactBookRepository;
this.contactRepository = contactRepository;
this.communicationEventRepository = communicationEventRepository;
}
/**
* controller method to display new {@link ContactBook} creation page
* @return filename of view that displays new contact page
*/
@RequestMapping(path="/addBook")
public String addContactBook(){
return "newBook";
}
/**
* method that performs actual creation of new {@link ContactBook}
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookName name of created contactbook, passed as POST request param
* @return filename of view to display (if still logged in, displays User home page else landing page)
*/
@PostMapping(path = "/addBook.do")
public String addContactBookToUser(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam String contactBookName){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
User loggedInUser = optionalUser.get();
ContactBook newBook = new ContactBook(contactBookName);
contactBookRepository.save(newBook);
loggedInUser.addContactBook(newBook);
userRepository.save(loggedInUser);
redirectAttributes.addFlashAttribute("successMessage","Added new contact book!");
return "redirect:/home";
}
/**
* method that handles deletion of a {@link ContactBook} by id
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of contactbook to delete
* @return filename of view for homepage
*/
@GetMapping(path = "/deleteBook")
public String deleteBook(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
User loggedInUser = optionalUser.get();
loggedInUser.removeContactBook(contactBookId);
userRepository.save(loggedInUser);
contactBookRepository.deleteById(contactBookId);
redirectAttributes.addFlashAttribute("successMessage", "Deleted contact book!");
return "redirect:/home";
}
/**
* method to handle changing {@link ContactBook} sortingStrategy
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of contactbook
* @param sortingStrategy strategy to sort this ContactBook with
* @return filename of view to display
*/
@GetMapping(path = "/openBook/changeSort")
public String changeContactSort(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId,
@RequestParam ContactListSortingStrategy sortingStrategy){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<ContactBook> optionalContactBook = contactBookRepository.findById(contactBookId);
if(optionalContactBook.isPresent()){
ContactBook contactBook = optionalContactBook.get();
contactBook.setSortingStrategy(sortingStrategy);
contactBookRepository.save(contactBook);
redirectAttributes.addFlashAttribute("successMessage","sorting strategy changed!");
} else {
redirectAttributes.addFlashAttribute("errorMessage","sorting strategy not changed!");
}
redirectAttributes.addAttribute("contactBookId",contactBookId);
return "redirect:/users/openBook";
}
/**
* method to verify login and display a contactbook's contents
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of contact book to open
* @return filename of view to display
*/
@GetMapping(path = "/openBook")
public String viewBook(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
User loggedInUser = optionalUser.get();
Optional<ContactBook> optionalContactBook = contactBookRepository.findById(contactBookId);
if(!optionalContactBook.isPresent()){
redirectAttributes.addFlashAttribute("errorMessage","An Error Occurred While Deleting Contact Book!");
return "redirect:/home";
}
ContactBook contactBook = optionalContactBook.get();
model.addAttribute("sortStrategies",ContactListSortingStrategy.values());
model.addAttribute("firstName",loggedInUser.getFirstName());
model.addAttribute("contactBook",contactBook);
return "contactBook";
}
/**
* method to display view that allows User to create new {@link Contact} for ContactBook
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of book to add contact to
* @return filename of view to display
*/
@RequestMapping(path="/addContact")
public String addContact(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
model.addAttribute("contactBookId",contactBookId);
model.addAttribute("roles",RelativeImportance.values());
model.addAttribute("newContact", true);
return "addContact";
}
/**
* method to display view that allows User to make request to update existing {@link Contact} in ContactBook
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of book to add contact to
* @param contactId unique id of contact to update
* @return filename of view to display
*/
@RequestMapping(path="/updateContact")
public String updateContact(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactId, @RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<Contact> optionalContact = contactRepository.findById(contactId);
if(optionalContact.isPresent()) {
Contact contact = optionalContact.get();
model.addAttribute("contact", contact);
}
model.addAttribute("contactBookId", contactBookId);
model.addAttribute("contactId", contactId);
model.addAttribute("roles",RelativeImportance.values());
model.addAttribute("newContact", false);
return "addContact";
}
/**
* method to perform actual update of {@link Contact} in {@link ContactBook}
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of contact book to update contact in
* @param importance relative importance value of the contact
* @param contactFirstName new first name of contact
* @param contactLastName new last name of contact
* @param contactNotes new notes for contact
* @param contactPhoneNumber new phonenumber for contact
* @param contactEmailAddress new emailaddress for contact
* @param contactId contact to update
* @return filename of view to display
*/
@PostMapping(path = "/updateContact.do")
public String updateContactInContactBook(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId,
@RequestParam RelativeImportance importance,
@RequestParam String contactFirstName,
@RequestParam String contactLastName,
@RequestParam String contactNotes,
@RequestParam String contactPhoneNumber,
@RequestParam String contactEmailAddress,
@RequestParam Integer contactId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<Contact> optionalContact = contactRepository.findById(contactId);
if(optionalContact.isPresent()){
Contact contact = optionalContact.get();
contact.setFirstName(contactFirstName);
contact.setLastName(contactLastName);
contact.setRelativeImportance(importance);
contact.setPhoneNumber(contactPhoneNumber);
contact.setEmailAddress(contactEmailAddress);
contact.setNotes(contactNotes);
contactRepository.save(contact);
model.addAttribute("successMessage", "Contact updated!");
} else {
model.addAttribute("errorMessage","Error Updating Contact!");
}
return viewBook(httpSession, redirectAttributes, model,contactBookId);
}
/**
* method to perform actual addtion of {@link Contact} to {@link ContactBook}
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of contact book to update contact in
* @param importance relative importance value of the contact
* @param contactFirstName new first name of contact
* @param contactLastName new last name of contact
* @param contactNotes new notes for contact
* @param contactPhoneNumber new phonenumber for contact
* @param contactEmailAddress new emailaddress for contact
* @return filename of view to display
*/
@PostMapping(path = "/addContact.do")
public String addContactToContactBook(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId,
@RequestParam RelativeImportance importance,
@RequestParam String contactFirstName,
@RequestParam String contactLastName,
@RequestParam String contactNotes,
@RequestParam String contactPhoneNumber,
@RequestParam String contactEmailAddress){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<ContactBook> optionalContactBook = contactBookRepository.findById(contactBookId);
if(optionalContactBook.isPresent()){
ContactBook contactBook = optionalContactBook.get();
Contact newContact = new Contact(contactFirstName,contactLastName,contactEmailAddress,contactNotes,contactPhoneNumber,importance);
contactRepository.save(newContact);
contactBook.addContact(newContact);
contactBookRepository.save(contactBook);
model.addAttribute("successMessage", "Contact added!");
} else {
model.addAttribute("errorMessage","Error Updating Contact Book!");
}
return viewBook(httpSession, redirectAttributes, model, contactBookId);
}
/**
* method to delete to contact from specified contactbook
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId contactbook to delete from
* @param contactId contact to delete
* @return filename of view to display (if logged in it will be contactBook view page otherwise landing page)
*/
@GetMapping(path = "/deleteContact")
public String deleteBook(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId,
@RequestParam Integer contactId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<ContactBook> contactBookOptional = contactBookRepository.findById(contactBookId);
if(contactBookOptional.isPresent()){
ContactBook contactBook = contactBookOptional.get();
contactBook.removeContact(contactId);
contactBookRepository.save(contactBook);
}
contactRepository.deleteById(contactId);
model.addAttribute("successMessage", "Deleted contact!");
return viewBook(httpSession,redirectAttributes,model,contactBookId);
}
/**
* method to change sortingStrategy for events in specified contact
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactId unique id of contact to change strategy for
* @param contactBookId book to return to if goback option is selected
* @param sortingStrategy new strategy ({@link CommunicationEventSortingStrategy}
* @return filename of view to display (if logged in, we display contact view page else we display landing page)
*/
@GetMapping(path = "/openContact/changeSort")
public String changeEventSort(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactId,
@RequestParam Integer contactBookId,
@RequestParam CommunicationEventSortingStrategy sortingStrategy){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<Contact> contactOptional = contactRepository.findById(contactId);
if(contactOptional.isPresent()) {
Contact contact = contactOptional.get();
contact.setSortingStrategy(sortingStrategy);
contactRepository.save(contact);
redirectAttributes.addFlashAttribute("successMessage","sorting strategy changed!");
} else {
redirectAttributes.addFlashAttribute("errorMessage","sorting strategy not changed!");
}
redirectAttributes.addAttribute("contactId",contactId);
redirectAttributes.addAttribute("contactBookId",contactBookId);
return "redirect:/users/openContact#eventTable";
}
/**
* method to display view to see data for a given contact
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactId unique id of contact to view
* @param contactBookId book that contains this contact
* @return filename of view to display
*/
@GetMapping(path = "/openContact")
public String viewContact(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactId,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<Contact> contactOptional = contactRepository.findById(contactId);
if(!contactOptional.isPresent()) {
model.addAttribute("errorMessage","Something went wrong when trying to view contact!");
return viewBook(httpSession,redirectAttributes,model,contactBookId);
}
Contact contact = contactOptional.get();
model.addAttribute("contact",contact);
model.addAttribute("contactBookId", contactBookId);
model.addAttribute("sortStrategies", CommunicationEventSortingStrategy.values());
return "contact";
}
/**
* method to display view that contains form to create new communication event for a given contact in a given contact book
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactId unique id of contact to add event for
* @param contactBookId unique id of contact book to add to
* @return filename of view to display
*/
@GetMapping(path = "/addEvent")
public String addEvent(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactId,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
model.addAttribute("contactId", contactId);
model.addAttribute("contactBookId", contactBookId);
model.addAttribute("communicationTypes", CommunicationType.values());
return "addEvent";
}
/**
* method that handles POST request to actually add new communication event to given contact
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactId id of contact to add event to
* @param contactBookId id of contact book this contact belongs to
* @param date parameter (passed from form) that designates which date this occurred on
* @param eventType parameter (passed from form) that designates type of contact (enum {@link CommunicationType}
* @param eventNotes parameter (passed from form) that is notes related to this event, designated by user
* @return filename of view to display after transaction completed (landing if not logged in, contact view page if successful)
*/
@PostMapping(path = "/addEvent.do")
public String addEventToContact(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactId,
@RequestParam Integer contactBookId,
@RequestParam(name = "eventDate") String date,
@RequestParam String eventType,
@RequestParam String eventNotes){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
String[] yearMonthDayStrings = StringUtils.tokenizeToStringArray(date,"-");
if(yearMonthDayStrings == null || yearMonthDayStrings.length != 3){
model.addAttribute("errorMessage","Incorrect Date! Can not create event!");
return viewContact(httpSession,redirectAttributes,model,contactId,contactBookId);
}
// convert to date as strings to integers
List<Integer> yearMonthDayInt = Arrays.stream(yearMonthDayStrings).map(Integer::valueOf).collect(Collectors.toList());
Optional<Contact> contactOptional = contactRepository.findById(contactId);
if(!contactOptional.isPresent()){
model.addAttribute("errorMessage","Could not add event to contact: contact does not exist!");
return viewContact(httpSession,redirectAttributes,model,contactId,contactBookId);
}
LocalDate eventDate = LocalDate.of(yearMonthDayInt.get(0),yearMonthDayInt.get(1),yearMonthDayInt.get(2));
Contact contactToAddEventTo = contactOptional.get();
CommunicationEvent newEvent = new CommunicationEvent(eventDate,eventNotes,CommunicationType.valueOf(eventType));
communicationEventRepository.save(newEvent);
contactToAddEventTo.addCommunicationEvent(newEvent);
contactRepository.save(contactToAddEventTo);
model.addAttribute("successMessage","Successfully added event!");
return viewContact(httpSession,redirectAttributes,model,contactId,contactBookId);
}
/**
* method that completes GET request to delete a communication event from a contact
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param eventId unique id of event to delete
* @param contactId unique id of contact to delete event from
* @param contactBookId unique id of book this contact belongs to
* @return filename of view for controller to display
*/
@GetMapping(path = "/deleteEvent")
public String deleteEvent(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer eventId,
@RequestParam Integer contactId,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<Contact> contactOptional = contactRepository.findById(contactId);
if(contactOptional.isPresent()){
Contact contact = contactOptional.get();
contact.removeCommunicationEvent(eventId);
contactRepository.save(contact);
}
communicationEventRepository.deleteById(eventId);
model.addAttribute("successMessage", "Deleted event!");
return viewContact(httpSession,redirectAttributes,model,contactId,contactBookId);
}
/**
* UserController method to display all registered users (and their nested contact books, contacts, events)
* @return JSON response to be displayed by browser that contains all registered users and their data
*/
@GetMapping(path="/all")
public @ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the contact list
return userRepository.findAll();
}
// helper methods
private Optional<User> getLoggedInUserFromSession(HttpSession httpSession){
Integer loggedInUserId = HomeController.getUserIdFromSession(httpSession);
if(loggedInUserId == null){
return Optional.empty();
}
Optional<User> userOptional = userRepository.findById(loggedInUserId);
// if not found, we log out
if(!userOptional.isPresent()){
HomeController.removeLoggedInUserIdFromSession(httpSession);
}
return userOptional;
}
private static String authenticationErrorRedirect(RedirectAttributes redirectAttributes){
redirectAttributes.addFlashAttribute("errorMessage","LoginStatusError: Redirected to home!");
return "redirect:/home";
}
}
| UTF-8 | Java | 28,588 | java | UserController.java | Java | [] | null | [] | package com.friendlyreminder.application.person;
import com.friendlyreminder.application.HomeController;
import com.friendlyreminder.application.contactbook.ContactBook;
import com.friendlyreminder.application.contactbook.ContactBookRepository;
import com.friendlyreminder.application.event.CommunicationEvent;
import com.friendlyreminder.application.event.CommunicationEventRepository;
import com.friendlyreminder.application.sortstrategy.CommunicationEventSortingStrategy;
import com.friendlyreminder.application.sortstrategy.ContactListSortingStrategy;
import com.friendlyreminder.application.utility.CommunicationType;
import com.friendlyreminder.application.utility.RelativeImportance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
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.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* controller class that handles displaying all views for a logged-in user
* controller handles requests to add/update/delete {@link ContactBook}s,{@link Contact}s, {@link CommunicationEvent}s, and
* {@link com.friendlyreminder.application.sortstrategy.SortingStrategy}s
*/
@Controller
@RequestMapping(path = "/users")
public class UserController {
private final UserRepository userRepository;
private final ContactBookRepository contactBookRepository;
private final ContactRepository contactRepository;
private final CommunicationEventRepository communicationEventRepository;
@Autowired
public UserController(UserRepository userRepository,
ContactBookRepository contactBookRepository,
ContactRepository contactRepository,
CommunicationEventRepository communicationEventRepository) {
this.userRepository = userRepository;
this.contactBookRepository = contactBookRepository;
this.contactRepository = contactRepository;
this.communicationEventRepository = communicationEventRepository;
}
/**
* controller method to display new {@link ContactBook} creation page
* @return filename of view that displays new contact page
*/
@RequestMapping(path="/addBook")
public String addContactBook(){
return "newBook";
}
/**
* method that performs actual creation of new {@link ContactBook}
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookName name of created contactbook, passed as POST request param
* @return filename of view to display (if still logged in, displays User home page else landing page)
*/
@PostMapping(path = "/addBook.do")
public String addContactBookToUser(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam String contactBookName){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
User loggedInUser = optionalUser.get();
ContactBook newBook = new ContactBook(contactBookName);
contactBookRepository.save(newBook);
loggedInUser.addContactBook(newBook);
userRepository.save(loggedInUser);
redirectAttributes.addFlashAttribute("successMessage","Added new contact book!");
return "redirect:/home";
}
/**
* method that handles deletion of a {@link ContactBook} by id
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of contactbook to delete
* @return filename of view for homepage
*/
@GetMapping(path = "/deleteBook")
public String deleteBook(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
User loggedInUser = optionalUser.get();
loggedInUser.removeContactBook(contactBookId);
userRepository.save(loggedInUser);
contactBookRepository.deleteById(contactBookId);
redirectAttributes.addFlashAttribute("successMessage", "Deleted contact book!");
return "redirect:/home";
}
/**
* method to handle changing {@link ContactBook} sortingStrategy
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of contactbook
* @param sortingStrategy strategy to sort this ContactBook with
* @return filename of view to display
*/
@GetMapping(path = "/openBook/changeSort")
public String changeContactSort(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId,
@RequestParam ContactListSortingStrategy sortingStrategy){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<ContactBook> optionalContactBook = contactBookRepository.findById(contactBookId);
if(optionalContactBook.isPresent()){
ContactBook contactBook = optionalContactBook.get();
contactBook.setSortingStrategy(sortingStrategy);
contactBookRepository.save(contactBook);
redirectAttributes.addFlashAttribute("successMessage","sorting strategy changed!");
} else {
redirectAttributes.addFlashAttribute("errorMessage","sorting strategy not changed!");
}
redirectAttributes.addAttribute("contactBookId",contactBookId);
return "redirect:/users/openBook";
}
/**
* method to verify login and display a contactbook's contents
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of contact book to open
* @return filename of view to display
*/
@GetMapping(path = "/openBook")
public String viewBook(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
User loggedInUser = optionalUser.get();
Optional<ContactBook> optionalContactBook = contactBookRepository.findById(contactBookId);
if(!optionalContactBook.isPresent()){
redirectAttributes.addFlashAttribute("errorMessage","An Error Occurred While Deleting Contact Book!");
return "redirect:/home";
}
ContactBook contactBook = optionalContactBook.get();
model.addAttribute("sortStrategies",ContactListSortingStrategy.values());
model.addAttribute("firstName",loggedInUser.getFirstName());
model.addAttribute("contactBook",contactBook);
return "contactBook";
}
/**
* method to display view that allows User to create new {@link Contact} for ContactBook
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of book to add contact to
* @return filename of view to display
*/
@RequestMapping(path="/addContact")
public String addContact(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
model.addAttribute("contactBookId",contactBookId);
model.addAttribute("roles",RelativeImportance.values());
model.addAttribute("newContact", true);
return "addContact";
}
/**
* method to display view that allows User to make request to update existing {@link Contact} in ContactBook
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of book to add contact to
* @param contactId unique id of contact to update
* @return filename of view to display
*/
@RequestMapping(path="/updateContact")
public String updateContact(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactId, @RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<Contact> optionalContact = contactRepository.findById(contactId);
if(optionalContact.isPresent()) {
Contact contact = optionalContact.get();
model.addAttribute("contact", contact);
}
model.addAttribute("contactBookId", contactBookId);
model.addAttribute("contactId", contactId);
model.addAttribute("roles",RelativeImportance.values());
model.addAttribute("newContact", false);
return "addContact";
}
/**
* method to perform actual update of {@link Contact} in {@link ContactBook}
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of contact book to update contact in
* @param importance relative importance value of the contact
* @param contactFirstName new first name of contact
* @param contactLastName new last name of contact
* @param contactNotes new notes for contact
* @param contactPhoneNumber new phonenumber for contact
* @param contactEmailAddress new emailaddress for contact
* @param contactId contact to update
* @return filename of view to display
*/
@PostMapping(path = "/updateContact.do")
public String updateContactInContactBook(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId,
@RequestParam RelativeImportance importance,
@RequestParam String contactFirstName,
@RequestParam String contactLastName,
@RequestParam String contactNotes,
@RequestParam String contactPhoneNumber,
@RequestParam String contactEmailAddress,
@RequestParam Integer contactId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<Contact> optionalContact = contactRepository.findById(contactId);
if(optionalContact.isPresent()){
Contact contact = optionalContact.get();
contact.setFirstName(contactFirstName);
contact.setLastName(contactLastName);
contact.setRelativeImportance(importance);
contact.setPhoneNumber(contactPhoneNumber);
contact.setEmailAddress(contactEmailAddress);
contact.setNotes(contactNotes);
contactRepository.save(contact);
model.addAttribute("successMessage", "Contact updated!");
} else {
model.addAttribute("errorMessage","Error Updating Contact!");
}
return viewBook(httpSession, redirectAttributes, model,contactBookId);
}
/**
* method to perform actual addtion of {@link Contact} to {@link ContactBook}
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId unique id of contact book to update contact in
* @param importance relative importance value of the contact
* @param contactFirstName new first name of contact
* @param contactLastName new last name of contact
* @param contactNotes new notes for contact
* @param contactPhoneNumber new phonenumber for contact
* @param contactEmailAddress new emailaddress for contact
* @return filename of view to display
*/
@PostMapping(path = "/addContact.do")
public String addContactToContactBook(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId,
@RequestParam RelativeImportance importance,
@RequestParam String contactFirstName,
@RequestParam String contactLastName,
@RequestParam String contactNotes,
@RequestParam String contactPhoneNumber,
@RequestParam String contactEmailAddress){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<ContactBook> optionalContactBook = contactBookRepository.findById(contactBookId);
if(optionalContactBook.isPresent()){
ContactBook contactBook = optionalContactBook.get();
Contact newContact = new Contact(contactFirstName,contactLastName,contactEmailAddress,contactNotes,contactPhoneNumber,importance);
contactRepository.save(newContact);
contactBook.addContact(newContact);
contactBookRepository.save(contactBook);
model.addAttribute("successMessage", "Contact added!");
} else {
model.addAttribute("errorMessage","Error Updating Contact Book!");
}
return viewBook(httpSession, redirectAttributes, model, contactBookId);
}
/**
* method to delete to contact from specified contactbook
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactBookId contactbook to delete from
* @param contactId contact to delete
* @return filename of view to display (if logged in it will be contactBook view page otherwise landing page)
*/
@GetMapping(path = "/deleteContact")
public String deleteBook(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactBookId,
@RequestParam Integer contactId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<ContactBook> contactBookOptional = contactBookRepository.findById(contactBookId);
if(contactBookOptional.isPresent()){
ContactBook contactBook = contactBookOptional.get();
contactBook.removeContact(contactId);
contactBookRepository.save(contactBook);
}
contactRepository.deleteById(contactId);
model.addAttribute("successMessage", "Deleted contact!");
return viewBook(httpSession,redirectAttributes,model,contactBookId);
}
/**
* method to change sortingStrategy for events in specified contact
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactId unique id of contact to change strategy for
* @param contactBookId book to return to if goback option is selected
* @param sortingStrategy new strategy ({@link CommunicationEventSortingStrategy}
* @return filename of view to display (if logged in, we display contact view page else we display landing page)
*/
@GetMapping(path = "/openContact/changeSort")
public String changeEventSort(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactId,
@RequestParam Integer contactBookId,
@RequestParam CommunicationEventSortingStrategy sortingStrategy){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<Contact> contactOptional = contactRepository.findById(contactId);
if(contactOptional.isPresent()) {
Contact contact = contactOptional.get();
contact.setSortingStrategy(sortingStrategy);
contactRepository.save(contact);
redirectAttributes.addFlashAttribute("successMessage","sorting strategy changed!");
} else {
redirectAttributes.addFlashAttribute("errorMessage","sorting strategy not changed!");
}
redirectAttributes.addAttribute("contactId",contactId);
redirectAttributes.addAttribute("contactBookId",contactBookId);
return "redirect:/users/openContact#eventTable";
}
/**
* method to display view to see data for a given contact
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactId unique id of contact to view
* @param contactBookId book that contains this contact
* @return filename of view to display
*/
@GetMapping(path = "/openContact")
public String viewContact(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactId,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<Contact> contactOptional = contactRepository.findById(contactId);
if(!contactOptional.isPresent()) {
model.addAttribute("errorMessage","Something went wrong when trying to view contact!");
return viewBook(httpSession,redirectAttributes,model,contactBookId);
}
Contact contact = contactOptional.get();
model.addAttribute("contact",contact);
model.addAttribute("contactBookId", contactBookId);
model.addAttribute("sortStrategies", CommunicationEventSortingStrategy.values());
return "contact";
}
/**
* method to display view that contains form to create new communication event for a given contact in a given contact book
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactId unique id of contact to add event for
* @param contactBookId unique id of contact book to add to
* @return filename of view to display
*/
@GetMapping(path = "/addEvent")
public String addEvent(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactId,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
model.addAttribute("contactId", contactId);
model.addAttribute("contactBookId", contactBookId);
model.addAttribute("communicationTypes", CommunicationType.values());
return "addEvent";
}
/**
* method that handles POST request to actually add new communication event to given contact
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param contactId id of contact to add event to
* @param contactBookId id of contact book this contact belongs to
* @param date parameter (passed from form) that designates which date this occurred on
* @param eventType parameter (passed from form) that designates type of contact (enum {@link CommunicationType}
* @param eventNotes parameter (passed from form) that is notes related to this event, designated by user
* @return filename of view to display after transaction completed (landing if not logged in, contact view page if successful)
*/
@PostMapping(path = "/addEvent.do")
public String addEventToContact(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer contactId,
@RequestParam Integer contactBookId,
@RequestParam(name = "eventDate") String date,
@RequestParam String eventType,
@RequestParam String eventNotes){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
String[] yearMonthDayStrings = StringUtils.tokenizeToStringArray(date,"-");
if(yearMonthDayStrings == null || yearMonthDayStrings.length != 3){
model.addAttribute("errorMessage","Incorrect Date! Can not create event!");
return viewContact(httpSession,redirectAttributes,model,contactId,contactBookId);
}
// convert to date as strings to integers
List<Integer> yearMonthDayInt = Arrays.stream(yearMonthDayStrings).map(Integer::valueOf).collect(Collectors.toList());
Optional<Contact> contactOptional = contactRepository.findById(contactId);
if(!contactOptional.isPresent()){
model.addAttribute("errorMessage","Could not add event to contact: contact does not exist!");
return viewContact(httpSession,redirectAttributes,model,contactId,contactBookId);
}
LocalDate eventDate = LocalDate.of(yearMonthDayInt.get(0),yearMonthDayInt.get(1),yearMonthDayInt.get(2));
Contact contactToAddEventTo = contactOptional.get();
CommunicationEvent newEvent = new CommunicationEvent(eventDate,eventNotes,CommunicationType.valueOf(eventType));
communicationEventRepository.save(newEvent);
contactToAddEventTo.addCommunicationEvent(newEvent);
contactRepository.save(contactToAddEventTo);
model.addAttribute("successMessage","Successfully added event!");
return viewContact(httpSession,redirectAttributes,model,contactId,contactBookId);
}
/**
* method that completes GET request to delete a communication event from a contact
* @param redirectAttributes contains attributes used by controller in redirect scenario
* @param httpSession session that will contain login status as attribute
* @param model model object with model attributes used in displaying view
* @param eventId unique id of event to delete
* @param contactId unique id of contact to delete event from
* @param contactBookId unique id of book this contact belongs to
* @return filename of view for controller to display
*/
@GetMapping(path = "/deleteEvent")
public String deleteEvent(HttpSession httpSession, RedirectAttributes redirectAttributes, Model model,
@RequestParam Integer eventId,
@RequestParam Integer contactId,
@RequestParam Integer contactBookId){
Optional<User> optionalUser = getLoggedInUserFromSession(httpSession);
if(!optionalUser.isPresent()){
return authenticationErrorRedirect(redirectAttributes);
}
Optional<Contact> contactOptional = contactRepository.findById(contactId);
if(contactOptional.isPresent()){
Contact contact = contactOptional.get();
contact.removeCommunicationEvent(eventId);
contactRepository.save(contact);
}
communicationEventRepository.deleteById(eventId);
model.addAttribute("successMessage", "Deleted event!");
return viewContact(httpSession,redirectAttributes,model,contactId,contactBookId);
}
/**
* UserController method to display all registered users (and their nested contact books, contacts, events)
* @return JSON response to be displayed by browser that contains all registered users and their data
*/
@GetMapping(path="/all")
public @ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the contact list
return userRepository.findAll();
}
// helper methods
private Optional<User> getLoggedInUserFromSession(HttpSession httpSession){
Integer loggedInUserId = HomeController.getUserIdFromSession(httpSession);
if(loggedInUserId == null){
return Optional.empty();
}
Optional<User> userOptional = userRepository.findById(loggedInUserId);
// if not found, we log out
if(!userOptional.isPresent()){
HomeController.removeLoggedInUserIdFromSession(httpSession);
}
return userOptional;
}
private static String authenticationErrorRedirect(RedirectAttributes redirectAttributes){
redirectAttributes.addFlashAttribute("errorMessage","LoginStatusError: Redirected to home!");
return "redirect:/home";
}
}
| 28,588 | 0.698615 | 0.698475 | 530 | 52.939621 | 32.318874 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.649057 | false | false | 13 |
07853d420cb18a82568d9656b305b6f1d0c5144d | 17,377,437,684,947 | 1dccc9f81594e0e82a7ac0b78d4fdb4e3d6e9d67 | /src/main/java/edu/indiana/dlib/amppd/model/projection/MgmCategoryDetail.java | 3377801cdd9a4068735bdac4d11d6dd490e85323 | [
"Apache-2.0"
] | permissive | AudiovisualMetadataPlatform/amppd | https://github.com/AudiovisualMetadataPlatform/amppd | 10b3213701141d286e569ce3832f34b0ab1888ff | 0521e3004b52926f5578e36139d5dee6d1445d9f | refs/heads/master | 2023-08-03T04:08:25.592000 | 2023-08-01T21:59:42 | 2023-08-01T21:59:42 | 159,361,634 | 6 | 4 | Apache-2.0 | false | 2023-09-14T02:37:25 | 2018-11-27T15:59:04 | 2023-01-20T15:19:44 | 2023-09-14T02:37:24 | 11,980 | 5 | 4 | 1 | Java | false | false | package edu.indiana.dlib.amppd.model.projection;
import java.util.Set;
import org.springframework.data.rest.core.config.Projection;
import edu.indiana.dlib.amppd.model.MgmCategory;
/**
* Projection for a detailed view of an MgmCategory.
* @author yingfeng
*/
@Projection(name = "detail", types = {MgmCategory.class})
public interface MgmCategoryDetail extends MgmCategoryBrief, MgmMetaDetail {
public Set<MgmScoringToolBrief> getMsts();
public Set<MgmToolBrief> getMgms();
}
| UTF-8 | Java | 487 | java | MgmCategoryDetail.java | Java | [
{
"context": " for a detailed view of an MgmCategory.\n * @author yingfeng\n */\n@Projection(name = \"detail\", types = {MgmCate",
"end": 261,
"score": 0.994163990020752,
"start": 253,
"tag": "USERNAME",
"value": "yingfeng"
}
] | null | [] | package edu.indiana.dlib.amppd.model.projection;
import java.util.Set;
import org.springframework.data.rest.core.config.Projection;
import edu.indiana.dlib.amppd.model.MgmCategory;
/**
* Projection for a detailed view of an MgmCategory.
* @author yingfeng
*/
@Projection(name = "detail", types = {MgmCategory.class})
public interface MgmCategoryDetail extends MgmCategoryBrief, MgmMetaDetail {
public Set<MgmScoringToolBrief> getMsts();
public Set<MgmToolBrief> getMgms();
}
| 487 | 0.776181 | 0.776181 | 19 | 24.631578 | 25.639629 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 13 |
b3f9f192a3a688d1a960e6862f7f0cda80498e9f | 24,567,212,959,549 | f77673f91ef8b9a7f2dbde619b89e97ac5ff31d4 | /src/main/java/be/kdg/kandoe/frontend/controllers/resources/content/CardResource.java | 6d9919279aae8bfd1a13390980d56ff28f18d45b | [] | no_license | Shenno/kandoe | https://github.com/Shenno/kandoe | e683e80419bf65286828e0d8af791594ca1bebbe | 29f16720ef845e71929777d4fe9d5ab42d6ef701 | refs/heads/master | 2021-01-10T15:40:44.677000 | 2016-03-25T11:40:34 | 2016-03-25T11:40:34 | 51,761,892 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package be.kdg.kandoe.frontend.controllers.resources.content;
import be.kdg.kandoe.backend.dom.content.Card;
import org.springframework.hateoas.ResourceSupport;
import java.io.Serializable;
/**
* CardResource is a Resource object for a {link: Card}
*/
public class CardResource implements Serializable {
private Integer id;
private String text;
private String imageURL;
private Integer themeId;
public CardResource() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getText() {
return text;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public Integer getThemeId() {
return themeId;
}
public void setThemeId(Integer themeId) {
this.themeId = themeId;
}
public void setText(String text) {
this.text = text;
}
}
| UTF-8 | Java | 1,009 | java | CardResource.java | Java | [] | null | [] | package be.kdg.kandoe.frontend.controllers.resources.content;
import be.kdg.kandoe.backend.dom.content.Card;
import org.springframework.hateoas.ResourceSupport;
import java.io.Serializable;
/**
* CardResource is a Resource object for a {link: Card}
*/
public class CardResource implements Serializable {
private Integer id;
private String text;
private String imageURL;
private Integer themeId;
public CardResource() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getText() {
return text;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public Integer getThemeId() {
return themeId;
}
public void setThemeId(Integer themeId) {
this.themeId = themeId;
}
public void setText(String text) {
this.text = text;
}
}
| 1,009 | 0.640238 | 0.640238 | 52 | 18.403847 | 17.836069 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 13 |
fc38da98172de6e31f1ff9272673150ce43374c1 | 893,353,241,228 | 77213202ddb2a91cdb8491c15921cff27a3f12be | /src/dicegames/CrapsPlay.java | 9fe9e97370f27ee81064ebafe721db7784171874 | [] | no_license | tldoa/Dicegames-Projekt-1 | https://github.com/tldoa/Dicegames-Projekt-1 | cd4ee76ee1cf3f5745d2cdc1beb043c954d4f209 | b1aaf897c1769b8cdc8318c6b0ec63692339f53b | refs/heads/master | 2021-01-10T02:45:14.346000 | 2016-03-04T11:27:04 | 2016-03-04T11:27:04 | 53,130,498 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dicegames;
import java.util.Scanner;
public class CrapsPlay {
// Instance variables for the game CrapsPlay
private Die die1;
private Die die2;
private int state;
private Scanner scan;
private int firstRoll;
// Constructor for the CrapsPlay game, that creates 2 dices
public CrapsPlay() {
this.die1 = new Die();
this.die2 = new Die();
this.state = 0;
this.firstRoll = 0;
scan = new Scanner(System.in);
}
// Game greeting
private void sayHello() {
System.out.println("Velkommen til....trommehvirvel...CRAPS");
}
// A method that is called to print a suitable response to the way a game
// has ended
private void gameOver() {
if (state == 1) {
System.out.println("Du vandt");
} else if (state == 2) {
System.out.println("Du tabte");
} else if (state == 3) {
System.out.println("Du har givet op");
}
scan.close();
}
// A method that rolls the both dice and determines whether your roll is
// your first roll
// and the sets the conditions for winning and loosing
public void takeTurn() {
this.die1.roll();
this.die2.roll();
int actualRoll = die1.getFaceValue() + die2.getFaceValue();
System.out.println("Du slog: " + actualRoll);
if (firstRoll == 0) {
if (actualRoll == 7 || actualRoll == 11) {
state = 1;
} else if (actualRoll == 2 || actualRoll == 3 || actualRoll == 12) {
state = 2;
} else {
firstRoll = actualRoll;
}
} else {
if (actualRoll == 7) {
state = 2;
} else if (actualRoll == firstRoll) {
state = 1;
}
}
}
// A method that initializes the CrapsPlay game and determines whether the
// game has been won,
// lost or if the player has forfeited the game
public void startGame() {
sayHello();
while (state == 0) {
while (state == 0) {
System.out.println("Vil du kaste terningerne? Angiv Ja eller Nej: ");
String proceedWithGame = scan.nextLine();
if (proceedWithGame.equalsIgnoreCase("nej")) {
state = 3;
} else {
takeTurn();
}
}
gameOver();
System.out.println("Vil du spille igen? ");
String proceedWithGame = scan.nextLine();
if (proceedWithGame.equalsIgnoreCase("ja")) {
state = 0;
firstRoll = 0;
} else {
System.out.println("Taber");
}
}
}
}
| UTF-8 | Java | 2,258 | java | CrapsPlay.java | Java | [] | null | [] | package dicegames;
import java.util.Scanner;
public class CrapsPlay {
// Instance variables for the game CrapsPlay
private Die die1;
private Die die2;
private int state;
private Scanner scan;
private int firstRoll;
// Constructor for the CrapsPlay game, that creates 2 dices
public CrapsPlay() {
this.die1 = new Die();
this.die2 = new Die();
this.state = 0;
this.firstRoll = 0;
scan = new Scanner(System.in);
}
// Game greeting
private void sayHello() {
System.out.println("Velkommen til....trommehvirvel...CRAPS");
}
// A method that is called to print a suitable response to the way a game
// has ended
private void gameOver() {
if (state == 1) {
System.out.println("Du vandt");
} else if (state == 2) {
System.out.println("Du tabte");
} else if (state == 3) {
System.out.println("Du har givet op");
}
scan.close();
}
// A method that rolls the both dice and determines whether your roll is
// your first roll
// and the sets the conditions for winning and loosing
public void takeTurn() {
this.die1.roll();
this.die2.roll();
int actualRoll = die1.getFaceValue() + die2.getFaceValue();
System.out.println("Du slog: " + actualRoll);
if (firstRoll == 0) {
if (actualRoll == 7 || actualRoll == 11) {
state = 1;
} else if (actualRoll == 2 || actualRoll == 3 || actualRoll == 12) {
state = 2;
} else {
firstRoll = actualRoll;
}
} else {
if (actualRoll == 7) {
state = 2;
} else if (actualRoll == firstRoll) {
state = 1;
}
}
}
// A method that initializes the CrapsPlay game and determines whether the
// game has been won,
// lost or if the player has forfeited the game
public void startGame() {
sayHello();
while (state == 0) {
while (state == 0) {
System.out.println("Vil du kaste terningerne? Angiv Ja eller Nej: ");
String proceedWithGame = scan.nextLine();
if (proceedWithGame.equalsIgnoreCase("nej")) {
state = 3;
} else {
takeTurn();
}
}
gameOver();
System.out.println("Vil du spille igen? ");
String proceedWithGame = scan.nextLine();
if (proceedWithGame.equalsIgnoreCase("ja")) {
state = 0;
firstRoll = 0;
} else {
System.out.println("Taber");
}
}
}
}
| 2,258 | 0.632861 | 0.618689 | 99 | 21.808081 | 19.916836 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.313131 | false | false | 13 |
e8574d56c9ce0f5da86895a0c58bca8a9d7057da | 1,924,145,363,227 | c97459df65e35b7102bbc8fce3affa7213417733 | /L3/Projet_CPO5_Jeu_de_le_vie/HighLife.java | 622c97e6502d1fd87d180dfc61343548cb015908 | [] | no_license | MeriemFekih/L3 | https://github.com/MeriemFekih/L3 | 5e9da1b42eada8fe4869be14bcc4a9c92d268585 | 52eb225c6f679793c9df0a8625b1e2b3d2a108cb | refs/heads/master | 2022-05-13T17:56:00.173000 | 2018-01-17T22:08:46 | 2018-01-17T22:08:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class HighLife extends Cellule{
public HighLife(){
super();
this.setState(Etat.values()[new Random().nextInt(Etat.values().length)]);
}
public State nextState(){
int nb = numberAliveNeighbor();
if( first_rule(nb) || second_rule(nb) ){
return Etat.UN;
}
return Etat.ZERO;
}
public boolean first_rule(int n){
if( this.s == Etat.ZERO && (n == 3 || n == 6) ){
return true;
}
return false;
}
public boolean second_rule(int n){
if( this.s == Etat.UN && (n == 2 || n == 3)){
return true;
}
return false;
}
public int numberAliveNeighbor(){
int compteur = 0;
Set<SquareGridNbh> st = cellsNeighbors.keySet();
Iterator<SquareGridNbh> it = st.iterator();
while(it.hasNext()){
SquareGridNbh key = it.next();
Cellule c = cellsNeighbors.get(key);
if( (c != null) && (c.s == Etat.UN) ){
compteur++;
}
}
return compteur;
}
}
| UTF-8 | Java | 922 | java | HighLife.java | Java | [] | null | [] | import java.util.*;
public class HighLife extends Cellule{
public HighLife(){
super();
this.setState(Etat.values()[new Random().nextInt(Etat.values().length)]);
}
public State nextState(){
int nb = numberAliveNeighbor();
if( first_rule(nb) || second_rule(nb) ){
return Etat.UN;
}
return Etat.ZERO;
}
public boolean first_rule(int n){
if( this.s == Etat.ZERO && (n == 3 || n == 6) ){
return true;
}
return false;
}
public boolean second_rule(int n){
if( this.s == Etat.UN && (n == 2 || n == 3)){
return true;
}
return false;
}
public int numberAliveNeighbor(){
int compteur = 0;
Set<SquareGridNbh> st = cellsNeighbors.keySet();
Iterator<SquareGridNbh> it = st.iterator();
while(it.hasNext()){
SquareGridNbh key = it.next();
Cellule c = cellsNeighbors.get(key);
if( (c != null) && (c.s == Etat.UN) ){
compteur++;
}
}
return compteur;
}
}
| 922 | 0.605206 | 0.599783 | 46 | 19.043478 | 17.978195 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.195652 | false | false | 13 |
60e8262c72a329a69440c4379015121bddc3f6cc | 1,924,145,360,672 | 92f6fd1f41a4b9ab7edbe55d5c67b3e1b8ed1ce9 | /Certification Study/src/com/pkw/certification/study/view/ControlPanel.java | b40b2cb3772e2259a95934ec17cd99f62762c529 | [] | no_license | klsmith/Certification-Study | https://github.com/klsmith/Certification-Study | 2c46154c483c01ca67cf7ec568f9aa55f7772416 | 8ce13c49329e60f704f59d5e96cfb0c40a8b6f96 | refs/heads/master | 2021-01-13T01:30:54.998000 | 2015-01-09T17:30:57 | 2015-01-09T17:30:57 | 28,428,377 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pkw.certification.study.view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import com.pkw.certification.study.model.Problem;
import com.pkw.certification.study.model.Selector;
public class ControlPanel extends JPanel {
private static final long serialVersionUID = -8714212184565466822L;
public static ControlPanel createFor(Selector<Problem> selector) {
return new ControlPanel().setSelector(selector);
}
public static ControlPanel create() {
return new ControlPanel();
}
private ControlPanel() {
}
public ControlPanel setSelector(final Selector<Problem> selector) {
JButton previous = new JButton("Previous");
previous.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selector.moveToPrevious();
}
});
JButton next = new JButton("Next");
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selector.moveToNext();
}
});
add(previous);
add(next);
return this;
}
}
| UTF-8 | Java | 1,163 | java | ControlPanel.java | Java | [] | null | [] | package com.pkw.certification.study.view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import com.pkw.certification.study.model.Problem;
import com.pkw.certification.study.model.Selector;
public class ControlPanel extends JPanel {
private static final long serialVersionUID = -8714212184565466822L;
public static ControlPanel createFor(Selector<Problem> selector) {
return new ControlPanel().setSelector(selector);
}
public static ControlPanel create() {
return new ControlPanel();
}
private ControlPanel() {
}
public ControlPanel setSelector(final Selector<Problem> selector) {
JButton previous = new JButton("Previous");
previous.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selector.moveToPrevious();
}
});
JButton next = new JButton("Next");
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selector.moveToNext();
}
});
add(previous);
add(next);
return this;
}
}
| 1,163 | 0.72141 | 0.705073 | 45 | 23.844444 | 21.582869 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.688889 | false | false | 13 |
eb638057e759668d8edab523ccab1e203e19b2cf | 8,469,675,515,131 | f29c9dfd7cc2a77617fc85d8437108fbc1ebd3f5 | /src/hsd/symptom/checker/BP_List_View.java | 871c1aeede3de1f69c728dbfbdc91b6285deb5f4 | [] | no_license | MrinalRai/shekhar_symptom_checker | https://github.com/MrinalRai/shekhar_symptom_checker | b70a9518575719e93b2e2466a5d2824c2fbdc493 | 22f3d42de0a5b54efbdac77e3fa6d82fdd3dd012 | refs/heads/master | 2020-04-08T10:04:08.264000 | 2015-05-15T10:21:36 | 2015-05-15T10:21:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hsd.symptom.checker;
import hsd.symptom.checker.adapter.SugarBpAdapter;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class BP_List_View extends Fragment {
private View list_view;
private static ListView listViewChart;
private Button button_show_chart;
private static Context mContext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
list_view = inflater.inflate(R.layout.layout_list_view, container,
false);
mContext = getActivity();
button_show_chart = (Button) list_view
.findViewById(R.id.button_show_chart);
listViewChart = (ListView) list_view.findViewById(R.id.listViewChart);
SugarBpAdapter adapter = new SugarBpAdapter(mContext,
R.layout.speciality_item, Add_BP_Entry_Activity.xdVals);
listViewChart.setAdapter(adapter);
button_show_chart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Add_BP_Entry_Activity.pager.setCurrentItem(0);
}
});
return list_view;
}
static void generateListview() {
Toast.makeText(mContext, "generateListview", Toast.LENGTH_SHORT).show();
SugarBpAdapter adapter = new SugarBpAdapter(mContext,
R.layout.speciality_item, Add_BP_Entry_Activity.xdVals);
listViewChart.setAdapter(adapter);
}
}
| UTF-8 | Java | 1,596 | java | BP_List_View.java | Java | [] | null | [] | package hsd.symptom.checker;
import hsd.symptom.checker.adapter.SugarBpAdapter;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class BP_List_View extends Fragment {
private View list_view;
private static ListView listViewChart;
private Button button_show_chart;
private static Context mContext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
list_view = inflater.inflate(R.layout.layout_list_view, container,
false);
mContext = getActivity();
button_show_chart = (Button) list_view
.findViewById(R.id.button_show_chart);
listViewChart = (ListView) list_view.findViewById(R.id.listViewChart);
SugarBpAdapter adapter = new SugarBpAdapter(mContext,
R.layout.speciality_item, Add_BP_Entry_Activity.xdVals);
listViewChart.setAdapter(adapter);
button_show_chart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Add_BP_Entry_Activity.pager.setCurrentItem(0);
}
});
return list_view;
}
static void generateListview() {
Toast.makeText(mContext, "generateListview", Toast.LENGTH_SHORT).show();
SugarBpAdapter adapter = new SugarBpAdapter(mContext,
R.layout.speciality_item, Add_BP_Entry_Activity.xdVals);
listViewChart.setAdapter(adapter);
}
}
| 1,596 | 0.77005 | 0.768797 | 60 | 25.6 | 22.663628 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.716667 | false | false | 13 |
f49640027549c2f99079b86bc43635cb68de0b75 | 4,715,874,157,986 | 5b18c2aa61fd21f819520f1b614425fd6bc73c71 | /src/main/java/com/sinosoft/claim/ui/model/CiClaimCrashInsertCommand.java | 2359020096ccea579b40faac6dc002f00a9ca136 | [] | no_license | Akira-09/claim | https://github.com/Akira-09/claim | 471cc215fa77212099ca385e7628f3d69f83d6d8 | 6dd8a4d4eedb47098c09c2bf3f82502aa62220ad | refs/heads/master | 2022-01-07T13:08:27.760000 | 2019-03-24T23:50:09 | 2019-03-24T23:50:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sinosoft.claim.ui.model;
import com.sinosoft.claim.bl.facade.BLCiClaimCrashFacade;
import com.sinosoft.claim.dto.domain.CiClaimCrashDto;
import com.sinosoft.sysframework.web.model.BaseCommand;
/**
* ★★★★★警告:本文件不允许手工修改!!!请使用JToolpad生成!<br>
* 这是BLCiClaimCrashFacade的UI Command类,用于集中式部署<br>
* 创建于 JToolpad(1.5.1) Vendor:zhouxianli1978@msn.com
*/
public class CiClaimCrashInsertCommand extends BaseCommand{
private CiClaimCrashDto ciClaimCrashDtoCiClaimCrashDto;
/**
* 构造方法,构造一个CiClaimCrashInsertCommand对象
* @param ciClaimCrashDto 参数ciClaimCrashDto
* @throws Exception
*/
public CiClaimCrashInsertCommand(CiClaimCrashDto ciClaimCrashDto)
throws Exception{
this.ciClaimCrashDtoCiClaimCrashDto = ciClaimCrashDto;
}
/**
* 执行方法
* @return 执行结果
* @throws Exception
*/
private Object executeCommandCiClaimCrashDtoImpl()
throws Exception{
BLCiClaimCrashFacade facade = new BLCiClaimCrashFacade();
facade.insert(ciClaimCrashDtoCiClaimCrashDto);
return null;
}
/**
* 执行方法 (请勿直接调用此方法,请调用execute方法)
* @see com.sinosoft.sysframework.web.model.Command#executeCommand()
*/
public Object executeCommand() throws Exception{
Object object = null;
object = executeCommandCiClaimCrashDtoImpl();
return object;
}
}
| GB18030 | Java | 1,546 | java | CiClaimCrashInsertCommand.java | Java | [
{
"context": "ommand类,用于集中式部署<br>\n * 创建于 JToolpad(1.5.1) Vendor:zhouxianli1978@msn.com\n */\npublic class CiClaimCrashInsertCommand extend",
"end": 357,
"score": 0.9999222755432129,
"start": 335,
"tag": "EMAIL",
"value": "zhouxianli1978@msn.com"
}
] | null | [] | package com.sinosoft.claim.ui.model;
import com.sinosoft.claim.bl.facade.BLCiClaimCrashFacade;
import com.sinosoft.claim.dto.domain.CiClaimCrashDto;
import com.sinosoft.sysframework.web.model.BaseCommand;
/**
* ★★★★★警告:本文件不允许手工修改!!!请使用JToolpad生成!<br>
* 这是BLCiClaimCrashFacade的UI Command类,用于集中式部署<br>
* 创建于 JToolpad(1.5.1) Vendor:<EMAIL>
*/
public class CiClaimCrashInsertCommand extends BaseCommand{
private CiClaimCrashDto ciClaimCrashDtoCiClaimCrashDto;
/**
* 构造方法,构造一个CiClaimCrashInsertCommand对象
* @param ciClaimCrashDto 参数ciClaimCrashDto
* @throws Exception
*/
public CiClaimCrashInsertCommand(CiClaimCrashDto ciClaimCrashDto)
throws Exception{
this.ciClaimCrashDtoCiClaimCrashDto = ciClaimCrashDto;
}
/**
* 执行方法
* @return 执行结果
* @throws Exception
*/
private Object executeCommandCiClaimCrashDtoImpl()
throws Exception{
BLCiClaimCrashFacade facade = new BLCiClaimCrashFacade();
facade.insert(ciClaimCrashDtoCiClaimCrashDto);
return null;
}
/**
* 执行方法 (请勿直接调用此方法,请调用execute方法)
* @see com.sinosoft.sysframework.web.model.Command#executeCommand()
*/
public Object executeCommand() throws Exception{
Object object = null;
object = executeCommandCiClaimCrashDtoImpl();
return object;
}
}
| 1,531 | 0.708093 | 0.703035 | 44 | 30.454546 | 23.131496 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.295455 | false | false | 13 |
7950fa82f8079ad8638a94bb2822f837b1177319 | 16,466,904,640,294 | c59f24c507d30bbb80f39e9a4f120fec26a43439 | /hbase-src-1.2.1/hbase-client/src/main/java/org/apache/hadoop/hbase/replication/ReplicationListener.java | dfb5fdc199f7f30b2350950fc52afcacde1e8365 | [
"Apache-2.0",
"CC-BY-3.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-protobuf"
] | permissive | fengchen8086/ditb | https://github.com/fengchen8086/ditb | d1b3b9c8cf3118fb53e7f2720135ead8c8c0829b | d663ecf4a7c422edc4c5ba293191bf24db4170f0 | refs/heads/master | 2021-01-20T01:13:34.456000 | 2017-04-24T13:17:23 | 2017-04-24T13:17:23 | 89,239,936 | 13 | 3 | Apache-2.0 | false | 2023-03-20T11:57:01 | 2017-04-24T12:54:26 | 2019-03-07T10:54:31 | 2017-05-18T16:49:02 | 13,017 | 11 | 2 | 0 | Java | 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.hadoop.hbase.replication;
import java.util.List;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
/**
* The replication listener interface can be implemented if a class needs to subscribe to events
* generated by the ReplicationTracker. These events include things like addition/deletion of peer
* clusters or failure of a local region server. To receive events, the class also needs to register
* itself with a Replication Tracker.
*/
@InterfaceAudience.Private
public interface ReplicationListener {
/**
* A region server has been removed from the local cluster
* @param regionServer the removed region server
*/
public void regionServerRemoved(String regionServer);
/**
* A peer cluster has been removed (i.e. unregistered) from replication.
* @param peerId The peer id of the cluster that has been removed
*/
public void peerRemoved(String peerId);
/**
* The list of registered peer clusters has changed.
* @param peerIds A list of all currently registered peer clusters
*/
public void peerListChanged(List<String> peerIds);
}
| UTF-8 | Java | 1,925 | java | ReplicationListener.java | Java | [] | 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.hadoop.hbase.replication;
import java.util.List;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
/**
* The replication listener interface can be implemented if a class needs to subscribe to events
* generated by the ReplicationTracker. These events include things like addition/deletion of peer
* clusters or failure of a local region server. To receive events, the class also needs to register
* itself with a Replication Tracker.
*/
@InterfaceAudience.Private
public interface ReplicationListener {
/**
* A region server has been removed from the local cluster
* @param regionServer the removed region server
*/
public void regionServerRemoved(String regionServer);
/**
* A peer cluster has been removed (i.e. unregistered) from replication.
* @param peerId The peer id of the cluster that has been removed
*/
public void peerRemoved(String peerId);
/**
* The list of registered peer clusters has changed.
* @param peerIds A list of all currently registered peer clusters
*/
public void peerListChanged(List<String> peerIds);
}
| 1,925 | 0.754805 | 0.752727 | 51 | 36.745098 | 31.124571 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.235294 | false | false | 13 |
0147c839bd8c248db3b1c19f86b01e5489c7e7bb | 20,083,267,104,914 | e9a3d23d8000f59121ba0183a5eec7cbe1682af8 | /学生课程案例对集合操作案例/test06/src/student/test01/ListGeneric.java | 723dcca6cce3832a4ae7e7091b11ae53a0ecb12c | [] | no_license | laotongxiao/JavaCore | https://github.com/laotongxiao/JavaCore | 64dad8d3f15f275862db5101a8adbd98c8ed607f | 6080ab728cef62b1c0e1d0431b559a6713ce2e97 | refs/heads/master | 2020-06-07T12:35:48.848000 | 2019-06-29T09:20:44 | 2019-06-29T09:20:44 | 193,023,968 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package student.test01;
import java.util.ArrayList;
import java.util.List;
public class ListGeneric {
private List<Course> listToSelect;
public ListGeneric() {
this.listToSelect = new ArrayList<Course>();
}
public List getListToSelect() {
return listToSelect;
}
public void setListToSelect(List<Course> listToSelect) {
this.listToSelect = listToSelect;
}
public void testAdd() {
Course tr = new Course("1", "数据结构");
listToSelect.add(tr);
}
public void testForEach() {
for(Course temp : listToSelect) {
System.out.println("课程ID:" + temp.getId() + "课程名称:" + temp.getName());
}
}
public void testBasicType() {
List<Integer> list = new ArrayList<Integer>();//不可以是int基本类,要用相应对象型
list.add(1);
for(Integer temp: list) {
System.out.println(temp);
}
}
public void testChild() {
CourseChild tr = new CourseChild();
tr.setId("2");
tr.setName("大学英语");
listToSelect.add(tr);
}
}
| GB18030 | Java | 1,020 | java | ListGeneric.java | Java | [] | null | [] | package student.test01;
import java.util.ArrayList;
import java.util.List;
public class ListGeneric {
private List<Course> listToSelect;
public ListGeneric() {
this.listToSelect = new ArrayList<Course>();
}
public List getListToSelect() {
return listToSelect;
}
public void setListToSelect(List<Course> listToSelect) {
this.listToSelect = listToSelect;
}
public void testAdd() {
Course tr = new Course("1", "数据结构");
listToSelect.add(tr);
}
public void testForEach() {
for(Course temp : listToSelect) {
System.out.println("课程ID:" + temp.getId() + "课程名称:" + temp.getName());
}
}
public void testBasicType() {
List<Integer> list = new ArrayList<Integer>();//不可以是int基本类,要用相应对象型
list.add(1);
for(Integer temp: list) {
System.out.println(temp);
}
}
public void testChild() {
CourseChild tr = new CourseChild();
tr.setId("2");
tr.setName("大学英语");
listToSelect.add(tr);
}
}
| 1,020 | 0.658664 | 0.653445 | 39 | 22.564102 | 18.152905 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.769231 | false | false | 13 |
8b9d341369ca67483784b59698379e05ddbee04e | 26,706,106,696,458 | 5243518109b4efe18cfdf0555a7682e98a7c573c | /src/main/java/com/joelhockey/cirrus/DB.java | 1bca8b19bdf98d521c30306e2043af37f5afb8b2 | [
"MIT"
] | permissive | joelhockey/cirrus | https://github.com/joelhockey/cirrus | eb902ed441dd64828e2ea6f80c0324eaa1094b35 | 7dac6317f261d83947e43bd0587fa037f92e4f77 | refs/heads/master | 2020-12-24T14:57:21.586000 | 2012-02-13T16:24:54 | 2012-02-13T16:24:54 | 668,225 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Copyright 2010 Joel Hockey (joel.hockey@gmail.com). MIT Licence
package com.joelhockey.cirrus;
import static java.lang.String.format;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.joelhockey.codec.Hex;
import com.joelhockey.codec.JSON;
/**
* Wrapper for jdbc to make sql easier.
* This class is NOT thread-safe.
* @author Joel Hockey
*/
public class DB {
private static final Log log = LogFactory.getLog(DB.class);
private static final Object[] EMPTY = null;
private static final Map<Integer, String> TYPES = new HashMap<Integer, String>();
static {
try {
for (Field f : Types.class.getDeclaredFields()) {
// only put 'public static final int' in map
if (f.getType() == int.class && Modifier.isPublic(f.getModifiers())
&& Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers())) {
TYPES.put(f.getInt(null), f.getName());
}
}
} catch (Exception e) {} // ignore
}
private DataSource dataSource;
private Connection dbconn;
private boolean autoCommit;
/**
* Construct DB with data source and auto-commit=true.
* This class is NOT thread-safe.
* @param dataSource data source
*/
public DB(DataSource dataSource) {
this(dataSource, true);
}
/**
* Construct DB with data source and specified auto-commit.
* This class is NOT thread-safe.
* @param dataSource data source
* @param autoCommit true if auto-commit
*/
public DB(DataSource dataSource, boolean autoCommit) {
this.dataSource = dataSource;
this.autoCommit = autoCommit;
}
/**
* Open database connection.
* @throws SQLException if error getting db connection
*/
public void open() throws SQLException {
if (dbconn == null) {
dbconn = dataSource.getConnection();
dbconn.setAutoCommit(autoCommit);
} else {
log.warn("ignoring DB.open, dbconn already open");
}
}
/**
* Close DB connection.
*/
public void close() {
try {
if (dbconn != null) {
dbconn.close();
dbconn = null;
}
} catch (Exception e) {
log.error("Error closing dbconn", e);
}
}
/** commit - ignores any errors */
public void commit() {
boolean ok = false;
long start = System.currentTimeMillis();
try {
dbconn.commit();
ok = true;
} catch (Exception e) {
log.error("Commitment issues", e);
} finally {
long timeTaken = System.currentTimeMillis() - start;
log.debug(format("sql: commit : %s : 0 : %05d",
ok ? "ok" : "error", timeTaken));
}
}
/** rollback - ignores any errors */
public void rollback() {
boolean ok = false;
long start = System.currentTimeMillis();
try {
dbconn.rollback();
ok = true;
} catch (Exception e) {
log.error("Error rolling back", e);
} finally {
long timeTaken = System.currentTimeMillis() - start;
log.debug(format("sql: rollback : %s : 0 : %05d",
ok ? "ok" : "error", timeTaken));
}
}
/** @return db connection */
public Connection getConnection() {
return dbconn;
}
/**
* execute.
* @param sql sql statement(s) to execute
* @throws SQLException
*/
public void execute(String sql) throws SQLException {
executeAndClose(sql, "execute", EMPTY);
}
/**
* insert.
* @param sql sql insert statement
* @return number of records inserted
* @throws SQLException if sql error
*/
public int insert(String sql) throws SQLException {
return insert(sql, EMPTY);
}
/**
* insert.
* @param sql sql insert statement with '?' for params
* @param params params
* @return number of records inserted
* @throws SQLException if sql error
*/
public int insert(String sql, Object... params) throws SQLException {
return executeAndClose(sql, "insert", params);
}
/**
* insert record. Column names convert from camelCase to under_score.
* @param table name of table
* @param record Map that represents record
* @return number of records inserted.
* @throws SQLException if sql error
* @throws CodecException if error parsing JSON
* @throws ClassCastException if JSON not array of objects
*/
public int insert(String table, Map<String, Object> record) throws SQLException {
List<Map<String, Object>> records = new ArrayList<Map<String, Object>>(1);
records.add(record);
return insertAll(table, records);
}
/**
* insert json object or array of objects
* Column names convert from camelCase to under_score.
* @param table name of table
* @param json json formatted object or array of objects
* @return number of records inserted.
* @throws SQLException if sql error
* @throws CodecException if error parsing JSON
* @throws ClassCastException if JSON not array of objects
*/
public int insertJson(String table, String json) throws SQLException {
Object js = JSON.parse(json);
if (js instanceof Map) {
return insert(table, (Map) js);
}
return insertAll(table, (List) JSON.parse(json));
}
/**
* insert list of maps. Column names convert from camelCase
* to under_score.
* @param table name of table
* @param records List of Maps that represent records
* @return number of records inserted.
* @throws SQLException if sql error
* @throws CodecException if error parsing JSON
* @throws ClassCastException if JSON not array of objects
*/
public int insertAll(String table, List<Map<String, Object>> records)
throws SQLException {
for (int i = 0; i < records.size(); i++) {
Map<String, Object> record = records.get(i);
StringBuilder insert = new StringBuilder("insert into " + table + "(");
StringBuilder qmarks = new StringBuilder(" values (");
String[] cols = record.keySet().toArray(new String[0]);
Object[] params = new Object[cols.length];
boolean comma = false;
for (int j = 0; j < cols.length; j++) {
String camelCase = cols[j];
params[j] = record.get(camelCase);
StringBuilder colname = new StringBuilder();
boolean lastLower = false;
for (int k = 0; k < camelCase.length(); k++) {
char c = camelCase.charAt(k);
if (Character.isLowerCase(c)) {
lastLower = true;
} else {
// if last char lower and this one upper, then add underscore
if (lastLower) {
colname.append('_');
}
lastLower = false;
c = Character.toLowerCase(c);
}
colname.append(c);
}
if (comma) {
insert.append(',');
qmarks.append(',');
}
comma = true;
insert.append(colname);
qmarks.append('?');
}
String sql = insert.append(')').append(qmarks).append(')').toString();
insert(sql, params);
}
return records.size();
}
/**
* update.
* @param sql sql update statement
* @return number of records updated
* @throws SQLException if sql error
*/
public int update(String sql) throws SQLException {
return update(sql, EMPTY);
}
/**
* update.
* @param sql sql update statement with '?' for params
* @param params params
* @return number of records updated
* @throws SQLException if sql error
*/
public int update(String sql, Object... params) throws SQLException {
return executeAndClose(sql, "update", params);
}
/**
* execute. Caller must close statement.
* @param sql sql execute, insert, update, or delete statement with '?' for params
* @param sqlcmd 'execute', 'insert', 'update', 'delete', etc used for logging
* @param params params
* @return prepared statement
* @throws SQLException if sql error
*/
public PreparedStatement execute(String sql, String sqlcmd, Object... params) throws SQLException {
long start = System.currentTimeMillis();
boolean ok = false;
int count = -1;
PreparedStatement stmt = null;
try {
stmt = dbconn.prepareStatement(sql);
setParams(stmt, params);
if (!stmt.execute()) { // returns false if result is count
count = stmt.getUpdateCount();
}
ok = true;
return stmt;
} finally {
long timeTaken = System.currentTimeMillis() - start;
log.debug(format("sql: %s : %s : %d : %05d : %s : %s",
sqlcmd, ok ? "ok" : "error", count, timeTaken, sql,
JSON.stringify(params)));
}
}
/**
* execute.
* @param sql sql execute, insert, update, or delete statement with '?' for params
* @param sqlcmd 'execute', 'insert', 'update', 'delete', etc used for logging
* @param params params
* @return number of records inserted or updated
* @throws SQLException if sql error
*/
private int executeAndClose(String sql, String sqlcmd, Object... params) throws SQLException {
PreparedStatement stmt = null;
try {
stmt = execute(sql, sqlcmd, params);
return stmt.getUpdateCount();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
log.error("Error closing stmt", e);
}
}
}
}
/**
* delete.
* @param sql sql delete statement
* @return number of records deleted
* @throws SQLException if sql error
*/
public int delete(String sql) throws SQLException {
return delete(sql, EMPTY);
}
/**
* delete.
* @param sql sql delete statement with '?' for params
* @param params params
* @return number of records deleted
* @throws SQLException if sql error
*/
public int delete(String sql, Object... params) throws SQLException {
return executeAndClose(sql, "delete", params);
}
/**
* delete without using javascript 'delete' keyword.
* @param sql sql delete statement with '?' for params
* @return number of records deleted
* @throws SQLException if sql error
*/
public int del(String sql) throws SQLException {
return delete(sql, EMPTY);
}
/**
* delete without using javascript 'delete' keyword.
* @param sql sql delete statement with '?' for params
* @param params params
* @return number of records deleted
* @throws SQLException if sql error
*/
public int del(String sql, Object... params) throws SQLException {
return delete(sql, params);
}
/**
* select. Caller MUST close statement.
* @param sql sql select statement
* @return PreparedStatement and ResultSet
* @throws SQLException if sql error
*/
public StatementResultSet select(String sql) throws SQLException {
return select(sql, EMPTY);
}
/**
* select. Caller MUST close statement.
* @param sql sql select statement with '?' for params
* @param params params
* @return [PreparedStatement, ResultSet]
* @throws SQLException if sql error
*/
public StatementResultSet select(String sql, Object... params) throws SQLException {
long start = System.currentTimeMillis();
boolean ok = false;
try {
PreparedStatement stmt = dbconn.prepareStatement(sql);
setParams(stmt, params);
ResultSet rs = stmt.executeQuery();
ok = true;
return new StatementResultSet(stmt, rs);
} finally {
long timeTaken = System.currentTimeMillis() - start;
log.debug(format("sql: select : %s : %05d : %s : %s",
ok ? "ok" : "error", timeTaken, sql, JSON.stringify(params)));
}
}
/**
* Return all rows
* @param sql sql select statement with '?' for params
* @param params params
* @return List<Map<String, Object>> list of rows
* @throws SQLException if sql error
*/
public List<Map<String, Object>> selectAll(String sql) throws SQLException {
return selectAll(sql, EMPTY);
}
/**
* Return all rows
* @param sql sql select statement with '?' for params
* @param params params
* @return List<Map<String, Object>> list of rows
* @throws SQLException if sql error
*/
public List<Map<String, Object>> selectAll(String sql, Object... params) throws SQLException {
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
boolean ok = false;
StatementResultSet stmtRs = select(sql, params);
long start = System.currentTimeMillis();
try {
ResultSet rs = stmtRs.getResultSet();
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
Map<String, Object> row = new HashMap<String, Object>();
result.add(row);
// sql stuff is 1-based!
for (int i = 1; i <= meta.getColumnCount(); i++) {
Object value = null;
switch (meta.getColumnType(i)) {
case Types.DATE:
value = rs.getDate(i);
break;
case Types.INTEGER:
value = rs.getInt(i);
break;
case Types.VARCHAR:
value = rs.getString(i);
break;
case Types.TIMESTAMP:
value = new java.util.Date(rs.getTimestamp(i).getTime());
break;
default:
int type = meta.getColumnType(i);
throw new SQLException("unrecognised type: " + type
+ "(" + TYPES.get(type) + ")");
}
StringBuilder label = new StringBuilder();
String[] parts = meta.getColumnName(i).split("_");
for (int j = 0; j < parts.length; j++) {
String part = parts[j].toLowerCase();
if (j > 0) {
part = part.substring(0, 1).toUpperCase() + part.substring(1);
}
label.append(part);
}
row.put(label.toString(), value);
}
}
ok = true;
} finally {
stmtRs.close();
long timeTaken = System.currentTimeMillis() - start;
log.debug(format("sql: selectAll : %s : %05d : %d", ok ? "ok" : "error", timeTaken, result.size()));
}
return result;
}
/**
* select int.
* @param sql sql statement that selects a single int value
* @return result
* @throws SQLException if sql error
*/
public int selectInt(String sql) throws SQLException {
return selectInt(sql, EMPTY);
}
/**
* select int.
* @param sql sql statement with '?' for params that selects a single int value
* @param params params
* @return result
* @throws SQLException if sql error
*/
public int selectInt(String sql, Object... params) throws SQLException {
StatementResultSet stmtRs = select(sql, params);
try {
if (!stmtRs.getResultSet().next()) {
throw new SQLException(format("No records found for sql: %s, %s",
sql, JSON.stringify(params)));
}
int result = stmtRs.getResultSet().getInt(1);
try {
if (stmtRs.getResultSet().next()) {
log.warn(format("More than 1 object returned for sql: %s , %s",
sql, JSON.stringify(params)));
}
} catch (Throwable t) {
} // ignore
return result;
} finally {
stmtRs.getStatement().close();
}
}
/**
* select string.
* @param sql sql select statement that selects a single string
* @return result
* @throws SQLException if sql error
*/
public String selectStr(String sql) throws SQLException {
return selectStr(sql, EMPTY);
}
/**
* select string.
* @param dbconn db connection
* @param sql sql statement with '?' for params that selects a single string value
* @param params params
* @return result
* @throws SQLException if sql error
*/
public String selectStr(String sql, Object... params) throws SQLException {
StatementResultSet stmtRs = select(sql, params);
try {
if (!stmtRs.getResultSet().next()) {
throw new SQLException(format("No records found for sql: %s, %s",
sql, JSON.stringify(params)));
}
String result = stmtRs.getResultSet().getString(1);
try {
if (stmtRs.getResultSet().next()) {
log.warn(format("More than 1 object returned for sql: %s , %s",
sql, JSON.stringify(params)));
}
} catch (Throwable t) {} // ignore
return result;
} finally {
stmtRs.getStatement().close();
}
}
/**
* Set params on PreparedStatement. Uses reflection to determine param type and call appropriate setter on
* statement.
* @param stmt statement
* @param params params
* @throws SQLException if sql error
*/
public void setParams(PreparedStatement stmt, Object... params) throws SQLException {
if (params == null || params.length == 0) {
return;
}
for (int i = 0; i < params.length; i++) {
Object p = params[i];
if (p == null) {
// assume VARCHAR for null
stmt.setNull(i + 1, Types.VARCHAR);
} else if (p instanceof String) {
stmt.setString(i + 1, (String) p);
} else if (p instanceof Integer) {
stmt.setInt(i + 1, (Integer) p);
} else if (p instanceof Double) {
stmt.setDouble(i + 1, (Double) p);
} else if (p instanceof Date) {
stmt.setTimestamp(i + 1, new java.sql.Timestamp(((Date) p).getTime()));
} else if (p instanceof Boolean) {
stmt.setBoolean(i + 1, (Boolean) p);
} else if (p instanceof byte[]) {
stmt.setString(i + 1, Hex.b2s((byte[]) p));
} else if (p instanceof Throwable) {
StringWriter sw = new StringWriter();
((Throwable) p).printStackTrace(new PrintWriter(sw));
stmt.setString(i + 1, sw.toString());
} else {
throw new SQLException("unknown type in sql param class: " + p.getClass() + " : p: " + p);
}
}
}
/**
* Helper to get clob from result set.
* @param rs result set
* @param col column number
* @return clob retrieved as a string
* @throws IOException if io error
* @throws SQLException if sql error
*/
public String getClob(ResultSet rs, int col) throws IOException, SQLException {
char[] cbuf = new char[4096];
return getClob(rs, col, cbuf);
}
/**
* Helper to get clob from result set with user provided temp storage buffer.
* @param rs result set
* @param col column number
* @param cbuf user provided temp storage buffer
* @return clob retrieved as a string
* @throws IOException if io error
* @throws SQLException if sql error
*/
public String getClob(ResultSet rs, int col, char[] cbuf) throws IOException, SQLException {
Reader cs = rs.getCharacterStream(col);
if (cs == null) {
return null;
}
StringBuilder sb = new StringBuilder();
while (true) {
int l = cs.read(cbuf);
if (l == -1) {
return sb.toString();
}
sb.append(cbuf, 0, l);
}
}
/**
* Migrate database to specified version using
* files from '/db/migrate/'
* @param versionRequired optional version to migrate to if null,
* will use all available files in '/db/migrate/'
* @return previous version
* @throws SQLException if sql error
* @throws IOException if error reading files
*/
public int migrate(Integer versionRequired) throws SQLException, IOException {
// create timer, and DB object
Timer timer = new Timer();
timer.start();
boolean needToClose = false;
if (dbconn == null) {
needToClose = true;
open();
}
try {
int versionCurrent;
try {
// get current version from 'db_version' table
versionCurrent = selectInt("select max(version) from db_version");
} catch (Exception e) {
// error reading from 'db_version' table, try init script
log.warn("Error getting dbversion, will try and load init script: " + e);
String sql = Resource.readFile("/db/000_init.sql");
execute(sql);
insert("insert into db_version (version, filename, script) values (0, '000_init.sql', ?)", sql);
timer.mark("db init");
versionCurrent = selectInt("select max(version) from db_version");
}
// check if up to date
String msg = "db at version: " + versionCurrent
+ ", app requires version: " + versionRequired;
if (versionRequired != null && versionCurrent == versionRequired.intValue()) {
log.info("db version ok. " + msg);
return versionCurrent;
} else if (versionRequired != null
&& versionCurrent > versionRequired.intValue()) {
// very strange
throw new SQLException(msg);
}
// move from versionCurrent to versionRequired
log.info("db migration: " + msg);
// look in dir '/db/migrate' to find required files
Set<String> files = Resource.getResourcePaths("/db/migrate/");
if (files == null || files.size() == 0) {
throw new SQLException("No files found in /db/migrate/");
}
log.info("files in '/db/migrate/': " + files);
Map<Integer, String> fileMap = new HashMap<Integer, String>();
int versionMax = 0;
Pattern p = Pattern.compile("^\\/db\\/migrate\\/(\\d{3})_.*\\.sql$");
for (String file : files) {
// check for filename format <nnn>_<description>.sql
Matcher m = p.matcher(file);
if (m.matches()) {
int filenum = Integer.parseInt(m.group(1));
versionMax = Math.max(versionMax, filenum);
if (filenum > versionCurrent) {
// check for duplicates
String existing = fileMap.get(file);
if (existing != null) {
throw new java.sql.SQLException(
"Found duplicate file for migration: "
+ existing + ", " + file);
}
fileMap.put(filenum, file);
}
}
}
// if versionRequired not provided, set to max version found
if (versionRequired == null) {
log.warn("db migrate target version not provided, "
+ "using max value found: " + versionMax);
versionRequired = versionMax;
}
// ensure all files exist
for (int i = versionCurrent + 1; i <= versionRequired; i++) {
if (!fileMap.containsKey(i)) {
throw new SQLException("Migrating from: " + versionCurrent
+ " to: " + versionRequired + ", missing file: "
+ i + ", got files: " + fileMap);
}
}
timer.mark("check version");
// run scripts
for (int i = versionCurrent + 1; i <= versionRequired; i++) {
String script = fileMap.get(i);
log.info("db migration running script: " + script);
String sql = Resource.readFile(script);
insert("insert into db_version (version, filename, script) values (?, ?, ?)", i, script, sql);
execute(sql);
timer.mark(script);
}
// commit now
commit();
return versionCurrent;
} catch (SQLException sqle) {
// rollback on error
rollback();
throw sqle;
} catch (IOException ioe) {
// rollback on error
rollback();
throw ioe;
} finally {
// only close if we opened this connection
if (needToClose) {
close();
}
timer.end("DB migration");
}
};
} | UTF-8 | Java | 27,055 | java | DB.java | Java | [
{
"context": "// Copyright 2010 Joel Hockey (joel.hockey@gmail.com). MIT Licence\n\npackage co",
"end": 29,
"score": 0.9998869895935059,
"start": 18,
"tag": "NAME",
"value": "Joel Hockey"
},
{
"context": "// Copyright 2010 Joel Hockey (joel.hockey@gmail.com). MIT Licence\n\npackage com.joelhockey.cirrus;\n\ni",
"end": 52,
"score": 0.99992835521698,
"start": 31,
"tag": "EMAIL",
"value": "joel.hockey@gmail.com"
},
{
"context": "sier.\n * This class is NOT thread-safe.\n * @author Joel Hockey\n */\npublic class DB {\n private static final Lo",
"end": 1014,
"score": 0.9998475909233093,
"start": 1003,
"tag": "NAME",
"value": "Joel Hockey"
}
] | null | [] | // Copyright 2010 <NAME> (<EMAIL>). MIT Licence
package com.joelhockey.cirrus;
import static java.lang.String.format;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.joelhockey.codec.Hex;
import com.joelhockey.codec.JSON;
/**
* Wrapper for jdbc to make sql easier.
* This class is NOT thread-safe.
* @author <NAME>
*/
public class DB {
private static final Log log = LogFactory.getLog(DB.class);
private static final Object[] EMPTY = null;
private static final Map<Integer, String> TYPES = new HashMap<Integer, String>();
static {
try {
for (Field f : Types.class.getDeclaredFields()) {
// only put 'public static final int' in map
if (f.getType() == int.class && Modifier.isPublic(f.getModifiers())
&& Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers())) {
TYPES.put(f.getInt(null), f.getName());
}
}
} catch (Exception e) {} // ignore
}
private DataSource dataSource;
private Connection dbconn;
private boolean autoCommit;
/**
* Construct DB with data source and auto-commit=true.
* This class is NOT thread-safe.
* @param dataSource data source
*/
public DB(DataSource dataSource) {
this(dataSource, true);
}
/**
* Construct DB with data source and specified auto-commit.
* This class is NOT thread-safe.
* @param dataSource data source
* @param autoCommit true if auto-commit
*/
public DB(DataSource dataSource, boolean autoCommit) {
this.dataSource = dataSource;
this.autoCommit = autoCommit;
}
/**
* Open database connection.
* @throws SQLException if error getting db connection
*/
public void open() throws SQLException {
if (dbconn == null) {
dbconn = dataSource.getConnection();
dbconn.setAutoCommit(autoCommit);
} else {
log.warn("ignoring DB.open, dbconn already open");
}
}
/**
* Close DB connection.
*/
public void close() {
try {
if (dbconn != null) {
dbconn.close();
dbconn = null;
}
} catch (Exception e) {
log.error("Error closing dbconn", e);
}
}
/** commit - ignores any errors */
public void commit() {
boolean ok = false;
long start = System.currentTimeMillis();
try {
dbconn.commit();
ok = true;
} catch (Exception e) {
log.error("Commitment issues", e);
} finally {
long timeTaken = System.currentTimeMillis() - start;
log.debug(format("sql: commit : %s : 0 : %05d",
ok ? "ok" : "error", timeTaken));
}
}
/** rollback - ignores any errors */
public void rollback() {
boolean ok = false;
long start = System.currentTimeMillis();
try {
dbconn.rollback();
ok = true;
} catch (Exception e) {
log.error("Error rolling back", e);
} finally {
long timeTaken = System.currentTimeMillis() - start;
log.debug(format("sql: rollback : %s : 0 : %05d",
ok ? "ok" : "error", timeTaken));
}
}
/** @return db connection */
public Connection getConnection() {
return dbconn;
}
/**
* execute.
* @param sql sql statement(s) to execute
* @throws SQLException
*/
public void execute(String sql) throws SQLException {
executeAndClose(sql, "execute", EMPTY);
}
/**
* insert.
* @param sql sql insert statement
* @return number of records inserted
* @throws SQLException if sql error
*/
public int insert(String sql) throws SQLException {
return insert(sql, EMPTY);
}
/**
* insert.
* @param sql sql insert statement with '?' for params
* @param params params
* @return number of records inserted
* @throws SQLException if sql error
*/
public int insert(String sql, Object... params) throws SQLException {
return executeAndClose(sql, "insert", params);
}
/**
* insert record. Column names convert from camelCase to under_score.
* @param table name of table
* @param record Map that represents record
* @return number of records inserted.
* @throws SQLException if sql error
* @throws CodecException if error parsing JSON
* @throws ClassCastException if JSON not array of objects
*/
public int insert(String table, Map<String, Object> record) throws SQLException {
List<Map<String, Object>> records = new ArrayList<Map<String, Object>>(1);
records.add(record);
return insertAll(table, records);
}
/**
* insert json object or array of objects
* Column names convert from camelCase to under_score.
* @param table name of table
* @param json json formatted object or array of objects
* @return number of records inserted.
* @throws SQLException if sql error
* @throws CodecException if error parsing JSON
* @throws ClassCastException if JSON not array of objects
*/
public int insertJson(String table, String json) throws SQLException {
Object js = JSON.parse(json);
if (js instanceof Map) {
return insert(table, (Map) js);
}
return insertAll(table, (List) JSON.parse(json));
}
/**
* insert list of maps. Column names convert from camelCase
* to under_score.
* @param table name of table
* @param records List of Maps that represent records
* @return number of records inserted.
* @throws SQLException if sql error
* @throws CodecException if error parsing JSON
* @throws ClassCastException if JSON not array of objects
*/
public int insertAll(String table, List<Map<String, Object>> records)
throws SQLException {
for (int i = 0; i < records.size(); i++) {
Map<String, Object> record = records.get(i);
StringBuilder insert = new StringBuilder("insert into " + table + "(");
StringBuilder qmarks = new StringBuilder(" values (");
String[] cols = record.keySet().toArray(new String[0]);
Object[] params = new Object[cols.length];
boolean comma = false;
for (int j = 0; j < cols.length; j++) {
String camelCase = cols[j];
params[j] = record.get(camelCase);
StringBuilder colname = new StringBuilder();
boolean lastLower = false;
for (int k = 0; k < camelCase.length(); k++) {
char c = camelCase.charAt(k);
if (Character.isLowerCase(c)) {
lastLower = true;
} else {
// if last char lower and this one upper, then add underscore
if (lastLower) {
colname.append('_');
}
lastLower = false;
c = Character.toLowerCase(c);
}
colname.append(c);
}
if (comma) {
insert.append(',');
qmarks.append(',');
}
comma = true;
insert.append(colname);
qmarks.append('?');
}
String sql = insert.append(')').append(qmarks).append(')').toString();
insert(sql, params);
}
return records.size();
}
/**
* update.
* @param sql sql update statement
* @return number of records updated
* @throws SQLException if sql error
*/
public int update(String sql) throws SQLException {
return update(sql, EMPTY);
}
/**
* update.
* @param sql sql update statement with '?' for params
* @param params params
* @return number of records updated
* @throws SQLException if sql error
*/
public int update(String sql, Object... params) throws SQLException {
return executeAndClose(sql, "update", params);
}
/**
* execute. Caller must close statement.
* @param sql sql execute, insert, update, or delete statement with '?' for params
* @param sqlcmd 'execute', 'insert', 'update', 'delete', etc used for logging
* @param params params
* @return prepared statement
* @throws SQLException if sql error
*/
public PreparedStatement execute(String sql, String sqlcmd, Object... params) throws SQLException {
long start = System.currentTimeMillis();
boolean ok = false;
int count = -1;
PreparedStatement stmt = null;
try {
stmt = dbconn.prepareStatement(sql);
setParams(stmt, params);
if (!stmt.execute()) { // returns false if result is count
count = stmt.getUpdateCount();
}
ok = true;
return stmt;
} finally {
long timeTaken = System.currentTimeMillis() - start;
log.debug(format("sql: %s : %s : %d : %05d : %s : %s",
sqlcmd, ok ? "ok" : "error", count, timeTaken, sql,
JSON.stringify(params)));
}
}
/**
* execute.
* @param sql sql execute, insert, update, or delete statement with '?' for params
* @param sqlcmd 'execute', 'insert', 'update', 'delete', etc used for logging
* @param params params
* @return number of records inserted or updated
* @throws SQLException if sql error
*/
private int executeAndClose(String sql, String sqlcmd, Object... params) throws SQLException {
PreparedStatement stmt = null;
try {
stmt = execute(sql, sqlcmd, params);
return stmt.getUpdateCount();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
log.error("Error closing stmt", e);
}
}
}
}
/**
* delete.
* @param sql sql delete statement
* @return number of records deleted
* @throws SQLException if sql error
*/
public int delete(String sql) throws SQLException {
return delete(sql, EMPTY);
}
/**
* delete.
* @param sql sql delete statement with '?' for params
* @param params params
* @return number of records deleted
* @throws SQLException if sql error
*/
public int delete(String sql, Object... params) throws SQLException {
return executeAndClose(sql, "delete", params);
}
/**
* delete without using javascript 'delete' keyword.
* @param sql sql delete statement with '?' for params
* @return number of records deleted
* @throws SQLException if sql error
*/
public int del(String sql) throws SQLException {
return delete(sql, EMPTY);
}
/**
* delete without using javascript 'delete' keyword.
* @param sql sql delete statement with '?' for params
* @param params params
* @return number of records deleted
* @throws SQLException if sql error
*/
public int del(String sql, Object... params) throws SQLException {
return delete(sql, params);
}
/**
* select. Caller MUST close statement.
* @param sql sql select statement
* @return PreparedStatement and ResultSet
* @throws SQLException if sql error
*/
public StatementResultSet select(String sql) throws SQLException {
return select(sql, EMPTY);
}
/**
* select. Caller MUST close statement.
* @param sql sql select statement with '?' for params
* @param params params
* @return [PreparedStatement, ResultSet]
* @throws SQLException if sql error
*/
public StatementResultSet select(String sql, Object... params) throws SQLException {
long start = System.currentTimeMillis();
boolean ok = false;
try {
PreparedStatement stmt = dbconn.prepareStatement(sql);
setParams(stmt, params);
ResultSet rs = stmt.executeQuery();
ok = true;
return new StatementResultSet(stmt, rs);
} finally {
long timeTaken = System.currentTimeMillis() - start;
log.debug(format("sql: select : %s : %05d : %s : %s",
ok ? "ok" : "error", timeTaken, sql, JSON.stringify(params)));
}
}
/**
* Return all rows
* @param sql sql select statement with '?' for params
* @param params params
* @return List<Map<String, Object>> list of rows
* @throws SQLException if sql error
*/
public List<Map<String, Object>> selectAll(String sql) throws SQLException {
return selectAll(sql, EMPTY);
}
/**
* Return all rows
* @param sql sql select statement with '?' for params
* @param params params
* @return List<Map<String, Object>> list of rows
* @throws SQLException if sql error
*/
public List<Map<String, Object>> selectAll(String sql, Object... params) throws SQLException {
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
boolean ok = false;
StatementResultSet stmtRs = select(sql, params);
long start = System.currentTimeMillis();
try {
ResultSet rs = stmtRs.getResultSet();
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
Map<String, Object> row = new HashMap<String, Object>();
result.add(row);
// sql stuff is 1-based!
for (int i = 1; i <= meta.getColumnCount(); i++) {
Object value = null;
switch (meta.getColumnType(i)) {
case Types.DATE:
value = rs.getDate(i);
break;
case Types.INTEGER:
value = rs.getInt(i);
break;
case Types.VARCHAR:
value = rs.getString(i);
break;
case Types.TIMESTAMP:
value = new java.util.Date(rs.getTimestamp(i).getTime());
break;
default:
int type = meta.getColumnType(i);
throw new SQLException("unrecognised type: " + type
+ "(" + TYPES.get(type) + ")");
}
StringBuilder label = new StringBuilder();
String[] parts = meta.getColumnName(i).split("_");
for (int j = 0; j < parts.length; j++) {
String part = parts[j].toLowerCase();
if (j > 0) {
part = part.substring(0, 1).toUpperCase() + part.substring(1);
}
label.append(part);
}
row.put(label.toString(), value);
}
}
ok = true;
} finally {
stmtRs.close();
long timeTaken = System.currentTimeMillis() - start;
log.debug(format("sql: selectAll : %s : %05d : %d", ok ? "ok" : "error", timeTaken, result.size()));
}
return result;
}
/**
* select int.
* @param sql sql statement that selects a single int value
* @return result
* @throws SQLException if sql error
*/
public int selectInt(String sql) throws SQLException {
return selectInt(sql, EMPTY);
}
/**
* select int.
* @param sql sql statement with '?' for params that selects a single int value
* @param params params
* @return result
* @throws SQLException if sql error
*/
public int selectInt(String sql, Object... params) throws SQLException {
StatementResultSet stmtRs = select(sql, params);
try {
if (!stmtRs.getResultSet().next()) {
throw new SQLException(format("No records found for sql: %s, %s",
sql, JSON.stringify(params)));
}
int result = stmtRs.getResultSet().getInt(1);
try {
if (stmtRs.getResultSet().next()) {
log.warn(format("More than 1 object returned for sql: %s , %s",
sql, JSON.stringify(params)));
}
} catch (Throwable t) {
} // ignore
return result;
} finally {
stmtRs.getStatement().close();
}
}
/**
* select string.
* @param sql sql select statement that selects a single string
* @return result
* @throws SQLException if sql error
*/
public String selectStr(String sql) throws SQLException {
return selectStr(sql, EMPTY);
}
/**
* select string.
* @param dbconn db connection
* @param sql sql statement with '?' for params that selects a single string value
* @param params params
* @return result
* @throws SQLException if sql error
*/
public String selectStr(String sql, Object... params) throws SQLException {
StatementResultSet stmtRs = select(sql, params);
try {
if (!stmtRs.getResultSet().next()) {
throw new SQLException(format("No records found for sql: %s, %s",
sql, JSON.stringify(params)));
}
String result = stmtRs.getResultSet().getString(1);
try {
if (stmtRs.getResultSet().next()) {
log.warn(format("More than 1 object returned for sql: %s , %s",
sql, JSON.stringify(params)));
}
} catch (Throwable t) {} // ignore
return result;
} finally {
stmtRs.getStatement().close();
}
}
/**
* Set params on PreparedStatement. Uses reflection to determine param type and call appropriate setter on
* statement.
* @param stmt statement
* @param params params
* @throws SQLException if sql error
*/
public void setParams(PreparedStatement stmt, Object... params) throws SQLException {
if (params == null || params.length == 0) {
return;
}
for (int i = 0; i < params.length; i++) {
Object p = params[i];
if (p == null) {
// assume VARCHAR for null
stmt.setNull(i + 1, Types.VARCHAR);
} else if (p instanceof String) {
stmt.setString(i + 1, (String) p);
} else if (p instanceof Integer) {
stmt.setInt(i + 1, (Integer) p);
} else if (p instanceof Double) {
stmt.setDouble(i + 1, (Double) p);
} else if (p instanceof Date) {
stmt.setTimestamp(i + 1, new java.sql.Timestamp(((Date) p).getTime()));
} else if (p instanceof Boolean) {
stmt.setBoolean(i + 1, (Boolean) p);
} else if (p instanceof byte[]) {
stmt.setString(i + 1, Hex.b2s((byte[]) p));
} else if (p instanceof Throwable) {
StringWriter sw = new StringWriter();
((Throwable) p).printStackTrace(new PrintWriter(sw));
stmt.setString(i + 1, sw.toString());
} else {
throw new SQLException("unknown type in sql param class: " + p.getClass() + " : p: " + p);
}
}
}
/**
* Helper to get clob from result set.
* @param rs result set
* @param col column number
* @return clob retrieved as a string
* @throws IOException if io error
* @throws SQLException if sql error
*/
public String getClob(ResultSet rs, int col) throws IOException, SQLException {
char[] cbuf = new char[4096];
return getClob(rs, col, cbuf);
}
/**
* Helper to get clob from result set with user provided temp storage buffer.
* @param rs result set
* @param col column number
* @param cbuf user provided temp storage buffer
* @return clob retrieved as a string
* @throws IOException if io error
* @throws SQLException if sql error
*/
public String getClob(ResultSet rs, int col, char[] cbuf) throws IOException, SQLException {
Reader cs = rs.getCharacterStream(col);
if (cs == null) {
return null;
}
StringBuilder sb = new StringBuilder();
while (true) {
int l = cs.read(cbuf);
if (l == -1) {
return sb.toString();
}
sb.append(cbuf, 0, l);
}
}
/**
* Migrate database to specified version using
* files from '/db/migrate/'
* @param versionRequired optional version to migrate to if null,
* will use all available files in '/db/migrate/'
* @return previous version
* @throws SQLException if sql error
* @throws IOException if error reading files
*/
public int migrate(Integer versionRequired) throws SQLException, IOException {
// create timer, and DB object
Timer timer = new Timer();
timer.start();
boolean needToClose = false;
if (dbconn == null) {
needToClose = true;
open();
}
try {
int versionCurrent;
try {
// get current version from 'db_version' table
versionCurrent = selectInt("select max(version) from db_version");
} catch (Exception e) {
// error reading from 'db_version' table, try init script
log.warn("Error getting dbversion, will try and load init script: " + e);
String sql = Resource.readFile("/db/000_init.sql");
execute(sql);
insert("insert into db_version (version, filename, script) values (0, '000_init.sql', ?)", sql);
timer.mark("db init");
versionCurrent = selectInt("select max(version) from db_version");
}
// check if up to date
String msg = "db at version: " + versionCurrent
+ ", app requires version: " + versionRequired;
if (versionRequired != null && versionCurrent == versionRequired.intValue()) {
log.info("db version ok. " + msg);
return versionCurrent;
} else if (versionRequired != null
&& versionCurrent > versionRequired.intValue()) {
// very strange
throw new SQLException(msg);
}
// move from versionCurrent to versionRequired
log.info("db migration: " + msg);
// look in dir '/db/migrate' to find required files
Set<String> files = Resource.getResourcePaths("/db/migrate/");
if (files == null || files.size() == 0) {
throw new SQLException("No files found in /db/migrate/");
}
log.info("files in '/db/migrate/': " + files);
Map<Integer, String> fileMap = new HashMap<Integer, String>();
int versionMax = 0;
Pattern p = Pattern.compile("^\\/db\\/migrate\\/(\\d{3})_.*\\.sql$");
for (String file : files) {
// check for filename format <nnn>_<description>.sql
Matcher m = p.matcher(file);
if (m.matches()) {
int filenum = Integer.parseInt(m.group(1));
versionMax = Math.max(versionMax, filenum);
if (filenum > versionCurrent) {
// check for duplicates
String existing = fileMap.get(file);
if (existing != null) {
throw new java.sql.SQLException(
"Found duplicate file for migration: "
+ existing + ", " + file);
}
fileMap.put(filenum, file);
}
}
}
// if versionRequired not provided, set to max version found
if (versionRequired == null) {
log.warn("db migrate target version not provided, "
+ "using max value found: " + versionMax);
versionRequired = versionMax;
}
// ensure all files exist
for (int i = versionCurrent + 1; i <= versionRequired; i++) {
if (!fileMap.containsKey(i)) {
throw new SQLException("Migrating from: " + versionCurrent
+ " to: " + versionRequired + ", missing file: "
+ i + ", got files: " + fileMap);
}
}
timer.mark("check version");
// run scripts
for (int i = versionCurrent + 1; i <= versionRequired; i++) {
String script = fileMap.get(i);
log.info("db migration running script: " + script);
String sql = Resource.readFile(script);
insert("insert into db_version (version, filename, script) values (?, ?, ?)", i, script, sql);
execute(sql);
timer.mark(script);
}
// commit now
commit();
return versionCurrent;
} catch (SQLException sqle) {
// rollback on error
rollback();
throw sqle;
} catch (IOException ioe) {
// rollback on error
rollback();
throw ioe;
} finally {
// only close if we opened this connection
if (needToClose) {
close();
}
timer.end("DB migration");
}
};
} | 27,031 | 0.538607 | 0.536278 | 759 | 34.646904 | 24.126842 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55863 | false | false | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.