blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
559f3fd5db46f335254e7ae1323edffa33cc7572
1,589,137,902,448
fb0baa74d64ce2b223d8d61fece55344127ec92b
/app/src/main/java/demo/example/com/myapplication/OkHttpActivity.java
9b90c28aaf358a7f9584e0a53b924c47e4dd26e2
[]
no_license
szqataw/firstdemo
https://github.com/szqataw/firstdemo
0707ce1a907d14f72b74ba07987a3ce2d500be72
0da06c34f7ddf7831c1f404a53ffaf162376c58a
refs/heads/master
2018-04-18T00:30:27.395000
2017-05-23T09:26:22
2017-05-23T09:26:22
90,605,885
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package demo.example.com.myapplication; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.google.gson.Gson; import com.readystatesoftware.systembartint.SystemBarTintManager; import com.squareup.okhttp.Request; import com.zhy.http.okhttp.OkHttpUtils; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.Bind; import butterknife.OnClick; import demo.example.com.commonclass.CustomToast; import demo.example.com.commonclass.OkHttpClientManager; import demo.example.com.dataClass.OkHttpClass; import demo.example.com.dataClass.OkHttpResultClass; import demo.example.com.listadapter.OkhttpListViewAdapter; public class OkHttpActivity extends AppCompatActivity { @Bind(R.id.button3) Button button3; @Bind(R.id.lv_list) ListView lvList; @Bind(R.id.button4) Button button4; @Bind(R.id.textView6) TextView textView6; @Bind(R.id.textView7) TextView textView7; @Bind(R.id.textView8) TextView textView8; private OkhttpListViewAdapter mAdapter; private List<OkHttpClass> listClass = new ArrayList<OkHttpClass>(); private Gson gson = new Gson(); private SystemBarTintManager tintManager; private void initWindow() {//初始化,将状态栏和标题栏设为透明 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } tintManager = new SystemBarTintManager(this); tintManager.setStatusBarTintColor(Color.parseColor("#2b2b2b")); tintManager.setStatusBarTintEnabled(true); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initWindow(); setContentView(R.layout.activity_ok_http); ButterKnife.bind(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("测试网络请求"); toolbar.setTitleTextColor(Color.parseColor("#FFFFFF")); toolbar.setNavigationIcon(R.mipmap.icon_nav_back); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OkHttpActivity.this.finish(); } }); mAdapter = new OkhttpListViewAdapter(listClass, OkHttpActivity.this); lvList.setAdapter(mAdapter); } @OnClick({R.id.button3, R.id.button4}) public void onViewClicked(View view) { // String url = "http://192.168.66.3:8774/EstateWeb/app/GetStringNum"; String url = "http://192.168.68.36:8086/api/test/getmodel"; switch (view.getId()) { case R.id.button4: OkHttpClientManager.postAsyn(url, new OkHttpClientManager.ResultCallback<String>() { @Override public void onError(Request request, Exception e) { CustomToast.showToast(OkHttpActivity.this, e.toString(), 1500); } @Override public void onResponse(String response) { String result = response; OkHttpResultClass resultClass = gson.fromJson(result, OkHttpResultClass .class); textView6.setText(resultClass.getData() + ">>>" + 6); } }, new OkHttpClientManager.Param[]{new OkHttpClientManager.Param("", 6 + "")}); OkHttpClientManager.postAsyn(url, new OkHttpClientManager.ResultCallback<String>() { @Override public void onError(Request request, Exception e) { } @Override public void onResponse(String response) { String result = response; OkHttpResultClass resultClass = gson.fromJson(result, OkHttpResultClass .class); textView7.setText(resultClass.getData() + ">>>" + 7); } }, new OkHttpClientManager.Param[]{new OkHttpClientManager.Param("", 123 + "")}); OkHttpClientManager.postAsyn(url, new OkHttpClientManager.ResultCallback<String>() { @Override public void onError(Request request, Exception e) { } @Override public void onResponse(String response) { String result = response; OkHttpResultClass resultClass = gson.fromJson(result, OkHttpResultClass .class); textView8.setText(resultClass.getData() + ">>>" + 8); } }, new OkHttpClientManager.Param[]{new OkHttpClientManager.Param("", 123 + "")}); break; case R.id.button3: listClass.clear(); mAdapter.notifyDataSetChanged(); for (int i = 0; i < 50; i++) { final int finalI = i; OkHttpClientManager.postAsyn(url, new OkHttpClientManager .ResultCallback<String>() { @Override public void onError(Request request, Exception e) { OkHttpClass objClass = new OkHttpClass(); objClass.setIndex(finalI + ""); objClass.setGetResult("失败" + e.toString()); objClass.setResultIndex(finalI + ""); listClass.add(objClass); mAdapter.notifyDataSetChanged(); lvList.setSelection(mAdapter.getCount() - 1); } @Override public void onResponse(String response) { String result = response; OkHttpResultClass resultClass = gson.fromJson(result, OkHttpResultClass.class); OkHttpClass objClass = new OkHttpClass(); objClass.setIndex(finalI + ""); objClass.setGetResult("成功"); objClass.setResultIndex(resultClass.getData()); listClass.add(objClass); mAdapter.notifyDataSetChanged(); lvList.setSelection(mAdapter.getCount() - 1); } }, new OkHttpClientManager.Param[]{new OkHttpClientManager.Param("num", finalI + "")}); } break; } } }
UTF-8
Java
7,274
java
OkHttpActivity.java
Java
[ { "context": "icked(View view) {\n// String url = \"http://192.168.66.3:8774/EstateWeb/app/GetStringNum\";\n String ", "end": 2917, "score": 0.9940452575683594, "start": 2905, "tag": "IP_ADDRESS", "value": "192.168.66.3" }, { "context": "b/app/GetStringNum\";\n String url = \"http://192.168.68.36:8086/api/test/getmodel\";\n switch (view.get", "end": 2994, "score": 0.9995049238204956, "start": 2981, "tag": "IP_ADDRESS", "value": "192.168.68.36" } ]
null
[]
package demo.example.com.myapplication; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.google.gson.Gson; import com.readystatesoftware.systembartint.SystemBarTintManager; import com.squareup.okhttp.Request; import com.zhy.http.okhttp.OkHttpUtils; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.Bind; import butterknife.OnClick; import demo.example.com.commonclass.CustomToast; import demo.example.com.commonclass.OkHttpClientManager; import demo.example.com.dataClass.OkHttpClass; import demo.example.com.dataClass.OkHttpResultClass; import demo.example.com.listadapter.OkhttpListViewAdapter; public class OkHttpActivity extends AppCompatActivity { @Bind(R.id.button3) Button button3; @Bind(R.id.lv_list) ListView lvList; @Bind(R.id.button4) Button button4; @Bind(R.id.textView6) TextView textView6; @Bind(R.id.textView7) TextView textView7; @Bind(R.id.textView8) TextView textView8; private OkhttpListViewAdapter mAdapter; private List<OkHttpClass> listClass = new ArrayList<OkHttpClass>(); private Gson gson = new Gson(); private SystemBarTintManager tintManager; private void initWindow() {//初始化,将状态栏和标题栏设为透明 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } tintManager = new SystemBarTintManager(this); tintManager.setStatusBarTintColor(Color.parseColor("#2b2b2b")); tintManager.setStatusBarTintEnabled(true); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initWindow(); setContentView(R.layout.activity_ok_http); ButterKnife.bind(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("测试网络请求"); toolbar.setTitleTextColor(Color.parseColor("#FFFFFF")); toolbar.setNavigationIcon(R.mipmap.icon_nav_back); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OkHttpActivity.this.finish(); } }); mAdapter = new OkhttpListViewAdapter(listClass, OkHttpActivity.this); lvList.setAdapter(mAdapter); } @OnClick({R.id.button3, R.id.button4}) public void onViewClicked(View view) { // String url = "http://192.168.66.3:8774/EstateWeb/app/GetStringNum"; String url = "http://192.168.68.36:8086/api/test/getmodel"; switch (view.getId()) { case R.id.button4: OkHttpClientManager.postAsyn(url, new OkHttpClientManager.ResultCallback<String>() { @Override public void onError(Request request, Exception e) { CustomToast.showToast(OkHttpActivity.this, e.toString(), 1500); } @Override public void onResponse(String response) { String result = response; OkHttpResultClass resultClass = gson.fromJson(result, OkHttpResultClass .class); textView6.setText(resultClass.getData() + ">>>" + 6); } }, new OkHttpClientManager.Param[]{new OkHttpClientManager.Param("", 6 + "")}); OkHttpClientManager.postAsyn(url, new OkHttpClientManager.ResultCallback<String>() { @Override public void onError(Request request, Exception e) { } @Override public void onResponse(String response) { String result = response; OkHttpResultClass resultClass = gson.fromJson(result, OkHttpResultClass .class); textView7.setText(resultClass.getData() + ">>>" + 7); } }, new OkHttpClientManager.Param[]{new OkHttpClientManager.Param("", 123 + "")}); OkHttpClientManager.postAsyn(url, new OkHttpClientManager.ResultCallback<String>() { @Override public void onError(Request request, Exception e) { } @Override public void onResponse(String response) { String result = response; OkHttpResultClass resultClass = gson.fromJson(result, OkHttpResultClass .class); textView8.setText(resultClass.getData() + ">>>" + 8); } }, new OkHttpClientManager.Param[]{new OkHttpClientManager.Param("", 123 + "")}); break; case R.id.button3: listClass.clear(); mAdapter.notifyDataSetChanged(); for (int i = 0; i < 50; i++) { final int finalI = i; OkHttpClientManager.postAsyn(url, new OkHttpClientManager .ResultCallback<String>() { @Override public void onError(Request request, Exception e) { OkHttpClass objClass = new OkHttpClass(); objClass.setIndex(finalI + ""); objClass.setGetResult("失败" + e.toString()); objClass.setResultIndex(finalI + ""); listClass.add(objClass); mAdapter.notifyDataSetChanged(); lvList.setSelection(mAdapter.getCount() - 1); } @Override public void onResponse(String response) { String result = response; OkHttpResultClass resultClass = gson.fromJson(result, OkHttpResultClass.class); OkHttpClass objClass = new OkHttpClass(); objClass.setIndex(finalI + ""); objClass.setGetResult("成功"); objClass.setResultIndex(resultClass.getData()); listClass.add(objClass); mAdapter.notifyDataSetChanged(); lvList.setSelection(mAdapter.getCount() - 1); } }, new OkHttpClientManager.Param[]{new OkHttpClientManager.Param("num", finalI + "")}); } break; } } }
7,274
0.567017
0.557602
189
37.211639
28.338051
100
false
false
0
0
0
0
0
0
0.613757
false
false
7
c3becddde1cfd7fdc4d5e321b5840c3523cc0b4e
16,853,451,669,773
ae2f3fcd3064ef4a57e102910c718d29faacdadf
/java/Chap07/src/sec02/exam05/InternetTv.java
862e296bd4cb5dfe442d7239b0bf552c643b6526
[]
no_license
d-happy/Learn
https://github.com/d-happy/Learn
50b987f0760ba5197d43650f67b473047dc58e57
678d5b9ea3ea1475a704de6a43c8f172f44e6b55
refs/heads/master
2023-02-11T10:16:30.490000
2020-12-24T03:22:39
2020-12-24T03:22:39
307,252,785
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sec02.exam05; public class InternetTv extends Tv { String corp; void showInterInfo() { System.out.println("volume: "+volume); System.out.println("channel: "+channel); System.out.println("corp: "+corp); } }//class
UTF-8
Java
236
java
InternetTv.java
Java
[]
null
[]
package sec02.exam05; public class InternetTv extends Tv { String corp; void showInterInfo() { System.out.println("volume: "+volume); System.out.println("channel: "+channel); System.out.println("corp: "+corp); } }//class
236
0.686441
0.669492
12
18.666666
15.960019
42
false
false
0
0
0
0
0
0
1.333333
false
false
7
26512058e5f786105d22ed17f8f3147d64c09397
19,250,043,492,116
a80361b4b696b9e76f8185460b07ed5fdf1b8df4
/app/src/main/java/com/away/hk01demo/table/LookupTable.java
16afba3554f3f792129e8e59345e34fe905449fc
[]
no_license
away01/HK01
https://github.com/away01/HK01
fed769de0a676bd35e52afd87f391e96e479f229
c18b5c620bc3c61126593dbb0182dab78bdac49c
refs/heads/master
2020-08-07T11:22:42.932000
2019-10-07T17:06:41
2019-10-07T17:06:41
213,429,891
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.away.hk01demo.table; import org.litepal.crud.LitePalSupport; /** * appid--星星评分+用户量 */ public class LookupTable extends LitePalSupport { public String appId; public double averageUserRating;//评分 public int userRatingCount;//用户量 public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public double getAverageUserRating() { return averageUserRating; } public void setAverageUserRating(double averageUserRating) { this.averageUserRating = averageUserRating; } public int getUserRatingCount() { return userRatingCount; } public void setUserRatingCount(int userRatingCount) { this.userRatingCount = userRatingCount; } }
UTF-8
Java
815
java
LookupTable.java
Java
[]
null
[]
package com.away.hk01demo.table; import org.litepal.crud.LitePalSupport; /** * appid--星星评分+用户量 */ public class LookupTable extends LitePalSupport { public String appId; public double averageUserRating;//评分 public int userRatingCount;//用户量 public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public double getAverageUserRating() { return averageUserRating; } public void setAverageUserRating(double averageUserRating) { this.averageUserRating = averageUserRating; } public int getUserRatingCount() { return userRatingCount; } public void setUserRatingCount(int userRatingCount) { this.userRatingCount = userRatingCount; } }
815
0.681416
0.678887
36
20.972221
19.780022
64
false
false
0
0
0
0
0
0
0.305556
false
false
7
18f56aa07d32f88ce0c791857c0634f517432937
25,744,033,974,122
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/1/1_509cd7a0c30b1519d0811d961e04d8e73ab61a3f/MenuListFragment/1_509cd7a0c30b1519d0811d961e04d8e73ab61a3f_MenuListFragment_s.java
7ddf2554e466645db0271e1dd198f69da6a13a8f
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package org.svij.taskwarriorapp; import java.util.ArrayList; import org.svij.taskwarriorapp.data.Task; import org.svij.taskwarriorapp.db.TaskArrayAdapter; import org.svij.taskwarriorapp.db.TaskDataSource; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.actionbarsherlock.app.SherlockListFragment; import com.slidingmenu.lib.SlidingMenu; public class MenuListFragment extends SherlockListFragment { ArrayListFragment listFragment; TaskDataSource datasource; String column; ArrayAdapter<Task> adapter = null; SlidingMenu menu; public MenuListFragment() { super(); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.sidebar, null); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setMenuList(); } private class MenuItem { public String tag; public MenuItem(String tag) { this.tag = tag; } } public class MenuListAdapter extends ArrayAdapter<MenuItem> { public MenuListAdapter(Context context) { super(context, 0); } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate( R.layout.menu_row, null); } TextView title = (TextView) convertView .findViewById(R.id.menu_row_title); title.setText(getItem(position).tag); return convertView; } } @Override public void onListItemClick(ListView lv, View view, int position, long id) { column = (((TextView) view).getText().toString()); setTaskList(); menu.toggle(); } public void setMenuList() { MenuListAdapter adapter = new MenuListAdapter(getActivity()); adapter.add(new MenuItem("task next")); adapter.add(new MenuItem("task long")); adapter.add(new MenuItem("task all")); TaskDataSource datasource = new TaskDataSource(getActivity()); datasource.open(); ArrayList<Task> values = datasource.getProjects(); datasource.close(); for (Task task : values) { if (task.getProject().trim().length() == 0) { adapter.add(new MenuItem("no project")); } else { adapter.add(new MenuItem(task.getProject())); } } setListAdapter(adapter); } public void setTaskList() { ArrayList<Task> values; datasource = new TaskDataSource(getActivity()); datasource.open(); if (column == null || column == "task next" || column == "task long") { values = datasource.getPendingTasks(); } else if (column == "no project") { values = datasource.getProjectsTasks(""); } else if (column == "task all") { values = datasource.getAllTasks(); } else { values = datasource.getProjectsTasks(column); } adapter = new TaskArrayAdapter(getActivity(), R.layout.task_row, values); ArrayListFragment listFragment = (ArrayListFragment) getActivity() .getSupportFragmentManager().findFragmentById( android.R.id.content); listFragment.setListAdapter(adapter); } public String getColumn() { return column; } public void setColumn(String column) { this.column = column; } public SlidingMenu getMenu() { return menu; } public void setMenu(SlidingMenu menu) { this.menu = menu; } }
UTF-8
Java
3,579
java
1_509cd7a0c30b1519d0811d961e04d8e73ab61a3f_MenuListFragment_s.java
Java
[]
null
[]
package org.svij.taskwarriorapp; import java.util.ArrayList; import org.svij.taskwarriorapp.data.Task; import org.svij.taskwarriorapp.db.TaskArrayAdapter; import org.svij.taskwarriorapp.db.TaskDataSource; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.actionbarsherlock.app.SherlockListFragment; import com.slidingmenu.lib.SlidingMenu; public class MenuListFragment extends SherlockListFragment { ArrayListFragment listFragment; TaskDataSource datasource; String column; ArrayAdapter<Task> adapter = null; SlidingMenu menu; public MenuListFragment() { super(); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.sidebar, null); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setMenuList(); } private class MenuItem { public String tag; public MenuItem(String tag) { this.tag = tag; } } public class MenuListAdapter extends ArrayAdapter<MenuItem> { public MenuListAdapter(Context context) { super(context, 0); } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate( R.layout.menu_row, null); } TextView title = (TextView) convertView .findViewById(R.id.menu_row_title); title.setText(getItem(position).tag); return convertView; } } @Override public void onListItemClick(ListView lv, View view, int position, long id) { column = (((TextView) view).getText().toString()); setTaskList(); menu.toggle(); } public void setMenuList() { MenuListAdapter adapter = new MenuListAdapter(getActivity()); adapter.add(new MenuItem("task next")); adapter.add(new MenuItem("task long")); adapter.add(new MenuItem("task all")); TaskDataSource datasource = new TaskDataSource(getActivity()); datasource.open(); ArrayList<Task> values = datasource.getProjects(); datasource.close(); for (Task task : values) { if (task.getProject().trim().length() == 0) { adapter.add(new MenuItem("no project")); } else { adapter.add(new MenuItem(task.getProject())); } } setListAdapter(adapter); } public void setTaskList() { ArrayList<Task> values; datasource = new TaskDataSource(getActivity()); datasource.open(); if (column == null || column == "task next" || column == "task long") { values = datasource.getPendingTasks(); } else if (column == "no project") { values = datasource.getProjectsTasks(""); } else if (column == "task all") { values = datasource.getAllTasks(); } else { values = datasource.getProjectsTasks(column); } adapter = new TaskArrayAdapter(getActivity(), R.layout.task_row, values); ArrayListFragment listFragment = (ArrayListFragment) getActivity() .getSupportFragmentManager().findFragmentById( android.R.id.content); listFragment.setListAdapter(adapter); } public String getColumn() { return column; } public void setColumn(String column) { this.column = column; } public SlidingMenu getMenu() { return menu; } public void setMenu(SlidingMenu menu) { this.menu = menu; } }
3,579
0.69824
0.697681
137
25.116789
21.525766
78
false
false
0
0
0
0
0
0
1.919708
false
false
7
efe9063a151a94f85f6107c6ac0b2e833df9532b
29,111,288,346,629
2e62ca109325f27dcd043d1385d3d40cc40354ce
/ShoppingList/src/java/mail/SSLMailSender.java
603d570c111e87de534f35a5be2507859fcd84d6
[]
no_license
popaconsta/ShoppingList
https://github.com/popaconsta/ShoppingList
c36ab6c1013fac1c2af193e266a98a517f2ccb79
df4267224121c9522fc57ed05150449e9d3701c2
refs/heads/master
2021-09-22T09:09:28.580000
2018-09-06T22:08:58
2018-09-06T22:08:58
141,138,405
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 mail; import java.util.Properties; import java.util.UUID; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SSLMailSender { public static void sendVerificationMail(String recipientAddress, String vericationCode) { final String username = "noreply.shoppinglists@gmail.com"; final String password = "bybfbnuyypvfmzwd"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.ssl.trust", "smtp.gmail.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("noreply.shoppinglists@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientAddress)); message.setSubject("Verify your email address"); message.setText("Welcome!\n" + "\n" + "Thanks for signing up. We just need you to verify your " + "email address to complete setting up your account.\n" + "\n" + "Copy and paste this link into your browser -> " + "http://localhost:8080/ShoppingListApp/VerifyEmail?verificationCode=" + vericationCode); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } } }
UTF-8
Java
2,244
java
SSLMailSender.java
Java
[ { "context": "ricationCode) {\n\n final String username = \"noreply.shoppinglists@gmail.com\";\n final String password = \"bybfbnuyypvfmz", "end": 690, "score": 0.9999256134033203, "start": 659, "tag": "EMAIL", "value": "noreply.shoppinglists@gmail.com" }, { "context": "ists@gmail.com\";\n final String password = \"bybfbnuyypvfmzwd\";\n\n Properties props = new Properties();\n ", "end": 742, "score": 0.999342679977417, "start": 726, "tag": "PASSWORD", "value": "bybfbnuyypvfmzwd" }, { "context": "\n message.setFrom(new InternetAddress(\"noreply.shoppinglists@gmail.com\"));\n message.setRecipients(Message.Rec", "end": 1479, "score": 0.9999259114265442, "start": 1448, "tag": "EMAIL", "value": "noreply.shoppinglists@gmail.com" } ]
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 mail; import java.util.Properties; import java.util.UUID; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SSLMailSender { public static void sendVerificationMail(String recipientAddress, String vericationCode) { final String username = "<EMAIL>"; final String password = "<PASSWORD>"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.ssl.trust", "smtp.gmail.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("<EMAIL>")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientAddress)); message.setSubject("Verify your email address"); message.setText("Welcome!\n" + "\n" + "Thanks for signing up. We just need you to verify your " + "email address to complete setting up your account.\n" + "\n" + "Copy and paste this link into your browser -> " + "http://localhost:8080/ShoppingListApp/VerifyEmail?verificationCode=" + vericationCode); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } } }
2,190
0.636364
0.633244
64
34.0625
28.437363
110
false
false
0
0
0
0
0
0
0.609375
false
false
7
0da67c16dc720d20b22ee0dc6e262511396c7bac
13,838,384,643,582
25fc6f52688bbe3ec45f1bab1f82ebb141048ad7
/ECommerce/src/main/java/pages/HomePage.java
be9efc277f93a9f4c7ca010facb238094623e49a
[]
no_license
Raheekhan/SideProject
https://github.com/Raheekhan/SideProject
c90f6881bec0327c162cee12093fa54ab5d32668
2ad19649a2b067cd3df8f1a56f6286464b414cf7
refs/heads/master
2021-08-23T22:45:17.528000
2017-12-06T23:15:20
2017-12-06T23:15:20
109,466,944
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pages; import base.BaseUtil; import base.CommonAPI; import com.aventstack.extentreports.Status; import helper.Waits; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class HomePage extends BaseUtil { private WebDriver driver; private Waits wait; public HomePage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); wait = new Waits(driver); } String Tshirts = "T-shirts"; String Blouses = "Blouses"; String CasualDresses = "Casual Dresses"; @FindBy(id = "email") WebElement emailField; @FindBy(id = "passwd") WebElement passwordField; @FindBy(css = ".login") WebElement signInBtnOne; @FindBy(id = "SubmitLogin") WebElement signInBtnTwo; @FindBy(xpath = "//p[contains(text(), 'Welcome to your account.')]") WebElement successLoginMessage; public void loggedInWith(String username, String password) { signInBtnOne.click(); test.log(Status.INFO, "Clicking on Sign In"); emailField.sendKeys(username); test.log(Status.INFO, "Sending " + username + " to email field"); passwordField.sendKeys(password); test.log(Status.INFO, "Sending " + password + " to password field"); signInBtnTwo.click(); test.log(Status.INFO, "Clicking on Sign In"); } public boolean successfulLoginMessage() { wait.waitUntilVisibilityOf(successLoginMessage, 5); if(successLoginMessage.isDisplayed()) { test.log(Status.PASS, "Successfully logged in"); } else { test.log(Status.FAIL, "Facing issues loggedInWith logging in ..."); } return true; } }
UTF-8
Java
1,857
java
HomePage.java
Java
[ { "context": " to email field\");\n passwordField.sendKeys(password);\n test.log(Status.INFO, \"Sending \" + pass", "end": 1336, "score": 0.7848008871078491, "start": 1328, "tag": "PASSWORD", "value": "password" } ]
null
[]
package pages; import base.BaseUtil; import base.CommonAPI; import com.aventstack.extentreports.Status; import helper.Waits; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class HomePage extends BaseUtil { private WebDriver driver; private Waits wait; public HomePage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); wait = new Waits(driver); } String Tshirts = "T-shirts"; String Blouses = "Blouses"; String CasualDresses = "Casual Dresses"; @FindBy(id = "email") WebElement emailField; @FindBy(id = "passwd") WebElement passwordField; @FindBy(css = ".login") WebElement signInBtnOne; @FindBy(id = "SubmitLogin") WebElement signInBtnTwo; @FindBy(xpath = "//p[contains(text(), 'Welcome to your account.')]") WebElement successLoginMessage; public void loggedInWith(String username, String password) { signInBtnOne.click(); test.log(Status.INFO, "Clicking on Sign In"); emailField.sendKeys(username); test.log(Status.INFO, "Sending " + username + " to email field"); passwordField.sendKeys(<PASSWORD>); test.log(Status.INFO, "Sending " + password + " to password field"); signInBtnTwo.click(); test.log(Status.INFO, "Clicking on Sign In"); } public boolean successfulLoginMessage() { wait.waitUntilVisibilityOf(successLoginMessage, 5); if(successLoginMessage.isDisplayed()) { test.log(Status.PASS, "Successfully logged in"); } else { test.log(Status.FAIL, "Facing issues loggedInWith logging in ..."); } return true; } }
1,859
0.667744
0.667205
63
28.492064
21.434191
79
false
false
0
0
0
0
0
0
0.714286
false
false
7
87b02b8b383d0a69ae82afc30f5ca9996859c46b
9,998,683,872,366
bac1ed8951542478ab787a5fd6c9dd6aba951c48
/src/main/java/org/fundacionjala/coding/marco/SortInnerContent.java
a6e6954a382af28e2e6786f67b31e203b688696e
[]
no_license
AT-05/coding
https://github.com/AT-05/coding
2b2c2856739d7808d74a9fec6b439e7847d61498
e87d426b7cc7b3b84f114ab20555a3f451078a59
refs/heads/develop
2021-01-18T13:16:48.971000
2018-03-20T23:26:56
2018-03-20T23:26:56
100,374,518
0
2
null
false
2018-03-20T23:26:57
2017-08-15T12:21:29
2018-03-20T22:55:11
2018-03-20T23:26:57
247
0
1
0
Java
false
null
package org.fundacionjala.coding.marco; import java.util.Arrays; import java.util.StringJoiner; /** * This kata was made by marco mendez august 29, 2017. */ public class SortInnerContent { private static final int ZERO = 0; private static final String QUOTE_SPACE = " "; private static final String REGEX = ""; private static final int WORD_SIZE = 3; /** * This method do the convect of a string. * * @param string test. * @return test. */ public String sortInnerContent(String string) { String[] words = string.split(QUOTE_SPACE); StringJoiner result = new StringJoiner(QUOTE_SPACE); for (String value : words) { if (value.length() >= WORD_SIZE) { String[] aux = value.substring(1, value.length() - 1).split(REGEX); Arrays.sort(aux); String word = value.substring(ZERO, 1) .concat(new StringBuilder(String.join(REGEX, aux)).reverse().toString()) .concat(value.substring(value.length() - 1, value.length())); result.add(word); } else { result.add(value); } } return result.toString(); } }
UTF-8
Java
1,253
java
SortInnerContent.java
Java
[ { "context": "a.util.StringJoiner;\n\n/**\n * This kata was made by marco mendez august 29, 2017.\n */\npublic class SortInnerConten", "end": 139, "score": 0.9998061656951904, "start": 127, "tag": "NAME", "value": "marco mendez" } ]
null
[]
package org.fundacionjala.coding.marco; import java.util.Arrays; import java.util.StringJoiner; /** * This kata was made by <NAME> august 29, 2017. */ public class SortInnerContent { private static final int ZERO = 0; private static final String QUOTE_SPACE = " "; private static final String REGEX = ""; private static final int WORD_SIZE = 3; /** * This method do the convect of a string. * * @param string test. * @return test. */ public String sortInnerContent(String string) { String[] words = string.split(QUOTE_SPACE); StringJoiner result = new StringJoiner(QUOTE_SPACE); for (String value : words) { if (value.length() >= WORD_SIZE) { String[] aux = value.substring(1, value.length() - 1).split(REGEX); Arrays.sort(aux); String word = value.substring(ZERO, 1) .concat(new StringBuilder(String.join(REGEX, aux)).reverse().toString()) .concat(value.substring(value.length() - 1, value.length())); result.add(word); } else { result.add(value); } } return result.toString(); } }
1,247
0.569832
0.560255
40
30.325001
24.816715
96
false
false
0
0
0
0
0
0
0.5
false
false
7
cd805733c213dd8e2744c8a25bff85d81c53281a
10,419,590,697,073
8bb168ad62413768f6437939999f32be7598b107
/app/src/main/java/com/example/akim/testeie/PagerAdapterCatalogue.java
ff96e4bf2d92c50badcbd6aadce31366b71804e4
[]
no_license
Mousticke/TestEIE
https://github.com/Mousticke/TestEIE
479567513297075dfcc1e3caebfd2d912c38313d
fcedcdfb4ab19984cd621ef9a4b6cc726eaf6f06
refs/heads/master
2017-11-08T08:10:49.291000
2017-03-01T19:35:34
2017-03-01T19:35:34
83,592,424
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.akim.testeie; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; /** * Created by Akim on 01/10/2015. */ public class PagerAdapterCatalogue extends FragmentStatePagerAdapter { int mNumOfTabs; public PagerAdapterCatalogue(FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } @Override public Fragment getItem(int position) { switch (position) { case 0: TabFragment1 tab1 = new TabFragmentVideoCatalogue(); return tab1; case 1: TabFragment2 tab2 = new TabFragmentFichierCatalogue(); return tab2; default: return null; } } @Override public int getCount() { return mNumOfTabs; } }
UTF-8
Java
915
java
PagerAdapterCatalogue.java
Java
[ { "context": "package com.example.akim.testeie;\n\nimport android.support.v4.app.Fragmen", "end": 22, "score": 0.5445303320884705, "start": 20, "tag": "USERNAME", "value": "ak" }, { "context": ".app.FragmentStatePagerAdapter;\n\n/**\n * Created by Akim on 01/10/2015.\n */\npublic class PagerAdapterCatal", "end": 202, "score": 0.870512843132019, "start": 198, "tag": "NAME", "value": "Akim" } ]
null
[]
package com.example.akim.testeie; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; /** * Created by Akim on 01/10/2015. */ public class PagerAdapterCatalogue extends FragmentStatePagerAdapter { int mNumOfTabs; public PagerAdapterCatalogue(FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } @Override public Fragment getItem(int position) { switch (position) { case 0: TabFragment1 tab1 = new TabFragmentVideoCatalogue(); return tab1; case 1: TabFragment2 tab2 = new TabFragmentFichierCatalogue(); return tab2; default: return null; } } @Override public int getCount() { return mNumOfTabs; } }
915
0.621858
0.601093
37
23.756756
21.56374
70
false
false
0
0
0
0
0
0
0.378378
false
false
7
4dd00ced47e4ba844a2829f625f129682205dcfd
23,751,169,157,905
fbc653a7f88e4373fcb98649f523c71134fe67fb
/pinyougou-service-sellergoods/src/main/java/com/pinyougou/core/service/impl/SellerServiceImpl.java
035abda0082e68eff273d428fc010a8504aa4a6e
[]
no_license
rentianxiao/pinyougou_329_03
https://github.com/rentianxiao/pinyougou_329_03
4351ea874c5c2bbd6789f7961102cf1352e6d357
a9069e8128eff50a679c61a4ff83113381dae6a4
refs/heads/master
2020-04-16T06:45:56.853000
2019-01-19T04:26:24
2019-01-19T04:26:24
165,359,516
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pinyougou.core.service.impl; import cn.itcast.core.dao.seller.SellerDao; import cn.itcast.core.pojo.entity.PageResult; import cn.itcast.core.pojo.seller.Seller; import cn.itcast.core.pojo.seller.SellerQuery; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.pinyougou.core.service.SellerService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service public class SellerServiceImpl implements SellerService { @Resource private SellerDao sellerDao; /** * 商家入驻申请 * @param seller */ @Override public void add(Seller seller) { //待审核状态 seller.setStatus("0"); seller.setCreateTime(new Date()); //密码加密:MD5、BCtypt、spring盐值 String password = seller.getPassword(); BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); password = bCryptPasswordEncoder.encode(password); seller.setPassword(password); sellerDao.insertSelective(seller); } /** * 待审核商家的列表查询 * @param page * @param rows * @param seller * @return */ @Override public PageResult search(Integer page, Integer rows, Seller seller) { //设置分页条件 PageHelper.startPage(page,rows); //2.设置查询条件 SellerQuery sellerQuery = new SellerQuery(); if (seller.getStatus() != null && !"".equals(seller.getStatus().trim())){ sellerQuery.createCriteria().andStatusEqualTo(seller.getStatus().trim()); } //3.根据条件查询 Page<Seller> p = (Page<Seller>) sellerDao.selectByExample(sellerQuery); List<Seller> list = new ArrayList<>(); List<Seller> sellerList = p.getResult(); for (Seller seller1 : sellerList) { if (seller1.getStatus().equals("0")){ list.add(seller1); } } //4.将结果封装到PageResult中并返回 return new PageResult(list,(long) list.size()); } /** * 回显商家详情 * @param sellerId * @return */ @Override public Seller findOne(String sellerId) { return sellerDao.selectByPrimaryKey(sellerId); } /** * 商家审核(修改商家状态) * @param sellerId * @param status */ @Transactional @Override public void updateStatus(String sellerId, String status) { Seller seller = new Seller(); seller.setSellerId(sellerId); seller.setStatus(status); sellerDao.updateByPrimaryKeySelective(seller); } }
UTF-8
Java
2,901
java
SellerServiceImpl.java
Java
[ { "context": "密码加密:MD5、BCtypt、spring盐值\n String password = seller.getPassword();\n BCryptPasswordEncoder bC", "end": 1019, "score": 0.6557344794273376, "start": 1015, "tag": "PASSWORD", "value": "sell" }, { "context": "5、BCtypt、spring盐值\n String password = seller.getPassword();\n BCryptPasswordEncoder bCryptPasswordEn", "end": 1033, "score": 0.643433690071106, "start": 1022, "tag": "PASSWORD", "value": "getPassword" } ]
null
[]
package com.pinyougou.core.service.impl; import cn.itcast.core.dao.seller.SellerDao; import cn.itcast.core.pojo.entity.PageResult; import cn.itcast.core.pojo.seller.Seller; import cn.itcast.core.pojo.seller.SellerQuery; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.pinyougou.core.service.SellerService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service public class SellerServiceImpl implements SellerService { @Resource private SellerDao sellerDao; /** * 商家入驻申请 * @param seller */ @Override public void add(Seller seller) { //待审核状态 seller.setStatus("0"); seller.setCreateTime(new Date()); //密码加密:MD5、BCtypt、spring盐值 String password = <PASSWORD>er.<PASSWORD>(); BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); password = bCryptPasswordEncoder.encode(password); seller.setPassword(password); sellerDao.insertSelective(seller); } /** * 待审核商家的列表查询 * @param page * @param rows * @param seller * @return */ @Override public PageResult search(Integer page, Integer rows, Seller seller) { //设置分页条件 PageHelper.startPage(page,rows); //2.设置查询条件 SellerQuery sellerQuery = new SellerQuery(); if (seller.getStatus() != null && !"".equals(seller.getStatus().trim())){ sellerQuery.createCriteria().andStatusEqualTo(seller.getStatus().trim()); } //3.根据条件查询 Page<Seller> p = (Page<Seller>) sellerDao.selectByExample(sellerQuery); List<Seller> list = new ArrayList<>(); List<Seller> sellerList = p.getResult(); for (Seller seller1 : sellerList) { if (seller1.getStatus().equals("0")){ list.add(seller1); } } //4.将结果封装到PageResult中并返回 return new PageResult(list,(long) list.size()); } /** * 回显商家详情 * @param sellerId * @return */ @Override public Seller findOne(String sellerId) { return sellerDao.selectByPrimaryKey(sellerId); } /** * 商家审核(修改商家状态) * @param sellerId * @param status */ @Transactional @Override public void updateStatus(String sellerId, String status) { Seller seller = new Seller(); seller.setSellerId(sellerId); seller.setStatus(status); sellerDao.updateByPrimaryKeySelective(seller); } }
2,906
0.651906
0.648639
97
27.402061
22.071888
85
false
false
0
0
0
0
0
0
0.42268
false
false
7
4254c24687b99b3ad412d1ecb3c5a4793002354f
6,451,040,895,038
daa6c62bbe1e5f5c5b4c790b0b1608572f719369
/src/main/java/ok/test/leetcode/BinaryTreeLevelOrderTraversal.java
4c8e92cdb3be00cbf509e6426dd752aae4a5e9b4
[]
no_license
naveenreddyalka/home
https://github.com/naveenreddyalka/home
97167df03420d37aa5001152ff918f5fa05d97f4
7895f754707f82d845d22c9567608b7420a96f71
refs/heads/master
2021-06-14T13:06:21.349000
2020-12-22T23:54:44
2020-12-22T23:54:44
204,424,093
1
0
null
false
2021-06-04T02:09:31
2019-08-26T07:49:58
2020-12-22T23:54:52
2021-06-04T02:09:31
6,595
1
0
2
Java
false
false
package ok.test.leetcode; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class BinaryTreeLevelOrderTraversal { public static void main(String[] args) { TreeNode r7 = new TreeNode(7); TreeNode l15 = new TreeNode(15); TreeNode r20 = new TreeNode(20); r20.left = l15; r20.right = r7; TreeNode l9 = new TreeNode(9); TreeNode root = new TreeNode(3); root.left = l9; root.right = r20; levelOrderBottom(root); } public static List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); if(root == null) return ret; Queue<TreeNode> que = new LinkedList<TreeNode>(); que.add(root); que.add(null); List<Integer> level = new ArrayList<Integer>(); while(!que.isEmpty()) { TreeNode n = que.poll(); if(n==null) { if(!que.isEmpty()) que.add(null); ret.add(new ArrayList<Integer>(level)); level = new ArrayList<Integer>(); }else { level.add(n.val); if(n.left!=null) que.add(n.left); if(n.right!=null) que.add(n.right); } } Collections.reverse(ret); return ret; } }
UTF-8
Java
1,193
java
BinaryTreeLevelOrderTraversal.java
Java
[]
null
[]
package ok.test.leetcode; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class BinaryTreeLevelOrderTraversal { public static void main(String[] args) { TreeNode r7 = new TreeNode(7); TreeNode l15 = new TreeNode(15); TreeNode r20 = new TreeNode(20); r20.left = l15; r20.right = r7; TreeNode l9 = new TreeNode(9); TreeNode root = new TreeNode(3); root.left = l9; root.right = r20; levelOrderBottom(root); } public static List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); if(root == null) return ret; Queue<TreeNode> que = new LinkedList<TreeNode>(); que.add(root); que.add(null); List<Integer> level = new ArrayList<Integer>(); while(!que.isEmpty()) { TreeNode n = que.poll(); if(n==null) { if(!que.isEmpty()) que.add(null); ret.add(new ArrayList<Integer>(level)); level = new ArrayList<Integer>(); }else { level.add(n.val); if(n.left!=null) que.add(n.left); if(n.right!=null) que.add(n.right); } } Collections.reverse(ret); return ret; } }
1,193
0.663034
0.643755
51
22.392157
16.905827
68
false
false
0
0
0
0
0
0
2.333333
false
false
7
dcbd27ceec251c878b01e97d50640f92cfdb56f7
30,176,440,233,041
8471913dd34aa55e04b4dd8796b014ab26d9b2b6
/charo_Spring_Web_Thymeleaf/src/main/java/com/dawes/servicios/ServicioLinea.java
88294f97542cfa6b00bbbc783b098e6fe774f763
[]
no_license
alonbalbuena/Java
https://github.com/alonbalbuena/Java
baa0fc0824f77789b9d90cb18114d556502c0dcb
2f59b1f01e3644c90ffb4e98575705917b97263e
refs/heads/master
2022-06-23T10:21:55.226000
2020-03-21T13:16:59
2020-03-21T13:16:59
167,030,948
0
0
null
false
2022-06-21T04:12:12
2019-01-22T16:49:34
2020-03-21T13:17:06
2022-06-21T04:12:11
14,087
0
0
18
Java
false
false
package com.dawes.servicios; import java.util.Optional; import com.dawes.modelo.LineaVO; public interface ServicioLinea { LineaVO findByDencorta(String dencorta); LineaVO findByDenlarga(String denlarga); <S extends LineaVO> S save(S entity); Optional<LineaVO> findById(Integer id); Iterable<LineaVO> findAll(); void deleteById(Integer id); void delete(LineaVO entity); void deleteAll(); LineaVO buscarParadasDeLinea(int idlinea); }
UTF-8
Java
448
java
ServicioLinea.java
Java
[]
null
[]
package com.dawes.servicios; import java.util.Optional; import com.dawes.modelo.LineaVO; public interface ServicioLinea { LineaVO findByDencorta(String dencorta); LineaVO findByDenlarga(String denlarga); <S extends LineaVO> S save(S entity); Optional<LineaVO> findById(Integer id); Iterable<LineaVO> findAll(); void deleteById(Integer id); void delete(LineaVO entity); void deleteAll(); LineaVO buscarParadasDeLinea(int idlinea); }
448
0.776786
0.776786
19
22.578947
16.236139
43
false
false
0
0
0
0
0
0
1.210526
false
false
7
611e4c2b2d7e1c44efa6d83715b112484334a2a5
8,529,805,077,106
2c7e1938da96960da8b65dbaef37c03b6d79be72
/src/main/java/com/example/currencyconverter/validation/CurrencyValidationServiceImpl.java
7bf4bb9855e765b939cf54a24ca6a223593857cd
[]
no_license
plamenborachev/CurrencyConverter
https://github.com/plamenborachev/CurrencyConverter
0685af79c30a2ec9cc956158d05a291988f69041
652b33d4bbe295a75b8fbdf5eeae8811eaef2930
refs/heads/master
2022-10-11T02:01:01.279000
2019-11-10T17:21:00
2019-11-10T17:21:00
219,808,915
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.currencyconverter.validation; import com.example.currencyconverter.domain.entities.Currency; import com.example.currencyconverter.domain.models.service.CurrencyServiceModel; import org.springframework.stereotype.Component; @Component public class CurrencyValidationServiceImpl implements CurrencyValidationService { @Override public boolean isValid(Currency currency) { return currency != null; } @Override public boolean isValid(CurrencyServiceModel currency) { return currency != null; } }
UTF-8
Java
555
java
CurrencyValidationServiceImpl.java
Java
[]
null
[]
package com.example.currencyconverter.validation; import com.example.currencyconverter.domain.entities.Currency; import com.example.currencyconverter.domain.models.service.CurrencyServiceModel; import org.springframework.stereotype.Component; @Component public class CurrencyValidationServiceImpl implements CurrencyValidationService { @Override public boolean isValid(Currency currency) { return currency != null; } @Override public boolean isValid(CurrencyServiceModel currency) { return currency != null; } }
555
0.781982
0.781982
18
29.833334
27.604851
81
false
false
0
0
0
0
0
0
0.333333
false
false
7
c0987d3d4fafc6a37709d804c66747465b6eb9c1
17,179,869,193,367
87f73673d596ce9e436c999465fd9e5a1f2a91a7
/alarmcenter-domain/src/main/java/com/ymatou/alarmcenter/domain/repository/AppErrorLogRepository.java
121d7a6ef42a354b358c0bef51b1dc445508498f
[]
no_license
tigersshi/alarmcenter1
https://github.com/tigersshi/alarmcenter1
203ec303329a59627336aa5d10083c60f3315cbb
2d31c4a317d4fd3976774fb5aac0097cb204ed61
refs/heads/master
2018-04-23T02:43:32.605000
2017-05-05T08:33:26
2017-05-05T08:33:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ymatou.alarmcenter.domain.repository; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.MongoClient; import com.mongodb.ReadPreference; import com.ymatou.alarmcenter.domain.model.AppErrorLog; import com.ymatou.alarmcenter.domain.model.PagingQueryResult; import com.ymatou.alarmcenter.infrastructure.db.mongodb.MongoRepository; import io.netty.util.internal.ConcurrentSet; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.joda.time.DateTime; import org.mongodb.morphia.query.Criteria; import org.mongodb.morphia.query.Query; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import static com.ymatou.alarmcenter.infrastructure.common.Utils.getTimeStamp; /** * Created by zhangxiaoming on 2016/11/23. */ @Repository public class AppErrorLogRepository extends MongoRepository { private static ConcurrentSet concurrentSet = new ConcurrentSet(); @Resource(name = "logMongoClient") private MongoClient mongoClient; @Override protected MongoClient getMongoClient() { return mongoClient; } public String getDatabaseName(Date date) { if (date == null) return "AppLogDb"; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM"); return String.format("AppLogDb%s", dateFormat.format(date)); } public String getCollectionName(Date date) { if (date == null) return "AppErrLog"; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); return String.format("AppErrLog%s", dateFormat.format(date)); } public void saveAppErrLog(AppErrorLog appErrLog) { if (appErrLog == null) return; Date date = new Date(); String dbName = getDatabaseName(date); String collectionName = getCollectionName(date); insertEntiy(dbName, collectionName, appErrLog); String key = dbName + collectionName; if (!concurrentSet.contains(key)) { DBCollection dbCollection = getCollection(dbName, collectionName); dbCollection.createIndex(new BasicDBObject("AppId", 1)); dbCollection.createIndex(new BasicDBObject("ExceptionName", 1)); dbCollection.createIndex(new BasicDBObject("AddTimeStamp", -1)); concurrentSet.add(key); } } public AppErrorLog getAppErrLog(String dbName, String collectionName, String id) { Query<AppErrorLog> query = newQuery(AppErrorLog.class, dbName, collectionName, ReadPreference.primaryPreferred()); return query.field("_id").equal(new ObjectId(id)).get(); } public AppErrorLog getAppErrLog(Date date, String id) { String dbName = getDatabaseName(date); String collectionName = getCollectionName(date); return getAppErrLog(dbName, collectionName, id); } public long getErrorCount(String dbName, String collectionName, String appId, int errorLevel, Date beginTime, Date endTime) { Query<AppErrorLog> query = newQuery(AppErrorLog.class, dbName, collectionName, ReadPreference.primaryPreferred()); DateTime dt = new DateTime(beginTime); long begin = getTimeStamp(new DateTime(dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth(), dt.getHourOfDay(), dt.getMinuteOfHour(), dt.getSecondOfMinute())); long end = getTimeStamp(new DateTime(endTime)); query.field("AppId").equal(appId).field("ErrorLevel").equal(errorLevel) .field("AddTimeStamp").greaterThan(begin) .field("AddTimeStamp").lessThanOrEq(end); long totalRecords = getDatastore(dbName).getCount(query); return totalRecords; } public long getErrorCount(String appId, int errorLevel, Date beginTime, Date endTime) { String dbName = getDatabaseName(beginTime); String collectionName = getCollectionName(beginTime); return getErrorCount(dbName, collectionName, appId, errorLevel, beginTime, endTime); } public List<AppErrorLog> getErrorList(String dbName, String collectionName, String appId, int errorLevel, Date beginTime, Date endTime) { Query<AppErrorLog> query = newQuery(AppErrorLog.class, dbName, collectionName, ReadPreference.primaryPreferred()); DateTime dt = new DateTime(beginTime); long begin = getTimeStamp(new DateTime(dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth(), dt.getHourOfDay(), dt.getMinuteOfHour(), dt.getSecondOfMinute())); long end = getTimeStamp(new DateTime(endTime)); query.field("AppId").equal(appId).field("ErrorLevel").equal(errorLevel) .field("AddTimeStamp").greaterThan(begin) .field("AddTimeStamp").lessThanOrEq(end); return query.order("-AddTimeStamp").limit(100).asList(); } public void deleteDatabse(String dbName) { getMongoClient().dropDatabase(dbName); } public PagingQueryResult<AppErrorLog> getAppErrorLogList(String dbName, String collectionName, String appId, Integer errorLevel, Date beginTime, Date endTime, String machineIp, String keyWord, int pageSize, int pageIndex) { if (pageIndex < 1) pageIndex = 1; Query<AppErrorLog> query = newQuery(AppErrorLog.class, dbName, collectionName, ReadPreference.secondaryPreferred()); ArrayList<Criteria> conditions = new ArrayList<>(); if (!StringUtils.isBlank(appId)) conditions.add(query.criteria("AppId").equal(appId)); if (errorLevel != null) conditions.add(query.criteria("ErrorLevel").equal(errorLevel)); if (!StringUtils.isBlank(machineIp)) { conditions.add(query.criteria("MachineIp").equal(machineIp)); } if (!StringUtils.isBlank(keyWord)) { conditions.add(query.criteria("StackTrace").contains(keyWord)); } if (beginTime != null) { DateTime dt = new DateTime(beginTime); long begin = getTimeStamp(new DateTime(dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth(), dt.getHourOfDay(), dt.getMinuteOfHour(), dt.getSecondOfMinute())); conditions.add(query.criteria("AddTimeStamp").greaterThanOrEq(begin)); } if (endTime != null) { long end = getTimeStamp(new DateTime(endTime)); conditions.add(query.criteria("AddTimeStamp").lessThan(end)); } int size = conditions.size(); Criteria[] array = conditions.toArray(new Criteria[size]); query.and(array); long totalRecords = getDatastore(dbName).getCount(query); query.order("-AddTimeStamp"); List<AppErrorLog> list = query.offset(pageSize * (pageIndex - 1)).limit(pageSize).asList(); if (list == null) list = new ArrayList<>(); PagingQueryResult<AppErrorLog> result = new PagingQueryResult<>(); result.setList(list); result.setTotalRecords(totalRecords); return result; } public PagingQueryResult<AppErrorLog> getAppErrorLogList(String appId, Integer errorLevel, Date beginTime, Date endTime, String machineIp, String keyWord, int pageSize, int pageIndex) { String dbName = getDatabaseName(beginTime); String collectionName = getCollectionName(beginTime); return getAppErrorLogList(dbName, collectionName, appId, errorLevel, beginTime, endTime, machineIp, keyWord, pageSize, pageIndex); } }
UTF-8
Java
7,915
java
AppErrorLogRepository.java
Java
[ { "context": "ture.common.Utils.getTimeStamp;\n\n/**\n * Created by zhangxiaoming on 2016/11/23.\n */\n@Repository\npublic class AppEr", "end": 918, "score": 0.9993187785148621, "start": 905, "tag": "USERNAME", "value": "zhangxiaoming" }, { "context": " collectionName, appErrLog);\n\n String key = dbName + collectionName;\n if (!concurrentSet.contains(key)) {\n ", "end": 2102, "score": 0.907258152961731, "start": 2079, "tag": "KEY", "value": "dbName + collectionName" } ]
null
[]
package com.ymatou.alarmcenter.domain.repository; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.MongoClient; import com.mongodb.ReadPreference; import com.ymatou.alarmcenter.domain.model.AppErrorLog; import com.ymatou.alarmcenter.domain.model.PagingQueryResult; import com.ymatou.alarmcenter.infrastructure.db.mongodb.MongoRepository; import io.netty.util.internal.ConcurrentSet; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.joda.time.DateTime; import org.mongodb.morphia.query.Criteria; import org.mongodb.morphia.query.Query; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import static com.ymatou.alarmcenter.infrastructure.common.Utils.getTimeStamp; /** * Created by zhangxiaoming on 2016/11/23. */ @Repository public class AppErrorLogRepository extends MongoRepository { private static ConcurrentSet concurrentSet = new ConcurrentSet(); @Resource(name = "logMongoClient") private MongoClient mongoClient; @Override protected MongoClient getMongoClient() { return mongoClient; } public String getDatabaseName(Date date) { if (date == null) return "AppLogDb"; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM"); return String.format("AppLogDb%s", dateFormat.format(date)); } public String getCollectionName(Date date) { if (date == null) return "AppErrLog"; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); return String.format("AppErrLog%s", dateFormat.format(date)); } public void saveAppErrLog(AppErrorLog appErrLog) { if (appErrLog == null) return; Date date = new Date(); String dbName = getDatabaseName(date); String collectionName = getCollectionName(date); insertEntiy(dbName, collectionName, appErrLog); String key = dbName + collectionName; if (!concurrentSet.contains(key)) { DBCollection dbCollection = getCollection(dbName, collectionName); dbCollection.createIndex(new BasicDBObject("AppId", 1)); dbCollection.createIndex(new BasicDBObject("ExceptionName", 1)); dbCollection.createIndex(new BasicDBObject("AddTimeStamp", -1)); concurrentSet.add(key); } } public AppErrorLog getAppErrLog(String dbName, String collectionName, String id) { Query<AppErrorLog> query = newQuery(AppErrorLog.class, dbName, collectionName, ReadPreference.primaryPreferred()); return query.field("_id").equal(new ObjectId(id)).get(); } public AppErrorLog getAppErrLog(Date date, String id) { String dbName = getDatabaseName(date); String collectionName = getCollectionName(date); return getAppErrLog(dbName, collectionName, id); } public long getErrorCount(String dbName, String collectionName, String appId, int errorLevel, Date beginTime, Date endTime) { Query<AppErrorLog> query = newQuery(AppErrorLog.class, dbName, collectionName, ReadPreference.primaryPreferred()); DateTime dt = new DateTime(beginTime); long begin = getTimeStamp(new DateTime(dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth(), dt.getHourOfDay(), dt.getMinuteOfHour(), dt.getSecondOfMinute())); long end = getTimeStamp(new DateTime(endTime)); query.field("AppId").equal(appId).field("ErrorLevel").equal(errorLevel) .field("AddTimeStamp").greaterThan(begin) .field("AddTimeStamp").lessThanOrEq(end); long totalRecords = getDatastore(dbName).getCount(query); return totalRecords; } public long getErrorCount(String appId, int errorLevel, Date beginTime, Date endTime) { String dbName = getDatabaseName(beginTime); String collectionName = getCollectionName(beginTime); return getErrorCount(dbName, collectionName, appId, errorLevel, beginTime, endTime); } public List<AppErrorLog> getErrorList(String dbName, String collectionName, String appId, int errorLevel, Date beginTime, Date endTime) { Query<AppErrorLog> query = newQuery(AppErrorLog.class, dbName, collectionName, ReadPreference.primaryPreferred()); DateTime dt = new DateTime(beginTime); long begin = getTimeStamp(new DateTime(dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth(), dt.getHourOfDay(), dt.getMinuteOfHour(), dt.getSecondOfMinute())); long end = getTimeStamp(new DateTime(endTime)); query.field("AppId").equal(appId).field("ErrorLevel").equal(errorLevel) .field("AddTimeStamp").greaterThan(begin) .field("AddTimeStamp").lessThanOrEq(end); return query.order("-AddTimeStamp").limit(100).asList(); } public void deleteDatabse(String dbName) { getMongoClient().dropDatabase(dbName); } public PagingQueryResult<AppErrorLog> getAppErrorLogList(String dbName, String collectionName, String appId, Integer errorLevel, Date beginTime, Date endTime, String machineIp, String keyWord, int pageSize, int pageIndex) { if (pageIndex < 1) pageIndex = 1; Query<AppErrorLog> query = newQuery(AppErrorLog.class, dbName, collectionName, ReadPreference.secondaryPreferred()); ArrayList<Criteria> conditions = new ArrayList<>(); if (!StringUtils.isBlank(appId)) conditions.add(query.criteria("AppId").equal(appId)); if (errorLevel != null) conditions.add(query.criteria("ErrorLevel").equal(errorLevel)); if (!StringUtils.isBlank(machineIp)) { conditions.add(query.criteria("MachineIp").equal(machineIp)); } if (!StringUtils.isBlank(keyWord)) { conditions.add(query.criteria("StackTrace").contains(keyWord)); } if (beginTime != null) { DateTime dt = new DateTime(beginTime); long begin = getTimeStamp(new DateTime(dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth(), dt.getHourOfDay(), dt.getMinuteOfHour(), dt.getSecondOfMinute())); conditions.add(query.criteria("AddTimeStamp").greaterThanOrEq(begin)); } if (endTime != null) { long end = getTimeStamp(new DateTime(endTime)); conditions.add(query.criteria("AddTimeStamp").lessThan(end)); } int size = conditions.size(); Criteria[] array = conditions.toArray(new Criteria[size]); query.and(array); long totalRecords = getDatastore(dbName).getCount(query); query.order("-AddTimeStamp"); List<AppErrorLog> list = query.offset(pageSize * (pageIndex - 1)).limit(pageSize).asList(); if (list == null) list = new ArrayList<>(); PagingQueryResult<AppErrorLog> result = new PagingQueryResult<>(); result.setList(list); result.setTotalRecords(totalRecords); return result; } public PagingQueryResult<AppErrorLog> getAppErrorLogList(String appId, Integer errorLevel, Date beginTime, Date endTime, String machineIp, String keyWord, int pageSize, int pageIndex) { String dbName = getDatabaseName(beginTime); String collectionName = getCollectionName(beginTime); return getAppErrorLogList(dbName, collectionName, appId, errorLevel, beginTime, endTime, machineIp, keyWord, pageSize, pageIndex); } }
7,915
0.663045
0.660771
167
46.39521
37.000721
172
false
false
0
0
0
0
0
0
1.02994
false
false
7
fa765d401d9cea7a9762974f71a4cdef86879bef
25,013,889,548,202
a0c4f5197b496fec49289aa32f4b451d98f64205
/coin-exchange/coin-admin/admin-service/src/main/java/com/kenji/controller/SysRolePrivilegeController.java
701ffb614c59727a51186c528af45b234ec05efb
[]
no_license
xiaoxiao1986/CoinExchange-1
https://github.com/xiaoxiao1986/CoinExchange-1
946b32c997b196ccdad52ba8edbacdfd33074707
ebcbd6bfa07be5f58c73de44c183ddbda5bb84b1
refs/heads/main
2023-07-16T21:50:35.617000
2021-09-06T12:30:24
2021-09-06T12:30:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kenji.controller; import cn.hutool.core.collection.CollectionUtil; import com.kenji.domain.RolePrivilegesParam; import com.kenji.domain.SysMenu; import com.kenji.model.R; import com.kenji.service.SysRolePrivilegeService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import springfox.documentation.schema.Collections; import java.util.List; /** * @Author Kenji * @Date 2021/8/18 10:22 * @Description 角色权限管理 */ @Api(tags = "角色权限的配置") @RestController public class SysRolePrivilegeController { @Autowired private SysRolePrivilegeService sysRolePrivilegeService; @GetMapping("/roles_privileges") @ApiOperation(value = "查询角色的权限列表") @ApiImplicitParams({ @ApiImplicitParam(name = "roleId", value = "角色的ID") }) public R<List<SysMenu>> findSysMenuAndPrivileges(Long roleId) { List<SysMenu> sysMenus = sysRolePrivilegeService.findSysMenuAndPrivileges(roleId); return R.ok(sysMenus); } @PostMapping("/grant_privileges") @ApiOperation(value = "授予角色某种权限") @ApiImplicitParams({ @ApiImplicitParam(name = "rolePrivilegesParam", value = "rolePrivilegesParam json数") }) public R grantPrivileges(@RequestBody RolePrivilegesParam rolePrivilegesParam) { boolean isOk = sysRolePrivilegeService.grantPrivileges(rolePrivilegesParam); if (isOk) { return R.ok(); } return R.fail("授予失败"); } }
UTF-8
Java
1,750
java
SysRolePrivilegeController.java
Java
[ { "context": "llections;\n\nimport java.util.List;\n\n/**\n * @Author Kenji\n * @Date 2021/8/18 10:22\n * @Description 角色权限管理\n ", "end": 619, "score": 0.8621160984039307, "start": 614, "tag": "USERNAME", "value": "Kenji" } ]
null
[]
package com.kenji.controller; import cn.hutool.core.collection.CollectionUtil; import com.kenji.domain.RolePrivilegesParam; import com.kenji.domain.SysMenu; import com.kenji.model.R; import com.kenji.service.SysRolePrivilegeService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import springfox.documentation.schema.Collections; import java.util.List; /** * @Author Kenji * @Date 2021/8/18 10:22 * @Description 角色权限管理 */ @Api(tags = "角色权限的配置") @RestController public class SysRolePrivilegeController { @Autowired private SysRolePrivilegeService sysRolePrivilegeService; @GetMapping("/roles_privileges") @ApiOperation(value = "查询角色的权限列表") @ApiImplicitParams({ @ApiImplicitParam(name = "roleId", value = "角色的ID") }) public R<List<SysMenu>> findSysMenuAndPrivileges(Long roleId) { List<SysMenu> sysMenus = sysRolePrivilegeService.findSysMenuAndPrivileges(roleId); return R.ok(sysMenus); } @PostMapping("/grant_privileges") @ApiOperation(value = "授予角色某种权限") @ApiImplicitParams({ @ApiImplicitParam(name = "rolePrivilegesParam", value = "rolePrivilegesParam json数") }) public R grantPrivileges(@RequestBody RolePrivilegesParam rolePrivilegesParam) { boolean isOk = sysRolePrivilegeService.grantPrivileges(rolePrivilegesParam); if (isOk) { return R.ok(); } return R.fail("授予失败"); } }
1,750
0.733572
0.727001
55
29.436363
25.333244
96
false
false
0
0
0
0
0
0
0.4
false
false
7
5f2f076cf19c9c7f2b887ef905bffea7fe0166fc
9,371,618,662,785
56dd9d548522032c75d0c78ff7d4d4099ed23d91
/src/me/Salt/JPI/Entities/Games/CardsAgainstDiscord/JDeck.java
bb51670db1e799286ebff8df27fe453ee4566d32
[]
no_license
DevJake/SaltBot
https://github.com/DevJake/SaltBot
793e9aead6d1f4f534526a8a1883709cec5d5cc7
7c7ba8c667a2a4cacaa8e24cfbc7537529621356
refs/heads/master
2022-05-10T15:44:21.610000
2016-12-12T12:12:32
2016-12-12T12:12:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.Salt.JPI.Entities.Games.CardsAgainstDiscord; /** * Created by 15122390 on 07/12/2016. */ public interface JDeck { }
UTF-8
Java
130
java
JDeck.java
Java
[ { "context": "ies.Games.CardsAgainstDiscord;\n\n/**\n * Created by 15122390 on 07/12/2016.\n */\npublic interface JDeck {\n}\n", "end": 83, "score": 0.8975447416305542, "start": 75, "tag": "USERNAME", "value": "15122390" } ]
null
[]
package me.Salt.JPI.Entities.Games.CardsAgainstDiscord; /** * Created by 15122390 on 07/12/2016. */ public interface JDeck { }
130
0.730769
0.607692
7
17.571428
20.098736
55
false
false
0
0
0
0
0
0
0.142857
false
false
7
5894540b41487e0b6b10559ccb377c3531adbf01
22,531,398,437,306
224eae8a908481424ef327e0320ca4e157b2d62c
/solution_api/src/main/java/cn/yangtengfei/api/server/pictureServer/luguo/LuGuoImageService.java
b318ab32a8844c28d3f16c0c513c85c65b19b12b
[]
no_license
soaryang/solution_system
https://github.com/soaryang/solution_system
7536081427568361f407abadabe889d55db456cb
3f5367cafb56d8e99fd95a47b17b2cef33cfaa0e
refs/heads/master
2022-12-27T02:59:46.550000
2021-01-15T18:06:53
2021-01-15T18:06:53
95,345,274
0
0
null
false
2022-12-16T04:22:29
2017-06-25T07:32:22
2021-01-15T18:07:14
2022-12-16T04:22:26
30,172
0
0
12
Java
false
false
package cn.yangtengfei.api.server.pictureServer.luguo; import cn.yangtengfei.api.util.http.HttpUtils; import com.alibaba.fastjson.JSON; import com.google.common.collect.Maps; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @Slf4j @Service public class LuGuoImageService { static final String BOUNDARY = "------WebKitFormBoundaryQx3F1tuoin1schAn"; // 定义数据分隔线 public static final String SAVE_PICTURE_TO_SERVER = "https://imgchr.com/json"; public static final String SESSIONID = "g8jeplrikv9j5i4akudvam49g6"; public Map<String, String> doLogin() throws IOException { return session(); } public String getLuGuoImageUrlPath(String token,String fileName, String contentType, String path, InputStream inputStream) { String urlPath = StringUtils.EMPTY; try { //执行登录获取token //Map<String, String> userMap = session(); //String token = userMap.get("token"); HttpURLConnection httpURLConnection = HttpUtils.initHttpURLConnection(SAVE_PICTURE_TO_SERVER); setProperties(httpURLConnection, "POST", SESSIONID); //String path = "D:/01.png"; //String fileName = FileUtils.getFileName(path); //String suffix = FileUtils.stringSuffix(path); String[] fileArray1 = {"source", fileName, contentType, path}; List<String[]> fileParams = new ArrayList<>(); fileParams.add(fileArray1); Map<String, String> paramMap = new HashMap<>(); paramMap.put("type", "file"); paramMap.put("action", "upload"); paramMap.put("timestamp", (new Date()).getTime() + ""); paramMap.put("auth_token", token); paramMap.put("nsfw", "0"); urlPath = saveFile(httpURLConnection, paramMap, fileParams, inputStream); System.out.println(urlPath); return urlPath; } catch (Exception e) { log.error("uploadPictureToAliServer error", e); } return urlPath; } /*public static void main(String[] args) { try { Map<String, String> userMap = session(); String session = ""; String token = userMap.get("token"); HttpURLConnection httpURLConnection = HttpUtils.initHttpURLConnection(SAVE_PICTURE_TO_SERVER); setProperties(httpURLConnection, "POST", SESSIONID); String path = "D:/01.png"; String fileName = FileUtils.getFileName(path); String suffix = FileUtils.stringSuffix(path); String[] fileArray1 = {"source", fileName, "image/" + suffix, ""}; List<String[]> fileParams = new ArrayList<>(); fileParams.add(fileArray1); Map<String, String> paramMap = new HashMap<>(); paramMap.put("type", "file"); paramMap.put("action", "upload"); paramMap.put("timestamp", (new Date()).getTime() + ""); paramMap.put("auth_token", token); paramMap.put("nsfw", "0"); String urlPath = saveFile(httpURLConnection, paramMap, fileParams, new FileInputStream(new File(path))); System.out.println(urlPath); } catch (Exception e) { log.error("uploadPictureToAliServer error", e); } }*/ public static String saveFile(HttpURLConnection httpURLConnection, Map<String, String> paramMap, List<String[]> fileParams, InputStream inputStream) throws Exception { ByteArrayOutputStream bos = null;//byte输出流,用来读取服务器返回的信息 InputStream is = null;//输入流,用来读取服务器返回的信息 byte[] res = null;//保存服务器返回的信息的byte数组 String url = StringUtils.EMPTY; try { OutputStream outputStream = httpURLConnection.getOutputStream(); ////1.先写文字形式的post流 //头 String boundary = BOUNDARY; //中 final StringBuffer resSB = new StringBuffer("\r\n"); //尾 String endBoundary = "\r\n--" + boundary + "--\r\n"; paramMap.entrySet().forEach(param -> { resSB.append("Content-Disposition: form-data; name=") .append(param.getKey()).append("\r\n") .append("\r\n").append(param.getValue()) .append("\r\n").append("--") .append(boundary).append("\r\n"); }); String boundaryMessage = resSB.toString(); log.info("boundaryMessage============:" + boundaryMessage); //写出流 outputStream.write(("--" + boundary + boundaryMessage).getBytes("utf-8")); //2.再写文件开式的post流 //fileParams 1:fileField, 2.fileName, 3.fileType, 4.filePath StringBuffer fileContentBuffer = new StringBuffer(); if (fileParams != null) { for (int i = 0, num = fileParams.size(); i < num; i++) { String[] parsm = fileParams.get(i); String fileField = parsm[0]; String fileName = parsm[1]; String fileType = parsm[2]; String filePath = parsm[3]; fileContentBuffer.append("Content-Disposition: form-data; name=").append(fileField).append("; filename=").append( fileName).append("\r\n").append("Content-Type: ").append(fileType).append("\r\n\r\n"); outputStream.write(fileContentBuffer.toString().getBytes("utf-8")); log.info("about file:{}", fileContentBuffer.toString()); //开始写文件 int bytes = 0; byte[] bufferOut = new byte[1024 * 5]; while ((bytes = inputStream.read(bufferOut)) != -1) { outputStream.write(bufferOut, 0, bytes); } if (i < num - 1) { outputStream.write(endBoundary.getBytes("utf-8")); } inputStream.close(); } } //3.最后写结尾 outputStream.write(endBoundary.getBytes("utf-8")); outputStream.close(); int ch; is = httpURLConnection.getInputStream(); bos = new ByteArrayOutputStream(); while ((ch = is.read()) != -1) { bos.write(ch); } res = bos.toByteArray(); String value = new String(res, "UTF-8"); log.info("result:{}", value); LuGuoImageResponse luGuoImageResponse = JSON.parseObject(res, LuGuoImageResponse.class); if (luGuoImageResponse != null && luGuoImageResponse.getStatus_code() == 200) { Image image = luGuoImageResponse.getImage(); UploadFile uploadFile = image.getFile(); UploadFileResource uploadFileResource = uploadFile.getResource(); UploadFileResourceChain chain = uploadFileResource.getChain(); url = chain.getThumb(); } /*Map maps = (Map) JSON.parse(res); if ("200".equals(maps.get("status_code"))) { Map mapImage = (Map) JSON.parse(String.valueOf(maps.get("image"))); url = String.valueOf(maps.get("imgurl")); }*/ } catch (Exception e) { e.printStackTrace(); } finally { try { if (bos != null) bos.close(); if (is != null) is.close(); } catch (Exception e2) { e2.printStackTrace(); } } return url; } public Map<String, String> session() throws IOException { HttpURLConnection httpURLConnection = HttpUtils.initHttpURLConnection("https://imgchr.com/"); setProperties(httpURLConnection, "GET", SESSIONID); StringBuffer stringBuffer = new StringBuffer(); InputStream inputStream = httpURLConnection.getInputStream(); byte[] b = new byte[1024]; int length = -1; while ((length = inputStream.read(b)) != -1) { stringBuffer.append(new String(b, 0, length, "utf-8")); } if (inputStream != null) { inputStream.close(); } String result = stringBuffer.toString(); Pattern p = Pattern.compile("PF.obj.config.auth_token = \"(.*?)\\\";"); Matcher m = p.matcher(result); String token = StringUtils.EMPTY; while (m.find()) { //System.out.println(m.group(1));//m.group(1)不包括这两个字符 token = m.group(1); } System.out.println("token:" + token); System.out.println(httpURLConnection.getHeaderField("Set-Cookie")); //String cookie = ((HttpsURLConnectionImpl) httpURLConnection) String sessionId = ""; String cookieVal = ""; String key = null; httpURLConnection = HttpUtils.initHttpURLConnection("https://imgchr.com/login"); setProperties(httpURLConnection, "POST", SESSIONID); StringBuffer params = new StringBuffer(); // 表单参数与get形式一样 params.append("login-subject").append("=").append("missedubefore") .append("&").append("password").append("=").append("longfei19880") .append("&").append("auth_token").append("=").append(token); System.out.println(params.toString()); byte[] bypes = params.toString().getBytes(); httpURLConnection.getOutputStream().write(bypes);// 输入参数 InputStream inStream = httpURLConnection.getInputStream(); //System.out.println(new String(StreamTool.readInputStream(inStream), "gbk")); while ((length = inStream.read(b)) != -1) { stringBuffer.append(new String(b, 0, length, "utf-8")); } if (inputStream != null) { inputStream.close(); } result = stringBuffer.toString(); System.out.println(result); for (int i = 1; (key = httpURLConnection.getHeaderFieldKey(i)) != null; i++) { if (key.equalsIgnoreCase("Set-Cookie")) { cookieVal = httpURLConnection.getHeaderField(i); cookieVal = cookieVal.substring(0, cookieVal.indexOf(";")); sessionId = sessionId + cookieVal + ";"; } } System.out.println(cookieVal); //return cookieVal; Map<String, String> resultMap = Maps.newHashMap(); resultMap.put("token", token); resultMap.put("session", cookieVal); return resultMap; } private static void setProperties(HttpURLConnection httpURLConnection, String method, String sessionId) throws ProtocolException { httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod(method); httpURLConnection.setRequestProperty("Host", "imgchr.com"); httpURLConnection.setRequestProperty("Connection", "keep-alive"); httpURLConnection.setRequestProperty("Accept", "application/json"); httpURLConnection.setRequestProperty("Origin", "https://imgchr.com"); httpURLConnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); httpURLConnection.setRequestProperty("Referer", "https://imgchr.com/i/l36QgS"); httpURLConnection.setRequestProperty("Cookie", "_ga=GA1.2.490248484.1576587968; PHPSESSID=" + sessionId + "; Hm_lvt_c1a64f283dcc84e35f0a947fcf3b8594=1577449018,1577706763,1577706788,1577795225; _gid=GA1.2.18614959.1577795225; KEEP_LOGIN=eatg0%3A2cf74704e5f4ea6bda3eeac71a0338ebe0d33b2728b82c268b3b07a8622092d45bd22467902f81c970bb61317457349f3f2be12718582988738abf182a3c4c5727e65226795bb6bfe6aa6f3279d02e2a1b7b430db60da05b3c1571f5325ababd7e7ac9417f48697ed66b0d77d3158dc019dbe%3A1577766627; _gat_gtag_UA_114322073_1=1; Hm_lpvt_c1a64f283dcc84e35f0a947fcf3b8594=1577795524"); } }
UTF-8
Java
10,787
java
LuGuoImageService.java
Java
[ { "context": "ppend(\"&\").append(\"password\").append(\"=\").append(\"longfei19880\")\n\t\t\t\t.append(\"&\").append(\"auth_token\").append(\"=", "end": 8014, "score": 0.9990993142127991, "start": 8002, "tag": "PASSWORD", "value": "longfei19880" } ]
null
[]
package cn.yangtengfei.api.server.pictureServer.luguo; import cn.yangtengfei.api.util.http.HttpUtils; import com.alibaba.fastjson.JSON; import com.google.common.collect.Maps; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @Slf4j @Service public class LuGuoImageService { static final String BOUNDARY = "------WebKitFormBoundaryQx3F1tuoin1schAn"; // 定义数据分隔线 public static final String SAVE_PICTURE_TO_SERVER = "https://imgchr.com/json"; public static final String SESSIONID = "g8jeplrikv9j5i4akudvam49g6"; public Map<String, String> doLogin() throws IOException { return session(); } public String getLuGuoImageUrlPath(String token,String fileName, String contentType, String path, InputStream inputStream) { String urlPath = StringUtils.EMPTY; try { //执行登录获取token //Map<String, String> userMap = session(); //String token = userMap.get("token"); HttpURLConnection httpURLConnection = HttpUtils.initHttpURLConnection(SAVE_PICTURE_TO_SERVER); setProperties(httpURLConnection, "POST", SESSIONID); //String path = "D:/01.png"; //String fileName = FileUtils.getFileName(path); //String suffix = FileUtils.stringSuffix(path); String[] fileArray1 = {"source", fileName, contentType, path}; List<String[]> fileParams = new ArrayList<>(); fileParams.add(fileArray1); Map<String, String> paramMap = new HashMap<>(); paramMap.put("type", "file"); paramMap.put("action", "upload"); paramMap.put("timestamp", (new Date()).getTime() + ""); paramMap.put("auth_token", token); paramMap.put("nsfw", "0"); urlPath = saveFile(httpURLConnection, paramMap, fileParams, inputStream); System.out.println(urlPath); return urlPath; } catch (Exception e) { log.error("uploadPictureToAliServer error", e); } return urlPath; } /*public static void main(String[] args) { try { Map<String, String> userMap = session(); String session = ""; String token = userMap.get("token"); HttpURLConnection httpURLConnection = HttpUtils.initHttpURLConnection(SAVE_PICTURE_TO_SERVER); setProperties(httpURLConnection, "POST", SESSIONID); String path = "D:/01.png"; String fileName = FileUtils.getFileName(path); String suffix = FileUtils.stringSuffix(path); String[] fileArray1 = {"source", fileName, "image/" + suffix, ""}; List<String[]> fileParams = new ArrayList<>(); fileParams.add(fileArray1); Map<String, String> paramMap = new HashMap<>(); paramMap.put("type", "file"); paramMap.put("action", "upload"); paramMap.put("timestamp", (new Date()).getTime() + ""); paramMap.put("auth_token", token); paramMap.put("nsfw", "0"); String urlPath = saveFile(httpURLConnection, paramMap, fileParams, new FileInputStream(new File(path))); System.out.println(urlPath); } catch (Exception e) { log.error("uploadPictureToAliServer error", e); } }*/ public static String saveFile(HttpURLConnection httpURLConnection, Map<String, String> paramMap, List<String[]> fileParams, InputStream inputStream) throws Exception { ByteArrayOutputStream bos = null;//byte输出流,用来读取服务器返回的信息 InputStream is = null;//输入流,用来读取服务器返回的信息 byte[] res = null;//保存服务器返回的信息的byte数组 String url = StringUtils.EMPTY; try { OutputStream outputStream = httpURLConnection.getOutputStream(); ////1.先写文字形式的post流 //头 String boundary = BOUNDARY; //中 final StringBuffer resSB = new StringBuffer("\r\n"); //尾 String endBoundary = "\r\n--" + boundary + "--\r\n"; paramMap.entrySet().forEach(param -> { resSB.append("Content-Disposition: form-data; name=") .append(param.getKey()).append("\r\n") .append("\r\n").append(param.getValue()) .append("\r\n").append("--") .append(boundary).append("\r\n"); }); String boundaryMessage = resSB.toString(); log.info("boundaryMessage============:" + boundaryMessage); //写出流 outputStream.write(("--" + boundary + boundaryMessage).getBytes("utf-8")); //2.再写文件开式的post流 //fileParams 1:fileField, 2.fileName, 3.fileType, 4.filePath StringBuffer fileContentBuffer = new StringBuffer(); if (fileParams != null) { for (int i = 0, num = fileParams.size(); i < num; i++) { String[] parsm = fileParams.get(i); String fileField = parsm[0]; String fileName = parsm[1]; String fileType = parsm[2]; String filePath = parsm[3]; fileContentBuffer.append("Content-Disposition: form-data; name=").append(fileField).append("; filename=").append( fileName).append("\r\n").append("Content-Type: ").append(fileType).append("\r\n\r\n"); outputStream.write(fileContentBuffer.toString().getBytes("utf-8")); log.info("about file:{}", fileContentBuffer.toString()); //开始写文件 int bytes = 0; byte[] bufferOut = new byte[1024 * 5]; while ((bytes = inputStream.read(bufferOut)) != -1) { outputStream.write(bufferOut, 0, bytes); } if (i < num - 1) { outputStream.write(endBoundary.getBytes("utf-8")); } inputStream.close(); } } //3.最后写结尾 outputStream.write(endBoundary.getBytes("utf-8")); outputStream.close(); int ch; is = httpURLConnection.getInputStream(); bos = new ByteArrayOutputStream(); while ((ch = is.read()) != -1) { bos.write(ch); } res = bos.toByteArray(); String value = new String(res, "UTF-8"); log.info("result:{}", value); LuGuoImageResponse luGuoImageResponse = JSON.parseObject(res, LuGuoImageResponse.class); if (luGuoImageResponse != null && luGuoImageResponse.getStatus_code() == 200) { Image image = luGuoImageResponse.getImage(); UploadFile uploadFile = image.getFile(); UploadFileResource uploadFileResource = uploadFile.getResource(); UploadFileResourceChain chain = uploadFileResource.getChain(); url = chain.getThumb(); } /*Map maps = (Map) JSON.parse(res); if ("200".equals(maps.get("status_code"))) { Map mapImage = (Map) JSON.parse(String.valueOf(maps.get("image"))); url = String.valueOf(maps.get("imgurl")); }*/ } catch (Exception e) { e.printStackTrace(); } finally { try { if (bos != null) bos.close(); if (is != null) is.close(); } catch (Exception e2) { e2.printStackTrace(); } } return url; } public Map<String, String> session() throws IOException { HttpURLConnection httpURLConnection = HttpUtils.initHttpURLConnection("https://imgchr.com/"); setProperties(httpURLConnection, "GET", SESSIONID); StringBuffer stringBuffer = new StringBuffer(); InputStream inputStream = httpURLConnection.getInputStream(); byte[] b = new byte[1024]; int length = -1; while ((length = inputStream.read(b)) != -1) { stringBuffer.append(new String(b, 0, length, "utf-8")); } if (inputStream != null) { inputStream.close(); } String result = stringBuffer.toString(); Pattern p = Pattern.compile("PF.obj.config.auth_token = \"(.*?)\\\";"); Matcher m = p.matcher(result); String token = StringUtils.EMPTY; while (m.find()) { //System.out.println(m.group(1));//m.group(1)不包括这两个字符 token = m.group(1); } System.out.println("token:" + token); System.out.println(httpURLConnection.getHeaderField("Set-Cookie")); //String cookie = ((HttpsURLConnectionImpl) httpURLConnection) String sessionId = ""; String cookieVal = ""; String key = null; httpURLConnection = HttpUtils.initHttpURLConnection("https://imgchr.com/login"); setProperties(httpURLConnection, "POST", SESSIONID); StringBuffer params = new StringBuffer(); // 表单参数与get形式一样 params.append("login-subject").append("=").append("missedubefore") .append("&").append("password").append("=").append("<PASSWORD>") .append("&").append("auth_token").append("=").append(token); System.out.println(params.toString()); byte[] bypes = params.toString().getBytes(); httpURLConnection.getOutputStream().write(bypes);// 输入参数 InputStream inStream = httpURLConnection.getInputStream(); //System.out.println(new String(StreamTool.readInputStream(inStream), "gbk")); while ((length = inStream.read(b)) != -1) { stringBuffer.append(new String(b, 0, length, "utf-8")); } if (inputStream != null) { inputStream.close(); } result = stringBuffer.toString(); System.out.println(result); for (int i = 1; (key = httpURLConnection.getHeaderFieldKey(i)) != null; i++) { if (key.equalsIgnoreCase("Set-Cookie")) { cookieVal = httpURLConnection.getHeaderField(i); cookieVal = cookieVal.substring(0, cookieVal.indexOf(";")); sessionId = sessionId + cookieVal + ";"; } } System.out.println(cookieVal); //return cookieVal; Map<String, String> resultMap = Maps.newHashMap(); resultMap.put("token", token); resultMap.put("session", cookieVal); return resultMap; } private static void setProperties(HttpURLConnection httpURLConnection, String method, String sessionId) throws ProtocolException { httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod(method); httpURLConnection.setRequestProperty("Host", "imgchr.com"); httpURLConnection.setRequestProperty("Connection", "keep-alive"); httpURLConnection.setRequestProperty("Accept", "application/json"); httpURLConnection.setRequestProperty("Origin", "https://imgchr.com"); httpURLConnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); httpURLConnection.setRequestProperty("Referer", "https://imgchr.com/i/l36QgS"); httpURLConnection.setRequestProperty("Cookie", "_ga=GA1.2.490248484.1576587968; PHPSESSID=" + sessionId + "; Hm_lvt_c1a64f283dcc84e35f0a947fcf3b8594=1577449018,1577706763,1577706788,1577795225; _gid=GA1.2.18614959.1577795225; KEEP_LOGIN=eatg0%3A2cf74704e5f4ea6bda3eeac71a0338ebe0d33b2728b82c268b3b07a8622092d45bd22467902f81c970bb61317457349f3f2be12718582988738abf182a3c4c5727e65226795bb6bfe6aa6f3279d02e2a1b7b430db60da05b3c1571f5325ababd7e7ac9417f48697ed66b0d77d3158dc019dbe%3A1577766627; _gat_gtag_UA_114322073_1=1; Hm_lpvt_c1a64f283dcc84e35f0a947fcf3b8594=1577795524"); } }
10,785
0.703304
0.664489
266
38.710526
43.499924
573
false
false
0
0
0
0
231
0.021869
3.398496
false
false
7
b4a4fc6a9a1b9a67ed2ae69a6e072aae2741ec89
22,531,398,438,996
3454174c3e211a24667a81670ba54dc93de38bd9
/Mower/src/main/java/xebia/ch/model/INC_TYPE.java
280db3d907d3f242717ea42ce95f857134111b20
[]
no_license
doukha/MowerItNow
https://github.com/doukha/MowerItNow
a54853262a288ce0863bca047d8d81a57882021c
67bbc2e4c1c22a2f1da31f35342ea6cabd18abad
refs/heads/master
2016-09-11T11:06:18.768000
2014-05-24T14:47:41
2014-05-24T14:47:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xebia.ch.model; public enum INC_TYPE { OVERRUN, COLLISION; }
UTF-8
Java
76
java
INC_TYPE.java
Java
[]
null
[]
package xebia.ch.model; public enum INC_TYPE { OVERRUN, COLLISION; }
76
0.684211
0.684211
5
13.2
10.419213
23
false
false
0
0
0
0
0
0
0.8
false
false
7
548f226befbf245a071706b5b6cb1ea5c5dc418c
10,642,928,960,458
54e4cfb24392a2ad33ac1961a9b0e5e0e0568abd
/risenetNewHall/src/net/risesoft/beans/bizbankroll/BizUnitBaseInfoBean.java
40d387e01d9ada0d8d20bdd9e74ecf88a82a56ef
[]
no_license
tangtaocode/tangtao.code
https://github.com/tangtaocode/tangtao.code
7810e66aa500c5ecfbc678386d7bb6e2a585079c
42c368f4fda2ed8618c2aada27ebfbdca42640a1
refs/heads/master
2021-01-10T02:49:57.078000
2017-07-28T15:51:39
2017-07-28T15:51:39
50,926,677
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.risesoft.beans.bizbankroll; import java.io.Serializable; import java.sql.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; /** * * @ClassName: BizUnitBaseInfoBean * @Description: 科技创新扶持申请单位基本信息表 * @author Comsys-zhangkun * @date Apr 10, 2013 4:30:46 PM * */ @Entity @Table(name="ZJFC_KJ_BASIC") public class BizUnitBaseInfoBean implements Serializable{ /** * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么) */ private static final long serialVersionUID = 308897603480391943L; private String guid; //主键 private String departmentname; //单位名称 private String corporationcode; //法人代码 private String departmentadd; //单位地址 private String bankname; //基本户开户银行 private Date founddate; //单位成立时间 private String businesssphere; //经营范围(按营业执照) private String qualification; //企业资质(□国家级高新技术企业 □市级高新技术企业 □市级软件企业 □互联网企业 □新一代信息技术企业) private String lawper; //法人代表 private String nationaltax; //国税登记证号 private String localtax; //地税登记证号 private String regcode; //营业执照注册号 private String bankcode; //帐号 private String regmoney; //注册资本 private String totalpeop; //员(职)工总数 private String dztotalpeop; //其中大专以上人员人数及占数百分比 private String researchpeop; //其中研究开发人员人数及占总数百分比 private String patentnum; //专利申请 总数 private String patentinvent; //发明(专利申请) private String patentsurface; //外观设计 (专利申请)" private String empowernum; //专利授权总数 """ private String empowerinvent; //发明(专利授权) private String empowerpractical; //实用新型 (专利授权)" private String empowersurface; //外观设计(专利授权)" private String softwarepower; //软件著作权 private String icdevisepower; //(IC)布图设计专有权 private String speciespower; //植物新品种权 private String patentpractical; //实用新型(专利申请)" private String appguid; //申请扶持项目GUID private Date createtime; //提交时间 private String userguid; //操作用户 private List<BizShareholderBean> shareholderList; private List<BizHistorySubsidize> historySubsidizeList; @Transient public List<BizShareholderBean> getShareholderList() { return shareholderList; } public void setShareholderList(List<BizShareholderBean> shareholderList) { this.shareholderList = shareholderList; } @Transient public List<BizHistorySubsidize> getHistorySubsidizeList() { return historySubsidizeList; } public void setHistorySubsidizeList( List<BizHistorySubsidize> historySubsidizeList) { this.historySubsidizeList = historySubsidizeList; } @Id public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } @Column public String getDepartmentname() { return departmentname; } public void setDepartmentname(String departmentname) { this.departmentname = departmentname; } @Column public String getCorporationcode() { return corporationcode; } public void setCorporationcode(String corporationcode) { this.corporationcode = corporationcode; } @Column public String getDepartmentadd() { return departmentadd; } public void setDepartmentadd(String departmentadd) { this.departmentadd = departmentadd; } @Column public String getBankname() { return bankname; } public void setBankname(String bankname) { this.bankname = bankname; } @Column public Date getFounddate() { return founddate; } public void setFounddate(Date founddate) { this.founddate = founddate; } @Column public String getBusinesssphere() { return businesssphere; } public void setBusinesssphere(String businesssphere) { this.businesssphere = businesssphere; } @Column public String getQualification() { return qualification; } public void setQualification(String qualification) { this.qualification = qualification; } @Column public String getLawper() { return lawper; } public void setLawper(String lawper) { this.lawper = lawper; } @Column public String getNationaltax() { return nationaltax; } public void setNationaltax(String nationaltax) { this.nationaltax = nationaltax; } @Column public String getLocaltax() { return localtax; } public void setLocaltax(String localtax) { this.localtax = localtax; } @Column public String getRegcode() { return regcode; } public void setRegcode(String regcode) { this.regcode = regcode; } @Column public String getBankcode() { return bankcode; } public void setBankcode(String bankcode) { this.bankcode = bankcode; } @Column public String getRegmoney() { return regmoney; } public void setRegmoney(String regmoney) { this.regmoney = regmoney; } @Column public String getTotalpeop() { return totalpeop; } public void setTotalpeop(String totalpeop) { this.totalpeop = totalpeop; } @Column public String getDztotalpeop() { return dztotalpeop; } public void setDztotalpeop(String dztotalpeop) { this.dztotalpeop = dztotalpeop; } @Column public String getResearchpeop() { return researchpeop; } public void setResearchpeop(String researchpeop) { this.researchpeop = researchpeop; } @Column public String getPatentnum() { return patentnum; } public void setPatentnum(String patentnum) { this.patentnum = patentnum; } @Column public String getPatentinvent() { return patentinvent; } public void setPatentinvent(String patentinvent) { this.patentinvent = patentinvent; } @Column public String getPatentsurface() { return patentsurface; } public void setPatentsurface(String patentsurface) { this.patentsurface = patentsurface; } @Column public String getEmpowernum() { return empowernum; } public void setEmpowernum(String empowernum) { this.empowernum = empowernum; } @Column public String getEmpowerinvent() { return empowerinvent; } public void setEmpowerinvent(String empowerinvent) { this.empowerinvent = empowerinvent; } @Column public String getEmpowerpractical() { return empowerpractical; } public void setEmpowerpractical(String empowerpractical) { this.empowerpractical = empowerpractical; } @Column public String getEmpowersurface() { return empowersurface; } public void setEmpowersurface(String empowersurface) { this.empowersurface = empowersurface; } @Column public String getSoftwarepower() { return softwarepower; } public void setSoftwarepower(String softwarepower) { this.softwarepower = softwarepower; } @Column public String getIcdevisepower() { return icdevisepower; } public void setIcdevisepower(String icdevisepower) { this.icdevisepower = icdevisepower; } @Column public String getSpeciespower() { return speciespower; } public void setSpeciespower(String speciespower) { this.speciespower = speciespower; } @Column public String getPatentpractical() { return patentpractical; } public void setPatentpractical(String patentpractical) { this.patentpractical = patentpractical; } @Column public String getAppguid() { return appguid; } public void setAppguid(String appguid) { this.appguid = appguid; } @Column public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } @Column public String getUserguid() { return userguid; } public void setUserguid(String userguid) { this.userguid = userguid; } }
UTF-8
Java
8,175
java
BizUnitBaseInfoBean.java
Java
[ { "context": "an\r\n * @Description: 科技创新扶持申请单位基本信息表\r\n * @author Comsys-zhangkun\r\n * @date Apr 10, 2013 4:30:46 PM\r\n *\r\n */\r\n@En", "end": 399, "score": 0.9997175335884094, "start": 384, "tag": "USERNAME", "value": "Comsys-zhangkun" } ]
null
[]
package net.risesoft.beans.bizbankroll; import java.io.Serializable; import java.sql.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; /** * * @ClassName: BizUnitBaseInfoBean * @Description: 科技创新扶持申请单位基本信息表 * @author Comsys-zhangkun * @date Apr 10, 2013 4:30:46 PM * */ @Entity @Table(name="ZJFC_KJ_BASIC") public class BizUnitBaseInfoBean implements Serializable{ /** * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么) */ private static final long serialVersionUID = 308897603480391943L; private String guid; //主键 private String departmentname; //单位名称 private String corporationcode; //法人代码 private String departmentadd; //单位地址 private String bankname; //基本户开户银行 private Date founddate; //单位成立时间 private String businesssphere; //经营范围(按营业执照) private String qualification; //企业资质(□国家级高新技术企业 □市级高新技术企业 □市级软件企业 □互联网企业 □新一代信息技术企业) private String lawper; //法人代表 private String nationaltax; //国税登记证号 private String localtax; //地税登记证号 private String regcode; //营业执照注册号 private String bankcode; //帐号 private String regmoney; //注册资本 private String totalpeop; //员(职)工总数 private String dztotalpeop; //其中大专以上人员人数及占数百分比 private String researchpeop; //其中研究开发人员人数及占总数百分比 private String patentnum; //专利申请 总数 private String patentinvent; //发明(专利申请) private String patentsurface; //外观设计 (专利申请)" private String empowernum; //专利授权总数 """ private String empowerinvent; //发明(专利授权) private String empowerpractical; //实用新型 (专利授权)" private String empowersurface; //外观设计(专利授权)" private String softwarepower; //软件著作权 private String icdevisepower; //(IC)布图设计专有权 private String speciespower; //植物新品种权 private String patentpractical; //实用新型(专利申请)" private String appguid; //申请扶持项目GUID private Date createtime; //提交时间 private String userguid; //操作用户 private List<BizShareholderBean> shareholderList; private List<BizHistorySubsidize> historySubsidizeList; @Transient public List<BizShareholderBean> getShareholderList() { return shareholderList; } public void setShareholderList(List<BizShareholderBean> shareholderList) { this.shareholderList = shareholderList; } @Transient public List<BizHistorySubsidize> getHistorySubsidizeList() { return historySubsidizeList; } public void setHistorySubsidizeList( List<BizHistorySubsidize> historySubsidizeList) { this.historySubsidizeList = historySubsidizeList; } @Id public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } @Column public String getDepartmentname() { return departmentname; } public void setDepartmentname(String departmentname) { this.departmentname = departmentname; } @Column public String getCorporationcode() { return corporationcode; } public void setCorporationcode(String corporationcode) { this.corporationcode = corporationcode; } @Column public String getDepartmentadd() { return departmentadd; } public void setDepartmentadd(String departmentadd) { this.departmentadd = departmentadd; } @Column public String getBankname() { return bankname; } public void setBankname(String bankname) { this.bankname = bankname; } @Column public Date getFounddate() { return founddate; } public void setFounddate(Date founddate) { this.founddate = founddate; } @Column public String getBusinesssphere() { return businesssphere; } public void setBusinesssphere(String businesssphere) { this.businesssphere = businesssphere; } @Column public String getQualification() { return qualification; } public void setQualification(String qualification) { this.qualification = qualification; } @Column public String getLawper() { return lawper; } public void setLawper(String lawper) { this.lawper = lawper; } @Column public String getNationaltax() { return nationaltax; } public void setNationaltax(String nationaltax) { this.nationaltax = nationaltax; } @Column public String getLocaltax() { return localtax; } public void setLocaltax(String localtax) { this.localtax = localtax; } @Column public String getRegcode() { return regcode; } public void setRegcode(String regcode) { this.regcode = regcode; } @Column public String getBankcode() { return bankcode; } public void setBankcode(String bankcode) { this.bankcode = bankcode; } @Column public String getRegmoney() { return regmoney; } public void setRegmoney(String regmoney) { this.regmoney = regmoney; } @Column public String getTotalpeop() { return totalpeop; } public void setTotalpeop(String totalpeop) { this.totalpeop = totalpeop; } @Column public String getDztotalpeop() { return dztotalpeop; } public void setDztotalpeop(String dztotalpeop) { this.dztotalpeop = dztotalpeop; } @Column public String getResearchpeop() { return researchpeop; } public void setResearchpeop(String researchpeop) { this.researchpeop = researchpeop; } @Column public String getPatentnum() { return patentnum; } public void setPatentnum(String patentnum) { this.patentnum = patentnum; } @Column public String getPatentinvent() { return patentinvent; } public void setPatentinvent(String patentinvent) { this.patentinvent = patentinvent; } @Column public String getPatentsurface() { return patentsurface; } public void setPatentsurface(String patentsurface) { this.patentsurface = patentsurface; } @Column public String getEmpowernum() { return empowernum; } public void setEmpowernum(String empowernum) { this.empowernum = empowernum; } @Column public String getEmpowerinvent() { return empowerinvent; } public void setEmpowerinvent(String empowerinvent) { this.empowerinvent = empowerinvent; } @Column public String getEmpowerpractical() { return empowerpractical; } public void setEmpowerpractical(String empowerpractical) { this.empowerpractical = empowerpractical; } @Column public String getEmpowersurface() { return empowersurface; } public void setEmpowersurface(String empowersurface) { this.empowersurface = empowersurface; } @Column public String getSoftwarepower() { return softwarepower; } public void setSoftwarepower(String softwarepower) { this.softwarepower = softwarepower; } @Column public String getIcdevisepower() { return icdevisepower; } public void setIcdevisepower(String icdevisepower) { this.icdevisepower = icdevisepower; } @Column public String getSpeciespower() { return speciespower; } public void setSpeciespower(String speciespower) { this.speciespower = speciespower; } @Column public String getPatentpractical() { return patentpractical; } public void setPatentpractical(String patentpractical) { this.patentpractical = patentpractical; } @Column public String getAppguid() { return appguid; } public void setAppguid(String appguid) { this.appguid = appguid; } @Column public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } @Column public String getUserguid() { return userguid; } public void setUserguid(String userguid) { this.userguid = userguid; } }
8,175
0.723253
0.719437
294
23.846939
18.432642
105
false
false
0
0
0
0
0
0
1.537415
false
false
7
f592a6b26f1cc4f565c230266b158fcb5e964668
11,029,476,033,919
8305e13fb033ebcaf80a6f9d7a9ace2d374f803b
/src/main/java/com/archer/livequote/util/CommonUtils.java
62127686c42adccba973453afd6693e5fbcdba51
[]
no_license
zn13621236/live-quote
https://github.com/zn13621236/live-quote
08e6a5c8cc9c294e59a01ea8ef9a37cac209af4a
aee009c4d8c0efbbb62c5153015bf0dd8a33c02c
refs/heads/master
2016-09-05T14:20:19.876000
2013-08-20T04:17:25
2013-08-20T04:17:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.archer.livequote.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.UUID; public class CommonUtils { private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public static String generateUid(){ String uuid = UUID.randomUUID().toString(); return uuid.replaceAll("[\\-]", ""); } public static String getCurrentTime(){ Calendar cal = Calendar.getInstance(); return dateFormat.format(cal.getTime()); } }
UTF-8
Java
530
java
CommonUtils.java
Java
[]
null
[]
package com.archer.livequote.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.UUID; public class CommonUtils { private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public static String generateUid(){ String uuid = UUID.randomUUID().toString(); return uuid.replaceAll("[\\-]", ""); } public static String getCurrentTime(){ Calendar cal = Calendar.getInstance(); return dateFormat.format(cal.getTime()); } }
530
0.728302
0.728302
22
23.09091
21.742102
84
false
false
0
0
0
0
0
0
1.5
false
false
7
46da6702f4f6355cf9ff42b28eb094b71bb5cd49
4,166,118,283,881
4686dd88101fa2c7bf401f1338114fcf2f3fc28e
/modules/tribe/src/test/java/org/elasticsearch/tribe/TribeIntegrationTests.java
9957ad6bae9ee1d2d7a502d53a439c48265caab1
[ "Apache-2.0", "LicenseRef-scancode-elastic-license-2018" ]
permissive
strapdata/elassandra
https://github.com/strapdata/elassandra
55f25be97533435d7d3ebaf9fa70d985020163e2
b90667791768188a98641be0f758ff7cd9f411f0
refs/heads/v6.8.4-strapdata
2023-08-27T18:06:35.023000
2022-01-03T14:21:32
2022-01-03T14:21:32
41,209,174
1,199
203
Apache-2.0
false
2022-12-08T00:38:37
2015-08-22T13:52:08
2022-12-02T03:57:09
2022-12-08T00:38:37
457,389
1,666
207
51
Java
false
false
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.tribe; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.support.DestructiveOperations; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterStateUpdateTask; import org.elasticsearch.cluster.NamedDiff; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.Priority; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.discovery.DiscoverySettings; import org.elasticsearch.discovery.MasterNotDiscoveredException; import org.elasticsearch.env.Environment; import org.elasticsearch.node.MockNode; import org.elasticsearch.node.Node; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.InternalTestCluster; import org.elasticsearch.test.NodeConfigurationSource; import org.elasticsearch.test.TestCustomMetaData; import org.elasticsearch.test.discovery.TestZenDiscovery; import org.elasticsearch.tribe.TribeServiceTests.MergableCustomMetaData1; import org.elasticsearch.tribe.TribeServiceTests.MergableCustomMetaData2; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.util.stream.Collectors.toSet; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.Is.is; /** * Note, when talking to tribe client, no need to set the local flag on master read operations, it * does it by default. */ @ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE, numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0.0) public class TribeIntegrationTests extends ESIntegTestCase { private static final String TRIBE_NODE = "tribe_node"; private static InternalTestCluster cluster1; private static InternalTestCluster cluster2; /** * A predicate that is used to select none of the remote clusters **/ private static final Predicate<InternalTestCluster> NONE = c -> false; /** * A predicate that is used to select the remote cluster 1 only **/ private static final Predicate<InternalTestCluster> CLUSTER1_ONLY = c -> c.getClusterName().equals(cluster1.getClusterName()); /** * A predicate that is used to select the remote cluster 2 only **/ private static final Predicate<InternalTestCluster> CLUSTER2_ONLY = c -> c.getClusterName().equals(cluster2.getClusterName()); /** * A predicate that is used to select the two remote clusters **/ private static final Predicate<InternalTestCluster> ALL = c -> true; @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() .put(super.nodeSettings(nodeOrdinal)) // Required to delete _all indices on remote clusters .put(DestructiveOperations.REQUIRES_NAME_SETTING.getKey(), false) .build(); } public static class TestCustomMetaDataPlugin extends Plugin { private final List<NamedWriteableRegistry.Entry> namedWritables = new ArrayList<>(); public TestCustomMetaDataPlugin() { registerBuiltinWritables(); } private <T extends MetaData.Custom> void registerMetaDataCustom(String name, Writeable.Reader<? extends T> reader, Writeable.Reader<NamedDiff> diffReader) { namedWritables.add(new NamedWriteableRegistry.Entry(MetaData.Custom.class, name, reader)); namedWritables.add(new NamedWriteableRegistry.Entry(NamedDiff.class, name, diffReader)); } private void registerBuiltinWritables() { registerMetaDataCustom(MergableCustomMetaData1.TYPE, MergableCustomMetaData1::readFrom, MergableCustomMetaData1::readDiffFrom); registerMetaDataCustom(MergableCustomMetaData2.TYPE, MergableCustomMetaData2::readFrom, MergableCustomMetaData2::readDiffFrom); } @Override public List<NamedWriteableRegistry.Entry> getNamedWriteables() { return namedWritables; } } public static class MockTribePlugin extends TribePlugin { public MockTribePlugin(Settings settings) { super(settings); } protected Function<Settings, Node> nodeBuilder(Path configPath) { return settings -> new MockNode(new Environment(settings, configPath), internalCluster().getPlugins()); } } @Override protected Collection<Class<? extends Plugin>> nodePlugins() { ArrayList<Class<? extends Plugin>> plugins = new ArrayList<>(); plugins.addAll(getMockPlugins()); plugins.add(MockTribePlugin.class); plugins.add(TribeAwareTestZenDiscoveryPlugin.class); plugins.add(TestCustomMetaDataPlugin.class); return plugins; } @Override protected boolean addTestZenDiscovery() { return false; } public static class TribeAwareTestZenDiscoveryPlugin extends TestZenDiscovery.TestPlugin { public TribeAwareTestZenDiscoveryPlugin(Settings settings) { super(settings); } @Override public Settings additionalSettings() { if (settings.getGroups("tribe", true).isEmpty()) { return super.additionalSettings(); } else { return Settings.EMPTY; } } } @Before public void startRemoteClusters() { final int minNumDataNodes = 2; final int maxNumDataNodes = 4; final NodeConfigurationSource nodeConfigurationSource = getNodeConfigSource(); final Collection<Class<? extends Plugin>> plugins = nodePlugins(); if (cluster1 == null) { cluster1 = new InternalTestCluster(randomLong(), createTempDir(), true, true, minNumDataNodes, maxNumDataNodes, UUIDs.randomBase64UUID(random()), nodeConfigurationSource, 0, false, "cluster_1", plugins, Function.identity()); } if (cluster2 == null) { cluster2 = new InternalTestCluster(randomLong(), createTempDir(), true, true, minNumDataNodes, maxNumDataNodes, UUIDs.randomBase64UUID(random()), nodeConfigurationSource, 0, false, "cluster_2", plugins, Function.identity()); } doWithAllClusters(c -> { try { c.beforeTest(random(), 0.1); c.ensureAtLeastNumDataNodes(minNumDataNodes); } catch (Exception e) { throw new RuntimeException("Failed to set up remote cluster [" + c.getClusterName() + "]", e); } }); } @After public void wipeRemoteClusters() { doWithAllClusters(c -> { final String clusterName = c.getClusterName(); try { c.client().admin().indices().prepareDelete(MetaData.ALL).get(); c.afterTest(); } catch (IOException e) { throw new RuntimeException("Failed to clean up remote cluster [" + clusterName + "]", e); } }); } @AfterClass public static void stopRemoteClusters() { try { doWithAllClusters(InternalTestCluster::close); } finally { cluster1 = null; cluster2 = null; } } private Releasable startTribeNode() throws Exception { return startTribeNode(ALL, Settings.EMPTY); } private Releasable startTribeNode(Predicate<InternalTestCluster> filter, Settings settings) throws Exception { final String node = internalCluster().startNode(createTribeSettings(filter).put(settings).build()); // wait for node to be connected to all tribe clusters final Set<String> expectedNodes = Sets.newHashSet(internalCluster().getNodeNames()); doWithAllClusters(filter, c -> { // Adds the tribe client node dedicated to this remote cluster for (String tribeNode : internalCluster().getNodeNames()) { expectedNodes.add(tribeNode + "/" + c.getClusterName()); } // Adds the remote clusters nodes names Collections.addAll(expectedNodes, c.getNodeNames()); }); assertBusy(() -> { ClusterState state = client().admin().cluster().prepareState().setNodes(true).get().getState(); Set<String> nodes = StreamSupport.stream(state.getNodes().spliterator(), false).map(DiscoveryNode::getName).collect(toSet()); assertThat(nodes, containsInAnyOrder(expectedNodes.toArray())); }); // wait for join to be fully applied on all nodes in the tribe clusters, see https://github.com/elastic/elasticsearch/issues/23695 doWithAllClusters(filter, c -> { assertFalse(c.client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).get().isTimedOut()); }); return () -> { try { while(internalCluster().getNodeNames().length > 0) { internalCluster().stopRandomNode(s -> true); } } catch (Exception e) { throw new RuntimeException("Failed to close tribe node [" + node + "]", e); } }; } private Settings.Builder createTribeSettings(Predicate<InternalTestCluster> filter) { assertNotNull(filter); final Settings.Builder settings = Settings.builder(); settings.put(Node.NODE_NAME_SETTING.getKey(), TRIBE_NODE); settings.put(Node.NODE_DATA_SETTING.getKey(), false); settings.put(Node.NODE_MASTER_SETTING.getKey(), false); settings.put(Node.NODE_INGEST_SETTING.getKey(), false); settings.put(NetworkModule.HTTP_ENABLED.getKey(), false); settings.put(NetworkModule.TRANSPORT_TYPE_SETTING.getKey(), getTestTransportType()); // add dummy tribe setting so that node is always identifiable as tribe in this test even if the set of connecting cluster is empty settings.put(TribeService.BLOCKS_WRITE_SETTING.getKey(), TribeService.BLOCKS_WRITE_SETTING.getDefault(Settings.EMPTY)); doWithAllClusters(filter, c -> { String tribeSetting = "tribe." + c.getClusterName() + "."; settings.put(tribeSetting + ClusterName.CLUSTER_NAME_SETTING.getKey(), c.getClusterName()); settings.put(tribeSetting + DiscoverySettings.INITIAL_STATE_TIMEOUT_SETTING.getKey(), "100ms"); settings.put(tribeSetting + NetworkModule.TRANSPORT_TYPE_SETTING.getKey(), getTestTransportType()); }); return settings; } public void testTribeNodeWithBadSettings() throws Exception { Settings brokenSettings = Settings.builder() .put("tribe.some.setting.that.does.not.exist", true) .build(); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> startTribeNode(ALL, brokenSettings)); assertThat(e.getMessage(), containsString("unknown setting [setting.that.does.not.exist]")); } public void testGlobalReadWriteBlocks() throws Exception { Settings additionalSettings = Settings.builder() .put("tribe.blocks.write", true) .put("tribe.blocks.metadata", true) .build(); try (Releasable tribeNode = startTribeNode(ALL, additionalSettings)) { // Creates 2 indices, test1 on cluster1 and test2 on cluster2 assertAcked(cluster1.client().admin().indices().prepareCreate("test1")); ensureGreen(cluster1.client()); assertAcked(cluster2.client().admin().indices().prepareCreate("test2")); ensureGreen(cluster2.client()); // Wait for the tribe node to retrieve the indices into its cluster state assertIndicesExist(client(), "test1", "test2"); // Writes not allowed through the tribe node ClusterBlockException e = expectThrows(ClusterBlockException.class, () -> { client().prepareIndex("test1", "type1").setSource("field", "value").get(); }); assertThat(e.getMessage(), containsString("blocked by: [BAD_REQUEST/11/tribe node, write not allowed]")); e = expectThrows(ClusterBlockException.class, () -> client().prepareIndex("test2", "type2").setSource("field", "value").get()); assertThat(e.getMessage(), containsString("blocked by: [BAD_REQUEST/11/tribe node, write not allowed]")); e = expectThrows(ClusterBlockException.class, () -> client().admin().indices().prepareForceMerge("test1").get()); assertThat(e.getMessage(), containsString("blocked by: [BAD_REQUEST/10/tribe node, metadata not allowed]")); e = expectThrows(ClusterBlockException.class, () -> client().admin().indices().prepareForceMerge("test2").get()); assertThat(e.getMessage(), containsString("blocked by: [BAD_REQUEST/10/tribe node, metadata not allowed]")); } } public void testIndexWriteBlocks() throws Exception { Settings additionalSettings = Settings.builder() .put("tribe.blocks.write.indices", "block_*") .build(); try (Releasable tribeNode = startTribeNode(ALL, additionalSettings)) { // Creates 2 indices on each remote cluster, test1 and block_test1 on cluster1 and test2 and block_test2 on cluster2 assertAcked(cluster1.client().admin().indices().prepareCreate("test1")); assertAcked(cluster1.client().admin().indices().prepareCreate("block_test1")); ensureGreen(cluster1.client()); assertAcked(cluster2.client().admin().indices().prepareCreate("test2")); assertAcked(cluster2.client().admin().indices().prepareCreate("block_test2")); ensureGreen(cluster2.client()); // Wait for the tribe node to retrieve the indices into its cluster state assertIndicesExist(client(), "test1", "test2", "block_test1", "block_test2"); // Writes allowed through the tribe node for test1/test2 indices client().prepareIndex("test1", "type1").setSource("field", "value").get(); client().prepareIndex("test2", "type2").setSource("field", "value").get(); ClusterBlockException e; e = expectThrows(ClusterBlockException.class, () -> client().prepareIndex("block_test1", "type1").setSource("foo", 0).get()); assertThat(e.getMessage(), containsString("blocked by: [FORBIDDEN/8/index write (api)]")); e = expectThrows(ClusterBlockException.class, () -> client().prepareIndex("block_test2", "type2").setSource("foo", 0).get()); assertThat(e.getMessage(), containsString("blocked by: [FORBIDDEN/8/index write (api)]")); } } public void testOnConflictDrop() throws Exception { Settings additionalSettings = Settings.builder() .put("tribe.on_conflict", "drop") .build(); try (Releasable tribeNode = startTribeNode(ALL, additionalSettings)) { // Creates 2 indices on each remote cluster, test1 and conflict on cluster1 and test2 and also conflict on cluster2 assertAcked(cluster1.client().admin().indices().prepareCreate("test1")); assertAcked(cluster1.client().admin().indices().prepareCreate("conflict")); ensureGreen(cluster1.client()); assertAcked(cluster2.client().admin().indices().prepareCreate("test2")); assertAcked(cluster2.client().admin().indices().prepareCreate("conflict")); ensureGreen(cluster2.client()); // Wait for the tribe node to retrieve the indices into its cluster state assertIndicesExist(client(), "test1", "test2"); ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertThat(clusterState.getMetaData().hasIndex("test1"), is(true)); assertThat(clusterState.getMetaData().index("test1").getSettings().get("tribe.name"), equalTo(cluster1.getClusterName())); assertThat(clusterState.getMetaData().hasIndex("test2"), is(true)); assertThat(clusterState.getMetaData().index("test2").getSettings().get("tribe.name"), equalTo(cluster2.getClusterName())); assertThat(clusterState.getMetaData().hasIndex("conflict"), is(false)); } } public void testOnConflictPrefer() throws Exception { final String preference = randomFrom(cluster1, cluster2).getClusterName(); Settings additionalSettings = Settings.builder() .put("tribe.on_conflict", "prefer_" + preference) .build(); try (Releasable tribeNode = startTribeNode(ALL, additionalSettings)) { assertAcked(cluster1.client().admin().indices().prepareCreate("test1")); assertAcked(cluster1.client().admin().indices().prepareCreate("shared")); ensureGreen(cluster1.client()); assertAcked(cluster2.client().admin().indices().prepareCreate("test2")); assertAcked(cluster2.client().admin().indices().prepareCreate("shared")); ensureGreen(cluster2.client()); // Wait for the tribe node to retrieve the indices into its cluster state assertIndicesExist(client(), "test1", "test2", "shared"); ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertThat(clusterState.getMetaData().hasIndex("test1"), is(true)); assertThat(clusterState.getMetaData().index("test1").getSettings().get("tribe.name"), equalTo(cluster1.getClusterName())); assertThat(clusterState.getMetaData().hasIndex("test2"), is(true)); assertThat(clusterState.getMetaData().index("test2").getSettings().get("tribe.name"), equalTo(cluster2.getClusterName())); assertThat(clusterState.getMetaData().hasIndex("shared"), is(true)); assertThat(clusterState.getMetaData().index("shared").getSettings().get("tribe.name"), equalTo(preference)); } } public void testTribeOnOneCluster() throws Exception { try (Releasable tribeNode = startTribeNode()) { // Creates 2 indices, test1 on cluster1 and test2 on cluster2 assertAcked(cluster1.client().admin().indices().prepareCreate("test1")); ensureGreen(cluster1.client()); assertAcked(cluster2.client().admin().indices().prepareCreate("test2")); ensureGreen(cluster2.client()); // Wait for the tribe node to retrieve the indices into its cluster state assertIndicesExist(client(), "test1", "test2"); // Creates two docs using the tribe node indexRandom(true, client().prepareIndex("test1", "type1", "1").setSource("field1", "value1"), client().prepareIndex("test2", "type1", "1").setSource("field1", "value1") ); // Verify that documents are searchable using the tribe node assertHitCount(client().prepareSearch().get(), 2L); // Using assertBusy to check that the mappings are in the tribe node cluster state assertBusy(() -> { ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertThat(clusterState.getMetaData().index("test1").mapping("type1"), notNullValue()); assertThat(clusterState.getMetaData().index("test2").mapping("type1"), notNullValue()); }); // Make sure master level write operations fail... (we don't really have a master) expectThrows(MasterNotDiscoveredException.class, () -> { client().admin().indices().prepareCreate("tribe_index").setMasterNodeTimeout("10ms").get(); }); // Now delete an index and makes sure it's reflected in cluster state cluster2.client().admin().indices().prepareDelete("test2").get(); assertBusy(() -> { ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertFalse(clusterState.getMetaData().hasIndex("test2")); assertFalse(clusterState.getRoutingTable().hasIndex("test2")); }); } } public void testCloseAndOpenIndex() throws Exception { // Creates an index on remote cluster 1 assertTrue(cluster1.client().admin().indices().prepareCreate("first").get().isAcknowledged()); ensureGreen(cluster1.client()); // Closes the index assertTrue(cluster1.client().admin().indices().prepareClose("first").get().isAcknowledged()); try (Releasable tribeNode = startTribeNode()) { // The closed index is not part of the tribe node cluster state ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertFalse(clusterState.getMetaData().hasIndex("first")); // Open the index, it becomes part of the tribe node cluster state assertTrue(cluster1.client().admin().indices().prepareOpen("first").get().isAcknowledged()); assertIndicesExist(client(), "first"); // Create a second index, wait till it is seen from within the tribe node assertTrue(cluster2.client().admin().indices().prepareCreate("second").get().isAcknowledged()); assertIndicesExist(client(), "first", "second"); ensureGreen(cluster2.client()); // Close the second index, wait till it gets removed from the tribe node cluster state assertTrue(cluster2.client().admin().indices().prepareClose("second").get().isAcknowledged()); assertIndicesExist(client(), "first"); // Open the second index, wait till it gets added back to the tribe node cluster state assertTrue(cluster2.client().admin().indices().prepareOpen("second").get().isAcknowledged()); assertIndicesExist(client(), "first", "second"); ensureGreen(cluster2.client()); } } /** * Test that the tribe node's cluster state correctly reflect the number of nodes * of the remote clusters the tribe node is connected to. */ public void testClusterStateNodes() throws Exception { List<Predicate<InternalTestCluster>> predicates = Arrays.asList(NONE, CLUSTER1_ONLY, CLUSTER2_ONLY, ALL); Collections.shuffle(predicates, random()); for (Predicate<InternalTestCluster> predicate : predicates) { try (Releasable tribeNode = startTribeNode(predicate, Settings.EMPTY)) { } } } public void testMergingRemovedCustomMetaData() throws Exception { removeCustomMetaData(cluster1, MergableCustomMetaData1.TYPE); removeCustomMetaData(cluster2, MergableCustomMetaData1.TYPE); MergableCustomMetaData1 customMetaData1 = new MergableCustomMetaData1("a"); MergableCustomMetaData1 customMetaData2 = new MergableCustomMetaData1("b"); try (Releasable tribeNode = startTribeNode()) { putCustomMetaData(cluster1, customMetaData1); putCustomMetaData(cluster2, customMetaData2); assertCustomMetaDataUpdated(internalCluster(), customMetaData2); removeCustomMetaData(cluster2, customMetaData2.getWriteableName()); assertCustomMetaDataUpdated(internalCluster(), customMetaData1); } } public void testMergingCustomMetaData() throws Exception { removeCustomMetaData(cluster1, MergableCustomMetaData1.TYPE); removeCustomMetaData(cluster2, MergableCustomMetaData1.TYPE); MergableCustomMetaData1 customMetaData1 = new MergableCustomMetaData1(randomAlphaOfLength(10)); MergableCustomMetaData1 customMetaData2 = new MergableCustomMetaData1(randomAlphaOfLength(10)); List<MergableCustomMetaData1> customMetaDatas = Arrays.asList(customMetaData1, customMetaData2); Collections.sort(customMetaDatas, (cm1, cm2) -> cm2.getData().compareTo(cm1.getData())); final MergableCustomMetaData1 tribeNodeCustomMetaData = customMetaDatas.get(0); try (Releasable tribeNode = startTribeNode()) { ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); putCustomMetaData(cluster1, customMetaData1); assertCustomMetaDataUpdated(internalCluster(), customMetaData1); // check that cluster state version is properly incremented assertThat(client().admin().cluster().prepareState().get().getState().getVersion(), equalTo(clusterState.getVersion() + 1)); putCustomMetaData(cluster2, customMetaData2); assertCustomMetaDataUpdated(internalCluster(), tribeNodeCustomMetaData); } } public void testMergingMultipleCustomMetaData() throws Exception { removeCustomMetaData(cluster1, MergableCustomMetaData1.TYPE); removeCustomMetaData(cluster2, MergableCustomMetaData1.TYPE); MergableCustomMetaData1 firstCustomMetaDataType1 = new MergableCustomMetaData1(randomAlphaOfLength(10)); MergableCustomMetaData1 secondCustomMetaDataType1 = new MergableCustomMetaData1(randomAlphaOfLength(10)); MergableCustomMetaData2 firstCustomMetaDataType2 = new MergableCustomMetaData2(randomAlphaOfLength(10)); MergableCustomMetaData2 secondCustomMetaDataType2 = new MergableCustomMetaData2(randomAlphaOfLength(10)); List<MergableCustomMetaData1> mergedCustomMetaDataType1 = Arrays.asList(firstCustomMetaDataType1, secondCustomMetaDataType1); List<MergableCustomMetaData2> mergedCustomMetaDataType2 = Arrays.asList(firstCustomMetaDataType2, secondCustomMetaDataType2); Collections.sort(mergedCustomMetaDataType1, (cm1, cm2) -> cm2.getData().compareTo(cm1.getData())); Collections.sort(mergedCustomMetaDataType2, (cm1, cm2) -> cm2.getData().compareTo(cm1.getData())); try (Releasable tribeNode = startTribeNode()) { // test putting multiple custom md types propagates to tribe putCustomMetaData(cluster1, firstCustomMetaDataType1); putCustomMetaData(cluster1, firstCustomMetaDataType2); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType1); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType2); // test multiple same type custom md is merged and propagates to tribe putCustomMetaData(cluster2, secondCustomMetaDataType1); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType2); assertCustomMetaDataUpdated(internalCluster(), mergedCustomMetaDataType1.get(0)); // test multiple same type custom md is merged and propagates to tribe putCustomMetaData(cluster2, secondCustomMetaDataType2); assertCustomMetaDataUpdated(internalCluster(), mergedCustomMetaDataType1.get(0)); assertCustomMetaDataUpdated(internalCluster(), mergedCustomMetaDataType2.get(0)); // test removing custom md is propagates to tribe removeCustomMetaData(cluster2, secondCustomMetaDataType1.getWriteableName()); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType1); assertCustomMetaDataUpdated(internalCluster(), mergedCustomMetaDataType2.get(0)); removeCustomMetaData(cluster2, secondCustomMetaDataType2.getWriteableName()); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType1); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType2); } } private static void assertCustomMetaDataUpdated(InternalTestCluster cluster, TestCustomMetaData expectedCustomMetaData) throws Exception { assertBusy(() -> { ClusterState tribeState = cluster.getInstance(ClusterService.class, cluster.getNodeNames()[0]).state(); MetaData.Custom custom = tribeState.metaData().custom(expectedCustomMetaData.getWriteableName()); assertNotNull(custom); assertThat(custom, equalTo(expectedCustomMetaData)); }); } private void removeCustomMetaData(InternalTestCluster cluster, final String customMetaDataType) { logger.info("removing custom_md type [{}] from [{}]", customMetaDataType, cluster.getClusterName()); updateMetaData(cluster, builder -> builder.removeCustom(customMetaDataType)); } private void putCustomMetaData(InternalTestCluster cluster, final TestCustomMetaData customMetaData) { logger.info("putting custom_md type [{}] with data[{}] from [{}]", customMetaData.getWriteableName(), customMetaData.getData(), cluster.getClusterName()); updateMetaData(cluster, builder -> builder.putCustom(customMetaData.getWriteableName(), customMetaData)); } private static void updateMetaData(InternalTestCluster cluster, UnaryOperator<MetaData.Builder> addCustoms) { ClusterService clusterService = cluster.getInstance(ClusterService.class, cluster.getMasterName()); final CountDownLatch latch = new CountDownLatch(1); clusterService.submitStateUpdateTask("update customMetaData", new ClusterStateUpdateTask(Priority.IMMEDIATE) { @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { latch.countDown(); } @Override public ClusterState execute(ClusterState currentState) throws Exception { MetaData.Builder builder = MetaData.builder(currentState.metaData()); builder = addCustoms.apply(builder); return ClusterState.builder(currentState).metaData(builder).build(); } @Override public void onFailure(String source, Exception e) { fail("failed to apply cluster state from [" + source + "] with " + e.getMessage()); } }); try { latch.await(1, TimeUnit.MINUTES); } catch (InterruptedException e) { fail("latch waiting on publishing custom md interrupted [" + e.getMessage() + "]"); } assertThat("timed out trying to add custom metadata to " + cluster.getClusterName(), latch.getCount(), equalTo(0L)); } private void assertIndicesExist(Client client, String... indices) throws Exception { assertBusy(() -> { ClusterState state = client.admin().cluster().prepareState().setRoutingTable(true).setMetaData(true).get().getState(); assertThat(state.getMetaData().getIndices().size(), equalTo(indices.length)); for (String index : indices) { assertTrue(state.getMetaData().hasIndex(index)); assertTrue(state.getRoutingTable().hasIndex(index)); } }); } private void ensureGreen(Client client) throws Exception { assertBusy(() -> { ClusterHealthResponse clusterHealthResponse = client.admin().cluster() .prepareHealth() .setWaitForActiveShards(0) .setWaitForEvents(Priority.LANGUID) .setWaitForNoRelocatingShards(true) .get(); assertThat(clusterHealthResponse.getStatus(), equalTo(ClusterHealthStatus.GREEN)); assertFalse(clusterHealthResponse.isTimedOut()); }); } private static void doWithAllClusters(Consumer<InternalTestCluster> consumer) { doWithAllClusters(cluster -> cluster != null, consumer); } private static void doWithAllClusters(Predicate<InternalTestCluster> predicate, Consumer<InternalTestCluster> consumer) { Stream.of(cluster1, cluster2).filter(predicate).forEach(consumer); } }
UTF-8
Java
34,358
java
TribeIntegrationTests.java
Java
[ { "context": "des in the tribe clusters, see https://github.com/elastic/elasticsearch/issues/23695\n doWithAllClust", "end": 11033, "score": 0.9977259039878845, "start": 11026, "tag": "USERNAME", "value": "elastic" } ]
null
[]
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.tribe; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.support.DestructiveOperations; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterStateUpdateTask; import org.elasticsearch.cluster.NamedDiff; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.Priority; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.discovery.DiscoverySettings; import org.elasticsearch.discovery.MasterNotDiscoveredException; import org.elasticsearch.env.Environment; import org.elasticsearch.node.MockNode; import org.elasticsearch.node.Node; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.InternalTestCluster; import org.elasticsearch.test.NodeConfigurationSource; import org.elasticsearch.test.TestCustomMetaData; import org.elasticsearch.test.discovery.TestZenDiscovery; import org.elasticsearch.tribe.TribeServiceTests.MergableCustomMetaData1; import org.elasticsearch.tribe.TribeServiceTests.MergableCustomMetaData2; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.util.stream.Collectors.toSet; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.Is.is; /** * Note, when talking to tribe client, no need to set the local flag on master read operations, it * does it by default. */ @ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE, numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0.0) public class TribeIntegrationTests extends ESIntegTestCase { private static final String TRIBE_NODE = "tribe_node"; private static InternalTestCluster cluster1; private static InternalTestCluster cluster2; /** * A predicate that is used to select none of the remote clusters **/ private static final Predicate<InternalTestCluster> NONE = c -> false; /** * A predicate that is used to select the remote cluster 1 only **/ private static final Predicate<InternalTestCluster> CLUSTER1_ONLY = c -> c.getClusterName().equals(cluster1.getClusterName()); /** * A predicate that is used to select the remote cluster 2 only **/ private static final Predicate<InternalTestCluster> CLUSTER2_ONLY = c -> c.getClusterName().equals(cluster2.getClusterName()); /** * A predicate that is used to select the two remote clusters **/ private static final Predicate<InternalTestCluster> ALL = c -> true; @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() .put(super.nodeSettings(nodeOrdinal)) // Required to delete _all indices on remote clusters .put(DestructiveOperations.REQUIRES_NAME_SETTING.getKey(), false) .build(); } public static class TestCustomMetaDataPlugin extends Plugin { private final List<NamedWriteableRegistry.Entry> namedWritables = new ArrayList<>(); public TestCustomMetaDataPlugin() { registerBuiltinWritables(); } private <T extends MetaData.Custom> void registerMetaDataCustom(String name, Writeable.Reader<? extends T> reader, Writeable.Reader<NamedDiff> diffReader) { namedWritables.add(new NamedWriteableRegistry.Entry(MetaData.Custom.class, name, reader)); namedWritables.add(new NamedWriteableRegistry.Entry(NamedDiff.class, name, diffReader)); } private void registerBuiltinWritables() { registerMetaDataCustom(MergableCustomMetaData1.TYPE, MergableCustomMetaData1::readFrom, MergableCustomMetaData1::readDiffFrom); registerMetaDataCustom(MergableCustomMetaData2.TYPE, MergableCustomMetaData2::readFrom, MergableCustomMetaData2::readDiffFrom); } @Override public List<NamedWriteableRegistry.Entry> getNamedWriteables() { return namedWritables; } } public static class MockTribePlugin extends TribePlugin { public MockTribePlugin(Settings settings) { super(settings); } protected Function<Settings, Node> nodeBuilder(Path configPath) { return settings -> new MockNode(new Environment(settings, configPath), internalCluster().getPlugins()); } } @Override protected Collection<Class<? extends Plugin>> nodePlugins() { ArrayList<Class<? extends Plugin>> plugins = new ArrayList<>(); plugins.addAll(getMockPlugins()); plugins.add(MockTribePlugin.class); plugins.add(TribeAwareTestZenDiscoveryPlugin.class); plugins.add(TestCustomMetaDataPlugin.class); return plugins; } @Override protected boolean addTestZenDiscovery() { return false; } public static class TribeAwareTestZenDiscoveryPlugin extends TestZenDiscovery.TestPlugin { public TribeAwareTestZenDiscoveryPlugin(Settings settings) { super(settings); } @Override public Settings additionalSettings() { if (settings.getGroups("tribe", true).isEmpty()) { return super.additionalSettings(); } else { return Settings.EMPTY; } } } @Before public void startRemoteClusters() { final int minNumDataNodes = 2; final int maxNumDataNodes = 4; final NodeConfigurationSource nodeConfigurationSource = getNodeConfigSource(); final Collection<Class<? extends Plugin>> plugins = nodePlugins(); if (cluster1 == null) { cluster1 = new InternalTestCluster(randomLong(), createTempDir(), true, true, minNumDataNodes, maxNumDataNodes, UUIDs.randomBase64UUID(random()), nodeConfigurationSource, 0, false, "cluster_1", plugins, Function.identity()); } if (cluster2 == null) { cluster2 = new InternalTestCluster(randomLong(), createTempDir(), true, true, minNumDataNodes, maxNumDataNodes, UUIDs.randomBase64UUID(random()), nodeConfigurationSource, 0, false, "cluster_2", plugins, Function.identity()); } doWithAllClusters(c -> { try { c.beforeTest(random(), 0.1); c.ensureAtLeastNumDataNodes(minNumDataNodes); } catch (Exception e) { throw new RuntimeException("Failed to set up remote cluster [" + c.getClusterName() + "]", e); } }); } @After public void wipeRemoteClusters() { doWithAllClusters(c -> { final String clusterName = c.getClusterName(); try { c.client().admin().indices().prepareDelete(MetaData.ALL).get(); c.afterTest(); } catch (IOException e) { throw new RuntimeException("Failed to clean up remote cluster [" + clusterName + "]", e); } }); } @AfterClass public static void stopRemoteClusters() { try { doWithAllClusters(InternalTestCluster::close); } finally { cluster1 = null; cluster2 = null; } } private Releasable startTribeNode() throws Exception { return startTribeNode(ALL, Settings.EMPTY); } private Releasable startTribeNode(Predicate<InternalTestCluster> filter, Settings settings) throws Exception { final String node = internalCluster().startNode(createTribeSettings(filter).put(settings).build()); // wait for node to be connected to all tribe clusters final Set<String> expectedNodes = Sets.newHashSet(internalCluster().getNodeNames()); doWithAllClusters(filter, c -> { // Adds the tribe client node dedicated to this remote cluster for (String tribeNode : internalCluster().getNodeNames()) { expectedNodes.add(tribeNode + "/" + c.getClusterName()); } // Adds the remote clusters nodes names Collections.addAll(expectedNodes, c.getNodeNames()); }); assertBusy(() -> { ClusterState state = client().admin().cluster().prepareState().setNodes(true).get().getState(); Set<String> nodes = StreamSupport.stream(state.getNodes().spliterator(), false).map(DiscoveryNode::getName).collect(toSet()); assertThat(nodes, containsInAnyOrder(expectedNodes.toArray())); }); // wait for join to be fully applied on all nodes in the tribe clusters, see https://github.com/elastic/elasticsearch/issues/23695 doWithAllClusters(filter, c -> { assertFalse(c.client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).get().isTimedOut()); }); return () -> { try { while(internalCluster().getNodeNames().length > 0) { internalCluster().stopRandomNode(s -> true); } } catch (Exception e) { throw new RuntimeException("Failed to close tribe node [" + node + "]", e); } }; } private Settings.Builder createTribeSettings(Predicate<InternalTestCluster> filter) { assertNotNull(filter); final Settings.Builder settings = Settings.builder(); settings.put(Node.NODE_NAME_SETTING.getKey(), TRIBE_NODE); settings.put(Node.NODE_DATA_SETTING.getKey(), false); settings.put(Node.NODE_MASTER_SETTING.getKey(), false); settings.put(Node.NODE_INGEST_SETTING.getKey(), false); settings.put(NetworkModule.HTTP_ENABLED.getKey(), false); settings.put(NetworkModule.TRANSPORT_TYPE_SETTING.getKey(), getTestTransportType()); // add dummy tribe setting so that node is always identifiable as tribe in this test even if the set of connecting cluster is empty settings.put(TribeService.BLOCKS_WRITE_SETTING.getKey(), TribeService.BLOCKS_WRITE_SETTING.getDefault(Settings.EMPTY)); doWithAllClusters(filter, c -> { String tribeSetting = "tribe." + c.getClusterName() + "."; settings.put(tribeSetting + ClusterName.CLUSTER_NAME_SETTING.getKey(), c.getClusterName()); settings.put(tribeSetting + DiscoverySettings.INITIAL_STATE_TIMEOUT_SETTING.getKey(), "100ms"); settings.put(tribeSetting + NetworkModule.TRANSPORT_TYPE_SETTING.getKey(), getTestTransportType()); }); return settings; } public void testTribeNodeWithBadSettings() throws Exception { Settings brokenSettings = Settings.builder() .put("tribe.some.setting.that.does.not.exist", true) .build(); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> startTribeNode(ALL, brokenSettings)); assertThat(e.getMessage(), containsString("unknown setting [setting.that.does.not.exist]")); } public void testGlobalReadWriteBlocks() throws Exception { Settings additionalSettings = Settings.builder() .put("tribe.blocks.write", true) .put("tribe.blocks.metadata", true) .build(); try (Releasable tribeNode = startTribeNode(ALL, additionalSettings)) { // Creates 2 indices, test1 on cluster1 and test2 on cluster2 assertAcked(cluster1.client().admin().indices().prepareCreate("test1")); ensureGreen(cluster1.client()); assertAcked(cluster2.client().admin().indices().prepareCreate("test2")); ensureGreen(cluster2.client()); // Wait for the tribe node to retrieve the indices into its cluster state assertIndicesExist(client(), "test1", "test2"); // Writes not allowed through the tribe node ClusterBlockException e = expectThrows(ClusterBlockException.class, () -> { client().prepareIndex("test1", "type1").setSource("field", "value").get(); }); assertThat(e.getMessage(), containsString("blocked by: [BAD_REQUEST/11/tribe node, write not allowed]")); e = expectThrows(ClusterBlockException.class, () -> client().prepareIndex("test2", "type2").setSource("field", "value").get()); assertThat(e.getMessage(), containsString("blocked by: [BAD_REQUEST/11/tribe node, write not allowed]")); e = expectThrows(ClusterBlockException.class, () -> client().admin().indices().prepareForceMerge("test1").get()); assertThat(e.getMessage(), containsString("blocked by: [BAD_REQUEST/10/tribe node, metadata not allowed]")); e = expectThrows(ClusterBlockException.class, () -> client().admin().indices().prepareForceMerge("test2").get()); assertThat(e.getMessage(), containsString("blocked by: [BAD_REQUEST/10/tribe node, metadata not allowed]")); } } public void testIndexWriteBlocks() throws Exception { Settings additionalSettings = Settings.builder() .put("tribe.blocks.write.indices", "block_*") .build(); try (Releasable tribeNode = startTribeNode(ALL, additionalSettings)) { // Creates 2 indices on each remote cluster, test1 and block_test1 on cluster1 and test2 and block_test2 on cluster2 assertAcked(cluster1.client().admin().indices().prepareCreate("test1")); assertAcked(cluster1.client().admin().indices().prepareCreate("block_test1")); ensureGreen(cluster1.client()); assertAcked(cluster2.client().admin().indices().prepareCreate("test2")); assertAcked(cluster2.client().admin().indices().prepareCreate("block_test2")); ensureGreen(cluster2.client()); // Wait for the tribe node to retrieve the indices into its cluster state assertIndicesExist(client(), "test1", "test2", "block_test1", "block_test2"); // Writes allowed through the tribe node for test1/test2 indices client().prepareIndex("test1", "type1").setSource("field", "value").get(); client().prepareIndex("test2", "type2").setSource("field", "value").get(); ClusterBlockException e; e = expectThrows(ClusterBlockException.class, () -> client().prepareIndex("block_test1", "type1").setSource("foo", 0).get()); assertThat(e.getMessage(), containsString("blocked by: [FORBIDDEN/8/index write (api)]")); e = expectThrows(ClusterBlockException.class, () -> client().prepareIndex("block_test2", "type2").setSource("foo", 0).get()); assertThat(e.getMessage(), containsString("blocked by: [FORBIDDEN/8/index write (api)]")); } } public void testOnConflictDrop() throws Exception { Settings additionalSettings = Settings.builder() .put("tribe.on_conflict", "drop") .build(); try (Releasable tribeNode = startTribeNode(ALL, additionalSettings)) { // Creates 2 indices on each remote cluster, test1 and conflict on cluster1 and test2 and also conflict on cluster2 assertAcked(cluster1.client().admin().indices().prepareCreate("test1")); assertAcked(cluster1.client().admin().indices().prepareCreate("conflict")); ensureGreen(cluster1.client()); assertAcked(cluster2.client().admin().indices().prepareCreate("test2")); assertAcked(cluster2.client().admin().indices().prepareCreate("conflict")); ensureGreen(cluster2.client()); // Wait for the tribe node to retrieve the indices into its cluster state assertIndicesExist(client(), "test1", "test2"); ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertThat(clusterState.getMetaData().hasIndex("test1"), is(true)); assertThat(clusterState.getMetaData().index("test1").getSettings().get("tribe.name"), equalTo(cluster1.getClusterName())); assertThat(clusterState.getMetaData().hasIndex("test2"), is(true)); assertThat(clusterState.getMetaData().index("test2").getSettings().get("tribe.name"), equalTo(cluster2.getClusterName())); assertThat(clusterState.getMetaData().hasIndex("conflict"), is(false)); } } public void testOnConflictPrefer() throws Exception { final String preference = randomFrom(cluster1, cluster2).getClusterName(); Settings additionalSettings = Settings.builder() .put("tribe.on_conflict", "prefer_" + preference) .build(); try (Releasable tribeNode = startTribeNode(ALL, additionalSettings)) { assertAcked(cluster1.client().admin().indices().prepareCreate("test1")); assertAcked(cluster1.client().admin().indices().prepareCreate("shared")); ensureGreen(cluster1.client()); assertAcked(cluster2.client().admin().indices().prepareCreate("test2")); assertAcked(cluster2.client().admin().indices().prepareCreate("shared")); ensureGreen(cluster2.client()); // Wait for the tribe node to retrieve the indices into its cluster state assertIndicesExist(client(), "test1", "test2", "shared"); ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertThat(clusterState.getMetaData().hasIndex("test1"), is(true)); assertThat(clusterState.getMetaData().index("test1").getSettings().get("tribe.name"), equalTo(cluster1.getClusterName())); assertThat(clusterState.getMetaData().hasIndex("test2"), is(true)); assertThat(clusterState.getMetaData().index("test2").getSettings().get("tribe.name"), equalTo(cluster2.getClusterName())); assertThat(clusterState.getMetaData().hasIndex("shared"), is(true)); assertThat(clusterState.getMetaData().index("shared").getSettings().get("tribe.name"), equalTo(preference)); } } public void testTribeOnOneCluster() throws Exception { try (Releasable tribeNode = startTribeNode()) { // Creates 2 indices, test1 on cluster1 and test2 on cluster2 assertAcked(cluster1.client().admin().indices().prepareCreate("test1")); ensureGreen(cluster1.client()); assertAcked(cluster2.client().admin().indices().prepareCreate("test2")); ensureGreen(cluster2.client()); // Wait for the tribe node to retrieve the indices into its cluster state assertIndicesExist(client(), "test1", "test2"); // Creates two docs using the tribe node indexRandom(true, client().prepareIndex("test1", "type1", "1").setSource("field1", "value1"), client().prepareIndex("test2", "type1", "1").setSource("field1", "value1") ); // Verify that documents are searchable using the tribe node assertHitCount(client().prepareSearch().get(), 2L); // Using assertBusy to check that the mappings are in the tribe node cluster state assertBusy(() -> { ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertThat(clusterState.getMetaData().index("test1").mapping("type1"), notNullValue()); assertThat(clusterState.getMetaData().index("test2").mapping("type1"), notNullValue()); }); // Make sure master level write operations fail... (we don't really have a master) expectThrows(MasterNotDiscoveredException.class, () -> { client().admin().indices().prepareCreate("tribe_index").setMasterNodeTimeout("10ms").get(); }); // Now delete an index and makes sure it's reflected in cluster state cluster2.client().admin().indices().prepareDelete("test2").get(); assertBusy(() -> { ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertFalse(clusterState.getMetaData().hasIndex("test2")); assertFalse(clusterState.getRoutingTable().hasIndex("test2")); }); } } public void testCloseAndOpenIndex() throws Exception { // Creates an index on remote cluster 1 assertTrue(cluster1.client().admin().indices().prepareCreate("first").get().isAcknowledged()); ensureGreen(cluster1.client()); // Closes the index assertTrue(cluster1.client().admin().indices().prepareClose("first").get().isAcknowledged()); try (Releasable tribeNode = startTribeNode()) { // The closed index is not part of the tribe node cluster state ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); assertFalse(clusterState.getMetaData().hasIndex("first")); // Open the index, it becomes part of the tribe node cluster state assertTrue(cluster1.client().admin().indices().prepareOpen("first").get().isAcknowledged()); assertIndicesExist(client(), "first"); // Create a second index, wait till it is seen from within the tribe node assertTrue(cluster2.client().admin().indices().prepareCreate("second").get().isAcknowledged()); assertIndicesExist(client(), "first", "second"); ensureGreen(cluster2.client()); // Close the second index, wait till it gets removed from the tribe node cluster state assertTrue(cluster2.client().admin().indices().prepareClose("second").get().isAcknowledged()); assertIndicesExist(client(), "first"); // Open the second index, wait till it gets added back to the tribe node cluster state assertTrue(cluster2.client().admin().indices().prepareOpen("second").get().isAcknowledged()); assertIndicesExist(client(), "first", "second"); ensureGreen(cluster2.client()); } } /** * Test that the tribe node's cluster state correctly reflect the number of nodes * of the remote clusters the tribe node is connected to. */ public void testClusterStateNodes() throws Exception { List<Predicate<InternalTestCluster>> predicates = Arrays.asList(NONE, CLUSTER1_ONLY, CLUSTER2_ONLY, ALL); Collections.shuffle(predicates, random()); for (Predicate<InternalTestCluster> predicate : predicates) { try (Releasable tribeNode = startTribeNode(predicate, Settings.EMPTY)) { } } } public void testMergingRemovedCustomMetaData() throws Exception { removeCustomMetaData(cluster1, MergableCustomMetaData1.TYPE); removeCustomMetaData(cluster2, MergableCustomMetaData1.TYPE); MergableCustomMetaData1 customMetaData1 = new MergableCustomMetaData1("a"); MergableCustomMetaData1 customMetaData2 = new MergableCustomMetaData1("b"); try (Releasable tribeNode = startTribeNode()) { putCustomMetaData(cluster1, customMetaData1); putCustomMetaData(cluster2, customMetaData2); assertCustomMetaDataUpdated(internalCluster(), customMetaData2); removeCustomMetaData(cluster2, customMetaData2.getWriteableName()); assertCustomMetaDataUpdated(internalCluster(), customMetaData1); } } public void testMergingCustomMetaData() throws Exception { removeCustomMetaData(cluster1, MergableCustomMetaData1.TYPE); removeCustomMetaData(cluster2, MergableCustomMetaData1.TYPE); MergableCustomMetaData1 customMetaData1 = new MergableCustomMetaData1(randomAlphaOfLength(10)); MergableCustomMetaData1 customMetaData2 = new MergableCustomMetaData1(randomAlphaOfLength(10)); List<MergableCustomMetaData1> customMetaDatas = Arrays.asList(customMetaData1, customMetaData2); Collections.sort(customMetaDatas, (cm1, cm2) -> cm2.getData().compareTo(cm1.getData())); final MergableCustomMetaData1 tribeNodeCustomMetaData = customMetaDatas.get(0); try (Releasable tribeNode = startTribeNode()) { ClusterState clusterState = client().admin().cluster().prepareState().get().getState(); putCustomMetaData(cluster1, customMetaData1); assertCustomMetaDataUpdated(internalCluster(), customMetaData1); // check that cluster state version is properly incremented assertThat(client().admin().cluster().prepareState().get().getState().getVersion(), equalTo(clusterState.getVersion() + 1)); putCustomMetaData(cluster2, customMetaData2); assertCustomMetaDataUpdated(internalCluster(), tribeNodeCustomMetaData); } } public void testMergingMultipleCustomMetaData() throws Exception { removeCustomMetaData(cluster1, MergableCustomMetaData1.TYPE); removeCustomMetaData(cluster2, MergableCustomMetaData1.TYPE); MergableCustomMetaData1 firstCustomMetaDataType1 = new MergableCustomMetaData1(randomAlphaOfLength(10)); MergableCustomMetaData1 secondCustomMetaDataType1 = new MergableCustomMetaData1(randomAlphaOfLength(10)); MergableCustomMetaData2 firstCustomMetaDataType2 = new MergableCustomMetaData2(randomAlphaOfLength(10)); MergableCustomMetaData2 secondCustomMetaDataType2 = new MergableCustomMetaData2(randomAlphaOfLength(10)); List<MergableCustomMetaData1> mergedCustomMetaDataType1 = Arrays.asList(firstCustomMetaDataType1, secondCustomMetaDataType1); List<MergableCustomMetaData2> mergedCustomMetaDataType2 = Arrays.asList(firstCustomMetaDataType2, secondCustomMetaDataType2); Collections.sort(mergedCustomMetaDataType1, (cm1, cm2) -> cm2.getData().compareTo(cm1.getData())); Collections.sort(mergedCustomMetaDataType2, (cm1, cm2) -> cm2.getData().compareTo(cm1.getData())); try (Releasable tribeNode = startTribeNode()) { // test putting multiple custom md types propagates to tribe putCustomMetaData(cluster1, firstCustomMetaDataType1); putCustomMetaData(cluster1, firstCustomMetaDataType2); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType1); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType2); // test multiple same type custom md is merged and propagates to tribe putCustomMetaData(cluster2, secondCustomMetaDataType1); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType2); assertCustomMetaDataUpdated(internalCluster(), mergedCustomMetaDataType1.get(0)); // test multiple same type custom md is merged and propagates to tribe putCustomMetaData(cluster2, secondCustomMetaDataType2); assertCustomMetaDataUpdated(internalCluster(), mergedCustomMetaDataType1.get(0)); assertCustomMetaDataUpdated(internalCluster(), mergedCustomMetaDataType2.get(0)); // test removing custom md is propagates to tribe removeCustomMetaData(cluster2, secondCustomMetaDataType1.getWriteableName()); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType1); assertCustomMetaDataUpdated(internalCluster(), mergedCustomMetaDataType2.get(0)); removeCustomMetaData(cluster2, secondCustomMetaDataType2.getWriteableName()); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType1); assertCustomMetaDataUpdated(internalCluster(), firstCustomMetaDataType2); } } private static void assertCustomMetaDataUpdated(InternalTestCluster cluster, TestCustomMetaData expectedCustomMetaData) throws Exception { assertBusy(() -> { ClusterState tribeState = cluster.getInstance(ClusterService.class, cluster.getNodeNames()[0]).state(); MetaData.Custom custom = tribeState.metaData().custom(expectedCustomMetaData.getWriteableName()); assertNotNull(custom); assertThat(custom, equalTo(expectedCustomMetaData)); }); } private void removeCustomMetaData(InternalTestCluster cluster, final String customMetaDataType) { logger.info("removing custom_md type [{}] from [{}]", customMetaDataType, cluster.getClusterName()); updateMetaData(cluster, builder -> builder.removeCustom(customMetaDataType)); } private void putCustomMetaData(InternalTestCluster cluster, final TestCustomMetaData customMetaData) { logger.info("putting custom_md type [{}] with data[{}] from [{}]", customMetaData.getWriteableName(), customMetaData.getData(), cluster.getClusterName()); updateMetaData(cluster, builder -> builder.putCustom(customMetaData.getWriteableName(), customMetaData)); } private static void updateMetaData(InternalTestCluster cluster, UnaryOperator<MetaData.Builder> addCustoms) { ClusterService clusterService = cluster.getInstance(ClusterService.class, cluster.getMasterName()); final CountDownLatch latch = new CountDownLatch(1); clusterService.submitStateUpdateTask("update customMetaData", new ClusterStateUpdateTask(Priority.IMMEDIATE) { @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { latch.countDown(); } @Override public ClusterState execute(ClusterState currentState) throws Exception { MetaData.Builder builder = MetaData.builder(currentState.metaData()); builder = addCustoms.apply(builder); return ClusterState.builder(currentState).metaData(builder).build(); } @Override public void onFailure(String source, Exception e) { fail("failed to apply cluster state from [" + source + "] with " + e.getMessage()); } }); try { latch.await(1, TimeUnit.MINUTES); } catch (InterruptedException e) { fail("latch waiting on publishing custom md interrupted [" + e.getMessage() + "]"); } assertThat("timed out trying to add custom metadata to " + cluster.getClusterName(), latch.getCount(), equalTo(0L)); } private void assertIndicesExist(Client client, String... indices) throws Exception { assertBusy(() -> { ClusterState state = client.admin().cluster().prepareState().setRoutingTable(true).setMetaData(true).get().getState(); assertThat(state.getMetaData().getIndices().size(), equalTo(indices.length)); for (String index : indices) { assertTrue(state.getMetaData().hasIndex(index)); assertTrue(state.getRoutingTable().hasIndex(index)); } }); } private void ensureGreen(Client client) throws Exception { assertBusy(() -> { ClusterHealthResponse clusterHealthResponse = client.admin().cluster() .prepareHealth() .setWaitForActiveShards(0) .setWaitForEvents(Priority.LANGUID) .setWaitForNoRelocatingShards(true) .get(); assertThat(clusterHealthResponse.getStatus(), equalTo(ClusterHealthStatus.GREEN)); assertFalse(clusterHealthResponse.isTimedOut()); }); } private static void doWithAllClusters(Consumer<InternalTestCluster> consumer) { doWithAllClusters(cluster -> cluster != null, consumer); } private static void doWithAllClusters(Predicate<InternalTestCluster> predicate, Consumer<InternalTestCluster> consumer) { Stream.of(cluster1, cluster2).filter(predicate).forEach(consumer); } }
34,358
0.675418
0.666104
678
49.675518
39.121147
139
false
false
0
0
0
0
0
0
0.814159
false
false
7
83a4e7dd1a6f840dd869fb2805cb25bcfb895b73
22,909,355,561,899
b61db9863a59437a827d037b2a6d8ee92406ac6c
/backend/src/main/java/com/awctw/TFTItemBuild/database/dataHandler.java
a283593e6612ce4729b32833322e2d06b115fa65
[]
no_license
awctw/TFTItemBuild
https://github.com/awctw/TFTItemBuild
ac732baa8c1ebda32823e039c8c4db89ed865fc2
f36cbb724b2f0344b054a42d4c2aa78dd2c10022
refs/heads/master
2023-05-07T19:17:04.858000
2021-06-03T08:29:13
2021-06-03T08:29:13
367,818,979
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.awctw.TFTItemBuild.database; import com.awctw.TFTItemBuild.model.Champion; import com.awctw.TFTItemBuild.model.ChampionItems; import com.awctw.TFTItemBuild.model.FinalItem; import com.awctw.TFTItemBuild.model.Items; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface dataHandler { @Insert({"INSERT IGNORE INTO ChampionItems(championName,finalItemName1, finalItemName2, finalItemName3) " + "VALUES (#{champ},#{finalItem1}, #{finalItem2}, #{finalItem3})"}) void insertSpecChampItems(Items item, String champ, String finalItem1, String finalItem2, String finalItem3); @Insert({"INSERT INTO TeamComp(teamCompName, mainCarry1, mainCarry2, teammate3, teammate4, teammate5, teammate6, teammate7, teammate8) " + "VALUES (#{teamCompName}, #{mainCarry1}, #{mainCarry2}, #{teammate3}, #{teammate4}, #{teammate5}, #{teammate6}, #{teammate7}, #{teammate8})"}) void insertComp(Items item, String teamCompName, String mainCarry1, String mainCarry2, String teammate3, String teammate4, String teammate5,String teammate6,String teammate7, String teammate8); @Delete("DELETE FROM TeamComp") void deleteComp(); @Select("SELECT * FROM Champion") List<Champion> getAllChampion(); @Select("SELECT * " + "FROM ChampionItems " + "WHERE finalItemName1 = #{finalItem} OR " + "finalItemName2 = #{finalItem} OR " + "finalItemName3 = #{finalItem}") List<ChampionItems> getChampionItems(String finalItem); @Select("SELECT * FROM ChampionItems") List<ChampionItems> getAllChampionItems(); }
UTF-8
Java
1,639
java
dataHandler.java
Java
[]
null
[]
package com.awctw.TFTItemBuild.database; import com.awctw.TFTItemBuild.model.Champion; import com.awctw.TFTItemBuild.model.ChampionItems; import com.awctw.TFTItemBuild.model.FinalItem; import com.awctw.TFTItemBuild.model.Items; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface dataHandler { @Insert({"INSERT IGNORE INTO ChampionItems(championName,finalItemName1, finalItemName2, finalItemName3) " + "VALUES (#{champ},#{finalItem1}, #{finalItem2}, #{finalItem3})"}) void insertSpecChampItems(Items item, String champ, String finalItem1, String finalItem2, String finalItem3); @Insert({"INSERT INTO TeamComp(teamCompName, mainCarry1, mainCarry2, teammate3, teammate4, teammate5, teammate6, teammate7, teammate8) " + "VALUES (#{teamCompName}, #{mainCarry1}, #{mainCarry2}, #{teammate3}, #{teammate4}, #{teammate5}, #{teammate6}, #{teammate7}, #{teammate8})"}) void insertComp(Items item, String teamCompName, String mainCarry1, String mainCarry2, String teammate3, String teammate4, String teammate5,String teammate6,String teammate7, String teammate8); @Delete("DELETE FROM TeamComp") void deleteComp(); @Select("SELECT * FROM Champion") List<Champion> getAllChampion(); @Select("SELECT * " + "FROM ChampionItems " + "WHERE finalItemName1 = #{finalItem} OR " + "finalItemName2 = #{finalItem} OR " + "finalItemName3 = #{finalItem}") List<ChampionItems> getChampionItems(String finalItem); @Select("SELECT * FROM ChampionItems") List<ChampionItems> getAllChampionItems(); }
1,639
0.71446
0.692495
38
42.13158
45.92968
197
false
false
0
0
0
0
0
0
1.263158
false
false
7
7e0f600d1e2b1fafbe3f5456649ee10aa5f02e2d
16,913,581,276,930
56296e32f9335c69bb1f3d95352682699556327a
/server/process_server/ReportWeather.java
4fb6a9796561d1a6998068ff70433a4dda1058e1
[]
no_license
iKarosStudio/sv1
https://github.com/iKarosStudio/sv1
205f40e291fd6de4cee7a79ee3e593154344d97d
431d463c98218a3b01f1a0cc50f56f3bfef7043e
refs/heads/master
2020-03-31T11:16:52.111000
2018-10-18T02:40:33
2018-10-18T02:40:33
152,170,450
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package vidar.server.process_server; import vidar.server.packet.*; import vidar.server.opcodes.*; public class ReportWeather { PacketBuilder builder = new PacketBuilder () ; public ReportWeather (int weather) { builder.writeByte (ServerOpcodes.WEATHER) ; builder.writeByte (weather) ; } public byte[] getRaw () { return builder.getPacket () ; } }
UTF-8
Java
364
java
ReportWeather.java
Java
[]
null
[]
package vidar.server.process_server; import vidar.server.packet.*; import vidar.server.opcodes.*; public class ReportWeather { PacketBuilder builder = new PacketBuilder () ; public ReportWeather (int weather) { builder.writeByte (ServerOpcodes.WEATHER) ; builder.writeByte (weather) ; } public byte[] getRaw () { return builder.getPacket () ; } }
364
0.725275
0.725275
18
19.222221
17.119045
47
false
false
0
0
0
0
0
0
1.111111
false
false
7
70a2517189e413861dbc441f3a7f4086c1f7231a
28,467,043,290,144
ad58cdef9ef9f5da55e6c394bc9915fd84bc31d4
/Portal/portal-web/src/main/java/com/ffzx/portal/utils/UplaodImageController.java
21f34c3f584a856747b88620e90c786796a68835
[]
no_license
shawloong/code
https://github.com/shawloong/code
65f8e95134d82b35a5f76100cdb6d5c48cd08921
1f62cf18a5d36395f4602141c920b5c3e626951e
refs/heads/master
2020-02-29T17:20:56.706000
2017-04-30T05:19:17
2017-04-30T05:19:17
89,827,564
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.ffzx.portal.utils; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.MessageChannel; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.alibaba.dubbo.remoting.ExecutionException; import com.alibaba.dubbo.rpc.service.GenericService; import com.ffzx.commerce.framework.controller.BaseController; import com.ffzx.commerce.framework.dto.ResultDto; import com.ffzx.commerce.framework.utils.DateUtil; import com.ffzx.commerce.framework.utils.FTPUtil; import com.ffzx.commerce.framework.utils.ImageAttribute; import com.ffzx.commerce.framework.utils.ImageUtil; import com.ffzx.commerce.framework.utils.StringUtil; import com.ffzx.commerce.framework.utils.UUIDGenerator; import com.ffzx.parentweb.controller.UploadImageController; /** * * @author ying.cai * @date 2017年4月14日下午1:46:26 * @email ying.cai@ffzxnet.com * @version V1.0 */ @Controller @RequestMapping("/portal") public class UplaodImageController extends BaseController{ private static final Logger logger = LoggerFactory.getLogger(UploadImageController.class); @Autowired private MessageChannel ftpUploadChannel; private GenericService dictApiService; @RequestMapping(value={"upload"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) public void upload(@RequestParam("file") MultipartFile file, @RequestParam(value="fileName", required=false) String ordingName, @RequestParam(value="sizeType", required=false) String sizeType, String path, HttpServletResponse response) throws IOException, InterruptedException, ExecutionException{ Map<String, Object> output = new HashMap(); try{ byte[] bytes = file.getBytes(); String fileName = file.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".")); List<ImageAttribute> list = new ArrayList(); String savePath = DateUtil.formatMonthDate(new Date()); ImageAttribute imgattr = new ImageAttribute(null, null, true); list.add(new ImageAttribute(150, 150, true)); list.add(new ImageAttribute(499, 334, true)); list.add(new ImageAttribute(1000, 700, true)); list.add(new ImageAttribute(1180, 840, true)); list.add(imgattr); String imgType = null; if(null!=sizeType){ imgType = getDictByType("sys_img_type", sizeType); } if ((StringUtil.isNotNull(imgType)) && (!imgType.equals("-1"))){ String[] sizeList = imgType.split(";"); for (String string : sizeList) { String[] itemSize = string.split("X"); imgattr = new ImageAttribute(Integer.valueOf(Integer.parseInt(itemSize[0].trim())), Integer.valueOf(Integer.parseInt(itemSize[1].trim())), true); list.add(imgattr); } savePath = sizeType + "/" + DateUtil.formatMonthDate(new Date()); } if (StringUtil.isNotNull(path)) { savePath = savePath + "/" + path; } savePath = "new_2016/" + savePath; String imgUrl = compressSave(bytes, savePath, suffix, list); String imgPath = "/" + savePath + "/" + imgUrl + "_size" + suffix; if (StringUtils.isBlank(imgUrl)) { output.put("status", "-1"); output.put("infoStr", "上传文件失败"); output.put("path", imgPath); output.put("imgPath", System.getProperty("image.web.server") + imgPath); } else { output.put("status", "0"); output.put("infoStr", "上传文件成功"); output.put("path", imgPath); output.put("imgPath", System.getProperty("image.web.server") + imgPath); } }catch (Exception e) { output.put("status", "1"); output.put("infoStr", "上传文件失败"); logger.error("UploadImageController-upload=》图片上传-ServiceException", e); } responseWrite(response, getJsonByObject(output)); } public String getDictByType(String type, String label) { try { Map<?, ?> genericResult = (Map) dictApiService.$invoke("getDictByParams", new String[] { "java.lang.String", "java.lang.String" }, new Object[] { type, label }); ResultDto resultDto = new ResultDto(); resultDto.setCode((String) genericResult.get("code")); resultDto.setMessage((String) genericResult.get("message")); if ((resultDto != null) && (resultDto.getCode().equals("0"))) { return (String) genericResult.get("data"); } } catch (Exception e) { logger.error("UploadImageController-getDictByType-Exception=》-获取图片类型-Exception", e); } return null; } public String compressSave(byte[] bytes, String path, String suffix, List<ImageAttribute> list) { String fileId = UUIDGenerator.getUUID(); Boolean result = Boolean.valueOf(false); for (ImageAttribute imgattr : list) { byte[] compressedImage = ImageUtil.resize(bytes, imgattr.getWidth(), imgattr.getHeight(), imgattr.isEqualRatio()); String nameSuffix =""; if(null==imgattr.getWidth()){ nameSuffix = "_origin"; }else{ nameSuffix = "_" + imgattr.getWidth() + "X" + imgattr.getHeight(); } String tmpname = fileId + nameSuffix + suffix; String targetFilePath = path; try { result = Boolean.valueOf(FTPUtil.ftpUpload(ftpUploadChannel, compressedImage, tmpname, targetFilePath)); if (!result.booleanValue()) { break; } } catch (Exception e) { logger.error("UploadImageController-compressSave=》图片上传-compressSave-ServiceException", e); result = Boolean.valueOf(false); break; } } if (result.booleanValue()) { return fileId; } return null; } }
UTF-8
Java
6,221
java
UplaodImageController.java
Java
[ { "context": "troller.UploadImageController;\n\n/**\n * \n * @author ying.cai\n * @date 2017年4月14日下午1:46:26\n * @email ying.cai@f", "end": 1318, "score": 0.9993535280227661, "start": 1310, "tag": "NAME", "value": "ying.cai" }, { "context": "or ying.cai\n * @date 2017年4月14日下午1:46:26\n * @email ying.cai@ffzxnet.com\n * @version V1.0\n */\n@Controller\n@RequestMapping(", "end": 1378, "score": 0.9999282956123352, "start": 1358, "tag": "EMAIL", "value": "ying.cai@ffzxnet.com" } ]
null
[]
/** * */ package com.ffzx.portal.utils; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.MessageChannel; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.alibaba.dubbo.remoting.ExecutionException; import com.alibaba.dubbo.rpc.service.GenericService; import com.ffzx.commerce.framework.controller.BaseController; import com.ffzx.commerce.framework.dto.ResultDto; import com.ffzx.commerce.framework.utils.DateUtil; import com.ffzx.commerce.framework.utils.FTPUtil; import com.ffzx.commerce.framework.utils.ImageAttribute; import com.ffzx.commerce.framework.utils.ImageUtil; import com.ffzx.commerce.framework.utils.StringUtil; import com.ffzx.commerce.framework.utils.UUIDGenerator; import com.ffzx.parentweb.controller.UploadImageController; /** * * @author ying.cai * @date 2017年4月14日下午1:46:26 * @email <EMAIL> * @version V1.0 */ @Controller @RequestMapping("/portal") public class UplaodImageController extends BaseController{ private static final Logger logger = LoggerFactory.getLogger(UploadImageController.class); @Autowired private MessageChannel ftpUploadChannel; private GenericService dictApiService; @RequestMapping(value={"upload"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) public void upload(@RequestParam("file") MultipartFile file, @RequestParam(value="fileName", required=false) String ordingName, @RequestParam(value="sizeType", required=false) String sizeType, String path, HttpServletResponse response) throws IOException, InterruptedException, ExecutionException{ Map<String, Object> output = new HashMap(); try{ byte[] bytes = file.getBytes(); String fileName = file.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".")); List<ImageAttribute> list = new ArrayList(); String savePath = DateUtil.formatMonthDate(new Date()); ImageAttribute imgattr = new ImageAttribute(null, null, true); list.add(new ImageAttribute(150, 150, true)); list.add(new ImageAttribute(499, 334, true)); list.add(new ImageAttribute(1000, 700, true)); list.add(new ImageAttribute(1180, 840, true)); list.add(imgattr); String imgType = null; if(null!=sizeType){ imgType = getDictByType("sys_img_type", sizeType); } if ((StringUtil.isNotNull(imgType)) && (!imgType.equals("-1"))){ String[] sizeList = imgType.split(";"); for (String string : sizeList) { String[] itemSize = string.split("X"); imgattr = new ImageAttribute(Integer.valueOf(Integer.parseInt(itemSize[0].trim())), Integer.valueOf(Integer.parseInt(itemSize[1].trim())), true); list.add(imgattr); } savePath = sizeType + "/" + DateUtil.formatMonthDate(new Date()); } if (StringUtil.isNotNull(path)) { savePath = savePath + "/" + path; } savePath = "new_2016/" + savePath; String imgUrl = compressSave(bytes, savePath, suffix, list); String imgPath = "/" + savePath + "/" + imgUrl + "_size" + suffix; if (StringUtils.isBlank(imgUrl)) { output.put("status", "-1"); output.put("infoStr", "上传文件失败"); output.put("path", imgPath); output.put("imgPath", System.getProperty("image.web.server") + imgPath); } else { output.put("status", "0"); output.put("infoStr", "上传文件成功"); output.put("path", imgPath); output.put("imgPath", System.getProperty("image.web.server") + imgPath); } }catch (Exception e) { output.put("status", "1"); output.put("infoStr", "上传文件失败"); logger.error("UploadImageController-upload=》图片上传-ServiceException", e); } responseWrite(response, getJsonByObject(output)); } public String getDictByType(String type, String label) { try { Map<?, ?> genericResult = (Map) dictApiService.$invoke("getDictByParams", new String[] { "java.lang.String", "java.lang.String" }, new Object[] { type, label }); ResultDto resultDto = new ResultDto(); resultDto.setCode((String) genericResult.get("code")); resultDto.setMessage((String) genericResult.get("message")); if ((resultDto != null) && (resultDto.getCode().equals("0"))) { return (String) genericResult.get("data"); } } catch (Exception e) { logger.error("UploadImageController-getDictByType-Exception=》-获取图片类型-Exception", e); } return null; } public String compressSave(byte[] bytes, String path, String suffix, List<ImageAttribute> list) { String fileId = UUIDGenerator.getUUID(); Boolean result = Boolean.valueOf(false); for (ImageAttribute imgattr : list) { byte[] compressedImage = ImageUtil.resize(bytes, imgattr.getWidth(), imgattr.getHeight(), imgattr.isEqualRatio()); String nameSuffix =""; if(null==imgattr.getWidth()){ nameSuffix = "_origin"; }else{ nameSuffix = "_" + imgattr.getWidth() + "X" + imgattr.getHeight(); } String tmpname = fileId + nameSuffix + suffix; String targetFilePath = path; try { result = Boolean.valueOf(FTPUtil.ftpUpload(ftpUploadChannel, compressedImage, tmpname, targetFilePath)); if (!result.booleanValue()) { break; } } catch (Exception e) { logger.error("UploadImageController-compressSave=》图片上传-compressSave-ServiceException", e); result = Boolean.valueOf(false); break; } } if (result.booleanValue()) { return fileId; } return null; } }
6,208
0.684091
0.675297
163
36.674847
32.376976
236
false
false
0
0
0
0
0
0
2.337423
false
false
7
d18a78baf5ef0574471d5c0a18943117ed33d772
18,983,755,456,381
504da556b9d459a2ac036ed704526b65a4f93b86
/hcm.ws.client/src/main/java/com/oracle/xmlns/apps/hcm/employment/core/workerservicev2/PersonCitizenship.java
c03928c643d4229c67199d2a6966ecbcf3017f89
[]
no_license
CITCLOUDCR/PMCRCL
https://github.com/CITCLOUDCR/PMCRCL
e28c2c924f8e230d1dd64a5a68749f6784b3506b
c334f1491b4892321c382329101c940756cc9bc9
refs/heads/master
2021-07-18T04:58:20.470000
2019-01-15T18:35:56
2019-01-15T18:35:56
148,048,567
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oracle.xmlns.apps.hcm.employment.core.workerservicev2; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; import com.oracle.xmlns.apps.hcm.people.core.flex.citizenshipsdff.CitizenshipDFF; /** * <p>Java class for PersonCitizenship complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PersonCitizenship"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CitizenshipId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="PersonId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="PersonNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="DateFrom" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/> * &lt;element name="DateTo" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/> * &lt;element name="LegislationCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CitizenshipStatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ObjectVersionNumber" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="SourceSystemOwner" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="SourceSystemId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="GUID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CitizenshipDFF" type="{http://xmlns.oracle.com/apps/hcm/people/core/flex/citizenshipsDFF/}CitizenshipDFF" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PersonCitizenship", propOrder = { "citizenshipId", "personId", "personNumber", "dateFrom", "dateTo", "legislationCode", "citizenshipStatus", "objectVersionNumber", "sourceSystemOwner", "sourceSystemId", "guid", "citizenshipDFF" }) public class PersonCitizenship { @XmlElement(name = "CitizenshipId") protected Long citizenshipId; @XmlElement(name = "PersonId") protected Long personId; @XmlElementRef(name = "PersonNumber", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<String> personNumber; @XmlElementRef(name = "DateFrom", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<XMLGregorianCalendar> dateFrom; @XmlElementRef(name = "DateTo", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<XMLGregorianCalendar> dateTo; @XmlElement(name = "LegislationCode") protected String legislationCode; @XmlElement(name = "CitizenshipStatus") protected String citizenshipStatus; @XmlElement(name = "ObjectVersionNumber") protected Integer objectVersionNumber; @XmlElementRef(name = "SourceSystemOwner", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<String> sourceSystemOwner; @XmlElementRef(name = "SourceSystemId", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<String> sourceSystemId; @XmlElementRef(name = "GUID", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<String> guid; @XmlElement(name = "CitizenshipDFF") protected CitizenshipDFF citizenshipDFF; /** * Gets the value of the citizenshipId property. * * @return * possible object is * {@link Long } * */ public Long getCitizenshipId() { return citizenshipId; } /** * Sets the value of the citizenshipId property. * * @param value * allowed object is * {@link Long } * */ public void setCitizenshipId(Long value) { this.citizenshipId = value; } /** * Gets the value of the personId property. * * @return * possible object is * {@link Long } * */ public Long getPersonId() { return personId; } /** * Sets the value of the personId property. * * @param value * allowed object is * {@link Long } * */ public void setPersonId(Long value) { this.personId = value; } /** * Gets the value of the personNumber property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getPersonNumber() { return personNumber; } /** * Sets the value of the personNumber property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setPersonNumber(JAXBElement<String> value) { this.personNumber = ((JAXBElement<String> ) value); } /** * Gets the value of the dateFrom property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public JAXBElement<XMLGregorianCalendar> getDateFrom() { return dateFrom; } /** * Sets the value of the dateFrom property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public void setDateFrom(JAXBElement<XMLGregorianCalendar> value) { this.dateFrom = ((JAXBElement<XMLGregorianCalendar> ) value); } /** * Gets the value of the dateTo property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public JAXBElement<XMLGregorianCalendar> getDateTo() { return dateTo; } /** * Sets the value of the dateTo property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public void setDateTo(JAXBElement<XMLGregorianCalendar> value) { this.dateTo = ((JAXBElement<XMLGregorianCalendar> ) value); } /** * Gets the value of the legislationCode property. * * @return * possible object is * {@link String } * */ public String getLegislationCode() { return legislationCode; } /** * Sets the value of the legislationCode property. * * @param value * allowed object is * {@link String } * */ public void setLegislationCode(String value) { this.legislationCode = value; } /** * Gets the value of the citizenshipStatus property. * * @return * possible object is * {@link String } * */ public String getCitizenshipStatus() { return citizenshipStatus; } /** * Sets the value of the citizenshipStatus property. * * @param value * allowed object is * {@link String } * */ public void setCitizenshipStatus(String value) { this.citizenshipStatus = value; } /** * Gets the value of the objectVersionNumber property. * * @return * possible object is * {@link Integer } * */ public Integer getObjectVersionNumber() { return objectVersionNumber; } /** * Sets the value of the objectVersionNumber property. * * @param value * allowed object is * {@link Integer } * */ public void setObjectVersionNumber(Integer value) { this.objectVersionNumber = value; } /** * Gets the value of the sourceSystemOwner property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getSourceSystemOwner() { return sourceSystemOwner; } /** * Sets the value of the sourceSystemOwner property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setSourceSystemOwner(JAXBElement<String> value) { this.sourceSystemOwner = ((JAXBElement<String> ) value); } /** * Gets the value of the sourceSystemId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getSourceSystemId() { return sourceSystemId; } /** * Sets the value of the sourceSystemId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setSourceSystemId(JAXBElement<String> value) { this.sourceSystemId = ((JAXBElement<String> ) value); } /** * Gets the value of the guid property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getGUID() { return guid; } /** * Sets the value of the guid property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setGUID(JAXBElement<String> value) { this.guid = ((JAXBElement<String> ) value); } /** * Gets the value of the citizenshipDFF property. * * @return * possible object is * {@link CitizenshipDFF } * */ public CitizenshipDFF getCitizenshipDFF() { return citizenshipDFF; } /** * Sets the value of the citizenshipDFF property. * * @param value * allowed object is * {@link CitizenshipDFF } * */ public void setCitizenshipDFF(CitizenshipDFF value) { this.citizenshipDFF = value; } }
UTF-8
Java
11,095
java
PersonCitizenship.java
Java
[]
null
[]
package com.oracle.xmlns.apps.hcm.employment.core.workerservicev2; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; import com.oracle.xmlns.apps.hcm.people.core.flex.citizenshipsdff.CitizenshipDFF; /** * <p>Java class for PersonCitizenship complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PersonCitizenship"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CitizenshipId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="PersonId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="PersonNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="DateFrom" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/> * &lt;element name="DateTo" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/> * &lt;element name="LegislationCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CitizenshipStatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ObjectVersionNumber" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="SourceSystemOwner" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="SourceSystemId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="GUID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CitizenshipDFF" type="{http://xmlns.oracle.com/apps/hcm/people/core/flex/citizenshipsDFF/}CitizenshipDFF" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PersonCitizenship", propOrder = { "citizenshipId", "personId", "personNumber", "dateFrom", "dateTo", "legislationCode", "citizenshipStatus", "objectVersionNumber", "sourceSystemOwner", "sourceSystemId", "guid", "citizenshipDFF" }) public class PersonCitizenship { @XmlElement(name = "CitizenshipId") protected Long citizenshipId; @XmlElement(name = "PersonId") protected Long personId; @XmlElementRef(name = "PersonNumber", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<String> personNumber; @XmlElementRef(name = "DateFrom", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<XMLGregorianCalendar> dateFrom; @XmlElementRef(name = "DateTo", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<XMLGregorianCalendar> dateTo; @XmlElement(name = "LegislationCode") protected String legislationCode; @XmlElement(name = "CitizenshipStatus") protected String citizenshipStatus; @XmlElement(name = "ObjectVersionNumber") protected Integer objectVersionNumber; @XmlElementRef(name = "SourceSystemOwner", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<String> sourceSystemOwner; @XmlElementRef(name = "SourceSystemId", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<String> sourceSystemId; @XmlElementRef(name = "GUID", namespace = "http://xmlns.oracle.com/apps/hcm/employment/core/workerServiceV2/", type = JAXBElement.class) protected JAXBElement<String> guid; @XmlElement(name = "CitizenshipDFF") protected CitizenshipDFF citizenshipDFF; /** * Gets the value of the citizenshipId property. * * @return * possible object is * {@link Long } * */ public Long getCitizenshipId() { return citizenshipId; } /** * Sets the value of the citizenshipId property. * * @param value * allowed object is * {@link Long } * */ public void setCitizenshipId(Long value) { this.citizenshipId = value; } /** * Gets the value of the personId property. * * @return * possible object is * {@link Long } * */ public Long getPersonId() { return personId; } /** * Sets the value of the personId property. * * @param value * allowed object is * {@link Long } * */ public void setPersonId(Long value) { this.personId = value; } /** * Gets the value of the personNumber property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getPersonNumber() { return personNumber; } /** * Sets the value of the personNumber property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setPersonNumber(JAXBElement<String> value) { this.personNumber = ((JAXBElement<String> ) value); } /** * Gets the value of the dateFrom property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public JAXBElement<XMLGregorianCalendar> getDateFrom() { return dateFrom; } /** * Sets the value of the dateFrom property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public void setDateFrom(JAXBElement<XMLGregorianCalendar> value) { this.dateFrom = ((JAXBElement<XMLGregorianCalendar> ) value); } /** * Gets the value of the dateTo property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public JAXBElement<XMLGregorianCalendar> getDateTo() { return dateTo; } /** * Sets the value of the dateTo property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public void setDateTo(JAXBElement<XMLGregorianCalendar> value) { this.dateTo = ((JAXBElement<XMLGregorianCalendar> ) value); } /** * Gets the value of the legislationCode property. * * @return * possible object is * {@link String } * */ public String getLegislationCode() { return legislationCode; } /** * Sets the value of the legislationCode property. * * @param value * allowed object is * {@link String } * */ public void setLegislationCode(String value) { this.legislationCode = value; } /** * Gets the value of the citizenshipStatus property. * * @return * possible object is * {@link String } * */ public String getCitizenshipStatus() { return citizenshipStatus; } /** * Sets the value of the citizenshipStatus property. * * @param value * allowed object is * {@link String } * */ public void setCitizenshipStatus(String value) { this.citizenshipStatus = value; } /** * Gets the value of the objectVersionNumber property. * * @return * possible object is * {@link Integer } * */ public Integer getObjectVersionNumber() { return objectVersionNumber; } /** * Sets the value of the objectVersionNumber property. * * @param value * allowed object is * {@link Integer } * */ public void setObjectVersionNumber(Integer value) { this.objectVersionNumber = value; } /** * Gets the value of the sourceSystemOwner property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getSourceSystemOwner() { return sourceSystemOwner; } /** * Sets the value of the sourceSystemOwner property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setSourceSystemOwner(JAXBElement<String> value) { this.sourceSystemOwner = ((JAXBElement<String> ) value); } /** * Gets the value of the sourceSystemId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getSourceSystemId() { return sourceSystemId; } /** * Sets the value of the sourceSystemId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setSourceSystemId(JAXBElement<String> value) { this.sourceSystemId = ((JAXBElement<String> ) value); } /** * Gets the value of the guid property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getGUID() { return guid; } /** * Sets the value of the guid property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setGUID(JAXBElement<String> value) { this.guid = ((JAXBElement<String> ) value); } /** * Gets the value of the citizenshipDFF property. * * @return * possible object is * {@link CitizenshipDFF } * */ public CitizenshipDFF getCitizenshipDFF() { return citizenshipDFF; } /** * Sets the value of the citizenshipDFF property. * * @param value * allowed object is * {@link CitizenshipDFF } * */ public void setCitizenshipDFF(CitizenshipDFF value) { this.citizenshipDFF = value; } }
11,095
0.601442
0.595223
373
28.742628
29.67705
153
false
false
0
0
0
0
0
0
0.238606
false
false
7
f3a8492bdbedd4a5b500478076b488fdc38d5ab3
16,432,544,939,763
dcbdfe7b60b599b7c1b061b2e5e1ec4b6605c3a6
/src/main/java/com/jxlg/haoqi/wechatreader/service/IUserService.java
cd9e0dbd9a223e2f88fcd6e8d5ceca08467df818
[]
no_license
Jcateye/wechatreader
https://github.com/Jcateye/wechatreader
b5982e0ef36827eb8ab2ed1418b152404484a174
03dc6f30f65a74d71caccce1526f243d169bb75f
refs/heads/master
2020-03-10T20:34:46.115000
2018-06-16T01:37:08
2018-06-16T01:37:08
129,573,587
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jxlg.haoqi.wechatreader.service; public interface IUserService { }
UTF-8
Java
80
java
IUserService.java
Java
[]
null
[]
package com.jxlg.haoqi.wechatreader.service; public interface IUserService { }
80
0.8125
0.8125
4
19
19.065676
44
false
false
0
0
0
0
0
0
0.25
false
false
7
7de4c8108e67a0e4de266d0d6f917370cd31d598
22,840,636,080,200
29b17061fca56e2ba31721d1772be6c0cd012d72
/ECommerceWebApp/src/java/br/mackenzie/fci/ec/lp2/action/ProdutoAction.java
3cf65eb50248b615efb55e051732db79e1ecb3f6
[]
no_license
victoroka/ECommerce-WebApp
https://github.com/victoroka/ECommerce-WebApp
d57dbee92a406d62ee34016f52ce4337621a99fa
630f82178d85b396044d6f05a17cff78d3e8f3c1
refs/heads/master
2021-06-01T18:17:26.326000
2016-05-31T00:44:08
2016-05-31T00:44:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.mackenzie.fci.ec.lp2.action; import com.br.lp2.model.dao.ProdutoDAO; import com.lp2.model.javabeans.Produto; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author VictorOka */ public class ProdutoAction extends ActionSupport { public String novoProduto() { return "WEB-INF/jsp/produto/cadastrarProduto.jsp"; } public String cadastrar() { String nomeProduto = this.getRequest().getParameter("nomeProduto"); double preco = Double.parseDouble(this.getRequest().getParameter("preco")); long codigo = Long.parseLong(this.getRequest().getParameter("codigo")); String descricao = this.getRequest().getParameter("descricao"); // String imagem = this.getRequest().getParameter("imagem"); int quantidade = Integer.parseInt(this.getRequest().getParameter("quantidade")); Produto produto = new Produto(); produto.setProductName(nomeProduto); produto.setPrice(preco); produto.setProductCode(codigo); produto.setDescricao(descricao); // produto.setImagem(imagem); produto.setQuantidade(quantidade); try { new ProdutoDAO().create(produto); this.getRequest().setAttribute("produtos", new ProdutoDAO().read()); } catch (Exception ex) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, ex); } return "WEB-INF/jsp/produto/listar.jsp"; } public String listar() { try { this.getRequest().setAttribute("produtos", new ProdutoDAO().read()); } catch (Exception e) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, e); } return "WEB-INF/jsp/produto/listar.jsp"; } public String alterar() { try { Produto produto = new Produto(); produto.setId_produto(Long.parseLong(this.getRequest().getParameter("code"))); ProdutoDAO produtoDAO = new ProdutoDAO(); this.getRequest().setAttribute("produto", produtoDAO.readById(produto.getId_produto())); } catch (Exception ex) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, ex); } return "WEB-INF/jsp/produto/alterar.jsp"; } public String confirmarAlteracao() { try { Produto produto = new Produto(); produto.setId_produto(Long.parseLong(this.getRequest().getParameter("codigo"))); produto.setProductName(this.getRequest().getParameter("nome")); produto.setProductCode(Long.parseLong(this.getRequest().getParameter("codigoProduto"))); produto.setPrice(Double.parseDouble(this.getRequest().getParameter("preco"))); produto.setDescricao(this.getRequest().getParameter("descricao")); produto.setImagem("urlImagem"); produto.setQuantidade(Integer.parseInt(this.getRequest().getParameter("quantidade"))); ProdutoDAO produtoDAO = new ProdutoDAO(); produtoDAO.update(produto); } catch (Exception ex) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, ex); } return this.listar(); } public String remover() { try { Produto produto = new Produto(); produto.setId_produto(Long.parseLong(this.getRequest().getParameter("code"))); ProdutoDAO produtoDAO = new ProdutoDAO(); this.getRequest().setAttribute("produto", produtoDAO.readById(produto.getId_produto())); } catch (Exception ex) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, ex); } return "WEB-INF/jsp/produto/remover.jsp"; } public String confirmarRemocao() { try { new ProdutoDAO().deleteById(Integer.parseInt(this.getRequest().getParameter("code"))); } catch (Exception ex) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, ex); } return this.listar(); } public String comprar() { try { this.getRequest().setAttribute("produtos", new ProdutoDAO().read()); } catch (Exception e) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, e); } return "shop.jsp"; } }
UTF-8
Java
4,625
java
ProdutoAction.java
Java
[ { "context": "mport java.util.logging.Logger;\n\n/**\n *\n * @author VictorOka\n */\npublic class ProdutoAction extends ActionSupp", "end": 399, "score": 0.9987200498580933, "start": 390, "tag": "NAME", "value": "VictorOka" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.mackenzie.fci.ec.lp2.action; import com.br.lp2.model.dao.ProdutoDAO; import com.lp2.model.javabeans.Produto; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author VictorOka */ public class ProdutoAction extends ActionSupport { public String novoProduto() { return "WEB-INF/jsp/produto/cadastrarProduto.jsp"; } public String cadastrar() { String nomeProduto = this.getRequest().getParameter("nomeProduto"); double preco = Double.parseDouble(this.getRequest().getParameter("preco")); long codigo = Long.parseLong(this.getRequest().getParameter("codigo")); String descricao = this.getRequest().getParameter("descricao"); // String imagem = this.getRequest().getParameter("imagem"); int quantidade = Integer.parseInt(this.getRequest().getParameter("quantidade")); Produto produto = new Produto(); produto.setProductName(nomeProduto); produto.setPrice(preco); produto.setProductCode(codigo); produto.setDescricao(descricao); // produto.setImagem(imagem); produto.setQuantidade(quantidade); try { new ProdutoDAO().create(produto); this.getRequest().setAttribute("produtos", new ProdutoDAO().read()); } catch (Exception ex) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, ex); } return "WEB-INF/jsp/produto/listar.jsp"; } public String listar() { try { this.getRequest().setAttribute("produtos", new ProdutoDAO().read()); } catch (Exception e) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, e); } return "WEB-INF/jsp/produto/listar.jsp"; } public String alterar() { try { Produto produto = new Produto(); produto.setId_produto(Long.parseLong(this.getRequest().getParameter("code"))); ProdutoDAO produtoDAO = new ProdutoDAO(); this.getRequest().setAttribute("produto", produtoDAO.readById(produto.getId_produto())); } catch (Exception ex) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, ex); } return "WEB-INF/jsp/produto/alterar.jsp"; } public String confirmarAlteracao() { try { Produto produto = new Produto(); produto.setId_produto(Long.parseLong(this.getRequest().getParameter("codigo"))); produto.setProductName(this.getRequest().getParameter("nome")); produto.setProductCode(Long.parseLong(this.getRequest().getParameter("codigoProduto"))); produto.setPrice(Double.parseDouble(this.getRequest().getParameter("preco"))); produto.setDescricao(this.getRequest().getParameter("descricao")); produto.setImagem("urlImagem"); produto.setQuantidade(Integer.parseInt(this.getRequest().getParameter("quantidade"))); ProdutoDAO produtoDAO = new ProdutoDAO(); produtoDAO.update(produto); } catch (Exception ex) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, ex); } return this.listar(); } public String remover() { try { Produto produto = new Produto(); produto.setId_produto(Long.parseLong(this.getRequest().getParameter("code"))); ProdutoDAO produtoDAO = new ProdutoDAO(); this.getRequest().setAttribute("produto", produtoDAO.readById(produto.getId_produto())); } catch (Exception ex) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, ex); } return "WEB-INF/jsp/produto/remover.jsp"; } public String confirmarRemocao() { try { new ProdutoDAO().deleteById(Integer.parseInt(this.getRequest().getParameter("code"))); } catch (Exception ex) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, ex); } return this.listar(); } public String comprar() { try { this.getRequest().setAttribute("produtos", new ProdutoDAO().read()); } catch (Exception e) { Logger.getLogger(ProdutoAction.class.getName()).log(Level.SEVERE, null, e); } return "shop.jsp"; } }
4,625
0.626811
0.626162
116
38.870689
30.809071
100
false
false
0
0
0
0
0
0
0.672414
false
false
7
895c8988b67431d4bdeb13e9102b9ca2f2838662
26,645,977,123,071
7bea7fb60b5f60f89f546a12b43ca239e39255b5
/src/org/xml/sax/SAXException.java
92b94084f539f6c1ab35586b5d2e5ce97d537e0b
[]
no_license
sorakeet/fitcorejdk
https://github.com/sorakeet/fitcorejdk
67623ab26f1defb072ab473f195795262a8ddcdd
f946930a826ddcd688b2ddbb5bc907d2fc4174c3
refs/heads/master
2021-01-01T05:52:19.696000
2017-07-15T01:33:41
2017-07-15T01:33:41
97,292,673
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ // SAX exception class. // http://www.saxproject.org // No warranty; no copyright -- use this as you will. // $Id: SAXException.java,v 1.3 2004/11/03 22:55:32 jsuttor Exp $ package org.xml.sax; public class SAXException extends Exception{ // Added serialVersionUID to preserve binary compatibility static final long serialVersionUID=583241635256073760L; ////////////////////////////////////////////////////////////////////// // Internal state. ////////////////////////////////////////////////////////////////////// private Exception exception; public SAXException(){ super(); this.exception=null; } public SAXException(String message){ super(message); this.exception=null; } public SAXException(Exception e){ super(); this.exception=e; } public SAXException(String message,Exception e){ super(message); this.exception=e; } public String getMessage(){ String message=super.getMessage(); if(message==null&&exception!=null){ return exception.getMessage(); }else{ return message; } } public Throwable getCause(){ return exception; } public String toString(){ if(exception!=null){ return super.toString()+"\n"+exception.toString(); }else{ return super.toString(); } } public Exception getException(){ return exception; } } // end of SAXException.java
UTF-8
Java
1,684
java
SAXException.java
Java
[ { "context": "/ $Id: SAXException.java,v 1.3 2004/11/03 22:55:32 jsuttor Exp $\npackage org.xml.sax;\n\npublic class SAXExcep", "end": 323, "score": 0.9673795700073242, "start": 316, "tag": "USERNAME", "value": "jsuttor" } ]
null
[]
/** * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ // SAX exception class. // http://www.saxproject.org // No warranty; no copyright -- use this as you will. // $Id: SAXException.java,v 1.3 2004/11/03 22:55:32 jsuttor Exp $ package org.xml.sax; public class SAXException extends Exception{ // Added serialVersionUID to preserve binary compatibility static final long serialVersionUID=583241635256073760L; ////////////////////////////////////////////////////////////////////// // Internal state. ////////////////////////////////////////////////////////////////////// private Exception exception; public SAXException(){ super(); this.exception=null; } public SAXException(String message){ super(message); this.exception=null; } public SAXException(Exception e){ super(); this.exception=e; } public SAXException(String message,Exception e){ super(message); this.exception=e; } public String getMessage(){ String message=super.getMessage(); if(message==null&&exception!=null){ return exception.getMessage(); }else{ return message; } } public Throwable getCause(){ return exception; } public String toString(){ if(exception!=null){ return super.toString()+"\n"+exception.toString(); }else{ return super.toString(); } } public Exception getException(){ return exception; } } // end of SAXException.java
1,684
0.566508
0.541568
64
25.3125
21.638994
79
false
false
0
0
0
0
71
0.084323
0.359375
false
false
7
e15e42e4ebc8f9e436a4acc3fb0a781fbba4e5d3
23,579,370,459,732
84125a032c2b2e150f62616c15f0089016aca05d
/src/com/prep2020/medium/Problem544.java
e839cc2019061b8af84f088d9da05f6e12740d76
[]
no_license
achowdhury80/leetcode
https://github.com/achowdhury80/leetcode
c577acc1bc8bce3da0c99e12d6d447c74fbed5c3
5ec97794cc5617cd7f35bafb058ada502ee7d802
refs/heads/master
2023-02-06T01:08:49.888000
2023-01-22T03:23:37
2023-01-22T03:23:37
115,574,715
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.prep2020.medium; import java.util.*; public class Problem544 { /** * O(NlogN) time and O(N) space * @param n * @return */ public String findContestMatch(int n) { List<String> list = new ArrayList<>(); for (int i = 1; i <= n; i++) list.add("" + i); while(list.size() > 1) { List<String> temp = new ArrayList<>(); int i = 0, j = list.size() - 1; while(i < j) { temp.add("(" + list.get(i) + "," + list.get(j) + ")"); i++; j--; } list = temp; } return list.get(0); } }
UTF-8
Java
606
java
Problem544.java
Java
[]
null
[]
package com.prep2020.medium; import java.util.*; public class Problem544 { /** * O(NlogN) time and O(N) space * @param n * @return */ public String findContestMatch(int n) { List<String> list = new ArrayList<>(); for (int i = 1; i <= n; i++) list.add("" + i); while(list.size() > 1) { List<String> temp = new ArrayList<>(); int i = 0, j = list.size() - 1; while(i < j) { temp.add("(" + list.get(i) + "," + list.get(j) + ")"); i++; j--; } list = temp; } return list.get(0); } }
606
0.457096
0.437294
24
24.25
16.877623
64
false
false
0
0
0
0
0
0
1.333333
false
false
7
4c26cf58742bafc47a97e06d8bf5c656d75293ac
5,506,148,093,466
b4e9e4e75cbff8d8332b448753b822cd0aec17d5
/br.com.minegames.gamemanager.test/src/com/thecraftcloud/test/LoadGameConfigTest.java
0818f6e46ca9503e2295edb6ae18d18774ee6ac7
[]
no_license
minegames-br/gm
https://github.com/minegames-br/gm
6cc6be4ed22415a127fb8662ab8c28cbd16e4121
4586ad8533de081849b86d44e7aea3282179fa55
refs/heads/master
2021-01-12T16:33:00.415000
2016-12-31T14:29:12
2016-12-31T14:29:12
71,399,292
0
0
null
false
2016-12-10T16:22:57
2016-10-19T21:06:57
2016-10-19T23:34:17
2016-12-10T16:22:57
58,134
0
0
0
Java
null
null
package com.thecraftcloud.test; import org.junit.Test; import com.thecraftcloud.client.exception.InvalidRegistrationException; import com.thecraftcloud.client.test.TheCraftCloudJUnitTest; import com.thecraftcloud.core.domain.Arena; import com.thecraftcloud.core.domain.Game; public class LoadGameConfigTest extends TheCraftCloudJUnitTest { @Test public void test() throws InvalidRegistrationException { Game game = delegate.findGame("e2f4757e-d7bc-43fc-a4e7-4b07ad646f1e"); Arena arena = delegate.findArena("4a84d366-9f64-4631-aecf-fc57fec48b6b"); } }
UTF-8
Java
598
java
LoadGameConfigTest.java
Java
[]
null
[]
package com.thecraftcloud.test; import org.junit.Test; import com.thecraftcloud.client.exception.InvalidRegistrationException; import com.thecraftcloud.client.test.TheCraftCloudJUnitTest; import com.thecraftcloud.core.domain.Arena; import com.thecraftcloud.core.domain.Game; public class LoadGameConfigTest extends TheCraftCloudJUnitTest { @Test public void test() throws InvalidRegistrationException { Game game = delegate.findGame("e2f4757e-d7bc-43fc-a4e7-4b07ad646f1e"); Arena arena = delegate.findArena("4a84d366-9f64-4631-aecf-fc57fec48b6b"); } }
598
0.772575
0.714047
22
25.181818
28.671551
75
false
false
0
0
0
0
0
0
1
false
false
7
5b8f7b6dabf7526d82cd63f3b87abffc5ed5b346
2,911,987,857,158
56845e936422bb966be7ce8161ae1b72a837676d
/src/tw/iii/model/TradingRecord.java
a7746f40d5b507efe7d10190d8beb228501f47c3
[]
no_license
ex5555555/Ani-life-
https://github.com/ex5555555/Ani-life-
839ac5dbec710cdd07181ed89578daab649991d1
a822d6011a0868751dad2c7ad3962417188a767f
refs/heads/master
2023-03-16T22:46:18.242000
2021-02-25T13:09:03
2021-02-25T13:09:03
342,239,950
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tw.iii.model; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Fetch; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Entity @Table(name="tradingrecord") @Component public class TradingRecord { @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name="date") private Date date; @Column(name="total") private int total; @Column(name="recipient") private String recipient; @Column(name="tel") private String tel; @Transient private String account; @Column(name="address") private String address; @Column(name="remarks") private String remarks; @Column(name="status") private String status; @Column(name="email") private String email; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="account") @Autowired private Member member; @OneToMany(fetch = FetchType.LAZY,mappedBy = "pk.tradingRecord",cascade = CascadeType.ALL) private Set<TradingDetail> tradingdetail = new HashSet<TradingDetail>(); public TradingRecord() { } public TradingRecord( Date date, int total, String account, String recipient, String tel, String address, String remarks,String email, Member member) { super(); this.date = date; this.total = total; this.account = account; this.recipient = recipient; this.tel = tel; this.address = address; this.remarks = remarks; this.email=email; this.member = member; } public TradingRecord( Date date, int total, String account, String recipient, String tel, String address, String remarks, String status, Member member, Set<TradingDetail> tradingdetail) { super(); this.date = date; this.total = total; this.account = account; this.recipient = recipient; this.tel = tel; this.address = address; this.remarks = remarks; this.status = status; this.member = member; this.tradingdetail = tradingdetail; } public int getid() { return id; } public void setid(int id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } public Set<TradingDetail> getTradingdetail() { return tradingdetail; } public void setTradingdetail(Set<TradingDetail> tradingdetail) { this.tradingdetail = tradingdetail; } public String getRecipient() { return recipient; } public void setRecipient(String recipient) { this.recipient = recipient; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
UTF-8
Java
3,899
java
TradingRecord.java
Java
[]
null
[]
package tw.iii.model; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Fetch; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Entity @Table(name="tradingrecord") @Component public class TradingRecord { @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name="date") private Date date; @Column(name="total") private int total; @Column(name="recipient") private String recipient; @Column(name="tel") private String tel; @Transient private String account; @Column(name="address") private String address; @Column(name="remarks") private String remarks; @Column(name="status") private String status; @Column(name="email") private String email; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="account") @Autowired private Member member; @OneToMany(fetch = FetchType.LAZY,mappedBy = "pk.tradingRecord",cascade = CascadeType.ALL) private Set<TradingDetail> tradingdetail = new HashSet<TradingDetail>(); public TradingRecord() { } public TradingRecord( Date date, int total, String account, String recipient, String tel, String address, String remarks,String email, Member member) { super(); this.date = date; this.total = total; this.account = account; this.recipient = recipient; this.tel = tel; this.address = address; this.remarks = remarks; this.email=email; this.member = member; } public TradingRecord( Date date, int total, String account, String recipient, String tel, String address, String remarks, String status, Member member, Set<TradingDetail> tradingdetail) { super(); this.date = date; this.total = total; this.account = account; this.recipient = recipient; this.tel = tel; this.address = address; this.remarks = remarks; this.status = status; this.member = member; this.tradingdetail = tradingdetail; } public int getid() { return id; } public void setid(int id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } public Set<TradingDetail> getTradingdetail() { return tradingdetail; } public void setTradingdetail(Set<TradingDetail> tradingdetail) { this.tradingdetail = tradingdetail; } public String getRecipient() { return recipient; } public void setRecipient(String recipient) { this.recipient = recipient; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
3,899
0.718902
0.718902
222
16.563063
18.68668
106
false
false
0
0
0
0
0
0
1.315315
false
false
7
9f1255236e44b879b0d6d7423c25407282567d18
13,580,686,611,086
b2938dfcfd93da3893b740477971690a1ce8aeaa
/initializr-docs/src/main/java/io/spring/initializr/doc/generator/project/SampleContributor.java
4695dfe813fde6952db9d8a940f6cd886a24bb2c
[ "Apache-2.0" ]
permissive
spring-io/initializr
https://github.com/spring-io/initializr
1056034f9bc68351917dff912a270c5c37aa919c
55888d5c6a2a935bca53267a510f1567d9f0230c
refs/heads/main
2023-09-02T15:13:14.433000
2023-08-25T08:52:48
2023-08-25T08:52:48
10,553,586
3,409
1,964
Apache-2.0
false
2023-09-14T19:36:24
2013-06-07T16:02:22
2023-09-14T11:04:55
2023-09-14T19:36:24
10,468
3,205
1,676
49
Java
false
false
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 io.spring.initializr.doc.generator.project; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import io.spring.initializr.generator.project.contributor.ProjectContributor; /** * A sample {@link ProjectContributor} that creates a {@code hello.txt} at the root of the * project directory with content {@code Test}. * * @author Stephane Nicoll */ // tag::code[] public class SampleContributor implements ProjectContributor { @Override public void contribute(Path projectRoot) throws IOException { Path file = Files.createFile(projectRoot.resolve("hello.txt")); try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file))) { writer.println("Test"); } } } // end::code[]
UTF-8
Java
1,393
java
SampleContributor.java
Java
[ { "context": "directory with content {@code Test}.\n *\n * @author Stephane Nicoll\n */\n// tag::code[]\npublic class SampleContributor", "end": 1039, "score": 0.9998598694801331, "start": 1024, "tag": "NAME", "value": "Stephane Nicoll" } ]
null
[]
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 io.spring.initializr.doc.generator.project; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import io.spring.initializr.generator.project.contributor.ProjectContributor; /** * A sample {@link ProjectContributor} that creates a {@code hello.txt} at the root of the * project directory with content {@code Test}. * * @author <NAME> */ // tag::code[] public class SampleContributor implements ProjectContributor { @Override public void contribute(Path projectRoot) throws IOException { Path file = Files.createFile(projectRoot.resolve("hello.txt")); try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file))) { writer.println("Test"); } } } // end::code[]
1,384
0.74659
0.737976
44
30.65909
29.13678
90
false
false
0
0
0
0
0
0
0.568182
false
false
7
ffc13cec8b99d1d73f639d29909a974e1dffb606
31,610,959,331,751
a7980002d827561dab5b5550e615706f6e2bee25
/src/com/zwonb/Example1.java
ec313c2e39e095698c54dc9937647f2bb0257e77
[]
no_license
zwonb/java-16
https://github.com/zwonb/java-16
142fb0cec3b1ff32c410da22b2d27452b5189364
3a97439dabcb1440223492c5d183faace6bd7e93
refs/heads/master
2021-01-01T19:14:44.011000
2017-07-28T03:27:04
2017-07-28T03:27:04
98,550,033
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zwonb; /** * 访问构造方法 * Created by zwonb on 2017/7/13. */ public class Example1 { String s; int i1, i2, i3; private Example1() { } protected Example1(String s, int i1) { this.s = s; this.i1 = i1; } public Example1(String... strings) throws NumberFormatException { if (strings.length > 0) { i1 = Integer.parseInt(strings[0]); } if (strings.length > 1) { i2 = Integer.parseInt(strings[1]); } if (strings.length > 2) { i3 = Integer.parseInt(strings[2]); } } public void print(){ System.out.println("s="+s); System.out.println("i1=" + i1); System.out.println("i2=" + i2); System.out.println("i3=" + i3); } }
UTF-8
Java
807
java
Example1.java
Java
[ { "context": "package com.zwonb;\n\n/**\n * 访问构造方法\n * Created by zwonb on 2017/7/13.\n */\npublic class Example1 {\n\n St", "end": 53, "score": 0.9996146559715271, "start": 48, "tag": "USERNAME", "value": "zwonb" } ]
null
[]
package com.zwonb; /** * 访问构造方法 * Created by zwonb on 2017/7/13. */ public class Example1 { String s; int i1, i2, i3; private Example1() { } protected Example1(String s, int i1) { this.s = s; this.i1 = i1; } public Example1(String... strings) throws NumberFormatException { if (strings.length > 0) { i1 = Integer.parseInt(strings[0]); } if (strings.length > 1) { i2 = Integer.parseInt(strings[1]); } if (strings.length > 2) { i3 = Integer.parseInt(strings[2]); } } public void print(){ System.out.println("s="+s); System.out.println("i1=" + i1); System.out.println("i2=" + i2); System.out.println("i3=" + i3); } }
807
0.51195
0.471698
38
19.921053
17.559496
69
false
false
0
0
0
0
0
0
0.394737
false
false
7
a0e453eb649ed71813a52f9379cafcc1b6f8ea02
19,335,942,793,160
379d56c1e62aeb35ff3db06feeb8ea10c4ca7316
/server/src/main/java/rs/ac/uns/ftn/isa/pharmacy/pharma/domain/DrugReservation.java
03f92e976f9468d21d2a456821efc9cf3feab689
[]
no_license
nikolapantelic-ftn/internet-software-architecture
https://github.com/nikolapantelic-ftn/internet-software-architecture
17620636072251b51965481f27261ddba1e2ce97
689ba3e52db22c46c2d91f491da77f6cf63601b2
refs/heads/main
2023-04-09T11:06:11.637000
2021-03-30T22:13:29
2021-03-30T22:13:29
307,677,938
0
1
null
false
2021-02-12T18:16:18
2020-10-27T11:27:35
2021-02-12T14:35:15
2021-02-12T18:16:18
874
2
0
0
Java
false
false
package rs.ac.uns.ftn.isa.pharmacy.pharma.domain; import rs.ac.uns.ftn.isa.pharmacy.users.user.domain.Patient; import rs.ac.uns.ftn.isa.pharmacy.pharma.exceptions.DateException; import rs.ac.uns.ftn.isa.pharmacy.pharma.exceptions.QuantityException; import javax.persistence.*; import java.time.LocalDate; @Entity @Table(name = "drug_reservations") public class DrugReservation { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @ManyToOne private Patient patient; @ManyToOne private StoredDrug storedDrug; private LocalDate pickUpBefore; private boolean isDispensed; private int quantity; public long getId() { return id; } public void setId(long id) { this.id = id; } public Patient getPatient() { return patient; } public void setPatient(Patient patient) { this.patient = patient; } public StoredDrug getStoredDrug() { return storedDrug; } public void setStoredDrug(StoredDrug storedDrug) { this.storedDrug = storedDrug; } public LocalDate getPickUpBefore() { return pickUpBefore; } public void setPickUpBefore(LocalDate pickUpBefore) { if (pickUpBefore.isBefore(LocalDate.now())) { throw new DateException(); } this.pickUpBefore = pickUpBefore; } public int getQuantity() { if (quantity < 1) { throw new QuantityException(); } return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public boolean isInPast() { return this.pickUpBefore.isBefore(LocalDate.now()); } public boolean isInPast(int days) { return this.pickUpBefore.isBefore(LocalDate.now().plusDays(days)); } public boolean canBeDispensed(){ return !this.isInPast(1) || !this.isDispensed; } public boolean isDispensed() { return isDispensed; } public void setDispensed(boolean dispensed) { isDispensed = dispensed; } }
UTF-8
Java
2,088
java
DrugReservation.java
Java
[]
null
[]
package rs.ac.uns.ftn.isa.pharmacy.pharma.domain; import rs.ac.uns.ftn.isa.pharmacy.users.user.domain.Patient; import rs.ac.uns.ftn.isa.pharmacy.pharma.exceptions.DateException; import rs.ac.uns.ftn.isa.pharmacy.pharma.exceptions.QuantityException; import javax.persistence.*; import java.time.LocalDate; @Entity @Table(name = "drug_reservations") public class DrugReservation { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @ManyToOne private Patient patient; @ManyToOne private StoredDrug storedDrug; private LocalDate pickUpBefore; private boolean isDispensed; private int quantity; public long getId() { return id; } public void setId(long id) { this.id = id; } public Patient getPatient() { return patient; } public void setPatient(Patient patient) { this.patient = patient; } public StoredDrug getStoredDrug() { return storedDrug; } public void setStoredDrug(StoredDrug storedDrug) { this.storedDrug = storedDrug; } public LocalDate getPickUpBefore() { return pickUpBefore; } public void setPickUpBefore(LocalDate pickUpBefore) { if (pickUpBefore.isBefore(LocalDate.now())) { throw new DateException(); } this.pickUpBefore = pickUpBefore; } public int getQuantity() { if (quantity < 1) { throw new QuantityException(); } return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public boolean isInPast() { return this.pickUpBefore.isBefore(LocalDate.now()); } public boolean isInPast(int days) { return this.pickUpBefore.isBefore(LocalDate.now().plusDays(days)); } public boolean canBeDispensed(){ return !this.isInPast(1) || !this.isDispensed; } public boolean isDispensed() { return isDispensed; } public void setDispensed(boolean dispensed) { isDispensed = dispensed; } }
2,088
0.648946
0.647988
89
22.460674
20.014072
74
false
false
0
0
0
0
0
0
0.348315
false
false
7
c3cd813581b64b7afeab6c7dd9f35d49ba416307
31,748,398,283,231
a225aa4163a0fa503769ce1aaba5ebd966a9ceaa
/src/main/java/com/netflix/imflibrary/writerTools/utils/IMFUtils.java
0e2bbff0f102722160f6c63c292f4296337e7f51
[ "Apache-2.0", "BSD-2-Clause" ]
permissive
dkrodel/photon
https://github.com/dkrodel/photon
e539b941ab9bbf4d474f454d6225e66c8fa97689
a80f814d316a52609c3861866ccab22730376bd5
refs/heads/master
2021-01-14T09:45:54.088000
2017-02-10T22:43:46
2017-02-10T22:43:46
81,999,334
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools.utils; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import org.smpte_ra.schemas.st2067_2_2013.BaseResourceType; import org.smpte_ra.schemas.st2067_2_2013.CompositionPlaylistType; import org.xml.sax.SAXException; import javax.annotation.Nullable; import javax.xml.bind.JAXBException; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import java.util.GregorianCalendar; import java.util.TimeZone; /** * A class that provides utility methods to help with serializing an IMF CPL to an XML document */ public class IMFUtils { /** * Private constructor to prevent instantiation */ private IMFUtils(){ } /** * A utility method to create an XMLGregorianCalendar * @return the constructed XMLGregorianCalendar */ @Nullable public static XMLGregorianCalendar createXMLGregorianCalendar(){ XMLGregorianCalendar result = null; try { DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); TimeZone utc = TimeZone.getTimeZone("UTC"); GregorianCalendar now = new GregorianCalendar(utc); result = datatypeFactory.newXMLGregorianCalendar(now); } catch (DatatypeConfigurationException e){ throw new IMFException("Could not create a XMLGregorianCalendar instance"); } return result; } /** * A method that generates a CPL schema valid TimecodeStartAddress string * @return a string representing the time code start address compliant with its regex definition */ public static String generateTimecodeStartAddress(){ String delimiter = ":"; String timeCodeStartAddress = "00:00:00:00"; if(timeCodeStartAddress.matches("[0-2][0-9](:|/|;|,|\\.|\\+|\\-)[0-5][0-9](:|/|;|,|\\.|\\+|\\-)[0-5][0-9](:|/|;|,|\\.|\\+|\\-)[0-5][0-9]")){ return timeCodeStartAddress; } else{ throw new IMFException(String.format("Could not generate a valid TimecodeStartAddress based on input " + "received")); } } /** * A method that generates a SHA-1 hash of the file and Base64 encode the result. * * @param file - the file whose SHA-1 hash is to be generated * @return a byte[] representing the generated base64 encoded hash of the file * @throws IOException - any I/O related error will be exposed through an IOException */ public static byte[] generateSHA1HashAndBase64Encode(File file) throws IOException { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); FileInputStream fileInputStream = new FileInputStream(file); byte[] bytes = new byte[1024]; int bytesRead = 0; while((bytesRead = fileInputStream.read(bytes)) != -1){ messageDigest.update(bytes, 0, bytesRead); } byte[] digest = messageDigest.digest(); byte[] base64EncodedDigest = Base64.getEncoder().encodeToString(digest).getBytes("UTF-8"); fileInputStream.close(); return base64EncodedDigest; } catch (NoSuchAlgorithmException | FileNotFoundException e){ throw new IMFException(e); } } /** * A method to generate a Base64 encoded representation of a byte[] * @param bytes a byte[] that is to be Base64 encoded * @return a byte[] representing the Base64 encode of the input */ public static byte[] generateBase64Encode(byte[] bytes){ byte[] hashCopy = Arrays.copyOf(bytes, bytes.length); return Base64.getEncoder().encode(hashCopy); } /** * A method to generate a SHA-1 digest of the incoming resource * @param resourceByteRangeProvider representing the resource whose SHA-1 digest is to be generated * @return a byte[] representing the SHA-1 digest of the resource * @throws NoSuchAlgorithmException - if no Provider supports a MessageDigestSpi implementation for the * specified algorithm. * @throws IOException - any I/O related error will be exposed through an IOException */ public static byte[] generateSHA1Hash(ResourceByteRangeProvider resourceByteRangeProvider) throws NoSuchAlgorithmException, IOException { MessageDigest md = MessageDigest.getInstance("SHA1"); long rangeStart = 0; long rangeEnd = (rangeStart + 1023 > resourceByteRangeProvider.getResourceSize()-1) ? resourceByteRangeProvider.getResourceSize()-1 : rangeStart + 1023; int nread = 0; while (rangeStart < resourceByteRangeProvider.getResourceSize() && rangeEnd < resourceByteRangeProvider.getResourceSize()) { byte[] dataBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); nread = (int)(rangeEnd - rangeStart + 1); md.update(dataBytes, 0, nread); rangeStart = rangeEnd+1; rangeEnd = (rangeStart + 1023 > resourceByteRangeProvider.getResourceSize()-1) ? resourceByteRangeProvider.getResourceSize()-1 : rangeStart + 1023; }; byte[] mdbytes = md.digest(); return Arrays.copyOf(mdbytes, mdbytes.length); } /** * A method to cast the object that was passed in to the specified subclass safely * * @param <T> the type of BaseResource * @param baseResourceType - the object that needs to cast to the subclass of this type * @param cls the Class for the casted type * @return T casted type * @throws IMFException - a class cast failure is exposed through an IMFException */ public static <T extends BaseResourceType> T safeCast(BaseResourceType baseResourceType, Class<T> cls) throws IMFException { if(baseResourceType == null){ return null; } if(!cls.isAssignableFrom(baseResourceType.getClass())) { throw new IMFException(String.format("Unable to cast from Box type %s to %s", baseResourceType.getClass() .getName(), cls.getName())); } return cls.cast(baseResourceType); } /** * A utility method that writes out the serialized IMF CPL document to a file * * @param compositionPlaylistType an instance of the composition playlist type * @param outputFile the file that the serialized XML is written to * @throws IOException - any I/O related error will be exposed through an IOException */ public static void writeCPLToFile(CompositionPlaylistType compositionPlaylistType, File outputFile) throws IOException { try { IMFCPLSerializer imfcplSerializer = new IMFCPLSerializer(); FileOutputStream fileOutputStream = new FileOutputStream(outputFile); imfcplSerializer.write(compositionPlaylistType, fileOutputStream, true); fileOutputStream.close(); } catch (FileNotFoundException e){ throw new IMFException(String.format("Error occurred while trying to serialize the CompositionPlaylistType, file %s not found", outputFile.getName())); } catch(SAXException | JAXBException e ){ throw new IMFException(e); } } }
UTF-8
Java
8,479
java
IMFUtils.java
Java
[ { "context": "/*\n *\n * Copyright 2015 Netflix, Inc.\n *\n * Licensed under the Apache License,", "end": 31, "score": 0.8109539747238159, "start": 24, "tag": "NAME", "value": "Netflix" } ]
null
[]
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.imflibrary.writerTools.utils; import com.netflix.imflibrary.IMFErrorLoggerImpl; import com.netflix.imflibrary.exceptions.IMFException; import com.netflix.imflibrary.utils.ResourceByteRangeProvider; import org.smpte_ra.schemas.st2067_2_2013.BaseResourceType; import org.smpte_ra.schemas.st2067_2_2013.CompositionPlaylistType; import org.xml.sax.SAXException; import javax.annotation.Nullable; import javax.xml.bind.JAXBException; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import java.util.GregorianCalendar; import java.util.TimeZone; /** * A class that provides utility methods to help with serializing an IMF CPL to an XML document */ public class IMFUtils { /** * Private constructor to prevent instantiation */ private IMFUtils(){ } /** * A utility method to create an XMLGregorianCalendar * @return the constructed XMLGregorianCalendar */ @Nullable public static XMLGregorianCalendar createXMLGregorianCalendar(){ XMLGregorianCalendar result = null; try { DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); TimeZone utc = TimeZone.getTimeZone("UTC"); GregorianCalendar now = new GregorianCalendar(utc); result = datatypeFactory.newXMLGregorianCalendar(now); } catch (DatatypeConfigurationException e){ throw new IMFException("Could not create a XMLGregorianCalendar instance"); } return result; } /** * A method that generates a CPL schema valid TimecodeStartAddress string * @return a string representing the time code start address compliant with its regex definition */ public static String generateTimecodeStartAddress(){ String delimiter = ":"; String timeCodeStartAddress = "00:00:00:00"; if(timeCodeStartAddress.matches("[0-2][0-9](:|/|;|,|\\.|\\+|\\-)[0-5][0-9](:|/|;|,|\\.|\\+|\\-)[0-5][0-9](:|/|;|,|\\.|\\+|\\-)[0-5][0-9]")){ return timeCodeStartAddress; } else{ throw new IMFException(String.format("Could not generate a valid TimecodeStartAddress based on input " + "received")); } } /** * A method that generates a SHA-1 hash of the file and Base64 encode the result. * * @param file - the file whose SHA-1 hash is to be generated * @return a byte[] representing the generated base64 encoded hash of the file * @throws IOException - any I/O related error will be exposed through an IOException */ public static byte[] generateSHA1HashAndBase64Encode(File file) throws IOException { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); FileInputStream fileInputStream = new FileInputStream(file); byte[] bytes = new byte[1024]; int bytesRead = 0; while((bytesRead = fileInputStream.read(bytes)) != -1){ messageDigest.update(bytes, 0, bytesRead); } byte[] digest = messageDigest.digest(); byte[] base64EncodedDigest = Base64.getEncoder().encodeToString(digest).getBytes("UTF-8"); fileInputStream.close(); return base64EncodedDigest; } catch (NoSuchAlgorithmException | FileNotFoundException e){ throw new IMFException(e); } } /** * A method to generate a Base64 encoded representation of a byte[] * @param bytes a byte[] that is to be Base64 encoded * @return a byte[] representing the Base64 encode of the input */ public static byte[] generateBase64Encode(byte[] bytes){ byte[] hashCopy = Arrays.copyOf(bytes, bytes.length); return Base64.getEncoder().encode(hashCopy); } /** * A method to generate a SHA-1 digest of the incoming resource * @param resourceByteRangeProvider representing the resource whose SHA-1 digest is to be generated * @return a byte[] representing the SHA-1 digest of the resource * @throws NoSuchAlgorithmException - if no Provider supports a MessageDigestSpi implementation for the * specified algorithm. * @throws IOException - any I/O related error will be exposed through an IOException */ public static byte[] generateSHA1Hash(ResourceByteRangeProvider resourceByteRangeProvider) throws NoSuchAlgorithmException, IOException { MessageDigest md = MessageDigest.getInstance("SHA1"); long rangeStart = 0; long rangeEnd = (rangeStart + 1023 > resourceByteRangeProvider.getResourceSize()-1) ? resourceByteRangeProvider.getResourceSize()-1 : rangeStart + 1023; int nread = 0; while (rangeStart < resourceByteRangeProvider.getResourceSize() && rangeEnd < resourceByteRangeProvider.getResourceSize()) { byte[] dataBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd); nread = (int)(rangeEnd - rangeStart + 1); md.update(dataBytes, 0, nread); rangeStart = rangeEnd+1; rangeEnd = (rangeStart + 1023 > resourceByteRangeProvider.getResourceSize()-1) ? resourceByteRangeProvider.getResourceSize()-1 : rangeStart + 1023; }; byte[] mdbytes = md.digest(); return Arrays.copyOf(mdbytes, mdbytes.length); } /** * A method to cast the object that was passed in to the specified subclass safely * * @param <T> the type of BaseResource * @param baseResourceType - the object that needs to cast to the subclass of this type * @param cls the Class for the casted type * @return T casted type * @throws IMFException - a class cast failure is exposed through an IMFException */ public static <T extends BaseResourceType> T safeCast(BaseResourceType baseResourceType, Class<T> cls) throws IMFException { if(baseResourceType == null){ return null; } if(!cls.isAssignableFrom(baseResourceType.getClass())) { throw new IMFException(String.format("Unable to cast from Box type %s to %s", baseResourceType.getClass() .getName(), cls.getName())); } return cls.cast(baseResourceType); } /** * A utility method that writes out the serialized IMF CPL document to a file * * @param compositionPlaylistType an instance of the composition playlist type * @param outputFile the file that the serialized XML is written to * @throws IOException - any I/O related error will be exposed through an IOException */ public static void writeCPLToFile(CompositionPlaylistType compositionPlaylistType, File outputFile) throws IOException { try { IMFCPLSerializer imfcplSerializer = new IMFCPLSerializer(); FileOutputStream fileOutputStream = new FileOutputStream(outputFile); imfcplSerializer.write(compositionPlaylistType, fileOutputStream, true); fileOutputStream.close(); } catch (FileNotFoundException e){ throw new IMFException(String.format("Error occurred while trying to serialize the CompositionPlaylistType, file %s not found", outputFile.getName())); } catch(SAXException | JAXBException e ){ throw new IMFException(e); } } }
8,479
0.672131
0.65845
205
40.360977
34.678402
163
false
false
0
0
0
0
0
0
0.560976
false
false
7
86e45e0a73525bb6a348822378a407bc2839fd99
4,904,852,668,325
e12871eac495eb8dbc43c8e385e79bd64c63afa2
/app/src/main/java/com/example/triviatime/User.java
7166b39150cff48c531ad6a9cfe65c9b844ff915
[]
no_license
jamyang-tamang/TriviaTime-Android
https://github.com/jamyang-tamang/TriviaTime-Android
d935fa5902a24b395d39f25cc4c24477ed110d4b
a714d72b7d8da66937e9a82996b4cbe01ad61c2e
refs/heads/master
2023-04-30T00:51:34.501000
2021-05-13T04:57:41
2021-05-13T04:57:41
366,939,212
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.triviatime; // Unused class, was going to be used for storing highscore in firebase // and displaying them using a recycler view in the end screen public class User { private String name; private int score; public User(){ } public User(String name, int score){ this.name = name; this.score = score; } public String getName() { return name; } public int getScore() { return score; } }
UTF-8
Java
484
java
User.java
Java
[]
null
[]
package com.example.triviatime; // Unused class, was going to be used for storing highscore in firebase // and displaying them using a recycler view in the end screen public class User { private String name; private int score; public User(){ } public User(String name, int score){ this.name = name; this.score = score; } public String getName() { return name; } public int getScore() { return score; } }
484
0.619835
0.619835
26
17.615385
18.72283
71
false
false
0
0
0
0
0
0
0.346154
false
false
7
83065d21b06f86e49503dec97cc801eacac89dab
22,179,211,157,527
dba9c224d422abc20484e7a83aeec26b2184cf84
/Placement_JAVA/15_While_DoWhile/src/Main.java
4efee9350a9d4d2de2ae698ecd96b9b7d40ec6e5
[]
no_license
sourishjana/java-language
https://github.com/sourishjana/java-language
5f0c62fffb9d4c87355a6e34bbc1ee627f0eaf94
d4ee1c7bda4554c181c96f96c7cc15df9459c58a
refs/heads/main
2023-06-04T08:53:28.514000
2021-06-29T04:54:09
2021-06-29T04:54:09
381,245,281
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int num= scanner.nextInt(); int copyOfNum=num; int sum=0; while(num!=0){ int remainder=num%10; sum+=remainder; num=num/10; } System.out.println(sum); // shortcut for the no of digits in a number : int numberOfDigits= (int)Math.log10(copyOfNum)+1; System.out.println("No of digits in "+copyOfNum+" is = "+numberOfDigits); // palindrome number : Palindrome p=new Palindrome(); p.checkPalindrome(copyOfNum); // do while loop ---------------------------------------------- int k; do{ k=scanner.nextInt(); System.out.println("Number is : "+k); }while (k!=0); } }
UTF-8
Java
901
java
Main.java
Java
[]
null
[]
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int num= scanner.nextInt(); int copyOfNum=num; int sum=0; while(num!=0){ int remainder=num%10; sum+=remainder; num=num/10; } System.out.println(sum); // shortcut for the no of digits in a number : int numberOfDigits= (int)Math.log10(copyOfNum)+1; System.out.println("No of digits in "+copyOfNum+" is = "+numberOfDigits); // palindrome number : Palindrome p=new Palindrome(); p.checkPalindrome(copyOfNum); // do while loop ---------------------------------------------- int k; do{ k=scanner.nextInt(); System.out.println("Number is : "+k); }while (k!=0); } }
901
0.509434
0.498335
39
22.102564
21.466486
81
false
false
0
0
0
0
0
0
0.435897
false
false
7
e30c839a269c610285efd13dbee7adf52a2aaa45
15,444,702,430,491
7a0d71e7e58cb7d7094fd81528e46ca3d0086302
/src/main/java/ua/phone/book/models/Department.java
d37942cf6f24c98aedf23e63dd14511d07995873
[]
no_license
Marius961/phone-book
https://github.com/Marius961/phone-book
7561344c23bab24478deabbee89e9c07602ce296
b99d9c26ea5035c809af22de8f2333fd23285223
refs/heads/master
2020-03-15T00:27:48.492000
2018-05-21T14:43:23
2018-05-21T14:43:23
131,869,028
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ua.phone.book.models; import java.util.List; public class Department { private int id; private String name; private int emploeeCount; private boolean canDelete; public boolean isCanDelete() { return canDelete; } public void setCanDelete(boolean canDelete) { this.canDelete = canDelete; } public int getEmploeeCount() { return emploeeCount; } public void setEmploeeCount(int emploeeCount) { this.emploeeCount = emploeeCount; } List<Employee> employeeList; public List<Employee> getEmployeeList() { return employeeList; } public void setEmployeeList(List<Employee> employeeList) { this.employeeList = employeeList; } 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; } }
UTF-8
Java
993
java
Department.java
Java
[]
null
[]
package ua.phone.book.models; import java.util.List; public class Department { private int id; private String name; private int emploeeCount; private boolean canDelete; public boolean isCanDelete() { return canDelete; } public void setCanDelete(boolean canDelete) { this.canDelete = canDelete; } public int getEmploeeCount() { return emploeeCount; } public void setEmploeeCount(int emploeeCount) { this.emploeeCount = emploeeCount; } List<Employee> employeeList; public List<Employee> getEmployeeList() { return employeeList; } public void setEmployeeList(List<Employee> employeeList) { this.employeeList = employeeList; } 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; } }
993
0.620342
0.620342
53
17.735849
16.714191
62
false
false
0
0
0
0
0
0
0.320755
false
false
7
01fd03f617d1d297e645f658513d0338decaccec
14,242,111,583,723
f258604737b37e95c87f91b5b85565035cb9489f
/unit-testing/src/test/java/com/example/unittesting/unittesting/business/SomeBusinessStubTest.java
33c948079fbd26773062c016a0e56200a78998ad
[]
no_license
leveneden/Udemy-Course-Master-Java-Unit-Testing-with-Spring-Boot-Mockito
https://github.com/leveneden/Udemy-Course-Master-Java-Unit-Testing-with-Spring-Boot-Mockito
85d10fa785458b85fdf80c037dd704aaa775b82a
7e3562b63b999785fd619410f0b84e6987f3ec1f
refs/heads/master
2020-07-16T05:20:16.093000
2019-09-03T15:43:17
2019-09-03T15:43:17
205,727,674
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.unittesting.unittesting.business; import static org.junit.Assert.*; import com.example.unittesting.unittesting.data.SomeDataService; import org.junit.Test; class SomeDataServiceStub implements SomeDataService { private int[] data; public SomeDataServiceStub(int[] data) { this.data = data; } @Override public int[] retrieveAllData() { return data; } } public class SomeBusinessStubTest { @Test public void calculateSumUsingDataService_normalScenario() { SomeBusinessImpl business = new SomeBusinessImpl(); business.setSomeDataService(new SomeDataServiceStub(new int[] {1, 2, 3})); assertEquals(6, business.calculateSumUsingDataService()); } @Test public void calculateSumUsingDataService_oneValue() { SomeBusinessImpl business = new SomeBusinessImpl(); business.setSomeDataService(new SomeDataServiceStub(new int[] {5})); assertEquals(5, business.calculateSumUsingDataService()); } @Test public void calculateSumUsingDataService_empty() { SomeBusinessImpl business = new SomeBusinessImpl(); business.setSomeDataService(new SomeDataServiceStub(new int[] { })); assertEquals(0, business.calculateSumUsingDataService()); } }
UTF-8
Java
1,301
java
SomeBusinessStubTest.java
Java
[]
null
[]
package com.example.unittesting.unittesting.business; import static org.junit.Assert.*; import com.example.unittesting.unittesting.data.SomeDataService; import org.junit.Test; class SomeDataServiceStub implements SomeDataService { private int[] data; public SomeDataServiceStub(int[] data) { this.data = data; } @Override public int[] retrieveAllData() { return data; } } public class SomeBusinessStubTest { @Test public void calculateSumUsingDataService_normalScenario() { SomeBusinessImpl business = new SomeBusinessImpl(); business.setSomeDataService(new SomeDataServiceStub(new int[] {1, 2, 3})); assertEquals(6, business.calculateSumUsingDataService()); } @Test public void calculateSumUsingDataService_oneValue() { SomeBusinessImpl business = new SomeBusinessImpl(); business.setSomeDataService(new SomeDataServiceStub(new int[] {5})); assertEquals(5, business.calculateSumUsingDataService()); } @Test public void calculateSumUsingDataService_empty() { SomeBusinessImpl business = new SomeBusinessImpl(); business.setSomeDataService(new SomeDataServiceStub(new int[] { })); assertEquals(0, business.calculateSumUsingDataService()); } }
1,301
0.709454
0.704074
45
27.911112
27.654875
82
false
false
0
0
0
0
0
0
0.466667
false
false
7
fdeb10d26f3ad9b282be03a3ae2f695866942523
28,896,540,029,525
1b03cee97a0bc9dc119f6d150bba7d26b5f2ee82
/src/NNM_LSTM.java
b0c23049aa82d09962636aac1a5f0663c4789d81
[]
no_license
lzpel/practice_ml_lstm
https://github.com/lzpel/practice_ml_lstm
7722eb0d8646f66086a8627e96c9cd86a1400402
50abcb26b3231a81c27c69d854e4a0db33c152c0
refs/heads/master
2021-07-05T01:42:12.839000
2017-09-26T20:56:53
2017-09-26T20:56:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Created by user on 2017/08/25. */ public class NNM_LSTM extends NNM{ NNL l0,l1; NNL[] l0l,l1l; int l; float[] vi,vo,vd; NNV vt; NNM_LSTM(int size_i,int size_m,int size_o,int active,int length){ super(size_i,size_m,size_o); l=length; vi=new float[l*si]; vo=new float[l*so]; vd=new float[l*so]; vt=new NNV(so); l0=new NNL_LSTM(si,sm); l0l=new NNL[l]; for(int i=0;i<l;i++){ l0l[i]=new NNL_LSTM(l0); } l1=new NNL_OUT(sm,so,active); l1l=new NNL[l]; for(int i=0;i<l;i++){ l1l[i]=new NNL_OUT(l1); } } public float learn(float rate){ if(rate>=0){ float loss=0; l1.zerovalue(); l0.zerovalue(); for(int n=0;n<l;n++){ for(int m=0;m<si;m++){ l0.geti().v[m]=vi[si*n+m]; } l0.propagate(true); NNV.vcpy(true, l1.geti(), l0.geto()); l1.propagate(true); for(int m=0;m<so;m++){ vo[so*n+m]=l1.geto().v[m]; } l1l[n].lcpy(true,l1); l0l[n].lcpy(true,l0); } l1.zerodelta(); l0.zerodelta(); for (int n=l-1; n >= 0; n--) { l1.lcpy(true,l1l[n]); l0.lcpy(true,l0l[n]); //ここから for(int m=0;m<so;m++){ vt.v[m]=vd[so*n+m]; } loss=l1.getloss(vt); //ここまで l1.propagate(false); NNV.vcpy(false, l1.geti(), l0.geto()); l0.propagate(false); l1.lcpy(false,l1l[n]); l0.lcpy(false,l0l[n]); } for(int n=0;n<l;n++) { l1.lcpy(true,l1l[n]); l0.lcpy(true,l0l[n]); l1l[n].lcpy(false,l1); l0l[n].lcpy(false,l0); l1.learn(rate); l0.learn(rate); } return loss; }else{ for(int i=0;i<si;i++){ l0.geti().v[i]=vi[i]; } l0.propagate(true); NNV.vcpy(true, l1.geti(), l0.geto()); l1.propagate(true); for(int i=0;i<so;i++){ vo[i]=l1.geto().v[i]; } return 0; } } public float[] geti(){ return vi; } public float[] geto(){ return vo; } public float[] getd(){ return vd; } public static void test(){ int T=10; NNM_LSTM nnm=new NNM_LSTM(1,10,1, NNL_OUT.ACTIVE_IDEN,50); for(int m=0;m<2000;m++){ for(int n=0;n<nnm.l;n++){ nnm.geti()[n]= (float) Math.sin(2*Math.PI*(n+m+0)/T); nnm.getd()[n]= (float) Math.sin(2*Math.PI*(n+m+1)/T); } nnm.learn(0.01f); } for(int m=0;m<100;m++){ if(m<50){ nnm.geti()[0]= (float) Math.sin(2*Math.PI*(m)/T); }else{ nnm.geti()[0]=nnm.geto()[0]; } nnm.learn(); System.out.println(nnm.geto()[0]); } } }
UTF-8
Java
2,509
java
NNM_LSTM.java
Java
[ { "context": "/**\r\n * Created by user on 2017/08/25.\r\n */\r\npublic class NNM_LSTM extend", "end": 23, "score": 0.9710410237312317, "start": 19, "tag": "USERNAME", "value": "user" } ]
null
[]
/** * Created by user on 2017/08/25. */ public class NNM_LSTM extends NNM{ NNL l0,l1; NNL[] l0l,l1l; int l; float[] vi,vo,vd; NNV vt; NNM_LSTM(int size_i,int size_m,int size_o,int active,int length){ super(size_i,size_m,size_o); l=length; vi=new float[l*si]; vo=new float[l*so]; vd=new float[l*so]; vt=new NNV(so); l0=new NNL_LSTM(si,sm); l0l=new NNL[l]; for(int i=0;i<l;i++){ l0l[i]=new NNL_LSTM(l0); } l1=new NNL_OUT(sm,so,active); l1l=new NNL[l]; for(int i=0;i<l;i++){ l1l[i]=new NNL_OUT(l1); } } public float learn(float rate){ if(rate>=0){ float loss=0; l1.zerovalue(); l0.zerovalue(); for(int n=0;n<l;n++){ for(int m=0;m<si;m++){ l0.geti().v[m]=vi[si*n+m]; } l0.propagate(true); NNV.vcpy(true, l1.geti(), l0.geto()); l1.propagate(true); for(int m=0;m<so;m++){ vo[so*n+m]=l1.geto().v[m]; } l1l[n].lcpy(true,l1); l0l[n].lcpy(true,l0); } l1.zerodelta(); l0.zerodelta(); for (int n=l-1; n >= 0; n--) { l1.lcpy(true,l1l[n]); l0.lcpy(true,l0l[n]); //ここから for(int m=0;m<so;m++){ vt.v[m]=vd[so*n+m]; } loss=l1.getloss(vt); //ここまで l1.propagate(false); NNV.vcpy(false, l1.geti(), l0.geto()); l0.propagate(false); l1.lcpy(false,l1l[n]); l0.lcpy(false,l0l[n]); } for(int n=0;n<l;n++) { l1.lcpy(true,l1l[n]); l0.lcpy(true,l0l[n]); l1l[n].lcpy(false,l1); l0l[n].lcpy(false,l0); l1.learn(rate); l0.learn(rate); } return loss; }else{ for(int i=0;i<si;i++){ l0.geti().v[i]=vi[i]; } l0.propagate(true); NNV.vcpy(true, l1.geti(), l0.geto()); l1.propagate(true); for(int i=0;i<so;i++){ vo[i]=l1.geto().v[i]; } return 0; } } public float[] geti(){ return vi; } public float[] geto(){ return vo; } public float[] getd(){ return vd; } public static void test(){ int T=10; NNM_LSTM nnm=new NNM_LSTM(1,10,1, NNL_OUT.ACTIVE_IDEN,50); for(int m=0;m<2000;m++){ for(int n=0;n<nnm.l;n++){ nnm.geti()[n]= (float) Math.sin(2*Math.PI*(n+m+0)/T); nnm.getd()[n]= (float) Math.sin(2*Math.PI*(n+m+1)/T); } nnm.learn(0.01f); } for(int m=0;m<100;m++){ if(m<50){ nnm.geti()[0]= (float) Math.sin(2*Math.PI*(m)/T); }else{ nnm.geti()[0]=nnm.geto()[0]; } nnm.learn(); System.out.println(nnm.geto()[0]); } } }
2,509
0.510229
0.466506
114
19.868422
13.151288
66
false
false
0
0
0
0
0
0
3.754386
false
false
7
8c3e02ea1f81ce4a01f2ede1917693496eeb827c
21,500,606,316,613
7bd94513184e654467474c83a18230e52342afcf
/src/main/java/com/gtafe/data/center/information/data/service/impl/DataStandardServiceImpl.java
23cfdefe89217a0422cfc18e9cc05991330f8783
[]
no_license
qq85609655/b1
https://github.com/qq85609655/b1
e33091030eecd59ade9b956b779940d349660523
73b5bba21fbce41297b0ac8fe4a3bfeadaa444fb
refs/heads/master
2020-04-04T18:39:01.993000
2018-09-12T00:38:05
2018-09-12T00:38:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gtafe.data.center.information.data.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.gtafe.data.center.common.common.constant.LogConstant; import com.gtafe.data.center.dataetl.datatask.mapper.DataTaskMapper; import com.gtafe.data.center.dataetl.datatask.vo.DataTaskVo; import com.gtafe.data.center.information.data.mapper.DataStandardItemMapper; import com.gtafe.data.center.information.data.mapper.DataStandardMapper; import com.gtafe.data.center.information.data.service.DataStandardService; import com.gtafe.data.center.information.data.vo.DataStandardItemVo; import com.gtafe.data.center.information.data.vo.DataStandardVo; import com.gtafe.data.center.system.log.service.LogService; import com.gtafe.data.center.system.log.vo.LogInfo; import com.gtafe.framework.base.controller.BaseController; import com.gtafe.framework.base.exception.OrdinaryException; import com.gtafe.framework.base.utils.StringUtil; @Service public class DataStandardServiceImpl extends BaseController implements DataStandardService { @Resource private DataStandardMapper dataStandardMapper; @Resource private DataStandardItemMapper dataStandardItemMapper; @Resource private DataTaskMapper dataTaskMapper; @Resource private LogService logServiceImpl; @Override public List<DataStandardVo> queryDataOrgList(String keyWord, int sourceId, String subsetCode, String classCode, int nodeType, int pageNum, int pageSize) { return dataStandardMapper.queryDataOrgList(keyWord, sourceId, subsetCode, classCode, nodeType, pageNum, pageSize); } @Override public List<DataStandardVo> queryDataOrgListAll(int sourceId, String subsetCode, String classCode, int nodeType) { return dataStandardMapper.queryDataOrgListAll(sourceId, subsetCode, classCode, nodeType); } @Override public DataStandardVo queryDataOrgTree(int sourceId) { List<DataStandardVo> list = this.dataStandardMapper.queryDataOrgTreeVos(sourceId); Map<String, DataStandardVo> map = new HashMap<String, DataStandardVo>(); for (DataStandardVo vo : list) { map.put(vo.getCode(), vo); } DataStandardVo root = null; for (DataStandardVo vo : list) { if (vo.getParentCode().equals("")) { root = vo; } DataStandardVo parent = map.get(vo.getParentCode()); if (parent != null) { if (parent.getChildren() == null) { parent.setChildren(new ArrayList<DataStandardVo>()); } parent.getChildren().add(vo); } } /*if(root!=null) { root.removeEmptys(); }*/ return root; } @Override public DataStandardVo getDataStandardVo(String code) { return dataStandardMapper.getDataStandardVo(code); } @Override public boolean addDataStandardVos(int sourceId, String parentCode, List<DataStandardVo> voList, int nodeType) { if (voList == null || voList.isEmpty()) { return true; } DataStandardVo parent = this.dataStandardMapper.getDataStandardVo(parentCode); if (parent == null) { throw new OrdinaryException("父节点不存在或已被删除!"); } List<String> codeList = new ArrayList<String>(); List<String> nameList = new ArrayList<String>(); List<String> tablenameList = new ArrayList<String>(); nodeType = parent.getNodeType() + 1; List<String> codenameList = new ArrayList<String>(); for (DataStandardVo vo : voList) { codenameList.add(vo.getCode() + "/" + vo.getName()); codeList.add(vo.getCode()); nameList.add(vo.getName()); if (nodeType == 3) { vo.setTableName(vo.getTableName().toUpperCase()); tablenameList.add(vo.getTableName()); } else { vo.setTableName(""); } vo.setParentCode(parentCode); vo.setNodeType(nodeType); vo.setDescription(vo.getDescription() == null ? "" : vo.getDescription()); } //检查数据准确性 codeList = this.dataStandardMapper.checkDataCodeRepeat(codeList); if (codeList != null && codeList.size() > 0) { throw new OrdinaryException("部分编号已存在" + codeList.toString() + "!"); } /*nameList = this.dataStandardMapper.checkDataNameRepeat(nameList, parentCode, null); if(nameList!=null && nameList.size()>0) { throw new OrdinaryException("部分名称已存在"+ nameList.toString() +"!"); }*/ if (nodeType == 3) { tablenameList = this.dataStandardMapper.checkDataTablenameRepeat(tablenameList); if (tablenameList != null && tablenameList.size() > 0) { throw new OrdinaryException("部分英文名称已存在" + tablenameList.toString() + "!"); } } this.dataStandardMapper.insertDataStandardVos(voList, sourceId, this.getUserId()); LogInfo logInfo = new LogInfo(); logInfo.setModuleId(this.getMoudleId(nodeType)); logInfo.setOperType("新增"); logInfo.setOperContent("新增" + this.getTypeName(nodeType) + ":" + StringUtil.join(codenameList)); this.logServiceImpl.saveLog(logInfo); return true; } @Override public boolean updateDataStandardVo(int sourceId, DataStandardVo dataVo, int nodeType) { DataStandardVo dbVo = this.dataStandardMapper.getDataStandardVo(dataVo.getCode()); if (dbVo == null) { throw new OrdinaryException("节点不存在或已被删除!"); } /*List<String> nameList = this.dataStandardMapper.checkDataNameRepeat( Arrays.asList(new String[] {dataVo.getName()}), dataVo.getParentCode(), dataVo.getCode()); if(nameList!=null && nameList.size()>0) { throw new OrdinaryException("名称已存在!"); }*/ nodeType = dbVo.getNodeType(); dataVo.setNodeType(dbVo.getNodeType()); if (dataVo.getNodeType() == 3) { this.checkTaskUsing(dataVo.getCode(), sourceId); //禁止修改表名,不再重建表 } this.dataStandardMapper.updateDataStandardVo(dataVo, sourceId, this.getUserId()); String content = dataVo.getCode() + "/" + (!dbVo.getName().equals(dataVo.getName()) ? dbVo.getName() + "->" : "") + dataVo.getName(); LogInfo logInfo = new LogInfo(); logInfo.setModuleId(this.getMoudleId(nodeType)); logInfo.setOperType("修改"); logInfo.setOperContent("修改" + this.getTypeName(nodeType) + ":" + content); this.logServiceImpl.saveLog(logInfo); return true; } @Override public boolean deleteDataStandardVo(int sourceId, String code, int nodeType) { DataStandardVo dbVo = this.dataStandardMapper.getDataStandardVo(code); if (dbVo == null) { return true; } if (dbVo.getNodeType() < 3) { List<DataStandardVo> list = this.dataStandardMapper.getChildDataStandardVos(code, sourceId); if (list != null && list.size() > 0) { throw new OrdinaryException("当前节点下存在下级节点,不能删除!"); } } else if (dbVo.getNodeType() == 3) { List<DataStandardItemVo> list = this.dataStandardItemMapper.querySubclassItemList(sourceId, code, 1, 1); if (list != null && list.size() > 0) { throw new OrdinaryException("当前子类下存在下级元数据,不能删除!"); } this.checkTaskUsing(code, sourceId); } nodeType = dbVo.getNodeType(); this.dataStandardMapper.deleteDataStandardVo(code, sourceId); LogInfo logInfo = new LogInfo(); logInfo.setModuleId(this.getMoudleId(nodeType)); logInfo.setOperType("删除"); logInfo.setOperContent("删除" + this.getTypeName(nodeType) + ":" + dbVo.getCode() + "/" + dbVo.getName()); this.logServiceImpl.saveLog(logInfo); return true; } /** * 检查是否存在资源任务使用数据表 * * @author 汪逢建 * @date 2017年12月12日 */ private void checkTaskUsing(String subclassCode, int sourceId) { List<DataTaskVo> dataTaskVoList = this.dataTaskMapper.findTasksBySubclass(subclassCode); if (!dataTaskVoList.isEmpty()) { StringBuffer fbtask = new StringBuffer(""); StringBuffer dytask = new StringBuffer(""); for (DataTaskVo vo : dataTaskVoList) { if (vo.getBusinessType() == 1) { fbtask.append(vo.getTaskName()).append(","); } else { dytask.append(vo.getTaskName()).append(","); } } StringBuffer error = new StringBuffer(); if (fbtask.length() > 0) { error.append("发布任务【").append(fbtask.substring(0, fbtask.length() - 1)).append("】"); } if (dytask.length() > 0) { if (error.length() > 0) { dytask.append(","); } error.append("订阅任务【").append(dytask.substring(0, dytask.length() - 1)).append("】"); } String msg = "当前元数据相关的数据表被" + error.toString() + "引用,请先删除数据资源任务!"; throw new OrdinaryException(msg); } } private String getTypeName(int nodeType) { if (nodeType == 1) { return "数据子集"; } else if (nodeType == 2) { return "数据类"; } else { return "数据子类"; } } private int getMoudleId(int nodeType) { if (nodeType == 1) { return LogConstant.Module_Standard_Subset; } else if (nodeType == 2) { return LogConstant.Module_Standard_Class; } else { return LogConstant.Module_Standard_Subclass; } } }
UTF-8
Java
10,716
java
DataStandardServiceImpl.java
Java
[ { "context": " /**\n * 检查是否存在资源任务使用数据表\n *\n * @author 汪逢建\n * @date 2017年12月12日\n */\n private void", "end": 8557, "score": 0.9998223185539246, "start": 8554, "tag": "NAME", "value": "汪逢建" } ]
null
[]
package com.gtafe.data.center.information.data.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.gtafe.data.center.common.common.constant.LogConstant; import com.gtafe.data.center.dataetl.datatask.mapper.DataTaskMapper; import com.gtafe.data.center.dataetl.datatask.vo.DataTaskVo; import com.gtafe.data.center.information.data.mapper.DataStandardItemMapper; import com.gtafe.data.center.information.data.mapper.DataStandardMapper; import com.gtafe.data.center.information.data.service.DataStandardService; import com.gtafe.data.center.information.data.vo.DataStandardItemVo; import com.gtafe.data.center.information.data.vo.DataStandardVo; import com.gtafe.data.center.system.log.service.LogService; import com.gtafe.data.center.system.log.vo.LogInfo; import com.gtafe.framework.base.controller.BaseController; import com.gtafe.framework.base.exception.OrdinaryException; import com.gtafe.framework.base.utils.StringUtil; @Service public class DataStandardServiceImpl extends BaseController implements DataStandardService { @Resource private DataStandardMapper dataStandardMapper; @Resource private DataStandardItemMapper dataStandardItemMapper; @Resource private DataTaskMapper dataTaskMapper; @Resource private LogService logServiceImpl; @Override public List<DataStandardVo> queryDataOrgList(String keyWord, int sourceId, String subsetCode, String classCode, int nodeType, int pageNum, int pageSize) { return dataStandardMapper.queryDataOrgList(keyWord, sourceId, subsetCode, classCode, nodeType, pageNum, pageSize); } @Override public List<DataStandardVo> queryDataOrgListAll(int sourceId, String subsetCode, String classCode, int nodeType) { return dataStandardMapper.queryDataOrgListAll(sourceId, subsetCode, classCode, nodeType); } @Override public DataStandardVo queryDataOrgTree(int sourceId) { List<DataStandardVo> list = this.dataStandardMapper.queryDataOrgTreeVos(sourceId); Map<String, DataStandardVo> map = new HashMap<String, DataStandardVo>(); for (DataStandardVo vo : list) { map.put(vo.getCode(), vo); } DataStandardVo root = null; for (DataStandardVo vo : list) { if (vo.getParentCode().equals("")) { root = vo; } DataStandardVo parent = map.get(vo.getParentCode()); if (parent != null) { if (parent.getChildren() == null) { parent.setChildren(new ArrayList<DataStandardVo>()); } parent.getChildren().add(vo); } } /*if(root!=null) { root.removeEmptys(); }*/ return root; } @Override public DataStandardVo getDataStandardVo(String code) { return dataStandardMapper.getDataStandardVo(code); } @Override public boolean addDataStandardVos(int sourceId, String parentCode, List<DataStandardVo> voList, int nodeType) { if (voList == null || voList.isEmpty()) { return true; } DataStandardVo parent = this.dataStandardMapper.getDataStandardVo(parentCode); if (parent == null) { throw new OrdinaryException("父节点不存在或已被删除!"); } List<String> codeList = new ArrayList<String>(); List<String> nameList = new ArrayList<String>(); List<String> tablenameList = new ArrayList<String>(); nodeType = parent.getNodeType() + 1; List<String> codenameList = new ArrayList<String>(); for (DataStandardVo vo : voList) { codenameList.add(vo.getCode() + "/" + vo.getName()); codeList.add(vo.getCode()); nameList.add(vo.getName()); if (nodeType == 3) { vo.setTableName(vo.getTableName().toUpperCase()); tablenameList.add(vo.getTableName()); } else { vo.setTableName(""); } vo.setParentCode(parentCode); vo.setNodeType(nodeType); vo.setDescription(vo.getDescription() == null ? "" : vo.getDescription()); } //检查数据准确性 codeList = this.dataStandardMapper.checkDataCodeRepeat(codeList); if (codeList != null && codeList.size() > 0) { throw new OrdinaryException("部分编号已存在" + codeList.toString() + "!"); } /*nameList = this.dataStandardMapper.checkDataNameRepeat(nameList, parentCode, null); if(nameList!=null && nameList.size()>0) { throw new OrdinaryException("部分名称已存在"+ nameList.toString() +"!"); }*/ if (nodeType == 3) { tablenameList = this.dataStandardMapper.checkDataTablenameRepeat(tablenameList); if (tablenameList != null && tablenameList.size() > 0) { throw new OrdinaryException("部分英文名称已存在" + tablenameList.toString() + "!"); } } this.dataStandardMapper.insertDataStandardVos(voList, sourceId, this.getUserId()); LogInfo logInfo = new LogInfo(); logInfo.setModuleId(this.getMoudleId(nodeType)); logInfo.setOperType("新增"); logInfo.setOperContent("新增" + this.getTypeName(nodeType) + ":" + StringUtil.join(codenameList)); this.logServiceImpl.saveLog(logInfo); return true; } @Override public boolean updateDataStandardVo(int sourceId, DataStandardVo dataVo, int nodeType) { DataStandardVo dbVo = this.dataStandardMapper.getDataStandardVo(dataVo.getCode()); if (dbVo == null) { throw new OrdinaryException("节点不存在或已被删除!"); } /*List<String> nameList = this.dataStandardMapper.checkDataNameRepeat( Arrays.asList(new String[] {dataVo.getName()}), dataVo.getParentCode(), dataVo.getCode()); if(nameList!=null && nameList.size()>0) { throw new OrdinaryException("名称已存在!"); }*/ nodeType = dbVo.getNodeType(); dataVo.setNodeType(dbVo.getNodeType()); if (dataVo.getNodeType() == 3) { this.checkTaskUsing(dataVo.getCode(), sourceId); //禁止修改表名,不再重建表 } this.dataStandardMapper.updateDataStandardVo(dataVo, sourceId, this.getUserId()); String content = dataVo.getCode() + "/" + (!dbVo.getName().equals(dataVo.getName()) ? dbVo.getName() + "->" : "") + dataVo.getName(); LogInfo logInfo = new LogInfo(); logInfo.setModuleId(this.getMoudleId(nodeType)); logInfo.setOperType("修改"); logInfo.setOperContent("修改" + this.getTypeName(nodeType) + ":" + content); this.logServiceImpl.saveLog(logInfo); return true; } @Override public boolean deleteDataStandardVo(int sourceId, String code, int nodeType) { DataStandardVo dbVo = this.dataStandardMapper.getDataStandardVo(code); if (dbVo == null) { return true; } if (dbVo.getNodeType() < 3) { List<DataStandardVo> list = this.dataStandardMapper.getChildDataStandardVos(code, sourceId); if (list != null && list.size() > 0) { throw new OrdinaryException("当前节点下存在下级节点,不能删除!"); } } else if (dbVo.getNodeType() == 3) { List<DataStandardItemVo> list = this.dataStandardItemMapper.querySubclassItemList(sourceId, code, 1, 1); if (list != null && list.size() > 0) { throw new OrdinaryException("当前子类下存在下级元数据,不能删除!"); } this.checkTaskUsing(code, sourceId); } nodeType = dbVo.getNodeType(); this.dataStandardMapper.deleteDataStandardVo(code, sourceId); LogInfo logInfo = new LogInfo(); logInfo.setModuleId(this.getMoudleId(nodeType)); logInfo.setOperType("删除"); logInfo.setOperContent("删除" + this.getTypeName(nodeType) + ":" + dbVo.getCode() + "/" + dbVo.getName()); this.logServiceImpl.saveLog(logInfo); return true; } /** * 检查是否存在资源任务使用数据表 * * @author 汪逢建 * @date 2017年12月12日 */ private void checkTaskUsing(String subclassCode, int sourceId) { List<DataTaskVo> dataTaskVoList = this.dataTaskMapper.findTasksBySubclass(subclassCode); if (!dataTaskVoList.isEmpty()) { StringBuffer fbtask = new StringBuffer(""); StringBuffer dytask = new StringBuffer(""); for (DataTaskVo vo : dataTaskVoList) { if (vo.getBusinessType() == 1) { fbtask.append(vo.getTaskName()).append(","); } else { dytask.append(vo.getTaskName()).append(","); } } StringBuffer error = new StringBuffer(); if (fbtask.length() > 0) { error.append("发布任务【").append(fbtask.substring(0, fbtask.length() - 1)).append("】"); } if (dytask.length() > 0) { if (error.length() > 0) { dytask.append(","); } error.append("订阅任务【").append(dytask.substring(0, dytask.length() - 1)).append("】"); } String msg = "当前元数据相关的数据表被" + error.toString() + "引用,请先删除数据资源任务!"; throw new OrdinaryException(msg); } } private String getTypeName(int nodeType) { if (nodeType == 1) { return "数据子集"; } else if (nodeType == 2) { return "数据类"; } else { return "数据子类"; } } private int getMoudleId(int nodeType) { if (nodeType == 1) { return LogConstant.Module_Standard_Subset; } else if (nodeType == 2) { return LogConstant.Module_Standard_Class; } else { return LogConstant.Module_Standard_Subclass; } } }
10,716
0.596865
0.593575
250
40.335999
29.198889
141
false
false
0
0
0
0
0
0
0.656
false
false
7
42e71c8bc919524f9cb8ea4b954a2dd3c1d2199a
17,093,969,887,475
d2aaa0c6d30f7ad9c12f8e9a53ab9c5a2c8b7823
/src/main/java/com/welyab/margelet/TelegramMethod.java
689fcc58a62274e4fd913c778dcf1b54002bcb83
[ "Apache-2.0" ]
permissive
welyab/margelet
https://github.com/welyab/margelet
44a498cd22080f45f877cd1b3bc878a0ddbe4779
fc3f4d9da95625aac87200347f2113e0f11bd1e4
refs/heads/master
2020-03-20T23:01:00.742000
2018-06-28T13:51:27
2018-06-28T13:51:27
137,825,375
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2018 Welyab da Silva Paula * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.welyab.margelet; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.CloseableHttpClient; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.welyab.margelet.gson.GsonFactory; import com.welyab.margelet.http.HttpClientPool; import com.welyab.margelet.types.Response; /** * A representation of an Telegram Bot API method. This class performs HTTP * requests and JSON processing. * * @author Welyab Paula */ public class TelegramMethod { /** * The name of the method to be called in Telegram service. */ private final String methodName; /** * The expected type as result of calling the Telegram method. This result * is always wrapped into a <code>Response</code> object. So, the actual * returned type from Telegram service will be * <code>Response&lt;type&gt;</code>. That type is marked in * {@link #responseType} field. */ private final Type type; /** * The Telegram Bot API auth token. */ private final String apiToken; /** * The target URL. This value is composite by API auth token and the method * name. */ private final String targetUrl; /** * The actual result type for Telegram method calling. All Telegram methods * that return JSON documents as its results are mapped as * <code>Response</code> object. The underlying result for an specific * method name is placed as the <code>"result"</code> in the * <code>Response</code> object. So, this field holds something like * <code>Response&lt;type&gt;</code>. * * @see #type * @see Response */ private final Type responseType; /** * Creates a new <code>TelegramMethod</code> representation. * * <p> * This method is thread safe. * * @param methodName The name of the method to be called in Telegram * service. * @param type The expected type as result of calling the Telegram method. * This result is always wrapped into a <code>Response</code> * object. So, the actual returned type from Telegram service * will be <code>Response&lt;type&gt;</code>. That type is marked * in {@link #responseType} field. * @param apiToken The API token to access Telegram services. */ public TelegramMethod(String methodName, Type type, String apiToken) { Preconditions.checkNotNull(methodName, "Parameter 'methodName' cannot be null"); Preconditions.checkNotNull(type, "Parameter 'type' cannot be null"); Preconditions.checkNotNull(apiToken, "Parameter 'apiToken' cannot be null"); this.methodName = methodName; this.type = type; this.apiToken = apiToken; this.targetUrl = createTargetUrl(methodName, apiToken); this.responseType = TypeToken.getParameterized(Response.class, type).getType(); } /** * Calls a Telegram method with given configuration. * * @param configuration The configuration. * * @return The method result. * * <p> * Telegram method responses are a JSON document in the format of an * <code>Response</code> object. The actual result of an Telegram * method calling is placed in the <code>"result"</code> field. */ public Response<?> call(Configuration configuration) { return call(ImmutableMap.of(), configuration); } /** * Calls a Telegram method with given parameters and configuration. * * @param parameters Parameters expected by Telegram method. This object * will be encoded as JSON document and delivered in HTTP request * boby. * * <p> * If the parameter is a instance of a <code>java.util.Map</code> * and is empty, it will be ignored. * * @param configuration The configuration. * * @return The method result. * * <p> * Telegram method responses are a JSON document in the format of an * <code>Response</code> object. The actual result of an Telegram * method calling is placed in the <code>"result"</code> field. */ public Response<?> call( ImmutableMap<String, Object> parameters, Configuration configuration ) { Preconditions.checkNotNull(parameters, "Parameter 'parameters' cannot be null"); Preconditions.checkNotNull(configuration, "Parameter 'configuration' cannot be null"); return call((Object) parameters, configuration); } /** * Calls a Telegram method with given parameters and configuration. * * @param parameters Parameters expected by Telegram method. This object * will be encoded as JSON document and delivered in HTTP request * boby. * * <p> * If the parameter is a instance of a <code>java.util.Map</code> * and is empty, it will be ignored. * * @param configuration The configuration. * * @return The method result. * * <p> * Telegram method responses are a JSON document in the format of an * <code>Response</code> object. The actual result of an Telegram * method calling is placed in the <code>"result"</code> field. */ public Response<?> call(Object parameters, Configuration configuration) { Preconditions.checkNotNull(parameters, "Parameter 'parameters' cannot be null"); Preconditions.checkNotNull(configuration, "Parameter 'configuration' cannot be null"); Gson gson = GsonFactory.create(configuration); HttpEntity parametersHttpEntity = null; if (parameters != null && !((Map<?, ?>) parameters).isEmpty()) { String jsonParameters = gson.toJson(parameters); parametersHttpEntity = new ByteArrayEntity(jsonParameters.getBytes(StandardCharsets.UTF_8)); } try (CloseableHttpClient httpClient = HttpClientPool.getClient(configuration)) { HttpPost request = new HttpPost(targetUrl); if (parametersHttpEntity != null) { request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); request.setEntity(parametersHttpEntity); } try (CloseableHttpResponse httpResponse = httpClient.execute(request)) { HttpEntity responseHttpEntity = httpResponse.getEntity(); InputStream inputStream = responseHttpEntity.getContent(); InputStreamReader reader = new InputStreamReader(inputStream); return gson.fromJson(reader, responseType); } } catch (IOException e) { throw new MargeletException("Fail during communication with Telegram services", e); } } /** * Returns the configured Telegram method name. * * @return The configured Telegram method name. */ public String getMethodName() { return methodName; } /** * Returns the underlying type. The type that will be wrapped into a * <code>Response</code> object. * * @return The type. */ public Type getType() { return type; } /** * Returns the configured API access token. * * @return The configured API access token. */ public String getApiToken() { return apiToken; } /** * Creates the API method end point. Telegram API method endpoints are fixed * URLs based on the api access token and the method name, this method * creates that URLs. * * @param methodName The method name. * @param apiToken The api access token. * * @return The URL. */ private static String createTargetUrl(String methodName, String apiToken) { return StringUtils.replaceEach( Constants.URL_API, new String[] { Constants.URL_API_PARAM_API_TOKEN, Constants.URL_API_PARAM_METHOD_NAME }, new String[] { apiToken, methodName } ); } }
UTF-8
Java
9,014
java
TelegramMethod.java
Java
[ { "context": "/*\n * Copyright 2018 Welyab da Silva Paula\n *\n * Licensed under the Apache License, Version ", "end": 42, "score": 0.9998815655708313, "start": 21, "tag": "NAME", "value": "Welyab da Silva Paula" }, { "context": "TP\n * requests and JSON processing.\n * \n * @author Welyab Paula\n */\npublic class TelegramMethod {\n\n /**\n *", "end": 1590, "score": 0.9998766779899597, "start": 1578, "tag": "NAME", "value": "Welyab Paula" } ]
null
[]
/* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.welyab.margelet; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.CloseableHttpClient; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.welyab.margelet.gson.GsonFactory; import com.welyab.margelet.http.HttpClientPool; import com.welyab.margelet.types.Response; /** * A representation of an Telegram Bot API method. This class performs HTTP * requests and JSON processing. * * @author <NAME> */ public class TelegramMethod { /** * The name of the method to be called in Telegram service. */ private final String methodName; /** * The expected type as result of calling the Telegram method. This result * is always wrapped into a <code>Response</code> object. So, the actual * returned type from Telegram service will be * <code>Response&lt;type&gt;</code>. That type is marked in * {@link #responseType} field. */ private final Type type; /** * The Telegram Bot API auth token. */ private final String apiToken; /** * The target URL. This value is composite by API auth token and the method * name. */ private final String targetUrl; /** * The actual result type for Telegram method calling. All Telegram methods * that return JSON documents as its results are mapped as * <code>Response</code> object. The underlying result for an specific * method name is placed as the <code>"result"</code> in the * <code>Response</code> object. So, this field holds something like * <code>Response&lt;type&gt;</code>. * * @see #type * @see Response */ private final Type responseType; /** * Creates a new <code>TelegramMethod</code> representation. * * <p> * This method is thread safe. * * @param methodName The name of the method to be called in Telegram * service. * @param type The expected type as result of calling the Telegram method. * This result is always wrapped into a <code>Response</code> * object. So, the actual returned type from Telegram service * will be <code>Response&lt;type&gt;</code>. That type is marked * in {@link #responseType} field. * @param apiToken The API token to access Telegram services. */ public TelegramMethod(String methodName, Type type, String apiToken) { Preconditions.checkNotNull(methodName, "Parameter 'methodName' cannot be null"); Preconditions.checkNotNull(type, "Parameter 'type' cannot be null"); Preconditions.checkNotNull(apiToken, "Parameter 'apiToken' cannot be null"); this.methodName = methodName; this.type = type; this.apiToken = apiToken; this.targetUrl = createTargetUrl(methodName, apiToken); this.responseType = TypeToken.getParameterized(Response.class, type).getType(); } /** * Calls a Telegram method with given configuration. * * @param configuration The configuration. * * @return The method result. * * <p> * Telegram method responses are a JSON document in the format of an * <code>Response</code> object. The actual result of an Telegram * method calling is placed in the <code>"result"</code> field. */ public Response<?> call(Configuration configuration) { return call(ImmutableMap.of(), configuration); } /** * Calls a Telegram method with given parameters and configuration. * * @param parameters Parameters expected by Telegram method. This object * will be encoded as JSON document and delivered in HTTP request * boby. * * <p> * If the parameter is a instance of a <code>java.util.Map</code> * and is empty, it will be ignored. * * @param configuration The configuration. * * @return The method result. * * <p> * Telegram method responses are a JSON document in the format of an * <code>Response</code> object. The actual result of an Telegram * method calling is placed in the <code>"result"</code> field. */ public Response<?> call( ImmutableMap<String, Object> parameters, Configuration configuration ) { Preconditions.checkNotNull(parameters, "Parameter 'parameters' cannot be null"); Preconditions.checkNotNull(configuration, "Parameter 'configuration' cannot be null"); return call((Object) parameters, configuration); } /** * Calls a Telegram method with given parameters and configuration. * * @param parameters Parameters expected by Telegram method. This object * will be encoded as JSON document and delivered in HTTP request * boby. * * <p> * If the parameter is a instance of a <code>java.util.Map</code> * and is empty, it will be ignored. * * @param configuration The configuration. * * @return The method result. * * <p> * Telegram method responses are a JSON document in the format of an * <code>Response</code> object. The actual result of an Telegram * method calling is placed in the <code>"result"</code> field. */ public Response<?> call(Object parameters, Configuration configuration) { Preconditions.checkNotNull(parameters, "Parameter 'parameters' cannot be null"); Preconditions.checkNotNull(configuration, "Parameter 'configuration' cannot be null"); Gson gson = GsonFactory.create(configuration); HttpEntity parametersHttpEntity = null; if (parameters != null && !((Map<?, ?>) parameters).isEmpty()) { String jsonParameters = gson.toJson(parameters); parametersHttpEntity = new ByteArrayEntity(jsonParameters.getBytes(StandardCharsets.UTF_8)); } try (CloseableHttpClient httpClient = HttpClientPool.getClient(configuration)) { HttpPost request = new HttpPost(targetUrl); if (parametersHttpEntity != null) { request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); request.setEntity(parametersHttpEntity); } try (CloseableHttpResponse httpResponse = httpClient.execute(request)) { HttpEntity responseHttpEntity = httpResponse.getEntity(); InputStream inputStream = responseHttpEntity.getContent(); InputStreamReader reader = new InputStreamReader(inputStream); return gson.fromJson(reader, responseType); } } catch (IOException e) { throw new MargeletException("Fail during communication with Telegram services", e); } } /** * Returns the configured Telegram method name. * * @return The configured Telegram method name. */ public String getMethodName() { return methodName; } /** * Returns the underlying type. The type that will be wrapped into a * <code>Response</code> object. * * @return The type. */ public Type getType() { return type; } /** * Returns the configured API access token. * * @return The configured API access token. */ public String getApiToken() { return apiToken; } /** * Creates the API method end point. Telegram API method endpoints are fixed * URLs based on the api access token and the method name, this method * creates that URLs. * * @param methodName The method name. * @param apiToken The api access token. * * @return The URL. */ private static String createTargetUrl(String methodName, String apiToken) { return StringUtils.replaceEach( Constants.URL_API, new String[] { Constants.URL_API_PARAM_API_TOKEN, Constants.URL_API_PARAM_METHOD_NAME }, new String[] { apiToken, methodName } ); } }
8,993
0.670845
0.669736
261
33.5364
28.225752
97
false
false
0
0
0
0
0
0
0.643678
false
false
7
3b9c7b86cec5362a92e0619e22eb576cbae6a39b
22,351,009,858,819
38c1fc8881d66cdd30db9fb97ea670f9b3340fdf
/flow/src/test/java/xyz/iamray/flow/impl/getfansflow/GetFansFlowTest.java
0b7fe2ce1add4e56fdfd1d077a330392af209677
[ "Apache-2.0" ]
permissive
ScarlettRay/WeiBoManger
https://github.com/ScarlettRay/WeiBoManger
0b82b2b34d29dca094ace5608672583d43602350
08abe407ec4134b5ce51448684d0f7cc740307de
refs/heads/master
2020-12-27T15:19:20.548000
2020-07-10T14:44:30
2020-07-10T14:44:30
237,950,146
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xyz.iamray.flow.impl.getfansflow; import lombok.extern.slf4j.Slf4j; import xyz.iamray.flow.Flow; import xyz.iamray.flow.LoginUtil; import xyz.iamray.flow.RegisterCenter; import xyz.iamray.flow.TestConstant; import xyz.iamray.flow.common.SpiderPool; import xyz.iamray.weiboapi.api.ContextBuilder; import xyz.iamray.weiboapi.api.context.Context; import java.util.Arrays; import java.util.List; @Slf4j public class GetFansFlowTest { public static void main(String[] args) throws Exception { RegisterCenter.registerAll(); LoginUtil.createSession();//创建会话 GetFansFlow flow = new GetFansFlow(); List<String> groups = Arrays.asList("4480524380658668","4483270710201090","4486374369563128"); Context context = ContextBuilder.buildContext(SpiderPool.executorService); flow.put(BuildGroupsBridgeAPI.GROUPS,groups); flow.put(AddFollowingToGroupWrapperAPI.GROUP_NAME,"测试分组"); flow.put(AddFollowingToGroupWrapperAPI.GROUP_DESC,"测试分组描述"); flow.put(Flow.INIT_PARAM, TestConstant.WEIBOER); flow.put(Flow.INIT_UID,TestConstant.UID); log.info(flow.execute(context).toString()); } }
UTF-8
Java
1,204
java
GetFansFlowTest.java
Java
[]
null
[]
package xyz.iamray.flow.impl.getfansflow; import lombok.extern.slf4j.Slf4j; import xyz.iamray.flow.Flow; import xyz.iamray.flow.LoginUtil; import xyz.iamray.flow.RegisterCenter; import xyz.iamray.flow.TestConstant; import xyz.iamray.flow.common.SpiderPool; import xyz.iamray.weiboapi.api.ContextBuilder; import xyz.iamray.weiboapi.api.context.Context; import java.util.Arrays; import java.util.List; @Slf4j public class GetFansFlowTest { public static void main(String[] args) throws Exception { RegisterCenter.registerAll(); LoginUtil.createSession();//创建会话 GetFansFlow flow = new GetFansFlow(); List<String> groups = Arrays.asList("4480524380658668","4483270710201090","4486374369563128"); Context context = ContextBuilder.buildContext(SpiderPool.executorService); flow.put(BuildGroupsBridgeAPI.GROUPS,groups); flow.put(AddFollowingToGroupWrapperAPI.GROUP_NAME,"测试分组"); flow.put(AddFollowingToGroupWrapperAPI.GROUP_DESC,"测试分组描述"); flow.put(Flow.INIT_PARAM, TestConstant.WEIBOER); flow.put(Flow.INIT_UID,TestConstant.UID); log.info(flow.execute(context).toString()); } }
1,204
0.741497
0.698129
35
32.599998
26.177635
102
false
false
0
0
0
0
0
0
0.828571
false
false
7
ffa9ca524545213d63ba455a9fc98445f4e4adaf
22,351,009,862,489
720a7fcc567fab882fbee67f94860975f2555546
/strings/extra/strings-additional-examples/src/M22.java
1359c5584bf23fc3cc1bcb892bd8774a7df8226f
[]
no_license
Peddaraju/core-java-advanced
https://github.com/Peddaraju/core-java-advanced
4f4b1bdf20c9f63bdac5e8f630f2107d5b4d4755
bb0e3978450567c58c4f6cd2f4bd3e18eaf9a8f8
refs/heads/main
2023-08-07T03:33:19.105000
2021-10-03T03:42:17
2021-10-03T03:42:17
412,963,785
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class M22 { public static void main(String[] args) { String s1 = new String("Hello"); System.out.println(s1); char[] x = s1.toCharArray(); for(int i = 0; i < x.length; i++) { System.out.print(x[i] + ","); } } }
UTF-8
Java
245
java
M22.java
Java
[]
null
[]
class M22 { public static void main(String[] args) { String s1 = new String("Hello"); System.out.println(s1); char[] x = s1.toCharArray(); for(int i = 0; i < x.length; i++) { System.out.print(x[i] + ","); } } }
245
0.526531
0.502041
13
16.846153
15.416506
40
false
false
0
0
0
0
0
0
2.076923
false
false
7
41c047d1f8e83c21ee58af27b04d8b55886bebae
23,733,989,333,482
875087fce8f3d5ff617e8681a1be8bb99833f873
/Velocity/src/main/java/me/egg82/antivpn/commands/internal/CheckCommand.java
936de2db2b775e0e7e3c943a4735a01ab87218d4
[ "MIT" ]
permissive
jascotty2/AntiVPN
https://github.com/jascotty2/AntiVPN
55ca500e393b3824fd67c3aadec03eb70b044199
2b30952da7134eff7237163ed99f7f7a4136f05b
refs/heads/master
2020-08-04T09:45:59.116000
2019-10-01T13:34:58
2019-10-01T13:34:58
212,095,117
0
0
MIT
true
2019-10-01T12:51:45
2019-10-01T12:51:44
2019-08-26T16:40:32
2019-08-05T04:26:46
926
0
0
0
null
false
false
package me.egg82.antivpn.commands.internal; import com.velocitypowered.api.command.CommandSource; import java.util.Optional; import me.egg82.antivpn.APIException; import me.egg82.antivpn.VPNAPI; import me.egg82.antivpn.extended.Configuration; import me.egg82.antivpn.utils.ConfigUtil; import me.egg82.antivpn.utils.LogUtil; import net.kyori.text.TextComponent; import net.kyori.text.format.TextColor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CheckCommand implements Runnable { private final Logger logger = LoggerFactory.getLogger(getClass()); private final CommandSource source; private final String ip; private final VPNAPI api = VPNAPI.getInstance(); public CheckCommand(CommandSource source, String ip) { this.source = source; this.ip = ip; } public void run() { source.sendMessage(LogUtil.getHeading().append(TextComponent.of("Checking ").color(TextColor.YELLOW)).append(TextComponent.of(ip).color(TextColor.WHITE)).append(TextComponent.of("..").color(TextColor.YELLOW)).build()); Optional<Configuration> config = ConfigUtil.getConfig(); if (!config.isPresent()) { source.sendMessage(LogUtil.getHeading().append(TextComponent.of("Internal error").color(TextColor.DARK_RED)).build()); return; } Optional<Boolean> isVPN = Optional.empty(); if (config.get().getNode("action", "algorithm", "method").getString("cascade").equalsIgnoreCase("consensus")) { double consensus = clamp(0.0d, 1.0d, config.get().getNode("action", "algorithm", "min-consensus").getDouble(0.6d)); try { isVPN = Optional.of(api.consensus(ip) >= consensus); } catch (APIException ex) { logger.error(ex.getMessage(), ex); } } else { try { isVPN = Optional.of(api.cascade(ip)); } catch (APIException ex) { logger.error(ex.getMessage(), ex); } } if (!isVPN.isPresent()) { source.sendMessage(LogUtil.getHeading().append(TextComponent.of("Internal error").color(TextColor.DARK_RED)).build()); return; } if (isVPN.get()) { source.sendMessage(LogUtil.getHeading().append(TextComponent.of("VPN/Proxy detected").color(TextColor.DARK_RED)).build()); } else { source.sendMessage(LogUtil.getHeading().append(TextComponent.of("No VPN/Proxy detected").color(TextColor.GREEN)).build()); } } private double clamp(double min, double max, double val) { return Math.min(max, Math.max(min, val)); } }
UTF-8
Java
2,669
java
CheckCommand.java
Java
[]
null
[]
package me.egg82.antivpn.commands.internal; import com.velocitypowered.api.command.CommandSource; import java.util.Optional; import me.egg82.antivpn.APIException; import me.egg82.antivpn.VPNAPI; import me.egg82.antivpn.extended.Configuration; import me.egg82.antivpn.utils.ConfigUtil; import me.egg82.antivpn.utils.LogUtil; import net.kyori.text.TextComponent; import net.kyori.text.format.TextColor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CheckCommand implements Runnable { private final Logger logger = LoggerFactory.getLogger(getClass()); private final CommandSource source; private final String ip; private final VPNAPI api = VPNAPI.getInstance(); public CheckCommand(CommandSource source, String ip) { this.source = source; this.ip = ip; } public void run() { source.sendMessage(LogUtil.getHeading().append(TextComponent.of("Checking ").color(TextColor.YELLOW)).append(TextComponent.of(ip).color(TextColor.WHITE)).append(TextComponent.of("..").color(TextColor.YELLOW)).build()); Optional<Configuration> config = ConfigUtil.getConfig(); if (!config.isPresent()) { source.sendMessage(LogUtil.getHeading().append(TextComponent.of("Internal error").color(TextColor.DARK_RED)).build()); return; } Optional<Boolean> isVPN = Optional.empty(); if (config.get().getNode("action", "algorithm", "method").getString("cascade").equalsIgnoreCase("consensus")) { double consensus = clamp(0.0d, 1.0d, config.get().getNode("action", "algorithm", "min-consensus").getDouble(0.6d)); try { isVPN = Optional.of(api.consensus(ip) >= consensus); } catch (APIException ex) { logger.error(ex.getMessage(), ex); } } else { try { isVPN = Optional.of(api.cascade(ip)); } catch (APIException ex) { logger.error(ex.getMessage(), ex); } } if (!isVPN.isPresent()) { source.sendMessage(LogUtil.getHeading().append(TextComponent.of("Internal error").color(TextColor.DARK_RED)).build()); return; } if (isVPN.get()) { source.sendMessage(LogUtil.getHeading().append(TextComponent.of("VPN/Proxy detected").color(TextColor.DARK_RED)).build()); } else { source.sendMessage(LogUtil.getHeading().append(TextComponent.of("No VPN/Proxy detected").color(TextColor.GREEN)).build()); } } private double clamp(double min, double max, double val) { return Math.min(max, Math.max(min, val)); } }
2,669
0.65118
0.643687
66
39.439392
42.979252
226
false
false
0
0
0
0
0
0
0.69697
false
false
7
8aaa8fa68f93cbe2dd58492412086ab1bbdf066a
37,297,496,000,832
bacdf46cbdc4ccf4325c9a60062d8997786367b4
/src/phones/SmartPhone.java
6906d996ee86b9e3c746e90e1c0aa0c39143cdc7
[]
no_license
BrittanyPruneau/Inheritance_Polymorphism
https://github.com/BrittanyPruneau/Inheritance_Polymorphism
985e6f269a025c606de93aaf88f8319f0868477d
757ba100922d416e002be00b6f102587a46e25e3
refs/heads/main
2023-07-08T23:54:48.330000
2021-08-21T20:10:30
2021-08-21T20:10:30
398,647,659
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package phones; /** * @author Brittany Pruneau * * Holds information about phones and what phones can do. */ import java.util.Random; import java.util.Scanner; public class SmartPhone extends Phone { private int storage; /** * Constructor initializes the fields. * @param model Describes the model of phone. * @param dimension Holds the dimensions to a specified phone. * @param storage Holds the amount of memory in the phone. */ public SmartPhone(String model, Dimension dimension, int storage) { super(model, dimension); if(storage <1) { throw new IllegalArgumentException("Storage needs to be assigned a positive value."); } this.storage = storage; // TODO Auto-generated constructor stub } /** * Returns a smart phone making a phone call. */ @Override public String call(long number) { return "Calling " + number + " by selecting the number"; } /** * * @returns Browsing the web. */ public String browse() { return "Browsing the web"; } /** * * @returns Taking a horizontal or vertical picture. */ public String takePicture() { Random r = new Random(); return r.nextBoolean() ? "Taking a horizontal picture" : "Taking a vertical picture"; } /** * Returns the model phone, it's dimensions, and the amount of storage it has. */ @Override public String toString() { return super.toString() + " " + storage + "GB"; } }
UTF-8
Java
1,498
java
SmartPhone.java
Java
[ { "context": "package phones;\r\n/**\r\n * @author Brittany Pruneau \r\n * \r\n * Holds information about phones and what", "end": 49, "score": 0.9998601078987122, "start": 33, "tag": "NAME", "value": "Brittany Pruneau" } ]
null
[]
package phones; /** * @author <NAME> * * Holds information about phones and what phones can do. */ import java.util.Random; import java.util.Scanner; public class SmartPhone extends Phone { private int storage; /** * Constructor initializes the fields. * @param model Describes the model of phone. * @param dimension Holds the dimensions to a specified phone. * @param storage Holds the amount of memory in the phone. */ public SmartPhone(String model, Dimension dimension, int storage) { super(model, dimension); if(storage <1) { throw new IllegalArgumentException("Storage needs to be assigned a positive value."); } this.storage = storage; // TODO Auto-generated constructor stub } /** * Returns a smart phone making a phone call. */ @Override public String call(long number) { return "Calling " + number + " by selecting the number"; } /** * * @returns Browsing the web. */ public String browse() { return "Browsing the web"; } /** * * @returns Taking a horizontal or vertical picture. */ public String takePicture() { Random r = new Random(); return r.nextBoolean() ? "Taking a horizontal picture" : "Taking a vertical picture"; } /** * Returns the model phone, it's dimensions, and the amount of storage it has. */ @Override public String toString() { return super.toString() + " " + storage + "GB"; } }
1,488
0.638852
0.638184
65
21.046154
23.867216
88
false
false
0
0
0
0
0
0
1.353846
false
false
7
bd3a137aafe2bca50d6a49e83c969f255bc0720f
3,650,722,259,959
b3f955f5b00e9d97e70f2399186b24a36e783bf6
/HotelManagement/src/main/java/com/wap/controller/GuestController.java
a28a232a14bba01054ed9ecdf8ff2620dbad9323
[]
no_license
wd4444/AugWAP_Project
https://github.com/wd4444/AugWAP_Project
5ce10d064bfb6f5d81b4edbbc18a591d129718a7
94a0bc81728bc58bf14c8d605781f030c9956969
refs/heads/master
2022-05-29T02:23:52.116000
2019-08-19T01:03:54
2019-08-19T01:03:54
200,966,237
0
0
null
false
2022-05-20T21:05:58
2019-08-07T03:37:12
2019-08-19T01:04:04
2022-05-20T21:05:58
9,142
0
0
1
Java
false
false
package com.wap.controller; import com.google.gson.Gson; import com.wap.dao.GuestDao; import com.wap.model.Guest; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class GuestController extends HttpServlet { private GuestDao dao; private String contactUs; private Gson gson = new Gson(); @Override public void init() throws ServletException { dao = new GuestDao(); ServletContext sc = this.getServletContext(); this.contactUs = sc.getInitParameter("hotel-contact"); } // the service method doGet will accept the HttpServletRequest and HttpServlet Response /** * @param request the request from the client * @param response the response send to back to client * @throws ServletException * @throws IOException */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * @param request the response * @param response * @throws ServletException * @throws IOException */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String jsonString = request.getParameter("guest"); Guest guest = gson.fromJson(jsonString, Guest.class);// changes the josn 'guest' to object guest. // setAttribute to global getServletContext request.getServletContext().setAttribute("aGuest", guest); request.getServletContext().setAttribute("contactUs", contactUs);// not necessary // adding guest to dao if(request.getServletContext().getAttribute("guestDAO") != null) { dao = (GuestDao) request.getServletContext().getAttribute("guestDAO"); } dao.addGuest(guest); request.getServletContext().setAttribute("guestDAO", dao); // return to js PrintWriter out = response.getWriter(); out.print(gson.toJson(guest)); } }
UTF-8
Java
2,288
java
GuestController.java
Java
[]
null
[]
package com.wap.controller; import com.google.gson.Gson; import com.wap.dao.GuestDao; import com.wap.model.Guest; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class GuestController extends HttpServlet { private GuestDao dao; private String contactUs; private Gson gson = new Gson(); @Override public void init() throws ServletException { dao = new GuestDao(); ServletContext sc = this.getServletContext(); this.contactUs = sc.getInitParameter("hotel-contact"); } // the service method doGet will accept the HttpServletRequest and HttpServlet Response /** * @param request the request from the client * @param response the response send to back to client * @throws ServletException * @throws IOException */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * @param request the response * @param response * @throws ServletException * @throws IOException */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String jsonString = request.getParameter("guest"); Guest guest = gson.fromJson(jsonString, Guest.class);// changes the josn 'guest' to object guest. // setAttribute to global getServletContext request.getServletContext().setAttribute("aGuest", guest); request.getServletContext().setAttribute("contactUs", contactUs);// not necessary // adding guest to dao if(request.getServletContext().getAttribute("guestDAO") != null) { dao = (GuestDao) request.getServletContext().getAttribute("guestDAO"); } dao.addGuest(guest); request.getServletContext().setAttribute("guestDAO", dao); // return to js PrintWriter out = response.getWriter(); out.print(gson.toJson(guest)); } }
2,288
0.675262
0.675262
67
32.119404
26.742846
105
false
false
0
0
0
0
0
0
0.507463
false
false
7
49897cff86d89ce8aee33a5098bf00ad27d0742e
38,491,496,917,335
70a996a804adbc5692c70412197a9b8ae3f65047
/src/main/java/controladores/ControladorInformes.java
9467fddfa35b5986bacbb5a13842d6db89eadb65
[]
no_license
Yisusad/sistema-kinesio
https://github.com/Yisusad/sistema-kinesio
adeb5e24b67fc4701c5a5411992930ef4aa47a9d
d3840882a40a434fa9dc8f0a681ff6b136602851
refs/heads/master
2023-02-09T00:41:44.661000
2021-01-06T20:49:28
2021-01-06T20:49:28
327,429,675
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 controladores; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.engine.JasperRunManager; import servicios.BasedeDatos; import servicios.ServicioAlumno; import servicios.ServicioFicha; import servicios.ServicioPatologia; /** * * @author Fabi Garcia */ @WebServlet(name = "ControladorInformes", urlPatterns = {"/ControladorInformes"}) public class ControladorInformes extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet ControladorInforme</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet ControladorInforme at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Date dateDesde = new java.util.Date(); Date dateHasta = new java.util.Date(); dateDesde.setDate(1); java.text.DateFormat formato = new java.text.SimpleDateFormat("yyyy-MM-dd"); Date finicio = new Date(); finicio = new Date(finicio.getYear(), finicio.getMonth(), 1); request.setAttribute("desde", formato.format(finicio)); request.setAttribute("hasta", formato.format(new Date())); String accion = request.getParameter("accion"); String forward = "index.jsp?page="+accion; request.setAttribute("alumnos", ServicioAlumno.listar()); request.setAttribute("fichas", ServicioFicha.listar()); request.setAttribute("patologias", ServicioPatologia.listar()); if (accion.equals("fichakinesica")){ try { Connection con = null; con = BasedeDatos.getConnection(); ServletOutputStream output = response.getOutputStream(); File reportFile = null; String idDerivacion = request.getParameter("idDerivacion"); Map<String, Object> param = new HashMap<String, Object>(); param.put("IdDerivacion", Integer.valueOf(idDerivacion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/FichaKinesica.jasper")); byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), param, con); response.setContentType("application/pdf"); response.setContentLength(bytes.length); output.write(bytes, 0, bytes.length); output.flush(); output.close(); } catch (Exception ex) { ex.printStackTrace(); } }else if (accion.equals("ordenderivacion")){ try { Connection con = null; con = BasedeDatos.getConnection(); ServletOutputStream output = response.getOutputStream(); File reportFile = null; String idDerivacion = request.getParameter("idDerivacion"); Map<String, Object> param = new HashMap<String, Object>(); param.put("IdDerivacion", Integer.valueOf(idDerivacion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/OrdenPagoF.jasper")); byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), param, con); response.setContentType("application/pdf"); response.setContentLength(bytes.length); output.write(bytes, 0, bytes.length); output.flush(); output.close(); } catch (Exception ex) { ex.printStackTrace(); } }else if (accion.equals("ordenevolucion")){ try { Connection con = null; con = BasedeDatos.getConnection(); ServletOutputStream output = response.getOutputStream(); File reportFile = null; String idEvolucion = request.getParameter("idEvolucion"); Map<String, Object> param = new HashMap<String, Object>(); param.put("IdEvolucion", Integer.valueOf(idEvolucion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/OrdenPagoE.jasper")); byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), param, con); response.setContentType("application/pdf"); response.setContentLength(bytes.length); output.write(bytes, 0, bytes.length); output.flush(); output.close(); } catch (Exception ex) { ex.printStackTrace(); } }else if (accion.equals("fichapacientes")){ try { Connection con = null; con = BasedeDatos.getConnection(); ServletOutputStream output = response.getOutputStream(); File reportFile = null; String idFicha = request.getParameter("idFicha"); Map<String, Object> param = new HashMap<String, Object>(); param.put("IdFicha", Integer.valueOf(idFicha)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/OrdenPagoE.jasper")); byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), param, con); response.setContentType("application/pdf"); response.setContentLength(bytes.length); output.write(bytes, 0, bytes.length); output.flush(); output.close(); } catch (Exception ex) { ex.printStackTrace(); } }else{ RequestDispatcher view = request.getRequestDispatcher(forward); view.forward(request, response); } } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); Connection con = null; con = BasedeDatos.getConnection(); ServletOutputStream output = response.getOutputStream(); File reportFile = null; String inf = request.getParameter("informe"); String todos = request.getParameter("todos"); String idAlumno = request.getParameter("alumnos"); String idDerivacion = request.getParameter("idDerivacion"); Date desde = null; Date hasta = null; Map<String, Object> param = new HashMap<String, Object>(); param.put("idDerivacion", idDerivacion); SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd"); try { desde = formato.parse(request.getParameter("desde")); hasta = formato.parse(request.getParameter("hasta")); param.put("desde", desde); param.put("hasta", hasta); Integer.valueOf(idAlumno); } catch (Exception ex) { ex.printStackTrace(); } if (inf.equals("ingreso")) { if (todos == null) { param.put("idAlumno", Integer.valueOf(idAlumno)); } reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/InformeIngreso.jasper")); } else if (inf.endsWith("historialpaciente")) { reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/HistorialPaciente.jasper")); } else if (inf.equals("antecedentes")) { reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/AntecedentesPaciente.jasper")); } else if (inf.equals("estados")) { reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/EstadosPaciente.jasper")); } else if (inf.equals("estudios")) { reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/EstudiosPaciente.jasper")); } else if (inf.equals("evoluciones")) { reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/EvolucionesPaciente.jasper")); } else if (inf.equals("reportealumnos")){ param.put("idAlumno", Integer.valueOf(idAlumno)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/ReporteDerivacionesPorAlumno.jasper")); }else if (inf.equals("fichakinesica")){ param.put("idDerivacion", Integer.valueOf(idDerivacion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/FichaKinesica.jasper")); }else if (inf.equals("ordenderivacion")){ try { param.put("IdDerivacion", Integer.valueOf(idDerivacion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/OrdenPagoF.jasper")); } catch (Exception ex) { ex.printStackTrace(); } }else if (inf.equals("ordenevolucion")){ try { String idEvolucion = request.getParameter("idEvolucion"); param.put("IdEvolucion", Integer.valueOf(idEvolucion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/OrdenPagoE.jasper")); } catch (Exception ex) { ex.printStackTrace(); } } try { byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), param, con); response.setContentType("application/pdf"); response.setContentLength(bytes.length); output.write(bytes, 0, bytes.length); output.flush(); output.close(); } catch (Exception ex) { ex.printStackTrace(); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
UTF-8
Java
12,314
java
ControladorInformes.java
Java
[ { "context": "t servicios.ServicioPatologia;\n\n\n/**\n *\n * @author Fabi Garcia\n */\n@WebServlet(name = \"ControladorInformes\", url", "end": 934, "score": 0.9997968673706055, "start": 923, "tag": "NAME", "value": "Fabi Garcia" } ]
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 controladores; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.engine.JasperRunManager; import servicios.BasedeDatos; import servicios.ServicioAlumno; import servicios.ServicioFicha; import servicios.ServicioPatologia; /** * * @author <NAME> */ @WebServlet(name = "ControladorInformes", urlPatterns = {"/ControladorInformes"}) public class ControladorInformes extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet ControladorInforme</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet ControladorInforme at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Date dateDesde = new java.util.Date(); Date dateHasta = new java.util.Date(); dateDesde.setDate(1); java.text.DateFormat formato = new java.text.SimpleDateFormat("yyyy-MM-dd"); Date finicio = new Date(); finicio = new Date(finicio.getYear(), finicio.getMonth(), 1); request.setAttribute("desde", formato.format(finicio)); request.setAttribute("hasta", formato.format(new Date())); String accion = request.getParameter("accion"); String forward = "index.jsp?page="+accion; request.setAttribute("alumnos", ServicioAlumno.listar()); request.setAttribute("fichas", ServicioFicha.listar()); request.setAttribute("patologias", ServicioPatologia.listar()); if (accion.equals("fichakinesica")){ try { Connection con = null; con = BasedeDatos.getConnection(); ServletOutputStream output = response.getOutputStream(); File reportFile = null; String idDerivacion = request.getParameter("idDerivacion"); Map<String, Object> param = new HashMap<String, Object>(); param.put("IdDerivacion", Integer.valueOf(idDerivacion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/FichaKinesica.jasper")); byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), param, con); response.setContentType("application/pdf"); response.setContentLength(bytes.length); output.write(bytes, 0, bytes.length); output.flush(); output.close(); } catch (Exception ex) { ex.printStackTrace(); } }else if (accion.equals("ordenderivacion")){ try { Connection con = null; con = BasedeDatos.getConnection(); ServletOutputStream output = response.getOutputStream(); File reportFile = null; String idDerivacion = request.getParameter("idDerivacion"); Map<String, Object> param = new HashMap<String, Object>(); param.put("IdDerivacion", Integer.valueOf(idDerivacion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/OrdenPagoF.jasper")); byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), param, con); response.setContentType("application/pdf"); response.setContentLength(bytes.length); output.write(bytes, 0, bytes.length); output.flush(); output.close(); } catch (Exception ex) { ex.printStackTrace(); } }else if (accion.equals("ordenevolucion")){ try { Connection con = null; con = BasedeDatos.getConnection(); ServletOutputStream output = response.getOutputStream(); File reportFile = null; String idEvolucion = request.getParameter("idEvolucion"); Map<String, Object> param = new HashMap<String, Object>(); param.put("IdEvolucion", Integer.valueOf(idEvolucion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/OrdenPagoE.jasper")); byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), param, con); response.setContentType("application/pdf"); response.setContentLength(bytes.length); output.write(bytes, 0, bytes.length); output.flush(); output.close(); } catch (Exception ex) { ex.printStackTrace(); } }else if (accion.equals("fichapacientes")){ try { Connection con = null; con = BasedeDatos.getConnection(); ServletOutputStream output = response.getOutputStream(); File reportFile = null; String idFicha = request.getParameter("idFicha"); Map<String, Object> param = new HashMap<String, Object>(); param.put("IdFicha", Integer.valueOf(idFicha)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/OrdenPagoE.jasper")); byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), param, con); response.setContentType("application/pdf"); response.setContentLength(bytes.length); output.write(bytes, 0, bytes.length); output.flush(); output.close(); } catch (Exception ex) { ex.printStackTrace(); } }else{ RequestDispatcher view = request.getRequestDispatcher(forward); view.forward(request, response); } } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); Connection con = null; con = BasedeDatos.getConnection(); ServletOutputStream output = response.getOutputStream(); File reportFile = null; String inf = request.getParameter("informe"); String todos = request.getParameter("todos"); String idAlumno = request.getParameter("alumnos"); String idDerivacion = request.getParameter("idDerivacion"); Date desde = null; Date hasta = null; Map<String, Object> param = new HashMap<String, Object>(); param.put("idDerivacion", idDerivacion); SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd"); try { desde = formato.parse(request.getParameter("desde")); hasta = formato.parse(request.getParameter("hasta")); param.put("desde", desde); param.put("hasta", hasta); Integer.valueOf(idAlumno); } catch (Exception ex) { ex.printStackTrace(); } if (inf.equals("ingreso")) { if (todos == null) { param.put("idAlumno", Integer.valueOf(idAlumno)); } reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/InformeIngreso.jasper")); } else if (inf.endsWith("historialpaciente")) { reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/HistorialPaciente.jasper")); } else if (inf.equals("antecedentes")) { reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/AntecedentesPaciente.jasper")); } else if (inf.equals("estados")) { reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/EstadosPaciente.jasper")); } else if (inf.equals("estudios")) { reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/EstudiosPaciente.jasper")); } else if (inf.equals("evoluciones")) { reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/EvolucionesPaciente.jasper")); } else if (inf.equals("reportealumnos")){ param.put("idAlumno", Integer.valueOf(idAlumno)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/ReporteDerivacionesPorAlumno.jasper")); }else if (inf.equals("fichakinesica")){ param.put("idDerivacion", Integer.valueOf(idDerivacion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/FichaKinesica.jasper")); }else if (inf.equals("ordenderivacion")){ try { param.put("IdDerivacion", Integer.valueOf(idDerivacion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/OrdenPagoF.jasper")); } catch (Exception ex) { ex.printStackTrace(); } }else if (inf.equals("ordenevolucion")){ try { String idEvolucion = request.getParameter("idEvolucion"); param.put("IdEvolucion", Integer.valueOf(idEvolucion)); reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/OrdenPagoE.jasper")); } catch (Exception ex) { ex.printStackTrace(); } } try { byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), param, con); response.setContentType("application/pdf"); response.setContentLength(bytes.length); output.write(bytes, 0, bytes.length); output.flush(); output.close(); } catch (Exception ex) { ex.printStackTrace(); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
12,309
0.614341
0.613448
270
44.607407
30.085457
134
false
false
0
0
0
0
0
0
0.788889
false
false
7
383dd909dca19955091927c26005c52783c405e8
36,318,243,480,603
37a4579ab3b88f07e2f9672b6d60c2cc19b8784f
/JCH/src/main/java/pages/AllJournals.java
e5219892527832ff4630cda286d4b03f2643fbb4
[]
no_license
rncyjsph/New
https://github.com/rncyjsph/New
219a5bd6d1a81bf92ef4da8f4e31f0a77013f8ed
27da4331507f47992692a272432703f164fc4152
refs/heads/master
2020-12-27T12:20:09.687000
2020-02-03T06:44:56
2020-02-03T06:44:56
237,893,991
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pages; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import util.BaseClass; public class AllJournals extends BaseClass{ @FindBy(xpath="//p[@class='ng-binding']") WebElement journalpgtext; @FindBy(xpath="//div[@id=\"Action\"]//span[@class='jch-dropdown-iconset']") WebElement dropdown; @FindBy(xpath="//label[contains(text(),'Favorites')]") WebElement favorites; @FindBy(xpath="//tr[@id='jqry845']//i[@class='icon-jch-star jch-favourite-icon active ng-scope']") WebElement favorite_star; public AllJournals() { PageFactory.initElements(driver, this); } public boolean display_journal_text() { return journalpgtext.isDisplayed(); } public void select_favorite_queries() { JavascriptExecutor d=(JavascriptExecutor)driver; d.executeScript("arguments[0].click()", dropdown); WebDriverWait wait=new WebDriverWait(driver, 50); wait.until((ExpectedConditions.elementToBeClickable(favorites))); JavascriptExecutor f=(JavascriptExecutor)driver; f.executeScript("arguments[0].click()", favorites); if (favorites.isDisplayed()) { Actions action=new Actions(driver); action.click().perform(); } } public boolean display_favorite_star() { return favorite_star.isDisplayed(); } }
UTF-8
Java
1,653
java
AllJournals.java
Java
[ { "context": "bElement favorites;\r\n\t\r\n\t@FindBy(xpath=\"//tr[@id='jqry845']//i[@class='icon-jch-star jch-favourite-icon act", "end": 775, "score": 0.9767818450927734, "start": 768, "tag": "USERNAME", "value": "jqry845" } ]
null
[]
package pages; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import util.BaseClass; public class AllJournals extends BaseClass{ @FindBy(xpath="//p[@class='ng-binding']") WebElement journalpgtext; @FindBy(xpath="//div[@id=\"Action\"]//span[@class='jch-dropdown-iconset']") WebElement dropdown; @FindBy(xpath="//label[contains(text(),'Favorites')]") WebElement favorites; @FindBy(xpath="//tr[@id='jqry845']//i[@class='icon-jch-star jch-favourite-icon active ng-scope']") WebElement favorite_star; public AllJournals() { PageFactory.initElements(driver, this); } public boolean display_journal_text() { return journalpgtext.isDisplayed(); } public void select_favorite_queries() { JavascriptExecutor d=(JavascriptExecutor)driver; d.executeScript("arguments[0].click()", dropdown); WebDriverWait wait=new WebDriverWait(driver, 50); wait.until((ExpectedConditions.elementToBeClickable(favorites))); JavascriptExecutor f=(JavascriptExecutor)driver; f.executeScript("arguments[0].click()", favorites); if (favorites.isDisplayed()) { Actions action=new Actions(driver); action.click().perform(); } } public boolean display_favorite_star() { return favorite_star.isDisplayed(); } }
1,653
0.710224
0.705989
65
23.430769
23.7169
99
false
false
0
0
0
0
0
0
1.415385
false
false
7
82649b94b7cd228f342f1e8d0d29626d7c88526c
1,254,130,490,718
f490501fc310d8267c8580aca218d2c41f66fb97
/src/test/java/CategoryTest.java
6262f15e3086757e69f230a58423da45f8b04984
[ "MIT" ]
permissive
johnmbklein/library
https://github.com/johnmbklein/library
a66b9b7bc6580c08db86347098c3b2e090f53e7e
2ac972601288f73450f32dca011906c955e1956e
refs/heads/master
2019-01-21T05:37:19.473000
2016-05-10T23:31:51
2016-05-10T23:31:51
58,475,465
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.sql2o.*; import org.junit.*; import static org.junit.Assert.*; import java.util.Arrays; public class CategoryTest { @Rule public DatabaseRule database = new DatabaseRule(); @Test public void CategoryTest_instantiatesCorrectly_true() { Category testCategory = new Category("Fiction"); assertTrue(testCategory instanceof Category); } @Test public void getName_returnsName_string() { Category testCategory = new Category("Fiction"); assertEquals("Fiction", testCategory.getName()); } @Test public void all_emptyAtFirst_true() { assertEquals(0, Category.all().size()); } @Test public void all_returnsAllCategories_list() { Category testCategory = new Category("Fiction"); testCategory.save(); assertTrue(testCategory.equals(Category.all().get(0))); } @Test public void equals_returnsTrueIfNamesAreSame_true() { Category firstCategory = new Category("Fiction"); Category secondCategory = new Category("Fiction"); assertTrue(firstCategory.equals(secondCategory)); } @Test public void save_assignIdtoObject() { Category testCategory = new Category("Fiction"); testCategory.save(); Category savedCategory = Category.all().get(0); assertEquals(savedCategory, testCategory); } @Test public void find_findCategoryInDatabase_true() { Category testCategory = new Category("Fiction"); testCategory.save(); Category savedCategory = Category.find(testCategory.getId()); assertTrue(testCategory.equals(savedCategory)); } @Test public void update_updateCategoryName_true() { Category testCategory = new Category("Fiction"); testCategory.save(); testCategory.update("Non-Fiction"); assertEquals("Non-Fiction", Category.find(testCategory.getId()).getName()); } @Test public void delete_deleteCategory_true() { Category testCategory = new Category("Fiction"); testCategory.save(); testCategory.delete(); assertEquals(0, Category.all().size()); } @Test public void getBooks_returnsAllBooks_list() { Category myCategory = new Category("Fiction"); myCategory.save(); Book firstBook = new Book("Little Prince", myCategory.getId()); firstBook.save(); Book secondBook = new Book("Bigger Prince", myCategory.getId()); secondBook.save(); Book[] books = new Book[] {firstBook, secondBook}; // System.out.println(myCategory.getBooks().get(0).getTitle()); assertEquals(2, myCategory.getBooks().size()); // assertTrue(myCategory.getBooks().containsAll(Arrays.asList(books))); } }
UTF-8
Java
2,585
java
CategoryTest.java
Java
[]
null
[]
import org.sql2o.*; import org.junit.*; import static org.junit.Assert.*; import java.util.Arrays; public class CategoryTest { @Rule public DatabaseRule database = new DatabaseRule(); @Test public void CategoryTest_instantiatesCorrectly_true() { Category testCategory = new Category("Fiction"); assertTrue(testCategory instanceof Category); } @Test public void getName_returnsName_string() { Category testCategory = new Category("Fiction"); assertEquals("Fiction", testCategory.getName()); } @Test public void all_emptyAtFirst_true() { assertEquals(0, Category.all().size()); } @Test public void all_returnsAllCategories_list() { Category testCategory = new Category("Fiction"); testCategory.save(); assertTrue(testCategory.equals(Category.all().get(0))); } @Test public void equals_returnsTrueIfNamesAreSame_true() { Category firstCategory = new Category("Fiction"); Category secondCategory = new Category("Fiction"); assertTrue(firstCategory.equals(secondCategory)); } @Test public void save_assignIdtoObject() { Category testCategory = new Category("Fiction"); testCategory.save(); Category savedCategory = Category.all().get(0); assertEquals(savedCategory, testCategory); } @Test public void find_findCategoryInDatabase_true() { Category testCategory = new Category("Fiction"); testCategory.save(); Category savedCategory = Category.find(testCategory.getId()); assertTrue(testCategory.equals(savedCategory)); } @Test public void update_updateCategoryName_true() { Category testCategory = new Category("Fiction"); testCategory.save(); testCategory.update("Non-Fiction"); assertEquals("Non-Fiction", Category.find(testCategory.getId()).getName()); } @Test public void delete_deleteCategory_true() { Category testCategory = new Category("Fiction"); testCategory.save(); testCategory.delete(); assertEquals(0, Category.all().size()); } @Test public void getBooks_returnsAllBooks_list() { Category myCategory = new Category("Fiction"); myCategory.save(); Book firstBook = new Book("Little Prince", myCategory.getId()); firstBook.save(); Book secondBook = new Book("Bigger Prince", myCategory.getId()); secondBook.save(); Book[] books = new Book[] {firstBook, secondBook}; // System.out.println(myCategory.getBooks().get(0).getTitle()); assertEquals(2, myCategory.getBooks().size()); // assertTrue(myCategory.getBooks().containsAll(Arrays.asList(books))); } }
2,585
0.700193
0.697486
90
27.722221
23.770208
79
false
false
0
0
0
0
0
0
0.566667
false
false
7
66fa929230f25be8aa270312f64484e93ab6fd69
9,809,705,343,694
f02970fe3eab51557ae665fcab420d720ef0a9c8
/src/RectangleFactory.java
165e628cd1665474c86c44054712ca32631ee553
[]
no_license
FOF-TM/-
https://github.com/FOF-TM/-
22f581d8903526125239b23e4ecb119c346f6e5f
feda8fc8aba22ded19bec8cbca29989d60e544b1
refs/heads/main
2023-01-23T04:22:37.800000
2020-11-30T07:26:48
2020-11-30T07:26:48
314,199,962
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Color; public class RectangleFactory implements GraphFactory { private RectangleFactory() {} private static GraphFactory instance = new RectangleFactory(); public static GraphFactory getInstance() { return instance; } @Override public Graph genGraph(int x1, int y1, int x2, int y2, Color color, MouseState s) { if (s == MouseState.Dragged) Drawer.undo(true); return new Rectangle(x1, y1, x2, y2, color); } }
UTF-8
Java
459
java
RectangleFactory.java
Java
[]
null
[]
import java.awt.Color; public class RectangleFactory implements GraphFactory { private RectangleFactory() {} private static GraphFactory instance = new RectangleFactory(); public static GraphFactory getInstance() { return instance; } @Override public Graph genGraph(int x1, int y1, int x2, int y2, Color color, MouseState s) { if (s == MouseState.Dragged) Drawer.undo(true); return new Rectangle(x1, y1, x2, y2, color); } }
459
0.705882
0.688453
18
24.5
26.0411
84
false
false
0
0
0
0
0
0
0.777778
false
false
7
4a0825ea8d19edd35bd2a270440b89f5b6c9b562
16,423,954,974,425
ccf82688f082e26cba5fc397c76c77cc007ab2e8
/Mage.Tests/src/test/java/org/mage/test/AI/basic/CopyAITest.java
061c89e8cb78a24c486637cc15fd25ac1ad943cb
[ "MIT" ]
permissive
magefree/mage
https://github.com/magefree/mage
3261a89320f586d698dd03ca759a7562829f247f
5dba61244c738f4a184af0d256046312ce21d911
refs/heads/master
2023-09-03T15:55:36.650000
2023-09-03T03:53:12
2023-09-03T03:53:12
4,158,448
1,803
1,133
MIT
false
2023-09-14T20:18:55
2012-04-27T13:18:34
2023-09-11T18:25:38
2023-09-14T20:18:55
801,396
1,632
712
1,307
Java
false
false
package org.mage.test.AI.basic; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBaseWithAIHelps; /** * @author JayDi85 */ public class CopyAITest extends CardTestPlayerBaseWithAIHelps { // AI makes decisions by two different modes: // 1. Simulation: If it searching playable spells then it play it in FULL SIMULATION (abilities + all possible targets) // 2. Response: If it searching response on dialog then it use simple target search (without simulation) @Test public void test_CloneChoose_Manual() { // You may have Clone enter the battlefield as a copy of any creature on the battlefield. addCard(Zone.HAND, playerA, "Clone", 1); // {3}{U} addCard(Zone.BATTLEFIELD, playerA, "Island", 4); // addCard(Zone.BATTLEFIELD, playerA, "Arbor Elf", 1); // 1/1 addCard(Zone.BATTLEFIELD, playerB, "Balduvian Bears", 1); // 2/2 addCard(Zone.BATTLEFIELD, playerB, "Spectral Bears", 1); // 3/3 // clone castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Clone"); setChoice(playerA, true); setChoice(playerA, "Spectral Bears"); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertPermanentCount(playerB, "Spectral Bears", 1); } @Test public void test_CloneChoose_AI_Simulation_MostValueableFromOwn() { // You may have Clone enter the battlefield as a copy of any creature on the battlefield. addCard(Zone.HAND, playerA, "Clone", 1); // {3}{U} addCard(Zone.BATTLEFIELD, playerA, "Island", 4); // addCard(Zone.BATTLEFIELD, playerA, "Arbor Elf", 1); // 1/1 addCard(Zone.BATTLEFIELD, playerA, "Spectral Bears", 1); // 3/3 // addCard(Zone.BATTLEFIELD, playerB, "Balduvian Bears", 1); // 2/2 // clone (AI must choose most valueable permanent - own) aiPlayPriority(1, PhaseStep.PRECOMBAT_MAIN, playerA); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 2); assertPermanentCount(playerB, "Spectral Bears", 0); } @Test public void test_CloneChoose_AI_Simulation_MostValueableFromOpponent() { // You may have Clone enter the battlefield as a copy of any creature on the battlefield. addCard(Zone.HAND, playerA, "Clone", 1); // {3}{U} addCard(Zone.BATTLEFIELD, playerA, "Island", 4); // addCard(Zone.BATTLEFIELD, playerA, "Arbor Elf", 1); // 1/1 // addCard(Zone.BATTLEFIELD, playerB, "Balduvian Bears", 1); // 2/2 addCard(Zone.BATTLEFIELD, playerB, "Spectral Bears", 1); // 3/3 // clone (AI must choose most valueable permanent - opponent) aiPlayPriority(1, PhaseStep.PRECOMBAT_MAIN, playerA); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertPermanentCount(playerB, "Spectral Bears", 1); } @Test public void test_CopyTarget_Manual() { // Exile target creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it has this ability. addCard(Zone.BATTLEFIELD, playerA, "Dimir Doppelganger", 1); // {1}{U}{B} addCard(Zone.BATTLEFIELD, playerA, "Island", 2); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); // addCard(Zone.GRAVEYARD, playerA, "Arbor Elf", 1); // 1/1 addCard(Zone.GRAVEYARD, playerB, "Balduvian Bears", 1); // 2/2 addCard(Zone.GRAVEYARD, playerB, "Spectral Bears", 1); // 3/3 // copy activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{1}{U}{B}: Exile target"); addTarget(playerA, "Spectral Bears"); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertExileCount("Spectral Bears", 1); } @Test public void test_CopyTarget_AI_Simulation_MostValueableFromOwn() { // Exile target creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it has this ability. addCard(Zone.BATTLEFIELD, playerA, "Dimir Doppelganger", 1); // {1}{U}{B} addCard(Zone.BATTLEFIELD, playerA, "Island", 2); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); // addCard(Zone.GRAVEYARD, playerA, "Arbor Elf", 1); // 1/1 addCard(Zone.GRAVEYARD, playerA, "Spectral Bears", 1); // 3/3 // addCard(Zone.GRAVEYARD, playerB, "Balduvian Bears", 1); // 2/2 // copy (AI must choose most valueable permanent - own) aiPlayPriority(1, PhaseStep.PRECOMBAT_MAIN, playerA); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertExileCount("Spectral Bears", 1); } @Test public void test_CopyTarget_AI_Simulation_MostValueableFromOpponent() { // Exile target creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it has this ability. addCard(Zone.BATTLEFIELD, playerA, "Dimir Doppelganger", 1); // {1}{U}{B} addCard(Zone.BATTLEFIELD, playerA, "Island", 2); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); // addCard(Zone.GRAVEYARD, playerA, "Arbor Elf", 1); // 1/1 // addCard(Zone.GRAVEYARD, playerB, "Balduvian Bears", 1); // 2/2 addCard(Zone.GRAVEYARD, playerB, "Spectral Bears", 1); // 3/3 // copy (AI must choose most valueable permanent - opponent) aiPlayPriority(1, PhaseStep.PRECOMBAT_MAIN, playerA); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertExileCount("Spectral Bears", 1); } @Test public void test_CopyTarget_AI_Response_MostValueableFromOwn() { // Exile target creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it has this ability. addCard(Zone.BATTLEFIELD, playerA, "Dimir Doppelganger", 1); // {1}{U}{B} addCard(Zone.BATTLEFIELD, playerA, "Island", 2); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); // addCard(Zone.GRAVEYARD, playerA, "Arbor Elf", 1); // 1/1 addCard(Zone.GRAVEYARD, playerA, "Spectral Bears", 1); // 3/3 // addCard(Zone.GRAVEYARD, playerB, "Balduvian Bears", 1); // 2/2 // copy (AI must choose most valueable permanent - own) activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{1}{U}{B}: Exile target"); //addTarget(playerA, "Spectral Bears"); // AI must choose setStopAt(1, PhaseStep.END_TURN); //setStrictChooseMode(true); // AI must choose execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertExileCount("Spectral Bears", 1); } @Test public void test_CopyTarget_AI_Response_MostValueableFromOpponent() { // Exile target creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it has this ability. addCard(Zone.BATTLEFIELD, playerA, "Dimir Doppelganger", 1); // {1}{U}{B} addCard(Zone.BATTLEFIELD, playerA, "Island", 2); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); // addCard(Zone.GRAVEYARD, playerA, "Arbor Elf", 1); // 1/1 // addCard(Zone.GRAVEYARD, playerB, "Balduvian Bears", 1); // 2/2 addCard(Zone.GRAVEYARD, playerB, "Spectral Bears", 1); // 3/3 // copy (AI must choose most valueable permanent - opponent) activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{1}{U}{B}: Exile target"); //addTarget(playerA, "Spectral Bears"); // AI must choose setStopAt(1, PhaseStep.END_TURN); //setStrictChooseMode(true); // AI must choose execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertExileCount("Spectral Bears", 1); } }
UTF-8
Java
8,325
java
CopyAITest.java
Java
[ { "context": "ase.CardTestPlayerBaseWithAIHelps;\n\n/**\n * @author JayDi85\n */\npublic class CopyAITest extends CardTestPlaye", "end": 208, "score": 0.999669075012207, "start": 201, "tag": "USERNAME", "value": "JayDi85" }, { "context": "lity.\n addCard(Zone.BATTLEFIELD, playerA, \"Dimir Doppelganger\", 1); // {1}{U}{B}\n addCard(Zone.BATTLEFIE", "end": 3465, "score": 0.9988088011741638, "start": 3447, "tag": "NAME", "value": "Dimir Doppelganger" }, { "context": " // Exile target creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it has this a", "end": 4335, "score": 0.9593492150306702, "start": 4317, "tag": "NAME", "value": "Dimir Doppelganger" }, { "context": "lity.\n addCard(Zone.BATTLEFIELD, playerA, \"Dimir Doppelganger\", 1); // {1}{U}{B}\n addCard(Zone.BATTLEFIE", "end": 4455, "score": 0.9927072525024414, "start": 4437, "tag": "NAME", "value": "Dimir Doppelganger" }, { "context": " // Exile target creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it has this a", "end": 5315, "score": 0.8993702530860901, "start": 5297, "tag": "NAME", "value": "Dimir Doppelganger" }, { "context": "lity.\n addCard(Zone.BATTLEFIELD, playerA, \"Dimir Doppelganger\", 1); // {1}{U}{B}\n addCard(Zone.BATTLEFIE", "end": 5435, "score": 0.9468899369239807, "start": 5417, "tag": "NAME", "value": "Dimir Doppelganger" }, { "context": " // Exile target creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it ha", "end": 6285, "score": 0.8107829689979553, "start": 6275, "tag": "NAME", "value": "Dimir Dopp" }, { "context": "arget creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it has this a", "end": 6293, "score": 0.6185306906700134, "start": 6287, "tag": "NAME", "value": "ganger" }, { "context": "lity.\n addCard(Zone.BATTLEFIELD, playerA, \"Dimir Doppelganger\", 1); // {1}{U}{B}\n addCard(Zone.BATTLEFIE", "end": 6413, "score": 0.9529834389686584, "start": 6395, "tag": "NAME", "value": "Dimir Doppelganger" }, { "context": " // Exile target creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it has this a", "end": 7385, "score": 0.9881421327590942, "start": 7367, "tag": "NAME", "value": "Dimir Doppelganger" }, { "context": "lity.\n addCard(Zone.BATTLEFIELD, playerA, \"Dimir Doppelganger\", 1); // {1}{U}{B}\n addCard(Zone.BATTLEFIE", "end": 7505, "score": 0.9983102679252625, "start": 7487, "tag": "NAME", "value": "Dimir Doppelganger" } ]
null
[]
package org.mage.test.AI.basic; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBaseWithAIHelps; /** * @author JayDi85 */ public class CopyAITest extends CardTestPlayerBaseWithAIHelps { // AI makes decisions by two different modes: // 1. Simulation: If it searching playable spells then it play it in FULL SIMULATION (abilities + all possible targets) // 2. Response: If it searching response on dialog then it use simple target search (without simulation) @Test public void test_CloneChoose_Manual() { // You may have Clone enter the battlefield as a copy of any creature on the battlefield. addCard(Zone.HAND, playerA, "Clone", 1); // {3}{U} addCard(Zone.BATTLEFIELD, playerA, "Island", 4); // addCard(Zone.BATTLEFIELD, playerA, "Arbor Elf", 1); // 1/1 addCard(Zone.BATTLEFIELD, playerB, "Balduvian Bears", 1); // 2/2 addCard(Zone.BATTLEFIELD, playerB, "Spectral Bears", 1); // 3/3 // clone castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Clone"); setChoice(playerA, true); setChoice(playerA, "Spectral Bears"); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertPermanentCount(playerB, "Spectral Bears", 1); } @Test public void test_CloneChoose_AI_Simulation_MostValueableFromOwn() { // You may have Clone enter the battlefield as a copy of any creature on the battlefield. addCard(Zone.HAND, playerA, "Clone", 1); // {3}{U} addCard(Zone.BATTLEFIELD, playerA, "Island", 4); // addCard(Zone.BATTLEFIELD, playerA, "Arbor Elf", 1); // 1/1 addCard(Zone.BATTLEFIELD, playerA, "Spectral Bears", 1); // 3/3 // addCard(Zone.BATTLEFIELD, playerB, "Balduvian Bears", 1); // 2/2 // clone (AI must choose most valueable permanent - own) aiPlayPriority(1, PhaseStep.PRECOMBAT_MAIN, playerA); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 2); assertPermanentCount(playerB, "Spectral Bears", 0); } @Test public void test_CloneChoose_AI_Simulation_MostValueableFromOpponent() { // You may have Clone enter the battlefield as a copy of any creature on the battlefield. addCard(Zone.HAND, playerA, "Clone", 1); // {3}{U} addCard(Zone.BATTLEFIELD, playerA, "Island", 4); // addCard(Zone.BATTLEFIELD, playerA, "Arbor Elf", 1); // 1/1 // addCard(Zone.BATTLEFIELD, playerB, "Balduvian Bears", 1); // 2/2 addCard(Zone.BATTLEFIELD, playerB, "Spectral Bears", 1); // 3/3 // clone (AI must choose most valueable permanent - opponent) aiPlayPriority(1, PhaseStep.PRECOMBAT_MAIN, playerA); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertPermanentCount(playerB, "Spectral Bears", 1); } @Test public void test_CopyTarget_Manual() { // Exile target creature card from a graveyard. Dimir Doppelganger becomes a copy of that card, except it has this ability. addCard(Zone.BATTLEFIELD, playerA, "<NAME>", 1); // {1}{U}{B} addCard(Zone.BATTLEFIELD, playerA, "Island", 2); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); // addCard(Zone.GRAVEYARD, playerA, "Arbor Elf", 1); // 1/1 addCard(Zone.GRAVEYARD, playerB, "Balduvian Bears", 1); // 2/2 addCard(Zone.GRAVEYARD, playerB, "Spectral Bears", 1); // 3/3 // copy activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{1}{U}{B}: Exile target"); addTarget(playerA, "Spectral Bears"); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertExileCount("Spectral Bears", 1); } @Test public void test_CopyTarget_AI_Simulation_MostValueableFromOwn() { // Exile target creature card from a graveyard. <NAME> becomes a copy of that card, except it has this ability. addCard(Zone.BATTLEFIELD, playerA, "<NAME>", 1); // {1}{U}{B} addCard(Zone.BATTLEFIELD, playerA, "Island", 2); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); // addCard(Zone.GRAVEYARD, playerA, "Arbor Elf", 1); // 1/1 addCard(Zone.GRAVEYARD, playerA, "Spectral Bears", 1); // 3/3 // addCard(Zone.GRAVEYARD, playerB, "Balduvian Bears", 1); // 2/2 // copy (AI must choose most valueable permanent - own) aiPlayPriority(1, PhaseStep.PRECOMBAT_MAIN, playerA); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertExileCount("Spectral Bears", 1); } @Test public void test_CopyTarget_AI_Simulation_MostValueableFromOpponent() { // Exile target creature card from a graveyard. <NAME> becomes a copy of that card, except it has this ability. addCard(Zone.BATTLEFIELD, playerA, "<NAME>", 1); // {1}{U}{B} addCard(Zone.BATTLEFIELD, playerA, "Island", 2); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); // addCard(Zone.GRAVEYARD, playerA, "Arbor Elf", 1); // 1/1 // addCard(Zone.GRAVEYARD, playerB, "Balduvian Bears", 1); // 2/2 addCard(Zone.GRAVEYARD, playerB, "Spectral Bears", 1); // 3/3 // copy (AI must choose most valueable permanent - opponent) aiPlayPriority(1, PhaseStep.PRECOMBAT_MAIN, playerA); setStopAt(1, PhaseStep.END_TURN); setStrictChooseMode(true); execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertExileCount("Spectral Bears", 1); } @Test public void test_CopyTarget_AI_Response_MostValueableFromOwn() { // Exile target creature card from a graveyard. <NAME>elganger becomes a copy of that card, except it has this ability. addCard(Zone.BATTLEFIELD, playerA, "<NAME>", 1); // {1}{U}{B} addCard(Zone.BATTLEFIELD, playerA, "Island", 2); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); // addCard(Zone.GRAVEYARD, playerA, "Arbor Elf", 1); // 1/1 addCard(Zone.GRAVEYARD, playerA, "Spectral Bears", 1); // 3/3 // addCard(Zone.GRAVEYARD, playerB, "Balduvian Bears", 1); // 2/2 // copy (AI must choose most valueable permanent - own) activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{1}{U}{B}: Exile target"); //addTarget(playerA, "Spectral Bears"); // AI must choose setStopAt(1, PhaseStep.END_TURN); //setStrictChooseMode(true); // AI must choose execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertExileCount("Spectral Bears", 1); } @Test public void test_CopyTarget_AI_Response_MostValueableFromOpponent() { // Exile target creature card from a graveyard. <NAME> becomes a copy of that card, except it has this ability. addCard(Zone.BATTLEFIELD, playerA, "<NAME>", 1); // {1}{U}{B} addCard(Zone.BATTLEFIELD, playerA, "Island", 2); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); // addCard(Zone.GRAVEYARD, playerA, "Arbor Elf", 1); // 1/1 // addCard(Zone.GRAVEYARD, playerB, "Balduvian Bears", 1); // 2/2 addCard(Zone.GRAVEYARD, playerB, "Spectral Bears", 1); // 3/3 // copy (AI must choose most valueable permanent - opponent) activateAbility(1, PhaseStep.PRECOMBAT_MAIN, playerA, "{1}{U}{B}: Exile target"); //addTarget(playerA, "Spectral Bears"); // AI must choose setStopAt(1, PhaseStep.END_TURN); //setStrictChooseMode(true); // AI must choose execute(); assertPermanentCount(playerA, "Spectral Bears", 1); assertExileCount("Spectral Bears", 1); } }
8,225
0.636517
0.6197
200
40.625
33.060921
131
false
false
0
0
0
0
0
0
1.515
false
false
7
b2a8cf44517cd3cc84811ae446ecbb9870a85a84
27,058,294,000,795
9abdafc7da55bf3624b87e5e9ee392884582fbab
/app/src/main/java/com/example/android/uploadimage/MainActivity.java
81080e391bccb4d6665ed6d9d71182390797bde8
[]
no_license
sourav2002/Image-Drive
https://github.com/sourav2002/Image-Drive
4c454f91aaea60ac5d4259be3226e3539496c575
d2d676ae4bf41f30e49ed55a6cb23d4da61f0ca4
refs/heads/master
2023-04-12T07:24:35.122000
2021-05-10T10:52:58
2021-05-10T10:52:58
366,008,856
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.android.uploadimage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private static final int REQUEST_CODE_IMAGE = 101; private static final String TAG = "MyActivity"; private ImageView imageViewAdd; private EditText inputImageName; private Button btnUpload; private TextView textViewProgress; private ProgressBar progressBar; DatabaseReference reference; StorageReference storageReference; Uri imageUri; boolean isImageAdded = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageViewAdd = findViewById(R.id.imageViewAdd); inputImageName = findViewById(R.id.inputImageName); btnUpload = findViewById(R.id.btnUpload); textViewProgress = findViewById(R.id.textViewProgress); progressBar = findViewById(R.id.progressBar); // set progessbar visibility gone // initially hide them textViewProgress.setVisibility(View.GONE); progressBar.setVisibility(View.GONE); // creating references in firebase => car | carimages reference = FirebaseDatabase.getInstance().getReference().child("Car"); storageReference = FirebaseStorage.getInstance().getReference().child("CarImages"); // select image from device | button imageViewAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); // this intent will save image in firebase storage intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, REQUEST_CODE_IMAGE); } }); // // Save image button => save image in firebase btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String imageName = inputImageName.getText().toString(); // this name is given by user in Edit view field if (isImageAdded !=false && imageName!= null) // this wil ensure that the image field and edit text field is not empty then run this statement { uploadImage(imageName); // created uoloadImage method and passing variable image name } } }); } private void uploadImage(final String imageName) { // this imageName is given by the user // while uploading the image make progress bar visible textViewProgress.setVisibility(View.VISIBLE); progressBar.setVisibility(View.VISIBLE); // make a unique key for saving every image with different name in firebase final String key = reference.push().getKey(); // this getKey() is randomly generated by firebase Log.d(TAG ,"value of key "+ key); // store image in firebase storage with unique_key_name.jpg storageReference.child(key+".jpg").putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { storageReference.child(key +".jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { HashMap hashMap = new HashMap(); // hash map is used to save image name and image url in realtime firebase hashMap.put("CarName", imageName); hashMap.put("ImageUrl", uri.toString()); // setting hashmap in realtime database reference reference.child(key).setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(MainActivity.this, "Data Successfully Uploaded", Toast.LENGTH_SHORT).show(); // redirect on home activity Intent intent = new Intent(MainActivity.this, HomeActivity.class); startActivity(intent); imageViewAdd.setImageResource(R.drawable.ic_image); inputImageName.setText(""); // making them empty after successfully uploading data progressBar.setVisibility(View.GONE); textViewProgress.setVisibility(View.GONE); // make them again hide } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e(TAG,"error while saving image"); } }); } }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override // this on progress listener is used to update progress bar public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) { double progress = (snapshot.getBytesTransferred()*100)/ snapshot.getTotalByteCount(); // dividing into 100 parts i.e 100% progressbar (data transfered) x 100 / (total data size) progressBar.setProgress((int)progress); textViewProgress.setText(progress + "%"); // showing progress value in progress bar } }); }// end of uploadImage() method // When we start another activity from current activity to get the result for it, // we call the method startActivityForResult(intent, RESPONSE_CODE);. // It redirects to another activity like opens camera, gallery, etc. // After taking image from gallery or camera then come back to current activity // first method that calls is onActivityResult(int requestCode, int resultCode, // Intent data). We get the result in this method like taken image from camera or gallery. @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode== REQUEST_CODE_IMAGE && data!=null) { imageUri = data.getData(); // finally setting the imageUri value by selecting image from gallery. isImageAdded= true; // this boollean variable is used in upload button to check if it is empty or having data imageViewAdd.setImageURI(imageUri); } } }
UTF-8
Java
7,789
java
MainActivity.java
Java
[]
null
[]
package com.example.android.uploadimage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private static final int REQUEST_CODE_IMAGE = 101; private static final String TAG = "MyActivity"; private ImageView imageViewAdd; private EditText inputImageName; private Button btnUpload; private TextView textViewProgress; private ProgressBar progressBar; DatabaseReference reference; StorageReference storageReference; Uri imageUri; boolean isImageAdded = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageViewAdd = findViewById(R.id.imageViewAdd); inputImageName = findViewById(R.id.inputImageName); btnUpload = findViewById(R.id.btnUpload); textViewProgress = findViewById(R.id.textViewProgress); progressBar = findViewById(R.id.progressBar); // set progessbar visibility gone // initially hide them textViewProgress.setVisibility(View.GONE); progressBar.setVisibility(View.GONE); // creating references in firebase => car | carimages reference = FirebaseDatabase.getInstance().getReference().child("Car"); storageReference = FirebaseStorage.getInstance().getReference().child("CarImages"); // select image from device | button imageViewAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); // this intent will save image in firebase storage intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, REQUEST_CODE_IMAGE); } }); // // Save image button => save image in firebase btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String imageName = inputImageName.getText().toString(); // this name is given by user in Edit view field if (isImageAdded !=false && imageName!= null) // this wil ensure that the image field and edit text field is not empty then run this statement { uploadImage(imageName); // created uoloadImage method and passing variable image name } } }); } private void uploadImage(final String imageName) { // this imageName is given by the user // while uploading the image make progress bar visible textViewProgress.setVisibility(View.VISIBLE); progressBar.setVisibility(View.VISIBLE); // make a unique key for saving every image with different name in firebase final String key = reference.push().getKey(); // this getKey() is randomly generated by firebase Log.d(TAG ,"value of key "+ key); // store image in firebase storage with unique_key_name.jpg storageReference.child(key+".jpg").putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { storageReference.child(key +".jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { HashMap hashMap = new HashMap(); // hash map is used to save image name and image url in realtime firebase hashMap.put("CarName", imageName); hashMap.put("ImageUrl", uri.toString()); // setting hashmap in realtime database reference reference.child(key).setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(MainActivity.this, "Data Successfully Uploaded", Toast.LENGTH_SHORT).show(); // redirect on home activity Intent intent = new Intent(MainActivity.this, HomeActivity.class); startActivity(intent); imageViewAdd.setImageResource(R.drawable.ic_image); inputImageName.setText(""); // making them empty after successfully uploading data progressBar.setVisibility(View.GONE); textViewProgress.setVisibility(View.GONE); // make them again hide } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e(TAG,"error while saving image"); } }); } }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override // this on progress listener is used to update progress bar public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) { double progress = (snapshot.getBytesTransferred()*100)/ snapshot.getTotalByteCount(); // dividing into 100 parts i.e 100% progressbar (data transfered) x 100 / (total data size) progressBar.setProgress((int)progress); textViewProgress.setText(progress + "%"); // showing progress value in progress bar } }); }// end of uploadImage() method // When we start another activity from current activity to get the result for it, // we call the method startActivityForResult(intent, RESPONSE_CODE);. // It redirects to another activity like opens camera, gallery, etc. // After taking image from gallery or camera then come back to current activity // first method that calls is onActivityResult(int requestCode, int resultCode, // Intent data). We get the result in this method like taken image from camera or gallery. @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode== REQUEST_CODE_IMAGE && data!=null) { imageUri = data.getData(); // finally setting the imageUri value by selecting image from gallery. isImageAdded= true; // this boollean variable is used in upload button to check if it is empty or having data imageViewAdd.setImageURI(imageUri); } } }
7,789
0.64039
0.638465
159
47.99371
37.322746
194
false
false
0
0
0
0
0
0
0.628931
false
false
7
01bb29567634772c5de2353a881d5b1c5c177711
31,078,383,387,263
8c877fd71dfe234c57730a874d43997acb787543
/TPVOL_JPA/src/main/java/sopra/vol/repository/IAdresseRepository.java
e4d98746c85c6c7e8016a8d72e2ea50377f0b068
[]
no_license
dessandb/TPVOL_JPA
https://github.com/dessandb/TPVOL_JPA
ae538564e6280fbca44b740ab212c7f49a342f0a
6c9eb3e4766dcc51bfae4bcdb50761aeaa7c66f0
refs/heads/main
2023-04-22T10:37:31.375000
2021-05-17T13:38:31
2021-05-17T13:38:31
368,088,997
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sopra.vol.repository; import sopra.vol.model.Adresse; public interface IAdresseRepository extends IRepository<Adresse,Long> { }
UTF-8
Java
139
java
IAdresseRepository.java
Java
[]
null
[]
package sopra.vol.repository; import sopra.vol.model.Adresse; public interface IAdresseRepository extends IRepository<Adresse,Long> { }
139
0.81295
0.81295
7
18.857143
24.942383
71
false
false
0
0
0
0
0
0
0.428571
false
false
7
97c090530ec67e7bdab6327cd084fdafbbd96c34
31,138,512,931,654
6832918e1b21bafdc9c9037cdfbcfe5838abddc4
/jdk_8_maven/cs/rest-gui/genome-nexus/web/src/main/java/org/cbioportal/genome_nexus/web/mixin/HotspotMixin.java
c850ee5dcfb532e88863cad8fccf687d422bae0a
[ "Apache-2.0", "GPL-1.0-or-later", "LGPL-2.0-or-later", "MIT" ]
permissive
EMResearch/EMB
https://github.com/EMResearch/EMB
200c5693fb169d5f5462d9ebaf5b61c46d6f9ac9
092c92f7b44d6265f240bcf6b1c21b8a5cba0c7f
refs/heads/master
2023-09-04T01:46:13.465000
2023-04-12T12:09:44
2023-04-12T12:09:44
94,008,854
25
14
Apache-2.0
false
2023-09-13T11:23:37
2017-06-11T14:13:22
2023-08-20T08:44:30
2023-09-13T11:23:36
154,785
19
12
3
Java
false
false
package org.cbioportal.genome_nexus.web.mixin; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModelProperty; @JsonInclude(JsonInclude.Include.NON_NULL) public class HotspotMixin { @JsonIgnore private String id; @ApiModelProperty(value = "Hugo gene symbol") private String hugoSymbol; @ApiModelProperty(value = "Ensembl Transcript Id") private String transcriptId; @ApiModelProperty(value = "Hotspot residue") private String residue; @ApiModelProperty(value = "Hotspot type") private String type; @ApiModelProperty(value = "Tumor count") private Integer tumorCount; @ApiModelProperty(value="Missense mutation count") private Integer missenseCount; @ApiModelProperty(value="Truncation mutation count") private Integer truncatingCount; @ApiModelProperty(value="Inframe mutation count") private Integer inframeCount; @ApiModelProperty(value="Splice mutation count") private Integer spliceCount; }
UTF-8
Java
1,075
java
HotspotMixin.java
Java
[]
null
[]
package org.cbioportal.genome_nexus.web.mixin; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModelProperty; @JsonInclude(JsonInclude.Include.NON_NULL) public class HotspotMixin { @JsonIgnore private String id; @ApiModelProperty(value = "Hugo gene symbol") private String hugoSymbol; @ApiModelProperty(value = "Ensembl Transcript Id") private String transcriptId; @ApiModelProperty(value = "Hotspot residue") private String residue; @ApiModelProperty(value = "Hotspot type") private String type; @ApiModelProperty(value = "Tumor count") private Integer tumorCount; @ApiModelProperty(value="Missense mutation count") private Integer missenseCount; @ApiModelProperty(value="Truncation mutation count") private Integer truncatingCount; @ApiModelProperty(value="Inframe mutation count") private Integer inframeCount; @ApiModelProperty(value="Splice mutation count") private Integer spliceCount; }
1,075
0.755349
0.755349
39
26.564102
20.946568
56
false
false
0
0
0
0
0
0
0.358974
false
false
7
f6bb31183580e4e3d4484c94a8a0c0fbdb894d79
29,059,748,781,044
c4ebef89772d60f8f92e8b83973b104bb84bac2b
/src/FindNumberWithSingleOccurrence.java
945434afe8ff9f09677f266a99ce8a4c5a4433e3
[]
no_license
aparnabhure/DataStructure
https://github.com/aparnabhure/DataStructure
0caecc798d25fdf03e769dfec492051af739dd95
d1398aa809d6e22c4d07b17107689173ea71296b
refs/heads/master
2023-08-31T03:29:36.265000
2023-08-20T12:39:14
2023-08-20T12:39:14
207,143,703
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Given a sorted array that contains n numbers out of which except one value all the other values are repeated twice. * Find the number in the array that occurs only once. Do it with constant space and log(n) time. */ public class FindNumberWithSingleOccurrence { public static void main(String[] args) { System.out.println(findNumber(new int[]{1,1,2,2,3,4,4,5,5})); System.out.println(findNumber(new int[]{1,1,2,3,3,4,4,5,5})); System.out.println(findNumber(new int[]{1,2,2,3,3,4,4,5,5})); System.out.println(findNumber(new int[]{1,1,2,2,3,3,4,5,5})); System.out.println(findNumber(new int[]{1,1,2,2,3,3,4,4,5})); System.out.println(findNumber(new int[]{1,1,2,2,3,3,4,4,5, 6,6,7,7,8,8,9,9})); } //Log(n) as we are dividing the arrays // Idea is as there is guarantee that except one all other numbers will have twice occurrence which means length of // the array would be odd. So we can device the array and check center item // If it is not equal to it's left or right then that is the ans else move or decide the direction based on the // even odd length of the divided array private static int findNumber(int[] numbers){ int number = -1; if(numbers.length%2 == 0){ return number; } int start = 0; int end = numbers.length-1; int mid = (end-start)/2; boolean isFound = false; do{ if(start == end){ isFound = true; number = numbers[start]; }else{ number = numbers[mid]; if(number != numbers[mid-1] && number != numbers[mid+1]){ isFound = true; }else { int lLen = 0; int rLen = 0; if(number == numbers[mid -1]){ lLen = mid - 1 - start; rLen = end - mid; if(lLen%2 != 0){ //Means left side end = mid - 2; } if(rLen%2 != 0){ //Means right side start = mid + 1; } }else{ lLen = mid - start; rLen = end - mid - 1; if(lLen%2 != 0){ //Means left side end = mid - 1; } if(rLen%2 != 0){ //Means right side start = mid + 2; } } mid = start + (end -start)/2; } } }while (!isFound); return number; } }
UTF-8
Java
2,824
java
FindNumberWithSingleOccurrence.java
Java
[]
null
[]
/** * Given a sorted array that contains n numbers out of which except one value all the other values are repeated twice. * Find the number in the array that occurs only once. Do it with constant space and log(n) time. */ public class FindNumberWithSingleOccurrence { public static void main(String[] args) { System.out.println(findNumber(new int[]{1,1,2,2,3,4,4,5,5})); System.out.println(findNumber(new int[]{1,1,2,3,3,4,4,5,5})); System.out.println(findNumber(new int[]{1,2,2,3,3,4,4,5,5})); System.out.println(findNumber(new int[]{1,1,2,2,3,3,4,5,5})); System.out.println(findNumber(new int[]{1,1,2,2,3,3,4,4,5})); System.out.println(findNumber(new int[]{1,1,2,2,3,3,4,4,5, 6,6,7,7,8,8,9,9})); } //Log(n) as we are dividing the arrays // Idea is as there is guarantee that except one all other numbers will have twice occurrence which means length of // the array would be odd. So we can device the array and check center item // If it is not equal to it's left or right then that is the ans else move or decide the direction based on the // even odd length of the divided array private static int findNumber(int[] numbers){ int number = -1; if(numbers.length%2 == 0){ return number; } int start = 0; int end = numbers.length-1; int mid = (end-start)/2; boolean isFound = false; do{ if(start == end){ isFound = true; number = numbers[start]; }else{ number = numbers[mid]; if(number != numbers[mid-1] && number != numbers[mid+1]){ isFound = true; }else { int lLen = 0; int rLen = 0; if(number == numbers[mid -1]){ lLen = mid - 1 - start; rLen = end - mid; if(lLen%2 != 0){ //Means left side end = mid - 2; } if(rLen%2 != 0){ //Means right side start = mid + 1; } }else{ lLen = mid - start; rLen = end - mid - 1; if(lLen%2 != 0){ //Means left side end = mid - 1; } if(rLen%2 != 0){ //Means right side start = mid + 2; } } mid = start + (end -start)/2; } } }while (!isFound); return number; } }
2,824
0.45255
0.421388
80
34.299999
27.777868
119
false
false
0
0
0
0
0
0
1.0625
false
false
7
e46a93036dfc7f83f600a6900de86e97e49622f2
8,194,797,661,709
bbddeb279df2aededc825a7f5c772066814ab7ef
/app/src/main/java/com/echoesnet/eatandmeet/presenters/viewinterface/IDOrderConfirmView.java
a66e6bd96963bda239d2f2e20f4a2d794d13f04c
[]
no_license
a35363507800/EatAndMeet
https://github.com/a35363507800/EatAndMeet
dfda19e0f761fa027ddcc40e2bb585a6b45a1a14
a4dbc0c92be08f413ba9621c77d52e76244550f8
refs/heads/master
2020-03-31T12:35:37.136000
2018-10-10T01:25:58
2018-10-10T01:33:29
152,222,308
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.echoesnet.eatandmeet.presenters.viewinterface; import android.view.View; import okhttp3.Call; /** * Created by Administrator on 2017/1/5. */ public interface IDOrderConfirmView { void callServerErrorCallback(String interfaceName, String code, String errBody,String change); void requestNetErrorCallback(String interfaceName, Throwable e); void checkPriceCallback(String response); void postOrderToServerCallback(String response, final View view, final String change); void postOrderToServerCallback2(String response, final View view, final String change); void queryMyConsultantCallback(String response); void getMyConsultantCallback(String response); void orderCheckCallback(String response,String date); }
UTF-8
Java
767
java
IDOrderConfirmView.java
Java
[ { "context": "iew.View;\n\nimport okhttp3.Call;\n\n/**\n * Created by Administrator on 2017/1/5.\n */\n\npublic interface IDOrderConfirm", "end": 140, "score": 0.8926771879196167, "start": 127, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.echoesnet.eatandmeet.presenters.viewinterface; import android.view.View; import okhttp3.Call; /** * Created by Administrator on 2017/1/5. */ public interface IDOrderConfirmView { void callServerErrorCallback(String interfaceName, String code, String errBody,String change); void requestNetErrorCallback(String interfaceName, Throwable e); void checkPriceCallback(String response); void postOrderToServerCallback(String response, final View view, final String change); void postOrderToServerCallback2(String response, final View view, final String change); void queryMyConsultantCallback(String response); void getMyConsultantCallback(String response); void orderCheckCallback(String response,String date); }
767
0.78618
0.77575
30
24.566668
31.736082
98
false
false
0
0
0
0
0
0
0.666667
false
false
7
e247f0ea1771fc2ac3c9b389dbc18f9d812d34cd
28,312,424,466,561
a1c73af660847b16ee88694827c737813581636c
/eclipse-workspace/techproedsummer2020turkish2/src/day36collectionsmaps/Ma02Ornek.java
a439809d5f961ad7e6224f87a5f34fdedb4eecec
[]
no_license
ismailozkan93/homework05
https://github.com/ismailozkan93/homework05
8521e365148a434ed00205f3c642efee801ff73c
2f4a0da654012a92cda9ac042679b7f8921f3667
refs/heads/main
2023-05-12T05:36:16.771000
2021-06-03T12:46:59
2021-06-03T12:46:59
317,010,606
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day36collectionsmaps; import java.util.Arrays; import java.util.HashMap; public class Ma02Ornek { /* * Size verilen bir yazida hangi kelimenin kac kere kullanildigini gösteren kodu yaziniz. * */ public static void main(String[] args) { String s="Java ogrenmek zevkliydi. Java ogrenmek kolay ama tekrar gerekiyor. Java tekrari zevkliydi ama vaktim yoktu."; String kelime[]=s.split(" "); System.out.println(Arrays.toString(kelime)); HashMap<String,Integer>hm=new HashMap<>(); for(String w:kelime) { if(w.contains(".")) { w.replace(".","" ); if(!hm.containsKey(w)) { hm.put(w, 1); }else { hm.put(w, hm.get(w)+1); } }else { if(!hm.containsKey(w)) { hm.put(w, 1); }else { hm.put(w, hm.get(w)+1); } } } System.out.println(hm); } }
ISO-8859-2
Java
824
java
Ma02Ornek.java
Java
[]
null
[]
package day36collectionsmaps; import java.util.Arrays; import java.util.HashMap; public class Ma02Ornek { /* * Size verilen bir yazida hangi kelimenin kac kere kullanildigini gösteren kodu yaziniz. * */ public static void main(String[] args) { String s="Java ogrenmek zevkliydi. Java ogrenmek kolay ama tekrar gerekiyor. Java tekrari zevkliydi ama vaktim yoktu."; String kelime[]=s.split(" "); System.out.println(Arrays.toString(kelime)); HashMap<String,Integer>hm=new HashMap<>(); for(String w:kelime) { if(w.contains(".")) { w.replace(".","" ); if(!hm.containsKey(w)) { hm.put(w, 1); }else { hm.put(w, hm.get(w)+1); } }else { if(!hm.containsKey(w)) { hm.put(w, 1); }else { hm.put(w, hm.get(w)+1); } } } System.out.println(hm); } }
824
0.622114
0.612394
49
15.795918
22.809753
121
false
false
0
0
0
0
0
0
1.795918
false
false
7
f30ad3ad10fe9cc1d8c686a6457ef295155f6d77
30,803,505,493,948
f5d5d0938d86e86d51504d39fe92235ee0715fde
/app/src/main/java/de/hsb/gastromaster/data/order/local/OrderDataStore.java
c7e2b9174d0c0992a0b4a806f39ede75bae6a224
[]
no_license
romqu/GastroMaster
https://github.com/romqu/GastroMaster
e2ce3434233e9ac25f0d966c54158ff60dba2899
32db62704de7ab0bea581dd36c61adeb26d070e3
refs/heads/master
2021-06-18T12:44:35.876000
2017-06-27T20:59:32
2017-06-27T20:59:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * @author Christian Schaf * @author Roman Quistler * @author Nassim Bendida * * Date: 27.6.2017 * Copyright (c) by Hochschule Bremen */ package de.hsb.gastromaster.data.order.local; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.hsb.gastromaster.data.order.Order; import de.hsb.gastromaster.data.order.dish.Dish; import de.hsb.gastromaster.data.request.Request; import de.hsb.gastromaster.data.response.Response; import io.reactivex.Single; /** * The type Order data store. */ public class OrderDataStore implements IOrderDataStore { /** * The constant LastID. */ public static int LastID = 1; private List<Dish> dishList = new ArrayList<>(); private List<Order> orderList = new ArrayList<>(); /** * Init. */ public void init() { dishList.add(Dish.builder().setId(1).setOrderId(0).setName("Spaghetti").setPrice(6.70).build()); dishList.add(Dish.builder().setId(2).setOrderId(0).setName("Coca Cola").setPrice(3.50).build()); dishList.add(Dish.builder().setId(3).setOrderId(0).setName("Salami Pizza").setPrice(11.30).build()); dishList.add(Dish.builder().setId(4).setOrderId(0).setName("Toast Hawaii").setPrice(5.20).build()); dishList.add(Dish.builder().setId(5).setOrderId(0).setName("Chef Salat").setPrice(10.00).build()); dishList.add(Dish.builder().setId(6).setOrderId(0).setName("Sparkled Water").setPrice(2.50).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("1A").setWaitressId(1).setDate("11-6-2017:19.00.33").setDishList(Arrays.asList(dishList.get(0), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("1A").setWaitressId(1).setDate("11-6-2017:19.05.13").setDishList(Arrays.asList(dishList.get(2), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("2A").setWaitressId(1).setDate("11-6-2017:16.00.33").setDishList(Arrays.asList(dishList.get(3), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("2A").setWaitressId(1).setDate("11-6-2017:17.15.13").setDishList(Arrays.asList(dishList.get(4), dishList.get(5))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("2A").setWaitressId(1).setDate("11-6-2017:16.00.33").setDishList(Arrays.asList(dishList.get(3), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("2A").setWaitressId(1).setDate("11-6-2017:17.15.13").setDishList(Arrays.asList(dishList.get(0), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("3A").setWaitressId(2).setDate("11-6-2017:10.00.00").setDishList(Arrays.asList(dishList.get(0), dishList.get(5))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("4A").setWaitressId(2).setDate("11-6-2017:18.04.03").setDishList(Arrays.asList(dishList.get(2), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("4A").setWaitressId(2).setDate("11-6-2017:16.25.33").setDishList(Arrays.asList(dishList.get(3), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("4A").setWaitressId(2).setDate("11-6-2017:17.05.13").setDishList(Arrays.asList(dishList.get(4), dishList.get(5))).build()); } @Override public Single<Response<Integer>> getNumberOfDishes() { return Single.create(singleEmitter -> { singleEmitter.onSuccess(Response.<Integer>builder() .setEntity(dishList.size()) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Void>> addDish(Request<Dish> request) { return Single.create(singleEmitter -> { dishList.add(request.getEntity()); singleEmitter.onSuccess( Response.<Void>builder() .setEntity(null) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Dish>> getDishByIndex(Request<Integer> request) { return Single.create(singleEmitter -> { Response.Builder<Dish> builder = Response.builder(); if (request.getEntity() >= 0 && request.getEntity() < dishList.size()) { singleEmitter.onSuccess( builder.setEntity(dishList.get(request.getEntity())) .setIsSuccessful(true) .build()); } singleEmitter.onSuccess( builder.setEntity(null) .setIsSuccessful(false) .setErrorMessage("Dish not found") .build()); }); } @Override public Single<Response<List<Dish>>> getAllDishes() { return Single.create(singleEmitter -> { singleEmitter.onSuccess( Response.<List<Dish>>builder() .setEntity(new ArrayList<>(dishList)) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Void>> addOrder(Request<Order> request) { return Single.create(singleEmitter -> { orderList.add(request.getEntity()); singleEmitter.onSuccess( Response.<Void>builder() .setEntity(null) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Order>> getOrderById(Request<Integer> request) { return Single.create(singleEmitter -> { Response.Builder<Order> builder = Response.builder(); for (Order order : orderList) { if (order.getId() == request.getEntity()) { singleEmitter.onSuccess(builder .setEntity(order) .setIsSuccessful(true) .build()); } } singleEmitter.onSuccess(builder .setEntity(null) .setIsSuccessful(false) .setErrorMessage("Order not found") .build()); }); } @Override public Single<Response<List<Order>>> getAllOrder() { return Single.create(singleEmitter -> { singleEmitter.onSuccess( Response.<List<Order>>builder() .setEntity(new ArrayList<>(orderList)) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Void>> updateOrder(Request<Order> request) { return Single.create(singleEmitter -> { for (int i = 0; i < orderList.size(); i++) { if (orderList.get(i).getId() == request.getEntity().getId()) { orderList.set(i, request.getEntity()); break; } } singleEmitter.onSuccess( Response.<Void>builder() .setEntity(null) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Void>> removeOrder(Request<Order> order) { return Single.create(singleEmitter -> { for (int i = 0; i < orderList.size(); i++) { if (order.getEntity().getId() == orderList.get(i).getId()) { orderList.remove(i); } } singleEmitter.onSuccess( Response.<Void>builder() .setEntity(null) .setIsSuccessful(true) .build()); }); } }
UTF-8
Java
8,113
java
OrderDataStore.java
Java
[ { "context": "/*\n * @author Christian Schaf\n * @author Roman Quistler\n * @author Nassim Bendi", "end": 29, "score": 0.9998440742492676, "start": 14, "tag": "NAME", "value": "Christian Schaf" }, { "context": "/*\n * @author Christian Schaf\n * @author Roman Quistler\n * @author Nassim Bendida\n *\n * Date: 27.6.2017\n ", "end": 55, "score": 0.9998260140419006, "start": 41, "tag": "NAME", "value": "Roman Quistler" }, { "context": "ristian Schaf\n * @author Roman Quistler\n * @author Nassim Bendida\n *\n * Date: 27.6.2017\n * Copyright (c) by Hochsch", "end": 81, "score": 0.9998490214347839, "start": 67, "tag": "NAME", "value": "Nassim Bendida" } ]
null
[]
/* * @author <NAME> * @author <NAME> * @author <NAME> * * Date: 27.6.2017 * Copyright (c) by Hochschule Bremen */ package de.hsb.gastromaster.data.order.local; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.hsb.gastromaster.data.order.Order; import de.hsb.gastromaster.data.order.dish.Dish; import de.hsb.gastromaster.data.request.Request; import de.hsb.gastromaster.data.response.Response; import io.reactivex.Single; /** * The type Order data store. */ public class OrderDataStore implements IOrderDataStore { /** * The constant LastID. */ public static int LastID = 1; private List<Dish> dishList = new ArrayList<>(); private List<Order> orderList = new ArrayList<>(); /** * Init. */ public void init() { dishList.add(Dish.builder().setId(1).setOrderId(0).setName("Spaghetti").setPrice(6.70).build()); dishList.add(Dish.builder().setId(2).setOrderId(0).setName("Coca Cola").setPrice(3.50).build()); dishList.add(Dish.builder().setId(3).setOrderId(0).setName("Salami Pizza").setPrice(11.30).build()); dishList.add(Dish.builder().setId(4).setOrderId(0).setName("Toast Hawaii").setPrice(5.20).build()); dishList.add(Dish.builder().setId(5).setOrderId(0).setName("Chef Salat").setPrice(10.00).build()); dishList.add(Dish.builder().setId(6).setOrderId(0).setName("Sparkled Water").setPrice(2.50).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("1A").setWaitressId(1).setDate("11-6-2017:19.00.33").setDishList(Arrays.asList(dishList.get(0), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("1A").setWaitressId(1).setDate("11-6-2017:19.05.13").setDishList(Arrays.asList(dishList.get(2), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("2A").setWaitressId(1).setDate("11-6-2017:16.00.33").setDishList(Arrays.asList(dishList.get(3), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("2A").setWaitressId(1).setDate("11-6-2017:17.15.13").setDishList(Arrays.asList(dishList.get(4), dishList.get(5))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("2A").setWaitressId(1).setDate("11-6-2017:16.00.33").setDishList(Arrays.asList(dishList.get(3), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("2A").setWaitressId(1).setDate("11-6-2017:17.15.13").setDishList(Arrays.asList(dishList.get(0), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("3A").setWaitressId(2).setDate("11-6-2017:10.00.00").setDishList(Arrays.asList(dishList.get(0), dishList.get(5))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("4A").setWaitressId(2).setDate("11-6-2017:18.04.03").setDishList(Arrays.asList(dishList.get(2), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("4A").setWaitressId(2).setDate("11-6-2017:16.25.33").setDishList(Arrays.asList(dishList.get(3), dishList.get(1))).build()); orderList.add(Order.builder().setId(LastID++).setTableNumber("4A").setWaitressId(2).setDate("11-6-2017:17.05.13").setDishList(Arrays.asList(dishList.get(4), dishList.get(5))).build()); } @Override public Single<Response<Integer>> getNumberOfDishes() { return Single.create(singleEmitter -> { singleEmitter.onSuccess(Response.<Integer>builder() .setEntity(dishList.size()) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Void>> addDish(Request<Dish> request) { return Single.create(singleEmitter -> { dishList.add(request.getEntity()); singleEmitter.onSuccess( Response.<Void>builder() .setEntity(null) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Dish>> getDishByIndex(Request<Integer> request) { return Single.create(singleEmitter -> { Response.Builder<Dish> builder = Response.builder(); if (request.getEntity() >= 0 && request.getEntity() < dishList.size()) { singleEmitter.onSuccess( builder.setEntity(dishList.get(request.getEntity())) .setIsSuccessful(true) .build()); } singleEmitter.onSuccess( builder.setEntity(null) .setIsSuccessful(false) .setErrorMessage("Dish not found") .build()); }); } @Override public Single<Response<List<Dish>>> getAllDishes() { return Single.create(singleEmitter -> { singleEmitter.onSuccess( Response.<List<Dish>>builder() .setEntity(new ArrayList<>(dishList)) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Void>> addOrder(Request<Order> request) { return Single.create(singleEmitter -> { orderList.add(request.getEntity()); singleEmitter.onSuccess( Response.<Void>builder() .setEntity(null) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Order>> getOrderById(Request<Integer> request) { return Single.create(singleEmitter -> { Response.Builder<Order> builder = Response.builder(); for (Order order : orderList) { if (order.getId() == request.getEntity()) { singleEmitter.onSuccess(builder .setEntity(order) .setIsSuccessful(true) .build()); } } singleEmitter.onSuccess(builder .setEntity(null) .setIsSuccessful(false) .setErrorMessage("Order not found") .build()); }); } @Override public Single<Response<List<Order>>> getAllOrder() { return Single.create(singleEmitter -> { singleEmitter.onSuccess( Response.<List<Order>>builder() .setEntity(new ArrayList<>(orderList)) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Void>> updateOrder(Request<Order> request) { return Single.create(singleEmitter -> { for (int i = 0; i < orderList.size(); i++) { if (orderList.get(i).getId() == request.getEntity().getId()) { orderList.set(i, request.getEntity()); break; } } singleEmitter.onSuccess( Response.<Void>builder() .setEntity(null) .setIsSuccessful(true) .build()); }); } @Override public Single<Response<Void>> removeOrder(Request<Order> order) { return Single.create(singleEmitter -> { for (int i = 0; i < orderList.size(); i++) { if (order.getEntity().getId() == orderList.get(i).getId()) { orderList.remove(i); } } singleEmitter.onSuccess( Response.<Void>builder() .setEntity(null) .setIsSuccessful(true) .build()); }); } }
8,088
0.559349
0.533095
213
37.089203
43.030796
192
false
false
0
0
0
0
0
0
0.328638
false
false
7
ac72592cdbd485dd75fae5dc2c2d50a48f389daa
23,149,873,767,660
237801bba9ed3c6b3179b75364fa93682fd3c8c0
/ProjetPropre/src/application/DemandeInvitation.java
dcd763c7e811c0946e6b39b21390992ce8b50d4c
[]
no_license
marionjure/ProjetPlatesFormesDeJeux
https://github.com/marionjure/ProjetPlatesFormesDeJeux
89728f861bd7d7462ef954a25c48e2fa657f1531
dc0f00f81d29ee7807c37e0c3e1365a1f817dc8f
refs/heads/master
2020-04-02T02:45:10.650000
2018-10-20T16:35:22
2018-10-20T16:35:22
153,925,803
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package src.application; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.util.Duration; import java.util.ArrayList; public class DemandeInvitation extends VBox { private String user; DemandeInvitation(String user){ this.user=user; this.setMaxWidth(220); Timeline tl = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent actionEvent) { getChildren().clear(); getChildren().add(plus(user)); getChildren().add(new Demande(user)); } })); tl.setCycleCount(Animation.INDEFINITE); tl.play(); //this.getChildren().add(plus()); } private VBox plus(String user){ HBox haut=new HBox(); haut.getChildren().add(new Label("Liste des amis")); VBox panal =new VBox(); panal.setPrefWidth(200); panal.setPrefHeight(200); Button res =new Button("+"); res.setOnAction(new ActionPlus(this.user)); haut.getChildren().add(res); haut.setSpacing(10); panal.getChildren().add(haut); panal.getChildren().add(liste(user)); return panal; } private VBox liste(String user){ ScrollPane scroll=new ScrollPane(); VBox res =new VBox(); VBox panel=new VBox(); //ArrayList<String> m=GLOBALS.REQUETE_BD.listePasAmis(user); ArrayList<String> m=GLOBALS.REQUETE_BD.listeMesAmis(user); for (int i=0;i<m.size();i++){ res.getChildren().add(new Label(m.get(i))); } scroll.setContent(res); scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS); scroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); scroll.setStyle("-fx-padding: 15;"); scroll.setVvalue(1); panel.getChildren().add(scroll); return panel; } }
UTF-8
Java
2,244
java
DemandeInvitation.java
Java
[]
null
[]
package src.application; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.util.Duration; import java.util.ArrayList; public class DemandeInvitation extends VBox { private String user; DemandeInvitation(String user){ this.user=user; this.setMaxWidth(220); Timeline tl = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent actionEvent) { getChildren().clear(); getChildren().add(plus(user)); getChildren().add(new Demande(user)); } })); tl.setCycleCount(Animation.INDEFINITE); tl.play(); //this.getChildren().add(plus()); } private VBox plus(String user){ HBox haut=new HBox(); haut.getChildren().add(new Label("Liste des amis")); VBox panal =new VBox(); panal.setPrefWidth(200); panal.setPrefHeight(200); Button res =new Button("+"); res.setOnAction(new ActionPlus(this.user)); haut.getChildren().add(res); haut.setSpacing(10); panal.getChildren().add(haut); panal.getChildren().add(liste(user)); return panal; } private VBox liste(String user){ ScrollPane scroll=new ScrollPane(); VBox res =new VBox(); VBox panel=new VBox(); //ArrayList<String> m=GLOBALS.REQUETE_BD.listePasAmis(user); ArrayList<String> m=GLOBALS.REQUETE_BD.listeMesAmis(user); for (int i=0;i<m.size();i++){ res.getChildren().add(new Label(m.get(i))); } scroll.setContent(res); scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS); scroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); scroll.setStyle("-fx-padding: 15;"); scroll.setVvalue(1); panel.getChildren().add(scroll); return panel; } }
2,244
0.636809
0.629679
69
31.52174
19.336538
101
false
false
0
0
0
0
0
0
0.753623
false
false
7
a9805f484f566560b63bc70f4ff8df21ce420e20
2,723,009,286,549
bf94430db8b130d788b9a8c53a4e5d5514d4afc2
/Level1_Problem7/src/level1_problem7/Level1_Problem7.java
a15d832ca6011d3c1c084d32f0ed448401e3ca89
[]
no_license
shadeshsaha/java-oop-chapter08
https://github.com/shadeshsaha/java-oop-chapter08
20e8a77296d00f46ea0f7d17914bf072cc00f418
5363838d92635230d44f574895e38ecebc2de068
refs/heads/main
2023-08-05T03:55:58.209000
2021-09-28T16:06:15
2021-09-28T16:06:15
411,121,494
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 level1_problem7; /** * * @author Shadesh */ import java.util.Scanner; public class Level1_Problem7 { /** * @param args the command line arguments */ public static void main(String[] args) throws EmptyInputException { Scanner sc = new Scanner(System.in); System.out.print("Enter name: "); String name = sc.nextLine(); try { if(name.startsWith(" ") || name.equals("")) { throw new EmptyInputException("Name cannot start with a space or it can't be blank :("); } else { System.out.println("Perfect !!!"); } } catch (EmptyInputException e) { System.out.println(e.getMessage().toString()); } } }
UTF-8
Java
1,018
java
Level1_Problem7.java
Java
[ { "context": "/\r\npackage level1_problem7;\r\n\r\n/**\r\n *\r\n * @author Shadesh\r\n */\r\n\r\nimport java.util.Scanner;\t\t\r\n\r\npublic cla", "end": 245, "score": 0.9997900128364563, "start": 238, "tag": "NAME", "value": "Shadesh" } ]
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 level1_problem7; /** * * @author Shadesh */ import java.util.Scanner; public class Level1_Problem7 { /** * @param args the command line arguments */ public static void main(String[] args) throws EmptyInputException { Scanner sc = new Scanner(System.in); System.out.print("Enter name: "); String name = sc.nextLine(); try { if(name.startsWith(" ") || name.equals("")) { throw new EmptyInputException("Name cannot start with a space or it can't be blank :("); } else { System.out.println("Perfect !!!"); } } catch (EmptyInputException e) { System.out.println(e.getMessage().toString()); } } }
1,018
0.547151
0.543222
39
24.102564
26.830708
104
false
false
0
0
0
0
0
0
0.384615
false
false
7
6983134ab4d6e8f896356742d9ef43d08727d403
3,564,822,910,241
7b6b53638f878f0b5c6034c13ff07bdc21bbdebe
/src/test/java/runner/TestRunner.java
27fb4fc10f6c97730f0f0d2b377642303e339953
[]
no_license
VastUAT/MeedAutomation
https://github.com/VastUAT/MeedAutomation
d7395c857f53f6e10e29814360eb3a39d8c815c2
76c25b67335ce90a80a22bedd45d19be3d53925d
refs/heads/master
2020-07-31T15:08:18.198000
2020-07-30T20:16:05
2020-07-30T20:16:05
210,647,342
0
1
null
false
2020-05-27T01:12:22
2019-09-24T16:19:25
2020-04-23T18:37:19
2020-05-26T19:37:22
23,460
0
1
1
Gherkin
false
false
package runner; import java.io.File; import org.junit.AfterClass; import org.junit.runner.RunWith; import com.cucumber.listener.Reporter; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features = "src/test/java/features/New App features/Onboarding.feature", glue= {"stepDefinations"}, plugin = {"com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/ExtentReport/TestAutomationReport.html", "json:target/cucumber-reports/JSON/TestAutomationResult.json"}, monochrome = true, tags= {"@TC001_Meed_Onboarding1"} ) public class TestRunner { @AfterClass public static void setup() { Reporter.loadXMLConfig(new File("src/main/resources/extent-config.xml")); Reporter.setSystemInfo("User Name", "Manoj"); Reporter.setSystemInfo("Application Name", "Meed Mobile App "); Reporter.setSystemInfo("Operating System Type", System.getProperty("os.name").toString()); Reporter.setSystemInfo("Environment", "UAT"); Reporter.setTestRunnerOutput("Test Execution Cucumber Report"); } }
UTF-8
Java
1,084
java
TestRunner.java
Java
[ { "context": "fig.xml\"));\n\tReporter.setSystemInfo(\"User Name\", \"Manoj\");\n\tReporter.setSystemInfo(\"Application Name\", \"M", "end": 804, "score": 0.9990383982658386, "start": 799, "tag": "NAME", "value": "Manoj" } ]
null
[]
package runner; import java.io.File; import org.junit.AfterClass; import org.junit.runner.RunWith; import com.cucumber.listener.Reporter; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features = "src/test/java/features/New App features/Onboarding.feature", glue= {"stepDefinations"}, plugin = {"com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/ExtentReport/TestAutomationReport.html", "json:target/cucumber-reports/JSON/TestAutomationResult.json"}, monochrome = true, tags= {"@TC001_Meed_Onboarding1"} ) public class TestRunner { @AfterClass public static void setup() { Reporter.loadXMLConfig(new File("src/main/resources/extent-config.xml")); Reporter.setSystemInfo("User Name", "Manoj"); Reporter.setSystemInfo("Application Name", "Meed Mobile App "); Reporter.setSystemInfo("Operating System Type", System.getProperty("os.name").toString()); Reporter.setSystemInfo("Environment", "UAT"); Reporter.setTestRunnerOutput("Test Execution Cucumber Report"); } }
1,084
0.77214
0.76845
35
29.942858
29.507328
122
false
false
0
0
0
0
0
0
1.085714
false
false
7
248efa74d1388a5534549da7807deecc9c2671c6
6,554,120,114,596
a50c3a10b07179eb6ed89a6a5dfb88afdb2203ea
/src/main/java/com/platformance/dbpad/repository/Teststs.java
23cdf42f1e0cec70bc52d447403fa7ea48e379fb
[]
no_license
tjdrlans119/platformance
https://github.com/tjdrlans119/platformance
f7a81a287b69b7ca7c26adbbb835ac4d5d5fbd06
0c28127f358d73a3b8ef7a009efb3f614946c50e
refs/heads/master
2020-04-18T17:07:15.459000
2019-05-18T10:45:31
2019-05-18T10:45:31
167,647,680
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.platformance.dbpad.repository; public class Teststs { }
UTF-8
Java
70
java
Teststs.java
Java
[]
null
[]
package com.platformance.dbpad.repository; public class Teststs { }
70
0.785714
0.785714
5
13
16.757088
42
false
false
0
0
0
0
0
0
0.2
false
false
7
3b2ad751e0a324fbc70ca5f131e47f3aee90b131
6,554,120,114,992
0d57bd1532e92144caba60f0538973f5264ad336
/pa4/java/src/cs224n/deep/FeatureFactory.java
4e3021479e517b46a484dc8d764e5cbd9920c60c
[]
no_license
JiajiHu/NLP_PA
https://github.com/JiajiHu/NLP_PA
2472381307a90fb710f00fa119acf12702c542df
3f262be26f6a4f882e2c0420422be02c98acc5aa
refs/heads/master
2021-03-24T09:22:17.072000
2017-09-21T04:29:47
2017-09-21T04:29:47
25,101,654
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cs224n.deep; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; import org.ejml.simple.*; public class FeatureFactory { public static final String UNKNOWN_WORD = "UUUNKKK"; public static final String DIGIT_WORD = "DG"; public static final String START_TOKEN = "<s>"; public static final String END_TOKEN = "</s>"; private FeatureFactory() { } static List<Datum> trainData; /** Do not modify this method **/ public static List<Datum> readTrainData(String filename) throws IOException { if (trainData==null) trainData= read(filename); return trainData; } static List<Datum> testData; /** Do not modify this method **/ public static List<Datum> readTestData(String filename) throws IOException { if (testData==null) testData= read(filename); return testData; } static List<Datum> finaltestData; /** Do not modify this method **/ public static List<Datum> readFinalTestData(String filename) throws IOException { if (finaltestData==null) finaltestData= read(filename); return finaltestData; } private static List<Datum> read(String filename) throws FileNotFoundException, IOException { // TODO: you'd want to handle sentence boundaries List<Datum> data = new ArrayList<Datum>(); BufferedReader in = new BufferedReader(new FileReader(filename)); for (String line = in.readLine(); line != null; line = in.readLine()) { if (line.trim().length() == 0) { continue; } String[] bits = line.split("\\s+"); String word = bits[0]; String label = bits[1]; Datum datum = new Datum(word, label); data.add(datum); } return data; } /* Look up table matrix with all word vectors as defined in lecture with dimensionality n x |V| */ static SimpleMatrix allVecs; //access it directly in WindowModel public static SimpleMatrix readWordVectors(String vecFilename) throws IOException { if (allVecs!=null) return allVecs; /* get vector matrix size */ int numVectors = 0; BufferedReader br = new BufferedReader(new FileReader(vecFilename)); String line = br.readLine(); int vectorDimension = line.trim().split(" ").length; while (line != null) { if (line.trim().length() != 0) { numVectors++; } line = br.readLine(); } br.close(); allVecs = new SimpleMatrix(vectorDimension, numVectors); /* populate vector matrix */ double[] column = new double[vectorDimension]; allVecs.setColumn(0, 0, column); br = new BufferedReader(new FileReader(vecFilename)); line = br.readLine(); int colIdx = 0; while (line != null) { if (line.trim().length() == 0) { continue; } String[] tokens = line.trim().split(" "); if (tokens.length != vectorDimension) { System.out.println("Tokens length doesn't match"); } for (int rowIdx = 0; rowIdx < vectorDimension; rowIdx++) { double val = Double.valueOf(tokens[rowIdx]); allVecs.set(rowIdx, colIdx, val); } colIdx++; line = br.readLine(); } br.close(); return null; } /* might be useful for word to number lookups, just access them directly in WindowModel */ public static HashMap<String, Integer> wordToNum = new HashMap<String, Integer>(); public static HashMap<Integer, String> numToWord = new HashMap<Integer, String>(); public static void initializeVocab(String vocabFilename) throws IOException { BufferedReader br = new BufferedReader(new FileReader(vocabFilename)); int rowIdx = 0; String line = br.readLine(); while (line != null) { String word = line.trim(); if (word.length() != 0) { wordToNum.put(word, rowIdx); numToWord.put(rowIdx, word); rowIdx++; } line = br.readLine(); } br.close(); } public static SimpleMatrix randomInitializeWordVectors(int vectorDimension, int numVectors) { allVecs = new SimpleMatrix(vectorDimension, numVectors); Random generator = new Random(); for (int colIdx = 0; colIdx < numVectors; colIdx++) { for (int rowIdx = 0; rowIdx < vectorDimension; rowIdx++) { double val = generator.nextDouble() * 2 - 1.0; // rand value between -1.0 and 1.0 allVecs.set(rowIdx, colIdx, val); } } return allVecs; } }
UTF-8
Java
4,745
java
FeatureFactory.java
Java
[]
null
[]
package cs224n.deep; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; import org.ejml.simple.*; public class FeatureFactory { public static final String UNKNOWN_WORD = "UUUNKKK"; public static final String DIGIT_WORD = "DG"; public static final String START_TOKEN = "<s>"; public static final String END_TOKEN = "</s>"; private FeatureFactory() { } static List<Datum> trainData; /** Do not modify this method **/ public static List<Datum> readTrainData(String filename) throws IOException { if (trainData==null) trainData= read(filename); return trainData; } static List<Datum> testData; /** Do not modify this method **/ public static List<Datum> readTestData(String filename) throws IOException { if (testData==null) testData= read(filename); return testData; } static List<Datum> finaltestData; /** Do not modify this method **/ public static List<Datum> readFinalTestData(String filename) throws IOException { if (finaltestData==null) finaltestData= read(filename); return finaltestData; } private static List<Datum> read(String filename) throws FileNotFoundException, IOException { // TODO: you'd want to handle sentence boundaries List<Datum> data = new ArrayList<Datum>(); BufferedReader in = new BufferedReader(new FileReader(filename)); for (String line = in.readLine(); line != null; line = in.readLine()) { if (line.trim().length() == 0) { continue; } String[] bits = line.split("\\s+"); String word = bits[0]; String label = bits[1]; Datum datum = new Datum(word, label); data.add(datum); } return data; } /* Look up table matrix with all word vectors as defined in lecture with dimensionality n x |V| */ static SimpleMatrix allVecs; //access it directly in WindowModel public static SimpleMatrix readWordVectors(String vecFilename) throws IOException { if (allVecs!=null) return allVecs; /* get vector matrix size */ int numVectors = 0; BufferedReader br = new BufferedReader(new FileReader(vecFilename)); String line = br.readLine(); int vectorDimension = line.trim().split(" ").length; while (line != null) { if (line.trim().length() != 0) { numVectors++; } line = br.readLine(); } br.close(); allVecs = new SimpleMatrix(vectorDimension, numVectors); /* populate vector matrix */ double[] column = new double[vectorDimension]; allVecs.setColumn(0, 0, column); br = new BufferedReader(new FileReader(vecFilename)); line = br.readLine(); int colIdx = 0; while (line != null) { if (line.trim().length() == 0) { continue; } String[] tokens = line.trim().split(" "); if (tokens.length != vectorDimension) { System.out.println("Tokens length doesn't match"); } for (int rowIdx = 0; rowIdx < vectorDimension; rowIdx++) { double val = Double.valueOf(tokens[rowIdx]); allVecs.set(rowIdx, colIdx, val); } colIdx++; line = br.readLine(); } br.close(); return null; } /* might be useful for word to number lookups, just access them directly in WindowModel */ public static HashMap<String, Integer> wordToNum = new HashMap<String, Integer>(); public static HashMap<Integer, String> numToWord = new HashMap<Integer, String>(); public static void initializeVocab(String vocabFilename) throws IOException { BufferedReader br = new BufferedReader(new FileReader(vocabFilename)); int rowIdx = 0; String line = br.readLine(); while (line != null) { String word = line.trim(); if (word.length() != 0) { wordToNum.put(word, rowIdx); numToWord.put(rowIdx, word); rowIdx++; } line = br.readLine(); } br.close(); } public static SimpleMatrix randomInitializeWordVectors(int vectorDimension, int numVectors) { allVecs = new SimpleMatrix(vectorDimension, numVectors); Random generator = new Random(); for (int colIdx = 0; colIdx < numVectors; colIdx++) { for (int rowIdx = 0; rowIdx < vectorDimension; rowIdx++) { double val = generator.nextDouble() * 2 - 1.0; // rand value between -1.0 and 1.0 allVecs.set(rowIdx, colIdx, val); } } return allVecs; } }
4,745
0.609905
0.604847
156
29.416666
26.607056
99
false
false
0
0
0
0
0
0
1.051282
false
false
7
f1e15d08e7bcedb0c1f7ee1c6ea4fa32213d5b58
11,871,289,649,031
997f6091a8a4885e01dfa0865a629e3d307859ad
/src/main/java/com/gupao/lzp/pattern/factory/abstractfactory/XiaoMiMobileFactory.java
7a17f6249ce795a545902f5443dc108db31f6f91
[]
no_license
zippo88li/netstudy
https://github.com/zippo88li/netstudy
a7a34c2c039b8ff25c562fc26d133efa553232cf
bc1a681cad1fe47539c60452c87db053079c731e
refs/heads/master
2020-04-29T22:38:10.046000
2019-03-19T08:25:12
2019-03-19T08:25:12
176,453,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gupao.lzp.pattern.factory.abstractfactory; public class XiaoMiMobileFactory extends AbstractMobileFactory { @Override IMobileCPU GetCPU() { return new MobileCPU(); } @Override IPingMu GetPingMu() { return new PingMu(); } @Override ISDKCard GetSDKCard() { return new SDkCard(); } }
UTF-8
Java
357
java
XiaoMiMobileFactory.java
Java
[]
null
[]
package com.gupao.lzp.pattern.factory.abstractfactory; public class XiaoMiMobileFactory extends AbstractMobileFactory { @Override IMobileCPU GetCPU() { return new MobileCPU(); } @Override IPingMu GetPingMu() { return new PingMu(); } @Override ISDKCard GetSDKCard() { return new SDkCard(); } }
357
0.638655
0.638655
18
18.833334
18.111538
65
false
false
0
0
0
0
0
0
0.222222
false
false
7
bfdb320cb380e88156689c7080a9f964a0b01523
23,751,169,216,510
b34e84cafbfcd449ccd665701aa1d0b134184454
/p1/gth773s/java/src/abcd/Memo.java
6a787b254c2cfc0a63dca72a01e9f9b4ca54f32e
[]
no_license
chris-martin/cs6241
https://github.com/chris-martin/cs6241
c2946bde3a5163d1cd366bf1c63f2e503a34bbee
49096936548477a1034280c729233f9b4806b3a1
refs/heads/master
2021-01-10T22:12:35.684000
2013-05-21T05:38:55
2013-05-21T05:38:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package abcd; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; class Memo { private Map<Diff, LBound> map = newHashMap(); L get(Inequality inequality) { Diff diff = inequality.diff(); LBound bound = diff.isConstant() ? diff.fixedBound() : map.get(diff); return bound == null ? null : bound.get(inequality.c()); } void modify(LBound.Action action, Inequality inequality, L l) { Diff diff = inequality.diff(); LBound bound = map.get(diff); if (bound == null) map.put(diff, bound = new LBound()); bound.modify(action, l, inequality.c()); if (bound.isVacuous()) map.remove(diff); } @Override public String toString() { List<Diff> keys = newArrayList(map.keySet()); Collections.sort(keys, valuePairComparator); return Joiner.on("\n").join(Lists.transform(keys, valuePairToString)); } private Function<Diff, String> valuePairToString = new Function<Diff, String>() { public String apply(Diff diff) { return map.get(diff).toString(diff); } }; private static Comparator<Diff> valuePairComparator = new Comparator<Diff>() { public int compare(Diff a, Diff b) { int result = compare(a.b(), b.b()); return result != 0 ? result : compare(a.a(), b.a()); } private int compare(Value a, Value b) { if (a == b) return 0; if (a.isConstant() != b.isConstant()) return Boolean.valueOf(a.isConstant()) .compareTo(Boolean.valueOf(b.isConstant())); else if (a.isConstant()) return Integer.valueOf(a.constant).compareTo(Integer.valueOf(b.constant)); else return a.nick.compareTo(b.nick); } }; }
UTF-8
Java
2,109
java
Memo.java
Java
[]
null
[]
package abcd; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; class Memo { private Map<Diff, LBound> map = newHashMap(); L get(Inequality inequality) { Diff diff = inequality.diff(); LBound bound = diff.isConstant() ? diff.fixedBound() : map.get(diff); return bound == null ? null : bound.get(inequality.c()); } void modify(LBound.Action action, Inequality inequality, L l) { Diff diff = inequality.diff(); LBound bound = map.get(diff); if (bound == null) map.put(diff, bound = new LBound()); bound.modify(action, l, inequality.c()); if (bound.isVacuous()) map.remove(diff); } @Override public String toString() { List<Diff> keys = newArrayList(map.keySet()); Collections.sort(keys, valuePairComparator); return Joiner.on("\n").join(Lists.transform(keys, valuePairToString)); } private Function<Diff, String> valuePairToString = new Function<Diff, String>() { public String apply(Diff diff) { return map.get(diff).toString(diff); } }; private static Comparator<Diff> valuePairComparator = new Comparator<Diff>() { public int compare(Diff a, Diff b) { int result = compare(a.b(), b.b()); return result != 0 ? result : compare(a.a(), b.a()); } private int compare(Value a, Value b) { if (a == b) return 0; if (a.isConstant() != b.isConstant()) return Boolean.valueOf(a.isConstant()) .compareTo(Boolean.valueOf(b.isConstant())); else if (a.isConstant()) return Integer.valueOf(a.constant).compareTo(Integer.valueOf(b.constant)); else return a.nick.compareTo(b.nick); } }; }
2,109
0.614509
0.613561
63
32.476189
25.871389
90
false
false
0
0
0
0
0
0
0.714286
false
false
4
5141d3019617ee9158e7a1045549c6ebd31ccf8f
29,308,856,886,522
8c5dab10499880b131c21e8611bec1ced30bc838
/src/main/java/com/zipato/logback/LoggingWebSocket.java
3aad13ee62f02bd34bf5e39cc89c5d456ebe3a52
[]
no_license
dbudor/logback-nanohttpd-appender
https://github.com/dbudor/logback-nanohttpd-appender
ad159ee22f85672c4c68f7e80d97823bf59d93f6
04c9eb84c2cb9088b32a707b17e88c73a2f81217
refs/heads/master
2021-07-21T08:10:31.302000
2017-10-30T16:16:52
2017-10-30T16:16:52
108,877,163
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zipato.logback; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.NanoWSD; import java.io.IOException; class LoggingWebSocket extends NanoWSD.WebSocket implements ClientWebsocket { private final NanoWSD server; private final LoggingWebsocketClient client; public LoggingWebSocket(NanoWSD server, NanoHTTPD.IHTTPSession handshakeRequest) { super(handshakeRequest); this.server = server; this.client = new LoggingWebsocketClient(this, handshakeRequest.getRemoteIpAddress() + ':' + handshakeRequest.getUri()); } @Override protected void onOpen() { } @Override protected void onClose(NanoWSD.WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) { client.close(); } @Override protected void onMessage(NanoWSD.WebSocketFrame message) { } @Override protected void onPong(NanoWSD.WebSocketFrame pong) { } @Override protected void onException(IOException exception) { } @Override protected void debugFrameReceived(NanoWSD.WebSocketFrame frame) { } @Override protected void debugFrameSent(NanoWSD.WebSocketFrame frame) { } @Override public WebsocketReceiverClient getClient() { return client; } }
UTF-8
Java
1,287
java
LoggingWebSocket.java
Java
[]
null
[]
package com.zipato.logback; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.NanoWSD; import java.io.IOException; class LoggingWebSocket extends NanoWSD.WebSocket implements ClientWebsocket { private final NanoWSD server; private final LoggingWebsocketClient client; public LoggingWebSocket(NanoWSD server, NanoHTTPD.IHTTPSession handshakeRequest) { super(handshakeRequest); this.server = server; this.client = new LoggingWebsocketClient(this, handshakeRequest.getRemoteIpAddress() + ':' + handshakeRequest.getUri()); } @Override protected void onOpen() { } @Override protected void onClose(NanoWSD.WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) { client.close(); } @Override protected void onMessage(NanoWSD.WebSocketFrame message) { } @Override protected void onPong(NanoWSD.WebSocketFrame pong) { } @Override protected void onException(IOException exception) { } @Override protected void debugFrameReceived(NanoWSD.WebSocketFrame frame) { } @Override protected void debugFrameSent(NanoWSD.WebSocketFrame frame) { } @Override public WebsocketReceiverClient getClient() { return client; } }
1,287
0.711733
0.711733
52
23.75
29.581617
128
false
false
0
0
0
0
0
0
0.288462
false
false
4
bd6701b0449fc8d29ba9ab391efbcc8016985c59
29,308,856,888,596
823aa47124a8e68074a4aee2c43ce58ce0591785
/app/src/main/java/co/audiobitts/audiobitts/Fragment/ExploreFragment.java
35d134431cf5b8fa3d36e5d0bf62887367c35198
[]
no_license
devcocup/AudioBitts_Android
https://github.com/devcocup/AudioBitts_Android
fbdde95a239a0697f5a8168b4024c567388e5b9e
50e8838458f167743b44a569b06c083c790c7677
refs/heads/master
2022-04-04T12:05:39.433000
2018-03-19T22:02:06
2018-03-19T22:02:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package co.audiobitts.audiobitts.Fragment; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import co.audiobitts.audiobitts.Adapter.BittsAdapter; import co.audiobitts.audiobitts.Class.Bitt; import co.audiobitts.audiobitts.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link ExploreFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link ExploreFragment#newInstance} factory method to * create an instance of this fragment. */ public class ExploreFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; private RecyclerView recyclerView; private BittsAdapter bittsAdapter; private List<Bitt> bittList; public ExploreFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ExploreFragment. */ // TODO: Rename and change types and number of parameters public static ExploreFragment newInstance(String param1, String param2) { ExploreFragment fragment = new ExploreFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_explore, container, false); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerView = view.findViewById(R.id.bitts_recycle_view); recyclerView.setLayoutManager(layoutManager); bittList = new ArrayList<>(); bittsAdapter = new BittsAdapter(getActivity(), bittList); recyclerView.setAdapter(bittsAdapter); prepareBitts(); return view; } private void prepareBitts() { Bitt bitt = new Bitt("heltleo59", "", "Let it go", "3 mo", "12", "4", "", "8", "0.15", "This is test."); bittList.add(bitt); bitt = new Bitt("heltleo59", "", "I see the light", "3 mo", "32", "11", "", "18", "3.15", "I love Tangled."); bittList.add(bitt); bitt = new Bitt("heltleo59", "", "Frozen", "3 mo", "42", "4", "", "25", "2.15", "Ice Girl."); bittList.add(bitt); bittsAdapter.notifyDataSetChanged(); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
UTF-8
Java
5,052
java
ExploreFragment.java
Java
[]
null
[]
package co.audiobitts.audiobitts.Fragment; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import co.audiobitts.audiobitts.Adapter.BittsAdapter; import co.audiobitts.audiobitts.Class.Bitt; import co.audiobitts.audiobitts.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link ExploreFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link ExploreFragment#newInstance} factory method to * create an instance of this fragment. */ public class ExploreFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; private RecyclerView recyclerView; private BittsAdapter bittsAdapter; private List<Bitt> bittList; public ExploreFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ExploreFragment. */ // TODO: Rename and change types and number of parameters public static ExploreFragment newInstance(String param1, String param2) { ExploreFragment fragment = new ExploreFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_explore, container, false); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerView = view.findViewById(R.id.bitts_recycle_view); recyclerView.setLayoutManager(layoutManager); bittList = new ArrayList<>(); bittsAdapter = new BittsAdapter(getActivity(), bittList); recyclerView.setAdapter(bittsAdapter); prepareBitts(); return view; } private void prepareBitts() { Bitt bitt = new Bitt("heltleo59", "", "Let it go", "3 mo", "12", "4", "", "8", "0.15", "This is test."); bittList.add(bitt); bitt = new Bitt("heltleo59", "", "I see the light", "3 mo", "32", "11", "", "18", "3.15", "I love Tangled."); bittList.add(bitt); bitt = new Bitt("heltleo59", "", "Frozen", "3 mo", "42", "4", "", "25", "2.15", "Ice Girl."); bittList.add(bitt); bittsAdapter.notifyDataSetChanged(); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
5,052
0.666667
0.655582
142
34.577465
25.04006
127
false
false
0
0
0
0
0
0
0.669014
false
false
4
af2a6d96ef8cf33a3fd38c3c666173293584a23f
8,177,617,741,290
d4f9b244b25b971a0f5272013b27e12a64c8258b
/src/main/java/com/alkemy/explorandodisney/domain/repository/CharacterRepository.java
4d70470b6cb59b05a5126f676a04af146600bf0f
[]
no_license
florenciazabala/Explorando-Disney
https://github.com/florenciazabala/Explorando-Disney
45e2b2636d18a7fbbf0ee4368ad07abfa9efc7ff
d5d3257fc83650d9ab89366db02ea882201375e0
refs/heads/master
2023-07-17T11:58:09.658000
2021-09-04T17:54:06
2021-09-04T17:54:06
400,032,414
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alkemy.explorandodisney.domain.repository; import com.alkemy.explorandodisney.domain.Character; import com.alkemy.explorandodisney.domain.CharacterList; import com.alkemy.explorandodisney.persistence.entity.Personaje; import java.util.List; import java.util.Optional; public interface CharacterRepository { void createCharacter(String name,Integer age,Double weight,String story); //List<CharacterList> getAll(); List<CharacterList> getAll(); List<CharacterList> getByName(String name); List<CharacterList> getByAge(Integer youngerAge, Integer olderAge); List<CharacterList> getByWeight(Double lowerWeight, Double higherWeight); List<CharacterList> getByMovies(String title); Optional<Character> getById(Long idCharacter); Optional<Character> getByExcactName(String name); void updateCharacter(String name,Integer age,Double weight,String story,Long id); void updateCharacterImage(String picture, Long idCharacter); void deleteByIdCharacter(Long idCharacter); void deleteByNameCharacter(String name); Integer existsRelation(Long idCharacter, Long idMovie); void createRelationMovie(Long idCharacter, Long idMovie); void deleteRelation(Long idCharacter); void deleteRelationCharacterMovie(Long idPersonaje,Long idPelicula); }
UTF-8
Java
1,310
java
CharacterRepository.java
Java
[]
null
[]
package com.alkemy.explorandodisney.domain.repository; import com.alkemy.explorandodisney.domain.Character; import com.alkemy.explorandodisney.domain.CharacterList; import com.alkemy.explorandodisney.persistence.entity.Personaje; import java.util.List; import java.util.Optional; public interface CharacterRepository { void createCharacter(String name,Integer age,Double weight,String story); //List<CharacterList> getAll(); List<CharacterList> getAll(); List<CharacterList> getByName(String name); List<CharacterList> getByAge(Integer youngerAge, Integer olderAge); List<CharacterList> getByWeight(Double lowerWeight, Double higherWeight); List<CharacterList> getByMovies(String title); Optional<Character> getById(Long idCharacter); Optional<Character> getByExcactName(String name); void updateCharacter(String name,Integer age,Double weight,String story,Long id); void updateCharacterImage(String picture, Long idCharacter); void deleteByIdCharacter(Long idCharacter); void deleteByNameCharacter(String name); Integer existsRelation(Long idCharacter, Long idMovie); void createRelationMovie(Long idCharacter, Long idMovie); void deleteRelation(Long idCharacter); void deleteRelationCharacterMovie(Long idPersonaje,Long idPelicula); }
1,310
0.79542
0.79542
30
42.666668
25.619436
85
false
false
0
0
0
0
0
0
1.2
false
false
4
df5a2dcf7ad5a6afda04bfc71b7e0b5e1c9582d6
12,077,448,036,611
9aa93b10798b1c07f12fea3f4b5370421ffd185e
/services-rest/exponential-service/src/com/exponential/ExponentialService.java
44ca8c8d272ec331bd4c22b4ba6e3b73f91b1c92
[]
no_license
alexgifei/tripping-adventure
https://github.com/alexgifei/tripping-adventure
f6f077c3c4cc18641e114e2a7f92247660a24e5d
489e9ffc83ae77d486e62c925b75021154895fe6
refs/heads/master
2021-01-22T11:47:16.919000
2014-06-23T20:20:29
2014-06-23T20:20:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.exponential; import com.fasterxml.jackson.databind.ObjectMapper; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.io.IOException; /** * Created by alexg on 01.06.2014. */ @Path("/Exponential") public class ExponentialService { @PUT @Path("/pow") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ExponentialResponse pow(final String json) throws IOException { final PowRequest request = new ObjectMapper().readValue(json, PowRequest.class); final long start = System.nanoTime(); final Double result = Math.pow(request.getFirstParam(), request.getSecondParam()); final String elapsedTime = System.nanoTime() - start + ""; final ExponentialResponse response = new ExponentialResponse(); response.setElapsedTime(elapsedTime); response.setOperationId(String.valueOf(start)); response.setResult(result); return response; } @PUT @Path("/log") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ExponentialResponse log(final String json) throws IOException { final LogRequest request = new ObjectMapper().readValue(json, LogRequest.class); final long start = System.nanoTime(); final Double result = Math.log(request.getParam()); final String elapsedTime = System.nanoTime() - start + ""; final ExponentialResponse response = new ExponentialResponse(); response.setElapsedTime(elapsedTime); response.setOperationId(String.valueOf(start)); response.setResult(result); return response; } @GET @Produces(MediaType.TEXT_HTML) public String info(){ return "Exponential Service"; } }
UTF-8
Java
1,792
java
ExponentialService.java
Java
[ { "context": "pe;\nimport java.io.IOException;\n\n/**\n * Created by alexg on 01.06.2014.\n */\n@Path(\"/Exponential\")\npublic c", "end": 188, "score": 0.9996426701545715, "start": 183, "tag": "USERNAME", "value": "alexg" } ]
null
[]
package com.exponential; import com.fasterxml.jackson.databind.ObjectMapper; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.io.IOException; /** * Created by alexg on 01.06.2014. */ @Path("/Exponential") public class ExponentialService { @PUT @Path("/pow") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ExponentialResponse pow(final String json) throws IOException { final PowRequest request = new ObjectMapper().readValue(json, PowRequest.class); final long start = System.nanoTime(); final Double result = Math.pow(request.getFirstParam(), request.getSecondParam()); final String elapsedTime = System.nanoTime() - start + ""; final ExponentialResponse response = new ExponentialResponse(); response.setElapsedTime(elapsedTime); response.setOperationId(String.valueOf(start)); response.setResult(result); return response; } @PUT @Path("/log") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ExponentialResponse log(final String json) throws IOException { final LogRequest request = new ObjectMapper().readValue(json, LogRequest.class); final long start = System.nanoTime(); final Double result = Math.log(request.getParam()); final String elapsedTime = System.nanoTime() - start + ""; final ExponentialResponse response = new ExponentialResponse(); response.setElapsedTime(elapsedTime); response.setOperationId(String.valueOf(start)); response.setResult(result); return response; } @GET @Produces(MediaType.TEXT_HTML) public String info(){ return "Exponential Service"; } }
1,792
0.689732
0.685268
52
33.46154
26.043943
90
false
false
0
0
0
0
0
0
0.519231
false
false
4
45be2ac88828161c87463332f1f0b5ebcab6616b
20,289,425,521,672
88ce808b877b60c55fa7069f24d43cdc1394adbe
/java/game_plaza/plazawss/src/com/lxtech/game/plaza/db/model/AnimalDialSettlementGroup.java
87c25949ea2e581b73f287809e6c67ca9a996b88
[]
no_license
moutainhigh/lxtx
https://github.com/moutainhigh/lxtx
d2f7130f7440a9d133951a333b7d6b387ca3e51f
a2ea814de9b6d62bb139bf8a1ff1642dd2cb9551
refs/heads/master
2021-07-23T08:14:58.164000
2017-11-02T11:48:45
2017-11-02T11:48:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lxtech.game.plaza.db.model; import java.util.Date; public class AnimalDialSettlementGroup { private Integer id; private Integer banker_id; private Long banker_carry_amount; private Date start_time; private Integer combined_two_tiandi; private Integer combined_two_animal; private Integer combined_three_tiandi; private Integer combined_three_wuxing; private Integer combined_three_animal; private Date end_time; private Integer result_tiandi; private Integer result_wuxing; private Integer result_animal; private Integer state; private Long banker_settlement_result; public Long getBanker_carry_amount() { return banker_carry_amount; } public void setBanker_carry_amount(Long banker_carry_amount) { this.banker_carry_amount = banker_carry_amount; } public Date getStart_time() { return start_time; } public void setStart_time(Date start_time) { this.start_time = start_time; } public Date getEnd_time() { return end_time; } public void setEnd_time(Date end_time) { this.end_time = end_time; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getBanker_id() { return banker_id; } public void setBanker_id(Integer banker_id) { this.banker_id = banker_id; } public Long getBanker_settlement_result() { return banker_settlement_result; } public void setBanker_settlement_result(Long banker_settlerment_result) { this.banker_settlement_result = banker_settlerment_result; } public Integer getCombined_two_tiandi() { return combined_two_tiandi; } public void setCombined_two_tiandi(Integer combined_two_tiandi) { this.combined_two_tiandi = combined_two_tiandi; } public Integer getCombined_two_animal() { return combined_two_animal; } public void setCombined_two_animal(Integer combined_two_animal) { this.combined_two_animal = combined_two_animal; } public Integer getCombined_three_tiandi() { return combined_three_tiandi; } public void setCombined_three_tiandi(Integer combined_three_tiandi) { this.combined_three_tiandi = combined_three_tiandi; } public Integer getCombined_three_wuxing() { return combined_three_wuxing; } public void setCombined_three_wuxing(Integer combined_three_wuxing) { this.combined_three_wuxing = combined_three_wuxing; } public Integer getCombined_three_animal() { return combined_three_animal; } public void setCombined_three_animal(Integer combined_three_animal) { this.combined_three_animal = combined_three_animal; } public Integer getResult_tiandi() { return result_tiandi; } public void setResult_tiandi(Integer result_tiandi) { this.result_tiandi = result_tiandi; } public Integer getResult_wuxing() { return result_wuxing; } public void setResult_wuxing(Integer result_wuxing) { this.result_wuxing = result_wuxing; } public Integer getResult_animal() { return result_animal; } public void setResult_animal(Integer result_animal) { this.result_animal = result_animal; } }
UTF-8
Java
3,139
java
AnimalDialSettlementGroup.java
Java
[]
null
[]
package com.lxtech.game.plaza.db.model; import java.util.Date; public class AnimalDialSettlementGroup { private Integer id; private Integer banker_id; private Long banker_carry_amount; private Date start_time; private Integer combined_two_tiandi; private Integer combined_two_animal; private Integer combined_three_tiandi; private Integer combined_three_wuxing; private Integer combined_three_animal; private Date end_time; private Integer result_tiandi; private Integer result_wuxing; private Integer result_animal; private Integer state; private Long banker_settlement_result; public Long getBanker_carry_amount() { return banker_carry_amount; } public void setBanker_carry_amount(Long banker_carry_amount) { this.banker_carry_amount = banker_carry_amount; } public Date getStart_time() { return start_time; } public void setStart_time(Date start_time) { this.start_time = start_time; } public Date getEnd_time() { return end_time; } public void setEnd_time(Date end_time) { this.end_time = end_time; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getBanker_id() { return banker_id; } public void setBanker_id(Integer banker_id) { this.banker_id = banker_id; } public Long getBanker_settlement_result() { return banker_settlement_result; } public void setBanker_settlement_result(Long banker_settlerment_result) { this.banker_settlement_result = banker_settlerment_result; } public Integer getCombined_two_tiandi() { return combined_two_tiandi; } public void setCombined_two_tiandi(Integer combined_two_tiandi) { this.combined_two_tiandi = combined_two_tiandi; } public Integer getCombined_two_animal() { return combined_two_animal; } public void setCombined_two_animal(Integer combined_two_animal) { this.combined_two_animal = combined_two_animal; } public Integer getCombined_three_tiandi() { return combined_three_tiandi; } public void setCombined_three_tiandi(Integer combined_three_tiandi) { this.combined_three_tiandi = combined_three_tiandi; } public Integer getCombined_three_wuxing() { return combined_three_wuxing; } public void setCombined_three_wuxing(Integer combined_three_wuxing) { this.combined_three_wuxing = combined_three_wuxing; } public Integer getCombined_three_animal() { return combined_three_animal; } public void setCombined_three_animal(Integer combined_three_animal) { this.combined_three_animal = combined_three_animal; } public Integer getResult_tiandi() { return result_tiandi; } public void setResult_tiandi(Integer result_tiandi) { this.result_tiandi = result_tiandi; } public Integer getResult_wuxing() { return result_wuxing; } public void setResult_wuxing(Integer result_wuxing) { this.result_wuxing = result_wuxing; } public Integer getResult_animal() { return result_animal; } public void setResult_animal(Integer result_animal) { this.result_animal = result_animal; } }
3,139
0.742593
0.742593
142
21.105635
21.059175
74
false
false
0
0
0
0
0
0
1.28169
false
false
4
9e0f08036cd2ded1c838451ddb2edf998c39b02d
1,133,871,426,528
ff01e72decb9e63513e99e08bfe6d28f34bfdde0
/src/com/signetitsolutions/bluebook/server/classes/Investigation.java
54afcf385d76479b74f485b77c87cf13eefbd5f4
[]
no_license
mahdera/blueBook
https://github.com/mahdera/blueBook
efd252bb674a003d653287250c6f66e0df72a5b6
ce230d39d5dfedd66e4adf6fefaac31860928106
refs/heads/master
2020-04-27T16:36:02.450000
2014-07-22T14:14:44
2014-07-22T14:14:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.signetitsolutions.bluebook.server.classes; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author Mahder on macbook Pro * */ public class Investigation { private long id; private String fileNumber; private String whatToRegister; private int caseStatusId; private String nextActionAndDate; private int modifiedBy; private Date modificationDate; /** * */ public Investigation() { } /** * @param fileNumber * @param whatToRegister * @param caseStatusId * @param nextActionAndDate * @param modifiedBy * @param modificationDate */ public Investigation(String fileNumber, String whatToRegister, int caseStatusId, String nextActionAndDate, int modifiedBy, Date modificationDate) { this.fileNumber = fileNumber; this.whatToRegister = whatToRegister; this.caseStatusId = caseStatusId; this.nextActionAndDate = nextActionAndDate; this.modifiedBy = modifiedBy; this.modificationDate = modificationDate; } /** * @param id * @param fileNumber * @param whatToRegister * @param caseStatusId * @param nextActionAndDate * @param modifiedBy * @param modificationDate */ public Investigation(long id, String fileNumber, String whatToRegister, int caseStatusId, String nextActionAndDate, int modifiedBy, Date modificationDate) { this.id = id; this.fileNumber = fileNumber; this.whatToRegister = whatToRegister; this.caseStatusId = caseStatusId; this.nextActionAndDate = nextActionAndDate; this.modifiedBy = modifiedBy; this.modificationDate = modificationDate; } /** * @return the id */ public long getId() { return id; } /** * @param id * the id to set */ public void setId(long id) { this.id = id; } /** * @return the fileNumber */ public String getFileNumber() { return fileNumber; } /** * @param fileNumber * the fileNumber to set */ public void setFileNumber(String fileNumber) { this.fileNumber = fileNumber; } /** * @return the whatToRegister */ public String getWhatToRegister() { return whatToRegister; } /** * @param whatToRegister * the whatToRegister to set */ public void setWhatToRegister(String whatToRegister) { this.whatToRegister = whatToRegister; } /** * @return the caseStatusId */ public int getCaseStatusId() { return caseStatusId; } /** * @param caseStatusId * the caseStatusId to set */ public void setCaseStatusId(int caseStatusId) { this.caseStatusId = caseStatusId; } /** * @return the nextActionAndDate */ public String getNextActionAndDate() { return nextActionAndDate; } /** * @param nextActionAndDate * the nextActionAndDate to set */ public void setNextActionAndDate(String nextActionAndDate) { this.nextActionAndDate = nextActionAndDate; } /** * @return the modifiedBy */ public int getModifiedBy() { return modifiedBy; } /** * @param modifiedBy * the modifiedBy to set */ public void setModifiedBy(int modifiedBy) { this.modifiedBy = modifiedBy; } /** * @return the modificationDate */ public Date getModificationDate() { return modificationDate; } /** * @param modificationDate * the modificationDate to set */ public void setModificationDate(Date modificationDate) { this.modificationDate = modificationDate; } public void save() { try { String sqlStr = "insert into tbl_investigation values(?,?,?,?,?,?,?)"; PreparedStatement pStmt = DBConnection.getPreparedStatement(sqlStr); pStmt.setLong(1, 0); pStmt.setString(2, this.getFileNumber()); pStmt.setString(3, this.getWhatToRegister()); pStmt.setInt(4, this.getCaseStatusId()); pStmt.setString(5, this.getNextActionAndDate()); pStmt.setInt(6, this.getModifiedBy()); pStmt.setDate(7, this.getModificationDate()); DBConnection.writeToDatabase(pStmt); } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } } public static void update(Investigation investigation) { try { String sqlStr = "update tbl_investigation set file_number = ?, what_to_register = ?," + "case_status_id = ?, next_action_and_date = ?, modified_by = ?, modification_date = ?" + " where id = ?"; PreparedStatement pStmt = DBConnection.getPreparedStatement(sqlStr); pStmt.setString(1, investigation.getFileNumber()); pStmt.setString(2, investigation.getWhatToRegister()); pStmt.setInt(3, investigation.getCaseStatusId()); pStmt.setString(4, investigation.getNextActionAndDate()); pStmt.setInt(5, investigation.getModifiedBy()); pStmt.setDate(6, investigation.getModificationDate()); pStmt.setLong(7, investigation.getId()); DBConnection.writeToDatabase(pStmt); } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } } public static void delete(long id) { try { String sqlStr = "delete from tbl_investigation where id = ?"; PreparedStatement pStmt = DBConnection.getPreparedStatement(sqlStr); pStmt.setLong(1, id); DBConnection.writeToDatabase(pStmt); } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } } public static List<Investigation> getAllInvestigations() { List<Investigation> list = new ArrayList<Investigation>(); Investigation investigation = null; try { String query = "select * from tbl_investigation order by modification_date desc"; ResultSet rSet = DBConnection.readFromDatabase(query); while(rSet.next()){ investigation = new Investigation(rSet.getLong("id"), rSet.getString("file_number"), rSet.getString("what_to_register"), rSet.getInt("case_status_id"), rSet.getString("next_action_and_date"), rSet.getInt("modified_by"), rSet.getDate("modification_date")); list.add(investigation); } } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } return list; } public static Investigation getInvestigation(long id) { Investigation investigation = null; try { String query = "select * from tbl_investigation where id = "+id; ResultSet rSet = DBConnection.readFromDatabase(query); while(rSet.next()){ investigation = new Investigation(rSet.getLong("id"), rSet.getString("file_number"), rSet.getString("what_to_register"), rSet.getInt("case_status_id"), rSet.getString("next_action_and_date"), rSet.getInt("modified_by"), rSet.getDate("modification_date")); } } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } return investigation; } public static Investigation getInvestigationObjectUsing(String fileNumber,String whatToRegister,int fileStatusId, int modifiedBy, Date modificationDate){ Investigation investigation = null; try { String query = "select * from tbl_investigation where file_number = '"+fileNumber+"' and what_to_register = '"+ whatToRegister+"' and case_status_id = "+fileStatusId+" and modified_by = "+modifiedBy+" and "+ "modification_date = '"+modificationDate+"'"; ResultSet rSet = DBConnection.readFromDatabase(query); while(rSet.next()){ investigation = new Investigation(rSet.getLong("id"), rSet.getString("file_number"), rSet.getString("what_to_register"), rSet.getInt("case_status_id"), rSet.getString("next_action_and_date"), rSet.getInt("modified_by"), rSet.getDate("modification_date")); } } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } return investigation; } public static List<Investigation> getAllInvestigationsForFileNumber(String fileNumber){ List<Investigation> list = new ArrayList<Investigation>(); Investigation investigation = null; try { String query = "select * from tbl_investigation where file_number = '"+fileNumber+"' order by id desc"; ResultSet rSet = DBConnection.readFromDatabase(query); while(rSet.next()){ investigation = new Investigation(rSet.getLong("id"), rSet.getString("file_number"), rSet.getString("what_to_register"), rSet.getInt("case_status_id"), rSet.getString("next_action_and_date"), rSet.getInt("modified_by"), rSet.getDate("modification_date")); list.add(investigation); } } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } return list; } }// end class
UTF-8
Java
8,632
java
Investigation.java
Java
[ { "context": "l.Iterator;\nimport java.util.List;\n\n/**\n * @author Mahder on macbook Pro\n * \n */\npublic class Investigation", "end": 252, "score": 0.9979975819587708, "start": 246, "tag": "USERNAME", "value": "Mahder" } ]
null
[]
/** * */ package com.signetitsolutions.bluebook.server.classes; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author Mahder on macbook Pro * */ public class Investigation { private long id; private String fileNumber; private String whatToRegister; private int caseStatusId; private String nextActionAndDate; private int modifiedBy; private Date modificationDate; /** * */ public Investigation() { } /** * @param fileNumber * @param whatToRegister * @param caseStatusId * @param nextActionAndDate * @param modifiedBy * @param modificationDate */ public Investigation(String fileNumber, String whatToRegister, int caseStatusId, String nextActionAndDate, int modifiedBy, Date modificationDate) { this.fileNumber = fileNumber; this.whatToRegister = whatToRegister; this.caseStatusId = caseStatusId; this.nextActionAndDate = nextActionAndDate; this.modifiedBy = modifiedBy; this.modificationDate = modificationDate; } /** * @param id * @param fileNumber * @param whatToRegister * @param caseStatusId * @param nextActionAndDate * @param modifiedBy * @param modificationDate */ public Investigation(long id, String fileNumber, String whatToRegister, int caseStatusId, String nextActionAndDate, int modifiedBy, Date modificationDate) { this.id = id; this.fileNumber = fileNumber; this.whatToRegister = whatToRegister; this.caseStatusId = caseStatusId; this.nextActionAndDate = nextActionAndDate; this.modifiedBy = modifiedBy; this.modificationDate = modificationDate; } /** * @return the id */ public long getId() { return id; } /** * @param id * the id to set */ public void setId(long id) { this.id = id; } /** * @return the fileNumber */ public String getFileNumber() { return fileNumber; } /** * @param fileNumber * the fileNumber to set */ public void setFileNumber(String fileNumber) { this.fileNumber = fileNumber; } /** * @return the whatToRegister */ public String getWhatToRegister() { return whatToRegister; } /** * @param whatToRegister * the whatToRegister to set */ public void setWhatToRegister(String whatToRegister) { this.whatToRegister = whatToRegister; } /** * @return the caseStatusId */ public int getCaseStatusId() { return caseStatusId; } /** * @param caseStatusId * the caseStatusId to set */ public void setCaseStatusId(int caseStatusId) { this.caseStatusId = caseStatusId; } /** * @return the nextActionAndDate */ public String getNextActionAndDate() { return nextActionAndDate; } /** * @param nextActionAndDate * the nextActionAndDate to set */ public void setNextActionAndDate(String nextActionAndDate) { this.nextActionAndDate = nextActionAndDate; } /** * @return the modifiedBy */ public int getModifiedBy() { return modifiedBy; } /** * @param modifiedBy * the modifiedBy to set */ public void setModifiedBy(int modifiedBy) { this.modifiedBy = modifiedBy; } /** * @return the modificationDate */ public Date getModificationDate() { return modificationDate; } /** * @param modificationDate * the modificationDate to set */ public void setModificationDate(Date modificationDate) { this.modificationDate = modificationDate; } public void save() { try { String sqlStr = "insert into tbl_investigation values(?,?,?,?,?,?,?)"; PreparedStatement pStmt = DBConnection.getPreparedStatement(sqlStr); pStmt.setLong(1, 0); pStmt.setString(2, this.getFileNumber()); pStmt.setString(3, this.getWhatToRegister()); pStmt.setInt(4, this.getCaseStatusId()); pStmt.setString(5, this.getNextActionAndDate()); pStmt.setInt(6, this.getModifiedBy()); pStmt.setDate(7, this.getModificationDate()); DBConnection.writeToDatabase(pStmt); } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } } public static void update(Investigation investigation) { try { String sqlStr = "update tbl_investigation set file_number = ?, what_to_register = ?," + "case_status_id = ?, next_action_and_date = ?, modified_by = ?, modification_date = ?" + " where id = ?"; PreparedStatement pStmt = DBConnection.getPreparedStatement(sqlStr); pStmt.setString(1, investigation.getFileNumber()); pStmt.setString(2, investigation.getWhatToRegister()); pStmt.setInt(3, investigation.getCaseStatusId()); pStmt.setString(4, investigation.getNextActionAndDate()); pStmt.setInt(5, investigation.getModifiedBy()); pStmt.setDate(6, investigation.getModificationDate()); pStmt.setLong(7, investigation.getId()); DBConnection.writeToDatabase(pStmt); } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } } public static void delete(long id) { try { String sqlStr = "delete from tbl_investigation where id = ?"; PreparedStatement pStmt = DBConnection.getPreparedStatement(sqlStr); pStmt.setLong(1, id); DBConnection.writeToDatabase(pStmt); } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } } public static List<Investigation> getAllInvestigations() { List<Investigation> list = new ArrayList<Investigation>(); Investigation investigation = null; try { String query = "select * from tbl_investigation order by modification_date desc"; ResultSet rSet = DBConnection.readFromDatabase(query); while(rSet.next()){ investigation = new Investigation(rSet.getLong("id"), rSet.getString("file_number"), rSet.getString("what_to_register"), rSet.getInt("case_status_id"), rSet.getString("next_action_and_date"), rSet.getInt("modified_by"), rSet.getDate("modification_date")); list.add(investigation); } } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } return list; } public static Investigation getInvestigation(long id) { Investigation investigation = null; try { String query = "select * from tbl_investigation where id = "+id; ResultSet rSet = DBConnection.readFromDatabase(query); while(rSet.next()){ investigation = new Investigation(rSet.getLong("id"), rSet.getString("file_number"), rSet.getString("what_to_register"), rSet.getInt("case_status_id"), rSet.getString("next_action_and_date"), rSet.getInt("modified_by"), rSet.getDate("modification_date")); } } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } return investigation; } public static Investigation getInvestigationObjectUsing(String fileNumber,String whatToRegister,int fileStatusId, int modifiedBy, Date modificationDate){ Investigation investigation = null; try { String query = "select * from tbl_investigation where file_number = '"+fileNumber+"' and what_to_register = '"+ whatToRegister+"' and case_status_id = "+fileStatusId+" and modified_by = "+modifiedBy+" and "+ "modification_date = '"+modificationDate+"'"; ResultSet rSet = DBConnection.readFromDatabase(query); while(rSet.next()){ investigation = new Investigation(rSet.getLong("id"), rSet.getString("file_number"), rSet.getString("what_to_register"), rSet.getInt("case_status_id"), rSet.getString("next_action_and_date"), rSet.getInt("modified_by"), rSet.getDate("modification_date")); } } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } return investigation; } public static List<Investigation> getAllInvestigationsForFileNumber(String fileNumber){ List<Investigation> list = new ArrayList<Investigation>(); Investigation investigation = null; try { String query = "select * from tbl_investigation where file_number = '"+fileNumber+"' order by id desc"; ResultSet rSet = DBConnection.readFromDatabase(query); while(rSet.next()){ investigation = new Investigation(rSet.getLong("id"), rSet.getString("file_number"), rSet.getString("what_to_register"), rSet.getInt("case_status_id"), rSet.getString("next_action_and_date"), rSet.getInt("modified_by"), rSet.getDate("modification_date")); list.add(investigation); } } catch (Exception e) { e.printStackTrace(); } finally { DBConnection.disconnectDatabase(); } return list; } }// end class
8,632
0.697521
0.695667
312
26.666666
24.508982
114
false
false
0
0
0
0
0
0
2.333333
false
false
4
1bee5788897bba67093550b6ede8c988e97ab75f
33,457,795,250,704
e16bd86304c7b8bbd101502c9d3b5924f19a708d
/project_a2w0b/src/main/model/pieces/Piece.java
604dd26574456a832adfcc6c7630b8a498a03ce2
[]
no_license
mamatthew/Chess
https://github.com/mamatthew/Chess
0fafcfbf8ba6e69c1f48f2636379306a46958980
27bda844a7443941daa05e039ab2caa261c561f7
refs/heads/main
2023-02-04T22:01:12.821000
2020-12-24T00:46:57
2020-12-24T00:46:57
324,030,724
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model.pieces; import model.Board; import model.Color; import model.Square; import java.util.List; /*Piece is an abstract class representing generic information common to all specific piece types*/ public abstract class Piece { protected Color color; protected Square square; protected Board board; public int value; public Board getBoard() { return board; } public void setBoard(Board board) { this.board = board; } //EFFECTS: initializes a piece with a given color and associates it with a board public Piece(Color color, Board board) { this.color = color; this.board = board; } public Color getColor() { return color; } public Square getSquare() { return square; } public void setSquare(Square square) { this.square = square; } //REQUIRES: square must exist on board //MODIFIES: this //EFFECTS: moves this to destination and return true if possible // return false otherwise public abstract boolean findPath(Square square); //REQUIRES: squares (x1, y1) and (x2, y2) exist on board //MODIFIES: this //EFFECTS: moves this from (x1, y1) to (x2, y2) and return true if possible // return false otherwise public abstract boolean hasValidPath(int x1, int y1, int x2, int y2); public abstract int getValue(); }
UTF-8
Java
1,451
java
Piece.java
Java
[]
null
[]
package model.pieces; import model.Board; import model.Color; import model.Square; import java.util.List; /*Piece is an abstract class representing generic information common to all specific piece types*/ public abstract class Piece { protected Color color; protected Square square; protected Board board; public int value; public Board getBoard() { return board; } public void setBoard(Board board) { this.board = board; } //EFFECTS: initializes a piece with a given color and associates it with a board public Piece(Color color, Board board) { this.color = color; this.board = board; } public Color getColor() { return color; } public Square getSquare() { return square; } public void setSquare(Square square) { this.square = square; } //REQUIRES: square must exist on board //MODIFIES: this //EFFECTS: moves this to destination and return true if possible // return false otherwise public abstract boolean findPath(Square square); //REQUIRES: squares (x1, y1) and (x2, y2) exist on board //MODIFIES: this //EFFECTS: moves this from (x1, y1) to (x2, y2) and return true if possible // return false otherwise public abstract boolean hasValidPath(int x1, int y1, int x2, int y2); public abstract int getValue(); }
1,451
0.636802
0.628532
56
23.910715
23.332439
98
false
false
0
0
0
0
0
0
0.482143
false
false
4
5d2bd83d0876461414e8df956845e781740d559e
11,682,311,048,102
ae753424f406d58db3f070a2416d0d7aeffcf747
/LibraryV1.6/src/modules/login/classes/Admin.java
0e84b609c51fbd089ba4cd09ea5c9c61cd88b0b3
[]
no_license
ALEJ4NDRO29/java
https://github.com/ALEJ4NDRO29/java
0509bef23f6ec587f4ad27e98bb12bbad6c593ae
7f084499edde7a57699f32a933aac80b38954872
refs/heads/master
2018-12-22T11:18:08.367000
2018-12-04T20:20:32
2018-12-04T20:20:32
150,475,630
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package modules.login.classes; import classes.dates.Dates; public class Admin extends User { private Dates contractDate; public Admin(String DNI, String password, String name, String surnames, Dates birthdate, Dates contractDate) { super(DNI, password, name, surnames, birthdate, "admin"); this.contractDate = contractDate; } public Dates getContractDate() { return contractDate; } public void setContractDate(Dates contractDate) { this.contractDate = contractDate; } public Admin copy() { return new Admin(this.getDNI(), this.getPassword(), this.getName(), this.getSurnames(), this.getBirthdate(), this.contractDate); } public String toString() { return "User [ DNI = " + getDNI() + "\n" + "name = " + getName() + "\n" + "surnames = " + getSurnames() + "\n" + "birthDate = " + getBirthdate() + "\n" + "yearsOld = " + getYearsOld() + "\n" + "type = " + getType() + "\n" + "contractDate = " + contractDate + "]"; } }
UTF-8
Java
991
java
Admin.java
Java
[]
null
[]
package modules.login.classes; import classes.dates.Dates; public class Admin extends User { private Dates contractDate; public Admin(String DNI, String password, String name, String surnames, Dates birthdate, Dates contractDate) { super(DNI, password, name, surnames, birthdate, "admin"); this.contractDate = contractDate; } public Dates getContractDate() { return contractDate; } public void setContractDate(Dates contractDate) { this.contractDate = contractDate; } public Admin copy() { return new Admin(this.getDNI(), this.getPassword(), this.getName(), this.getSurnames(), this.getBirthdate(), this.contractDate); } public String toString() { return "User [ DNI = " + getDNI() + "\n" + "name = " + getName() + "\n" + "surnames = " + getSurnames() + "\n" + "birthDate = " + getBirthdate() + "\n" + "yearsOld = " + getYearsOld() + "\n" + "type = " + getType() + "\n" + "contractDate = " + contractDate + "]"; } }
991
0.640767
0.640767
37
25.783783
29.357199
130
false
false
0
0
0
0
0
0
2.648649
false
false
4
b7560ec377093b080fab10c239e2b0eee583543b
11,682,311,049,734
7485a64fdfc29c4e2b397ffd4155ba1d3ff3eedc
/SRC/SupermovilWeb/SMovWSLib/src/com/oesia/movilidad/ws/response/dto/Contacto.java
73684a9be834ca3fa3c17de212364c865ae118d1
[]
no_license
CEyC/FSW
https://github.com/CEyC/FSW
e640d9eff5db737de909ed5954560342bac42978
a44ef4b188aacf03aa4d9c4fd7050d4a48bf5be6
refs/heads/master
2017-11-28T09:31:25.158000
2016-06-02T18:05:13
2016-06-02T18:05:13
40,670,638
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oesia.movilidad.ws.response.dto; public class Contacto { String nombre; String id; String email; String descripcion; String telefono1; String fax; String telefono2; String url; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getTelefono1() { return telefono1; } public void setTelefono1(String telefono1) { this.telefono1 = telefono1; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getTelefono2() { return telefono2; } public void setTelefono2(String telefono2) { this.telefono2 = telefono2; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
UTF-8
Java
1,175
java
Contacto.java
Java
[]
null
[]
package com.oesia.movilidad.ws.response.dto; public class Contacto { String nombre; String id; String email; String descripcion; String telefono1; String fax; String telefono2; String url; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getTelefono1() { return telefono1; } public void setTelefono1(String telefono1) { this.telefono1 = telefono1; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getTelefono2() { return telefono2; } public void setTelefono2(String telefono2) { this.telefono2 = telefono2; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
1,175
0.674043
0.662128
63
17.650793
13.415413
49
false
false
0
0
0
0
0
0
1.428571
false
false
4
1da3a81b6cee98063e0812fd07085c3f0fa82b97
14,345,190,787,975
595df3d71e6bb951e18c42020eb8c2cb3a0d0ae7
/JAVA/P003/src/BinaryNumber.java
155d42591b4a110dd9548884e7eb980fb112ce24
[]
no_license
cjungm/first
https://github.com/cjungm/first
7916a5c00dcfd0b24a42231e096b4906487c90f2
e099eb4e0d47a8e2c029c546871e85dbb8c87654
refs/heads/master
2020-05-19T18:07:37.348000
2019-12-03T14:56:30
2019-12-03T14:56:30
185,148,343
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class BinaryNumber { public static void main(String[] args) { // TODO 2진수를 10진수로 변환하는 알고리즘을 제시하라 int t[] = {1,1,1,1,0,1,1,0}; int c[] = new int [8]; int d=0,sign=1; if(t[0]!=0) { sign=-1; int b=1; for(int k=7;k>=1;k--){ c[k]=t[k]-b; if(t[k]!=0||b!=1) { b=0; } c[k]=Math.abs(c[k]); t[k]=1-c[k]; } } for(int k=1;k<=7;k++) { int t1=(int)Math.pow(2, (7-(double)k)); int t2=t[k]*t1; d+=t2; } d*=sign; System.out.println(d); } }
UTF-8
Java
569
java
BinaryNumber.java
Java
[]
null
[]
public class BinaryNumber { public static void main(String[] args) { // TODO 2진수를 10진수로 변환하는 알고리즘을 제시하라 int t[] = {1,1,1,1,0,1,1,0}; int c[] = new int [8]; int d=0,sign=1; if(t[0]!=0) { sign=-1; int b=1; for(int k=7;k>=1;k--){ c[k]=t[k]-b; if(t[k]!=0||b!=1) { b=0; } c[k]=Math.abs(c[k]); t[k]=1-c[k]; } } for(int k=1;k<=7;k++) { int t1=(int)Math.pow(2, (7-(double)k)); int t2=t[k]*t1; d+=t2; } d*=sign; System.out.println(d); } }
569
0.446328
0.386064
29
16.241379
11.955824
42
false
false
0
0
0
0
0
0
3.344828
false
false
4
6879553cbceb531947aa402a24cd2b4daa63645e
1,288,490,214,421
061e1f350670ec69b7cbe3bdbd6ab938ab467f63
/danger-common/src/main/java/com/gsafety/starscream/utils/tree/TreeFactory.java
096e5b32ac980fc8830bc2a5dd561b61621dc69f
[]
no_license
wanghuijava/vip-code-danger
https://github.com/wanghuijava/vip-code-danger
669a26323ea3c6b5db0ebb5b92020475f588504a
279ae25ca75c41ea1f649640c95468874e0784ee
refs/heads/master
2020-12-02T21:18:05.761000
2017-07-05T08:22:12
2017-07-05T08:22:12
96,290,554
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gsafety.starscream.utils.tree; import java.util.HashMap; import java.util.Properties; import org.apache.commons.lang.StringUtils; import com.gsafety.starscream.utils.file.PropertiesUtils; public class TreeFactory { /* 构造一个singleton模式的factory类 */ private static TreeFactory instance = null; private static Properties properties = null; /* 弹出窗口的配置文件路径 */ private static final String TREE_PROP_FILE = "tree.properties"; /* 装载弹出窗口的配置项对象OpenWinPropCfg */ private static HashMap<String, TreePropCfg> map = new HashMap<String, TreePropCfg>(); private TreeFactory() { loadProperties(); } /** * Description: 获取工厂类的实例 * * @return 工厂类的实例 2015-2-12 */ public static TreeFactory getInstance() { if (instance == null){ instance = new TreeFactory(); } return instance; } /** * Description: 初始化配置 * * @return 2015-2-12 */ private void loadProperties() { if (properties == null) { properties = PropertiesUtils.getProperties(TREE_PROP_FILE, null); } } /** * Description: 通过一个键获取配置文件中的一个对应值 * * @param key * 键 * @return 对应值 2015-2-12 */ public String getPropValue(String key) { return properties.getProperty(key); } /** * Description: 通过一个键获取配置文件中的一组对应值 * * @param id * 键 * @return 一个OpenWinPropCfg对象 2015-2-12 */ public TreePropCfg getTreeById(String id) { TreePropCfg rtn = (TreePropCfg) map.get(id); if (rtn == null) { rtn = loadTreePropCfgById(id); } return rtn; } /** * Description: 通过一个键获取配置文件中的一组对应值并装载到hashmap中 * * @param id * 键 * @return 一个OpenWinPropCfg对象 2015-2-12 */ private TreePropCfg loadTreePropCfgById(String id) { String type = getPropValue(id + ".type"); String root = getPropValue(id + ".root"); String parentName = getPropValue(id + ".parentName"); String select = getPropValue(id + ".select"); String table = getPropValue(id + ".table"); String results = getPropValue(id + ".results"); String filter = getPropValue(id + ".filter"); String order = getPropValue(id + ".order"); if (StringUtils.isEmpty(id) || StringUtils.isEmpty(table) || StringUtils.isEmpty(results)) { // 配置不正确 System.out.println(id+"配置不正确"); return null; } TreePropCfg rtn = new TreePropCfg(id, type, root, parentName, select, table, results, filter, order); map.put(id, rtn); return rtn; } }
UTF-8
Java
2,740
java
TreeFactory.java
Java
[]
null
[]
package com.gsafety.starscream.utils.tree; import java.util.HashMap; import java.util.Properties; import org.apache.commons.lang.StringUtils; import com.gsafety.starscream.utils.file.PropertiesUtils; public class TreeFactory { /* 构造一个singleton模式的factory类 */ private static TreeFactory instance = null; private static Properties properties = null; /* 弹出窗口的配置文件路径 */ private static final String TREE_PROP_FILE = "tree.properties"; /* 装载弹出窗口的配置项对象OpenWinPropCfg */ private static HashMap<String, TreePropCfg> map = new HashMap<String, TreePropCfg>(); private TreeFactory() { loadProperties(); } /** * Description: 获取工厂类的实例 * * @return 工厂类的实例 2015-2-12 */ public static TreeFactory getInstance() { if (instance == null){ instance = new TreeFactory(); } return instance; } /** * Description: 初始化配置 * * @return 2015-2-12 */ private void loadProperties() { if (properties == null) { properties = PropertiesUtils.getProperties(TREE_PROP_FILE, null); } } /** * Description: 通过一个键获取配置文件中的一个对应值 * * @param key * 键 * @return 对应值 2015-2-12 */ public String getPropValue(String key) { return properties.getProperty(key); } /** * Description: 通过一个键获取配置文件中的一组对应值 * * @param id * 键 * @return 一个OpenWinPropCfg对象 2015-2-12 */ public TreePropCfg getTreeById(String id) { TreePropCfg rtn = (TreePropCfg) map.get(id); if (rtn == null) { rtn = loadTreePropCfgById(id); } return rtn; } /** * Description: 通过一个键获取配置文件中的一组对应值并装载到hashmap中 * * @param id * 键 * @return 一个OpenWinPropCfg对象 2015-2-12 */ private TreePropCfg loadTreePropCfgById(String id) { String type = getPropValue(id + ".type"); String root = getPropValue(id + ".root"); String parentName = getPropValue(id + ".parentName"); String select = getPropValue(id + ".select"); String table = getPropValue(id + ".table"); String results = getPropValue(id + ".results"); String filter = getPropValue(id + ".filter"); String order = getPropValue(id + ".order"); if (StringUtils.isEmpty(id) || StringUtils.isEmpty(table) || StringUtils.isEmpty(results)) { // 配置不正确 System.out.println(id+"配置不正确"); return null; } TreePropCfg rtn = new TreePropCfg(id, type, root, parentName, select, table, results, filter, order); map.put(id, rtn); return rtn; } }
2,740
0.646322
0.632175
101
22.49505
21.337748
94
false
false
0
0
0
0
0
0
1.643564
false
false
4
58a2ab596483c53252b66b0b04a53423205b6efe
32,504,312,554,757
9f6c0e5fae946da8751b61606e490fdc7788a26e
/src/main/java/bus/events/PasajeroBajado.java
f575dadb9929077ab7dd796b36e8acb8be464af4
[]
no_license
eduardoramirez7/Sistema-Ruta-Transporte-Publico
https://github.com/eduardoramirez7/Sistema-Ruta-Transporte-Publico
25731f99e5fe32c245a2ce6cfea31c94c7dc4ae5
2f91d115aec424dd098ba0d6ea48e1a4950c9565
refs/heads/master
2023-06-04T12:15:01.340000
2021-06-16T08:53:45
2021-06-16T08:53:45
377,165,859
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bus.events; import co.com.sofka.domain.generic.DomainEvent; import pasajero.values.PasajeroId; public class PasajeroBajado extends DomainEvent { private final PasajeroId pasajeroId; public PasajeroBajado(PasajeroId pasajeroId) { super("sofka.bus.pasajerobajado"); this.pasajeroId = pasajeroId; } public PasajeroId getPasajeroId() { return pasajeroId; } }
UTF-8
Java
412
java
PasajeroBajado.java
Java
[]
null
[]
package bus.events; import co.com.sofka.domain.generic.DomainEvent; import pasajero.values.PasajeroId; public class PasajeroBajado extends DomainEvent { private final PasajeroId pasajeroId; public PasajeroBajado(PasajeroId pasajeroId) { super("sofka.bus.pasajerobajado"); this.pasajeroId = pasajeroId; } public PasajeroId getPasajeroId() { return pasajeroId; } }
412
0.720874
0.720874
18
21.888889
19.697403
50
false
false
0
0
0
0
0
0
0.388889
false
false
4
a688ee6997e0ebc429ba83251be698e76d6ca3b0
4,363,686,827,478
728e9148546aaf55051ccf21478eb62cfaf26016
/Project Euler/src/EvenFibonaccinumbers.java
8f62671711b0467b51540b32460d02f7c006f9f8
[]
no_license
theshubhamgoel/Online-Competitions-and-Practice
https://github.com/theshubhamgoel/Online-Competitions-and-Practice
e36998bea6670c9e7ebf7503841a4f673bbd5354
26864a02cfdac2e271da00263052cf1c9461912e
refs/heads/master
2021-05-01T14:58:01.790000
2018-02-10T15:24:16
2018-02-10T15:24:16
121,026,307
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class EvenFibonaccinumbers { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long test_cases = 0, n; long ans, a, b, c; test_cases = Integer.parseInt(br.readLine()); for (int i = 0; i < test_cases; i++) { n = Long.parseLong(br.readLine()); ans = 0; a = 1; b = 2; while (b <= n) { if (b % 2 == 0) ans += b; c = a; a = b; b = a + c; } System.out.println(ans); } } }
UTF-8
Java
646
java
EvenFibonaccinumbers.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class EvenFibonaccinumbers { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long test_cases = 0, n; long ans, a, b, c; test_cases = Integer.parseInt(br.readLine()); for (int i = 0; i < test_cases; i++) { n = Long.parseLong(br.readLine()); ans = 0; a = 1; b = 2; while (b <= n) { if (b % 2 == 0) ans += b; c = a; a = b; b = a + c; } System.out.println(ans); } } }
646
0.571207
0.560372
31
18.838709
18.608179
75
false
false
0
0
0
0
0
0
2.612903
false
false
4
a32754ec73db0b414e80b56fa650682479c4b98a
28,149,215,722,661
219dbee83ff40ba29b1ae38db072b3099ea89a62
/core/stock-business-api/src/main/java/com/ryd/business/dao/StTradeRecordDao.java
a3e96d9da1b281c8ea4a52cf4ce13d7edc19d9c2
[]
no_license
jessen163/stockserver
https://github.com/jessen163/stockserver
4ecd4eb8a6b827c8d3791136241cb63bae634942
fa349aca4efdcd770dcf9df0f66bc6fa05e3c36c
refs/heads/master
2021-01-01T05:10:15.019000
2016-05-12T03:47:55
2016-05-12T03:47:55
56,133,106
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ryd.business.dao; import com.ryd.basecommon.dao.BaseDao; import com.ryd.business.model.StTradeRecord; import java.util.List; /** * <p>标题:交易记录Dao</p> * <p>描述:交易记录Dao</p> * 包名:com.ryd.business.dao * 创建人:songby * 创建时间:2016/4/22 13:53 */ public interface StTradeRecordDao extends BaseDao<StTradeRecord> { public int addBatch(List<StTradeRecord> list); public int updateBatch(List<StTradeRecord> list); public int deleteBatch(List<String> list); }
UTF-8
Java
527
java
StTradeRecordDao.java
Java
[ { "context": ">描述:交易记录Dao</p>\n * 包名:com.ryd.business.dao\n * 创建人:songby\n * 创建时间:2016/4/22 13:53\n */\npublic interface StTr", "end": 226, "score": 0.9996644854545593, "start": 220, "tag": "USERNAME", "value": "songby" } ]
null
[]
package com.ryd.business.dao; import com.ryd.basecommon.dao.BaseDao; import com.ryd.business.model.StTradeRecord; import java.util.List; /** * <p>标题:交易记录Dao</p> * <p>描述:交易记录Dao</p> * 包名:com.ryd.business.dao * 创建人:songby * 创建时间:2016/4/22 13:53 */ public interface StTradeRecordDao extends BaseDao<StTradeRecord> { public int addBatch(List<StTradeRecord> list); public int updateBatch(List<StTradeRecord> list); public int deleteBatch(List<String> list); }
527
0.726514
0.703549
22
20.772728
20.433777
66
false
false
0
0
0
0
0
0
0.318182
false
false
4
994ee1ebe3c47e82d14a7509fc89c5ee4776bca4
30,562,987,342,767
2ec905b5b130bed2aa6f1f37591317d80b7ce70d
/ihmc-interfaces/src/main/generated-java/quadruped_msgs/msg/dds/QuadrupedGaitTimingsPacket.java
487fb62b8f3881a61845ad78f17c48930b96808b
[ "Apache-2.0" ]
permissive
ihmcrobotics/ihmc-open-robotics-software
https://github.com/ihmcrobotics/ihmc-open-robotics-software
dbb1f9d7a4eaf01c08068b7233d1b01d25c5d037
42a4e385af75e8e13291d6156a5c7bebebbecbfd
refs/heads/develop
2023-09-01T18:18:14.623000
2023-09-01T14:16:26
2023-09-01T14:16:26
50,613,360
227
91
null
false
2023-01-25T21:39:35
2016-01-28T21:00:16
2023-01-23T10:08:40
2023-01-25T21:39:32
980,849
195
77
30
Java
false
false
package quadruped_msgs.msg.dds; import us.ihmc.communication.packets.Packet; import us.ihmc.euclid.interfaces.Settable; import us.ihmc.euclid.interfaces.EpsilonComparable; import java.util.function.Supplier; import us.ihmc.pubsub.TopicDataType; /** * This message is part of the IHMC quadruped controller API. * This message sends the x gait settings used for determining gait. */ public class QuadrupedGaitTimingsPacket extends Packet<QuadrupedGaitTimingsPacket> implements Settable<QuadrupedGaitTimingsPacket>, EpsilonComparable<QuadrupedGaitTimingsPacket> { /** * Unique ID used to identify this message, should preferably be consecutively increasing. */ public long sequence_id_; public double step_duration_ = -1.0; public double end_double_support_duration_ = -1.0; public double max_speed_ = -1.0; public QuadrupedGaitTimingsPacket() { } public QuadrupedGaitTimingsPacket(QuadrupedGaitTimingsPacket other) { this(); set(other); } public void set(QuadrupedGaitTimingsPacket other) { sequence_id_ = other.sequence_id_; step_duration_ = other.step_duration_; end_double_support_duration_ = other.end_double_support_duration_; max_speed_ = other.max_speed_; } /** * Unique ID used to identify this message, should preferably be consecutively increasing. */ public void setSequenceId(long sequence_id) { sequence_id_ = sequence_id; } /** * Unique ID used to identify this message, should preferably be consecutively increasing. */ public long getSequenceId() { return sequence_id_; } public void setStepDuration(double step_duration) { step_duration_ = step_duration; } public double getStepDuration() { return step_duration_; } public void setEndDoubleSupportDuration(double end_double_support_duration) { end_double_support_duration_ = end_double_support_duration; } public double getEndDoubleSupportDuration() { return end_double_support_duration_; } public void setMaxSpeed(double max_speed) { max_speed_ = max_speed; } public double getMaxSpeed() { return max_speed_; } public static Supplier<QuadrupedGaitTimingsPacketPubSubType> getPubSubType() { return QuadrupedGaitTimingsPacketPubSubType::new; } @Override public Supplier<TopicDataType> getPubSubTypePacket() { return QuadrupedGaitTimingsPacketPubSubType::new; } @Override public boolean epsilonEquals(QuadrupedGaitTimingsPacket other, double epsilon) { if(other == null) return false; if(other == this) return true; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.sequence_id_, other.sequence_id_, epsilon)) return false; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.step_duration_, other.step_duration_, epsilon)) return false; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.end_double_support_duration_, other.end_double_support_duration_, epsilon)) return false; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.max_speed_, other.max_speed_, epsilon)) return false; return true; } @Override public boolean equals(Object other) { if(other == null) return false; if(other == this) return true; if(!(other instanceof QuadrupedGaitTimingsPacket)) return false; QuadrupedGaitTimingsPacket otherMyClass = (QuadrupedGaitTimingsPacket) other; if(this.sequence_id_ != otherMyClass.sequence_id_) return false; if(this.step_duration_ != otherMyClass.step_duration_) return false; if(this.end_double_support_duration_ != otherMyClass.end_double_support_duration_) return false; if(this.max_speed_ != otherMyClass.max_speed_) return false; return true; } @Override public java.lang.String toString() { StringBuilder builder = new StringBuilder(); builder.append("QuadrupedGaitTimingsPacket {"); builder.append("sequence_id="); builder.append(this.sequence_id_); builder.append(", "); builder.append("step_duration="); builder.append(this.step_duration_); builder.append(", "); builder.append("end_double_support_duration="); builder.append(this.end_double_support_duration_); builder.append(", "); builder.append("max_speed="); builder.append(this.max_speed_); builder.append("}"); return builder.toString(); } }
UTF-8
Java
4,575
java
QuadrupedGaitTimingsPacket.java
Java
[]
null
[]
package quadruped_msgs.msg.dds; import us.ihmc.communication.packets.Packet; import us.ihmc.euclid.interfaces.Settable; import us.ihmc.euclid.interfaces.EpsilonComparable; import java.util.function.Supplier; import us.ihmc.pubsub.TopicDataType; /** * This message is part of the IHMC quadruped controller API. * This message sends the x gait settings used for determining gait. */ public class QuadrupedGaitTimingsPacket extends Packet<QuadrupedGaitTimingsPacket> implements Settable<QuadrupedGaitTimingsPacket>, EpsilonComparable<QuadrupedGaitTimingsPacket> { /** * Unique ID used to identify this message, should preferably be consecutively increasing. */ public long sequence_id_; public double step_duration_ = -1.0; public double end_double_support_duration_ = -1.0; public double max_speed_ = -1.0; public QuadrupedGaitTimingsPacket() { } public QuadrupedGaitTimingsPacket(QuadrupedGaitTimingsPacket other) { this(); set(other); } public void set(QuadrupedGaitTimingsPacket other) { sequence_id_ = other.sequence_id_; step_duration_ = other.step_duration_; end_double_support_duration_ = other.end_double_support_duration_; max_speed_ = other.max_speed_; } /** * Unique ID used to identify this message, should preferably be consecutively increasing. */ public void setSequenceId(long sequence_id) { sequence_id_ = sequence_id; } /** * Unique ID used to identify this message, should preferably be consecutively increasing. */ public long getSequenceId() { return sequence_id_; } public void setStepDuration(double step_duration) { step_duration_ = step_duration; } public double getStepDuration() { return step_duration_; } public void setEndDoubleSupportDuration(double end_double_support_duration) { end_double_support_duration_ = end_double_support_duration; } public double getEndDoubleSupportDuration() { return end_double_support_duration_; } public void setMaxSpeed(double max_speed) { max_speed_ = max_speed; } public double getMaxSpeed() { return max_speed_; } public static Supplier<QuadrupedGaitTimingsPacketPubSubType> getPubSubType() { return QuadrupedGaitTimingsPacketPubSubType::new; } @Override public Supplier<TopicDataType> getPubSubTypePacket() { return QuadrupedGaitTimingsPacketPubSubType::new; } @Override public boolean epsilonEquals(QuadrupedGaitTimingsPacket other, double epsilon) { if(other == null) return false; if(other == this) return true; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.sequence_id_, other.sequence_id_, epsilon)) return false; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.step_duration_, other.step_duration_, epsilon)) return false; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.end_double_support_duration_, other.end_double_support_duration_, epsilon)) return false; if (!us.ihmc.idl.IDLTools.epsilonEqualsPrimitive(this.max_speed_, other.max_speed_, epsilon)) return false; return true; } @Override public boolean equals(Object other) { if(other == null) return false; if(other == this) return true; if(!(other instanceof QuadrupedGaitTimingsPacket)) return false; QuadrupedGaitTimingsPacket otherMyClass = (QuadrupedGaitTimingsPacket) other; if(this.sequence_id_ != otherMyClass.sequence_id_) return false; if(this.step_duration_ != otherMyClass.step_duration_) return false; if(this.end_double_support_duration_ != otherMyClass.end_double_support_duration_) return false; if(this.max_speed_ != otherMyClass.max_speed_) return false; return true; } @Override public java.lang.String toString() { StringBuilder builder = new StringBuilder(); builder.append("QuadrupedGaitTimingsPacket {"); builder.append("sequence_id="); builder.append(this.sequence_id_); builder.append(", "); builder.append("step_duration="); builder.append(this.step_duration_); builder.append(", "); builder.append("end_double_support_duration="); builder.append(this.end_double_support_duration_); builder.append(", "); builder.append("max_speed="); builder.append(this.max_speed_); builder.append("}"); return builder.toString(); } }
4,575
0.68459
0.683279
155
28.516129
33.603062
177
false
false
0
0
0
0
0
0
0.470968
false
false
4
7b7a4663ae78106a8cef32cb1df8ecbf075a143c
10,780,367,976,471
f596731f9259f89c89a5591d3facc0371e5aff2c
/Implement/src/implement/Enfermeiros_Impl.java
8a9e6c9786f3826144f749233f32622cc858c677
[]
no_license
fabiofranca92/Distributed-Applications---College
https://github.com/fabiofranca92/Distributed-Applications---College
6d01158bc38737dcc1a152a54554a4c2fce479b6
15c8fcd1ecfddc608ea82f322907498e02bf3554
refs/heads/master
2021-01-10T12:14:07.002000
2016-01-12T14:40:24
2016-01-12T14:40:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author fabiofranca */ package implement; import Interface.AtoEnfermagem; import Interface.Enfermeiros; import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import Interface.Utentes; /** * * @author Filipe */ public class Enfermeiros_Impl extends UnicastRemoteObject implements Enfermeiros, Serializable{ private String nome; private String morada; private HashSet<Utentes> utentes = new HashSet<>(); private HashSet<AtoEnfermagem> atosenferm = new HashSet<>(); private Date data; public Enfermeiros_Impl() throws RemoteException { this.atosenferm = new HashSet<>(); this.utentes = new HashSet<>(); } @Override public void setNomeEnfermeiro(String nome) throws RemoteException { this.nome = nome; } @Override public String getNomeEnfermeiro() throws RemoteException { return this.nome; } @Override public String getdataEnfermeiro() throws RemoteException { return this.data.toString(); } @Override public Date setdataEnfermeiro(int dia, int mes, int ano) throws RemoteException { Date d = new Date(ano - 1900, mes - 1, dia); return d; } @Override public String getMoradaEnfermeiro() throws RemoteException { return this.morada; } @Override public void setMoradaEnfermeiro(String morada) throws RemoteException { this.morada = morada; } @Override public int getAtos() throws RemoteException{ return this.atosenferm.size(); } @Override public void setAtos(AtoEnfermagem ae) throws RemoteException{ this.atosenferm.add(ae); } }
UTF-8
Java
1,978
java
Enfermeiros_Impl.java
Java
[ { "context": " the template in the editor.\n */\n/**\n *\n * @author fabiofranca\n */\npackage implement;\n\nimport Interface.", "end": 121, "score": 0.5507556200027466, "start": 118, "tag": "NAME", "value": "fab" }, { "context": " template in the editor.\n */\n/**\n *\n * @author fabiofranca\n */\npackage implement;\n\nimport Interface.AtoEnfer", "end": 129, "score": 0.8733798265457153, "start": 121, "tag": "USERNAME", "value": "iofranca" }, { "context": "nner;\nimport Interface.Utentes;\n\n/**\n *\n * @author Filipe\n */\npublic class Enfermeiros_Impl extends Unicast", "end": 537, "score": 0.9991115927696228, "start": 531, "tag": "NAME", "value": "Filipe" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author fabiofranca */ package implement; import Interface.AtoEnfermagem; import Interface.Enfermeiros; import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import Interface.Utentes; /** * * @author Filipe */ public class Enfermeiros_Impl extends UnicastRemoteObject implements Enfermeiros, Serializable{ private String nome; private String morada; private HashSet<Utentes> utentes = new HashSet<>(); private HashSet<AtoEnfermagem> atosenferm = new HashSet<>(); private Date data; public Enfermeiros_Impl() throws RemoteException { this.atosenferm = new HashSet<>(); this.utentes = new HashSet<>(); } @Override public void setNomeEnfermeiro(String nome) throws RemoteException { this.nome = nome; } @Override public String getNomeEnfermeiro() throws RemoteException { return this.nome; } @Override public String getdataEnfermeiro() throws RemoteException { return this.data.toString(); } @Override public Date setdataEnfermeiro(int dia, int mes, int ano) throws RemoteException { Date d = new Date(ano - 1900, mes - 1, dia); return d; } @Override public String getMoradaEnfermeiro() throws RemoteException { return this.morada; } @Override public void setMoradaEnfermeiro(String morada) throws RemoteException { this.morada = morada; } @Override public int getAtos() throws RemoteException{ return this.atosenferm.size(); } @Override public void setAtos(AtoEnfermagem ae) throws RemoteException{ this.atosenferm.add(ae); } }
1,978
0.692619
0.690091
80
23.737499
22.936729
95
false
false
0
0
0
0
0
0
0.45
false
false
4
c4196cd8c733d549cb2f2e58ca3ff5e630b65ee0
19,275,813,284,701
98dbde52ad9644e42e7068942233bdb0f0fa8760
/backend/test/com/searcheveryaspect/backend/database/update/ESDocumentBuilderTest.java
744cd0d554106969c27c7ef4b9b04c0d6a82f4f3
[]
no_license
Joppethus/ttip
https://github.com/Joppethus/ttip
5f3ee5f98edb9d820f66951be496df2648528750
3bf313aaf9b4e1a69964fc6443185c424f99d9ef
refs/heads/master
2020-12-25T20:42:31.282000
2015-05-21T22:50:09
2015-05-21T22:50:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.searcheveryaspect.backend.database.update; import static org.junit.Assert.assertArrayEquals; import org.junit.Test; /** * */ public class ESDocumentBuilderTest { @Test public void createPartyCommaTest() { final String input = "av Jane Doe m.fl. (M, C, FP, KD)"; final String[] expected = new String[] {"M", "C", "FP", "KD"}; assertArrayEquals(expected, ESDocumentBuilder.createParty(input)); } @Test public void createPartyMultipleParenthesisTest() { final String input = "av Jane Doe (V) och John Doe (S)"; final String[] expected = new String[] {"V", "S"}; assertArrayEquals(expected, ESDocumentBuilder.createParty(input)); } }
UTF-8
Java
686
java
ESDocumentBuilderTest.java
Java
[ { "context": "atePartyCommaTest() {\n final String input = \"av Jane Doe m.fl. (M, C, FP, KD)\";\n final String[] expecte", "end": 265, "score": 0.9997022151947021, "start": 257, "tag": "NAME", "value": "Jane Doe" }, { "context": "leParenthesisTest() {\n final String input = \"av Jane Doe (V) och John Doe (S)\";\n final String[] expecte", "end": 530, "score": 0.9993075728416443, "start": 522, "tag": "NAME", "value": "Jane Doe" }, { "context": "() {\n final String input = \"av Jane Doe (V) och John Doe (S)\";\n final String[] expected = new String[] ", "end": 547, "score": 0.9998009204864502, "start": 539, "tag": "NAME", "value": "John Doe" } ]
null
[]
package com.searcheveryaspect.backend.database.update; import static org.junit.Assert.assertArrayEquals; import org.junit.Test; /** * */ public class ESDocumentBuilderTest { @Test public void createPartyCommaTest() { final String input = "av <NAME> m.fl. (M, C, FP, KD)"; final String[] expected = new String[] {"M", "C", "FP", "KD"}; assertArrayEquals(expected, ESDocumentBuilder.createParty(input)); } @Test public void createPartyMultipleParenthesisTest() { final String input = "av <NAME> (V) och <NAME> (S)"; final String[] expected = new String[] {"V", "S"}; assertArrayEquals(expected, ESDocumentBuilder.createParty(input)); } }
680
0.690962
0.690962
25
26.440001
26.96973
70
false
false
0
0
0
0
0
0
0.72
false
false
4
606272d70092816344f9e1046118a077b2e94182
13,804,024,942,975
a53eee06c3fbf40a7de67c1599303b2581846b1d
/JChattr/JChattrServer/src/main/java/com/example/project/ChatThread.java
6c9a39d7b5b7086461829662127b7a276387162c
[]
no_license
Hagoodkk/Projects
https://github.com/Hagoodkk/Projects
f5d0eb0cbfb187278986c935d2bc750f19f215e7
8cb763cc584261597645bfda5639d46ba7be9081
refs/heads/master
2020-08-05T14:34:54.267000
2017-08-28T20:54:02
2017-08-28T20:54:02
66,464,954
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.project; import com.example.project.DatabaseManager.DatabaseManager; import com.example.project.Serializable.*; import com.example.project.SessionManager.SessionManager; import javafx.util.Pair; import sun.net.ConnectionResetException; import java.io.*; import java.net.Socket; import java.util.ArrayList; /** * Created by Kyle on 7/4/2017. */ public class ChatThread implements Runnable { private Socket clientSocket; public ChatThread(Socket clientSocket) { this.clientSocket = clientSocket; } public void run() { int requestType = pingClient(); if (requestType == 0) { accountCreation(); } else if (requestType == 1){ String verifiedUsername = verifyCredentials(); if (verifiedUsername != null) establishedConnection(verifiedUsername); else System.out.println("Connection failed."); } else if (requestType == -1) { System.out.println("Connection failed."); } } private boolean accountCreation() { try { ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream()); UserCredentials userCredentials = (UserCredentials) ois.readObject(); String username = userCredentials.getUsername(); String passwordSaltedHash = userCredentials.getPasswordSaltedHash(); String passwordSalt = userCredentials.getPasswordSalt(); System.out.println(passwordSalt); boolean accountCreated = false; if (isValid(username) && isValid(passwordSaltedHash) && isValid(passwordSalt)) { DatabaseManager databaseManager = DatabaseManager.getInstance(); accountCreated = (databaseManager.addUser(username, passwordSaltedHash, passwordSalt)); } if (accountCreated) { userCredentials.setRequestAccepted(true); oos.writeObject(userCredentials); oos.flush(); return true; } else { userCredentials.setRequestAccepted(false); oos.writeObject(userCredentials); oos.flush(); return false; } } catch (IOException ioe) { return false; } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); return false; } } private boolean isValid(String entry) { if (entry.contains(" ")) return false; if (entry.length() == 0) return false; return true; } private int pingClient() { try { ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream()); ServerHello serverHello = (ServerHello) ois.readObject(); oos.writeObject(new ServerHello()); oos.flush(); if (serverHello.isRequestUserCreation()) return 0; if (serverHello.isRequestLogin()) return 1; else return -1; } catch (IOException ioe) { ioe.printStackTrace(); return -1; } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); return -1; } } private String verifyCredentials() { UserCredentials userCredentials = null; SessionManager sessionManager = SessionManager.getInstance(); try { ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream()); userCredentials = (UserCredentials) ois.readObject(); String username = userCredentials.getUsername(); DatabaseManager databaseManager = DatabaseManager.getInstance(); String salt = databaseManager.getUserSalt(username); userCredentials.setPasswordSalt(salt); oos.writeObject(userCredentials); oos.flush(); userCredentials = (UserCredentials) ois.readObject(); if (databaseManager.comparePasswordSaltedHash(userCredentials.getUsername(), userCredentials.getPasswordSaltedHash()) && !sessionManager.isOnline(username)) { userCredentials.setDisplayName(databaseManager.getUserDisplayName(username)); userCredentials.setRequestAccepted(true); oos.writeObject(userCredentials); oos.flush(); oos = new ObjectOutputStream(clientSocket.getOutputStream()); ois = new ObjectInputStream(clientSocket.getInputStream()); BuddyList buddyList = (BuddyList) ois.readObject(); sessionManager.removeStateUpdatesFromUser(username); oos.writeObject(buildBuddyList(username)); sessionManager.addMember(username, clientSocket); sessionManager.printClientTracker(); System.out.println(userCredentials.getUsername() + " connected."); return username; } else { userCredentials.setRequestAccepted(false); oos.writeObject(userCredentials); oos.flush(); System.out.println("Connection refused."); return null; } } catch (IOException ioe) { ioe.printStackTrace(); return null; } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); return null; } } private void establishedConnection(String username) { SessionManager sessionManager = SessionManager.getInstance(); sessionManager.broadcastStateUpdate(username, 0); try { ObjectOutputStream toClient = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream fromClient = new ObjectInputStream(clientSocket.getInputStream()); while (true) { Message clientInbound = (Message) fromClient.readObject(); if (!clientInbound.isNullMessage()) { String recipient = clientInbound.getRecipient(); System.out.println("Inbound: " + clientInbound.getMessage()); if (sessionManager.isOnline(recipient)) { sessionManager.addOutgoingMessage(recipient, clientInbound); } else { sessionManager.addOutgoingMessage(recipient, clientInbound); } } Message clientOutbound = sessionManager.getNextOutgoing(username); if (!clientOutbound.isNullMessage()) System.out.println("Outbound: " + clientOutbound.getMessage()); if (clientInbound.isBuddyListUpdate()) { String user = clientInbound.getSender(); String buddyUsername = clientInbound.getBuddyList().getBuddies().get(0).getUsername().toLowerCase(); String groupName = clientInbound.getBuddyList().getBuddies().get(0).getGroupName(); DatabaseManager databaseManager = DatabaseManager.getInstance(); if (clientInbound.getBuddyList().isAddUser()) { boolean buddyAdded = databaseManager.addBuddyToUser(user, buddyUsername, groupName); if (buddyAdded) { String buddyDisplayName = databaseManager.getUserDisplayName(buddyUsername); BuddyList buddyList = new BuddyList(); buddyList.setAddUser(true); Buddy buddy = new Buddy(buddyUsername, buddyDisplayName, groupName); buddyList.addBuddy(buddy); if (sessionManager.isOnline(buddyUsername)) { buddyList.getCurrentlyOnline().add(buddy); } else { buddyList.getCurrentlyOffline().add(buddy); } clientOutbound.setBuddyList(buddyList); clientOutbound.setBuddyListUpdate(true); } else System.out.println("Buddy addition failed."); } else if (clientInbound.getBuddyList().isDeleteUser()) { boolean buddyDeleted = databaseManager.removeBuddyFromUser(user, buddyUsername); if (buddyDeleted) { String buddyDisplayName = databaseManager.getUserDisplayName(buddyUsername); BuddyList buddyList = new BuddyList(); buddyList.setDeleteUser(true); Buddy buddy = new Buddy(buddyUsername, buddyDisplayName, groupName); buddyList.addBuddy(buddy); clientOutbound.setBuddyList(buddyList); clientOutbound.setBuddyListUpdate(true); } else System.out.println("Buddy deletion failed."); } } if (clientInbound.isChatroomListingsRequest()) { clientOutbound.setChatroomListingsRequest(true); clientOutbound.setCategories(SessionManager.getInstance().getChatroomCategories()); clientOutbound.setUsers(SessionManager.getInstance().getChatroomUsers()); clientOutbound.setNullMessage(true); } if (clientInbound.isChatroomCreateRequest()) { createChatroom(clientInbound.getSenderDisplayName(), clientInbound.getChatroomCategory(), clientInbound.getChatroomName()); } if (clientInbound.isLeftChatroom()) { String chatroomName = clientInbound.getChatroomName(); SessionManager.getInstance().removeChatroomUser(clientInbound.getSenderDisplayName(), clientInbound.getChatroomCategory(), clientInbound.getChatroomName()); ArrayList<String> usersInRoom = SessionManager.getInstance().getChatroomUsers().get(chatroomName); Message message = new Message(true); message.setLeftChatroom(true); message.setChatroomCategory(clientInbound.getChatroomCategory()); message.setChatroomName(clientInbound.getChatroomName()); message.setSenderDisplayName(clientInbound.getSenderDisplayName()); if (usersInRoom != null) { for (String user : usersInRoom) { SessionManager.getInstance().addOutgoingMessage(user.toLowerCase(), message); } } } if (clientInbound.isEnteredChatroom()) { String chatroomCategory = clientInbound.getChatroomCategory(); String chatroomName = clientInbound.getChatroomName(); String displayName = clientInbound.getSenderDisplayName(); SessionManager.getInstance().addChatroomUser(displayName, chatroomCategory, chatroomName); Message message = new Message(true); message.setEnteredChatroom(true); message.setSenderDisplayName(clientInbound.getSenderDisplayName()); message.setChatroomCategory(clientInbound.getChatroomCategory()); message.setChatroomName(clientInbound.getChatroomName()); message.setChatroomUsers(SessionManager.getInstance().getChatroomUsers().get(chatroomName)); if (SessionManager.getInstance().getChatroomUsers().get(chatroomName) == null) { createChatroom(clientInbound.getSenderDisplayName(), clientInbound.getChatroomCategory(), clientInbound.getChatroomName()); message.setChatroomUsers(SessionManager.getInstance().getChatroomUsers().get(chatroomName)); } for (String user : SessionManager.getInstance().getChatroomUsers().get(chatroomName)) { SessionManager.getInstance().addOutgoingMessage(user.toLowerCase(), message); } } if (clientInbound.isCarryingChatroomMessage()) { Message message = clientInbound; for (String user : SessionManager.getInstance().getChatroomUsers().get(clientInbound.getChatroomName())) { SessionManager.getInstance().addOutgoingMessage(user, message); } } toClient.writeObject(clientOutbound); toClient.flush(); toClient.reset(); } } catch (ConnectionResetException cre) {} catch (EOFException eofe) {} catch (IOException ioe) { ioe.printStackTrace(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } finally { try { SessionManager.getInstance().removeUserFromAllChatrooms(username); sessionManager.broadcastStateUpdate(username, 1); System.out.println(username + " disconnected."); clientSocket.close(); sessionManager.removeMember(username); } catch (IOException ex) { ex.printStackTrace(); } } } private void createChatroom(String displayName, String chatroomCategory, String chatroomName) { SessionManager.getInstance().addChatroom(displayName, chatroomCategory, chatroomName); } private BuddyList buildBuddyList(String username) { DatabaseManager databaseManager = DatabaseManager.getInstance(); BuddyList buddyList = databaseManager.getBuddyList(username); ArrayList<Buddy> currentlyOffline = new ArrayList<>(); ArrayList<Buddy> currentlyOnline = new ArrayList<>(); SessionManager sessionManager = SessionManager.getInstance(); for (Buddy buddy : buddyList.getBuddies()) { if (sessionManager.isOnline(buddy.getUsername())) { currentlyOnline.add(buddy); } else currentlyOffline.add(buddy); } buddyList.setCurrentlyOffline(currentlyOffline); buddyList.setCurrentlyOnline(currentlyOnline); return buddyList; } }
UTF-8
Java
14,772
java
ChatThread.java
Java
[ { "context": "et;\nimport java.util.ArrayList;\n\n/**\n * Created by Kyle on 7/4/2017.\n */\n\npublic class ChatThread impleme", "end": 353, "score": 0.82706618309021, "start": 349, "tag": "NAME", "value": "Kyle" }, { "context": "eleted = databaseManager.removeBuddyFromUser(user, buddyUsername);\n if (buddyDeleted) {\n ", "end": 8694, "score": 0.9081838130950928, "start": 8681, "tag": "USERNAME", "value": "buddyUsername" }, { "context": "yDisplayName = databaseManager.getUserDisplayName(buddyUsername);\n BuddyList buddyList", "end": 8843, "score": 0.8454070091247559, "start": 8830, "tag": "USERNAME", "value": "buddyUsername" }, { "context": " Buddy buddy = new Buddy(buddyUsername, buddyDisplayName, groupName);\n ", "end": 9037, "score": 0.8895372152328491, "start": 9024, "tag": "USERNAME", "value": "buddyUsername" } ]
null
[]
package com.example.project; import com.example.project.DatabaseManager.DatabaseManager; import com.example.project.Serializable.*; import com.example.project.SessionManager.SessionManager; import javafx.util.Pair; import sun.net.ConnectionResetException; import java.io.*; import java.net.Socket; import java.util.ArrayList; /** * Created by Kyle on 7/4/2017. */ public class ChatThread implements Runnable { private Socket clientSocket; public ChatThread(Socket clientSocket) { this.clientSocket = clientSocket; } public void run() { int requestType = pingClient(); if (requestType == 0) { accountCreation(); } else if (requestType == 1){ String verifiedUsername = verifyCredentials(); if (verifiedUsername != null) establishedConnection(verifiedUsername); else System.out.println("Connection failed."); } else if (requestType == -1) { System.out.println("Connection failed."); } } private boolean accountCreation() { try { ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream()); UserCredentials userCredentials = (UserCredentials) ois.readObject(); String username = userCredentials.getUsername(); String passwordSaltedHash = userCredentials.getPasswordSaltedHash(); String passwordSalt = userCredentials.getPasswordSalt(); System.out.println(passwordSalt); boolean accountCreated = false; if (isValid(username) && isValid(passwordSaltedHash) && isValid(passwordSalt)) { DatabaseManager databaseManager = DatabaseManager.getInstance(); accountCreated = (databaseManager.addUser(username, passwordSaltedHash, passwordSalt)); } if (accountCreated) { userCredentials.setRequestAccepted(true); oos.writeObject(userCredentials); oos.flush(); return true; } else { userCredentials.setRequestAccepted(false); oos.writeObject(userCredentials); oos.flush(); return false; } } catch (IOException ioe) { return false; } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); return false; } } private boolean isValid(String entry) { if (entry.contains(" ")) return false; if (entry.length() == 0) return false; return true; } private int pingClient() { try { ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream()); ServerHello serverHello = (ServerHello) ois.readObject(); oos.writeObject(new ServerHello()); oos.flush(); if (serverHello.isRequestUserCreation()) return 0; if (serverHello.isRequestLogin()) return 1; else return -1; } catch (IOException ioe) { ioe.printStackTrace(); return -1; } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); return -1; } } private String verifyCredentials() { UserCredentials userCredentials = null; SessionManager sessionManager = SessionManager.getInstance(); try { ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream()); userCredentials = (UserCredentials) ois.readObject(); String username = userCredentials.getUsername(); DatabaseManager databaseManager = DatabaseManager.getInstance(); String salt = databaseManager.getUserSalt(username); userCredentials.setPasswordSalt(salt); oos.writeObject(userCredentials); oos.flush(); userCredentials = (UserCredentials) ois.readObject(); if (databaseManager.comparePasswordSaltedHash(userCredentials.getUsername(), userCredentials.getPasswordSaltedHash()) && !sessionManager.isOnline(username)) { userCredentials.setDisplayName(databaseManager.getUserDisplayName(username)); userCredentials.setRequestAccepted(true); oos.writeObject(userCredentials); oos.flush(); oos = new ObjectOutputStream(clientSocket.getOutputStream()); ois = new ObjectInputStream(clientSocket.getInputStream()); BuddyList buddyList = (BuddyList) ois.readObject(); sessionManager.removeStateUpdatesFromUser(username); oos.writeObject(buildBuddyList(username)); sessionManager.addMember(username, clientSocket); sessionManager.printClientTracker(); System.out.println(userCredentials.getUsername() + " connected."); return username; } else { userCredentials.setRequestAccepted(false); oos.writeObject(userCredentials); oos.flush(); System.out.println("Connection refused."); return null; } } catch (IOException ioe) { ioe.printStackTrace(); return null; } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); return null; } } private void establishedConnection(String username) { SessionManager sessionManager = SessionManager.getInstance(); sessionManager.broadcastStateUpdate(username, 0); try { ObjectOutputStream toClient = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream fromClient = new ObjectInputStream(clientSocket.getInputStream()); while (true) { Message clientInbound = (Message) fromClient.readObject(); if (!clientInbound.isNullMessage()) { String recipient = clientInbound.getRecipient(); System.out.println("Inbound: " + clientInbound.getMessage()); if (sessionManager.isOnline(recipient)) { sessionManager.addOutgoingMessage(recipient, clientInbound); } else { sessionManager.addOutgoingMessage(recipient, clientInbound); } } Message clientOutbound = sessionManager.getNextOutgoing(username); if (!clientOutbound.isNullMessage()) System.out.println("Outbound: " + clientOutbound.getMessage()); if (clientInbound.isBuddyListUpdate()) { String user = clientInbound.getSender(); String buddyUsername = clientInbound.getBuddyList().getBuddies().get(0).getUsername().toLowerCase(); String groupName = clientInbound.getBuddyList().getBuddies().get(0).getGroupName(); DatabaseManager databaseManager = DatabaseManager.getInstance(); if (clientInbound.getBuddyList().isAddUser()) { boolean buddyAdded = databaseManager.addBuddyToUser(user, buddyUsername, groupName); if (buddyAdded) { String buddyDisplayName = databaseManager.getUserDisplayName(buddyUsername); BuddyList buddyList = new BuddyList(); buddyList.setAddUser(true); Buddy buddy = new Buddy(buddyUsername, buddyDisplayName, groupName); buddyList.addBuddy(buddy); if (sessionManager.isOnline(buddyUsername)) { buddyList.getCurrentlyOnline().add(buddy); } else { buddyList.getCurrentlyOffline().add(buddy); } clientOutbound.setBuddyList(buddyList); clientOutbound.setBuddyListUpdate(true); } else System.out.println("Buddy addition failed."); } else if (clientInbound.getBuddyList().isDeleteUser()) { boolean buddyDeleted = databaseManager.removeBuddyFromUser(user, buddyUsername); if (buddyDeleted) { String buddyDisplayName = databaseManager.getUserDisplayName(buddyUsername); BuddyList buddyList = new BuddyList(); buddyList.setDeleteUser(true); Buddy buddy = new Buddy(buddyUsername, buddyDisplayName, groupName); buddyList.addBuddy(buddy); clientOutbound.setBuddyList(buddyList); clientOutbound.setBuddyListUpdate(true); } else System.out.println("Buddy deletion failed."); } } if (clientInbound.isChatroomListingsRequest()) { clientOutbound.setChatroomListingsRequest(true); clientOutbound.setCategories(SessionManager.getInstance().getChatroomCategories()); clientOutbound.setUsers(SessionManager.getInstance().getChatroomUsers()); clientOutbound.setNullMessage(true); } if (clientInbound.isChatroomCreateRequest()) { createChatroom(clientInbound.getSenderDisplayName(), clientInbound.getChatroomCategory(), clientInbound.getChatroomName()); } if (clientInbound.isLeftChatroom()) { String chatroomName = clientInbound.getChatroomName(); SessionManager.getInstance().removeChatroomUser(clientInbound.getSenderDisplayName(), clientInbound.getChatroomCategory(), clientInbound.getChatroomName()); ArrayList<String> usersInRoom = SessionManager.getInstance().getChatroomUsers().get(chatroomName); Message message = new Message(true); message.setLeftChatroom(true); message.setChatroomCategory(clientInbound.getChatroomCategory()); message.setChatroomName(clientInbound.getChatroomName()); message.setSenderDisplayName(clientInbound.getSenderDisplayName()); if (usersInRoom != null) { for (String user : usersInRoom) { SessionManager.getInstance().addOutgoingMessage(user.toLowerCase(), message); } } } if (clientInbound.isEnteredChatroom()) { String chatroomCategory = clientInbound.getChatroomCategory(); String chatroomName = clientInbound.getChatroomName(); String displayName = clientInbound.getSenderDisplayName(); SessionManager.getInstance().addChatroomUser(displayName, chatroomCategory, chatroomName); Message message = new Message(true); message.setEnteredChatroom(true); message.setSenderDisplayName(clientInbound.getSenderDisplayName()); message.setChatroomCategory(clientInbound.getChatroomCategory()); message.setChatroomName(clientInbound.getChatroomName()); message.setChatroomUsers(SessionManager.getInstance().getChatroomUsers().get(chatroomName)); if (SessionManager.getInstance().getChatroomUsers().get(chatroomName) == null) { createChatroom(clientInbound.getSenderDisplayName(), clientInbound.getChatroomCategory(), clientInbound.getChatroomName()); message.setChatroomUsers(SessionManager.getInstance().getChatroomUsers().get(chatroomName)); } for (String user : SessionManager.getInstance().getChatroomUsers().get(chatroomName)) { SessionManager.getInstance().addOutgoingMessage(user.toLowerCase(), message); } } if (clientInbound.isCarryingChatroomMessage()) { Message message = clientInbound; for (String user : SessionManager.getInstance().getChatroomUsers().get(clientInbound.getChatroomName())) { SessionManager.getInstance().addOutgoingMessage(user, message); } } toClient.writeObject(clientOutbound); toClient.flush(); toClient.reset(); } } catch (ConnectionResetException cre) {} catch (EOFException eofe) {} catch (IOException ioe) { ioe.printStackTrace(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } finally { try { SessionManager.getInstance().removeUserFromAllChatrooms(username); sessionManager.broadcastStateUpdate(username, 1); System.out.println(username + " disconnected."); clientSocket.close(); sessionManager.removeMember(username); } catch (IOException ex) { ex.printStackTrace(); } } } private void createChatroom(String displayName, String chatroomCategory, String chatroomName) { SessionManager.getInstance().addChatroom(displayName, chatroomCategory, chatroomName); } private BuddyList buildBuddyList(String username) { DatabaseManager databaseManager = DatabaseManager.getInstance(); BuddyList buddyList = databaseManager.getBuddyList(username); ArrayList<Buddy> currentlyOffline = new ArrayList<>(); ArrayList<Buddy> currentlyOnline = new ArrayList<>(); SessionManager sessionManager = SessionManager.getInstance(); for (Buddy buddy : buddyList.getBuddies()) { if (sessionManager.isOnline(buddy.getUsername())) { currentlyOnline.add(buddy); } else currentlyOffline.add(buddy); } buddyList.setCurrentlyOffline(currentlyOffline); buddyList.setCurrentlyOnline(currentlyOnline); return buddyList; } }
14,772
0.59518
0.593894
322
44.875778
34.186691
176
false
false
0
0
0
0
0
0
0.630435
false
false
4
64b378dc7f7f01a9b1ba96d4112113601a010214
29,815,663,036,758
2ae85c202966460ee60003df4f6aa2925ca26ad4
/app/src/main/java/com/example/fxplus/himetooplayer/activity/view/TitleBar.java
6188e54e466af1b1e1ad482ebda6ff7c54188b11
[]
no_license
zhanwgei666/himetooPlayer
https://github.com/zhanwgei666/himetooPlayer
9b0254446fe140ed7b7f4bfa1ccf1b58b7f02dcc
87f4f311fb7e7b7e6603a62da475ad5ab9bb40bd
refs/heads/master
2020-04-22T09:24:23.157000
2019-03-08T03:41:24
2019-03-08T03:41:24
170,271,051
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.fxplus.himetooplayer.activity.view; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; import com.example.fxplus.himetooplayer.R; import com.example.fxplus.himetooplayer.activity.activity.SearchActivity; //自定义标题栏 public class TitleBar extends LinearLayout implements View.OnClickListener { private View tv_search; private View rl_game; private View history; private Context context; //在代码中实例化改类的时候使用这个方法 public TitleBar(Context context) { this(context,null); } //当在布局文件中使用该类的时候,Android系统通过这个构造方法实例化该类 public TitleBar(Context context,AttributeSet attrs) { this(context, attrs,0); } //当需要使用设置样式的时候,可以使用该方法 public TitleBar(Context context,AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; } //当布局文件加载完成的时候回调这个方法 @Override protected void onFinishInflate() { super.onFinishInflate(); //得到孩子的实例 tv_search = getChildAt(1); rl_game = getChildAt(2); history = getChildAt(3); //设置点击事件 tv_search.setOnClickListener(this); rl_game.setOnClickListener(this); history.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.tv_search: // Toast.makeText(context,"搜索",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(context, SearchActivity.class); context.startActivity(intent); break; case R.id.rl_game: Toast.makeText(context,"游戏",Toast.LENGTH_SHORT).show(); break; case R.id.history: Toast.makeText(context,"历史记录",Toast.LENGTH_SHORT).show(); break; } } }
UTF-8
Java
2,236
java
TitleBar.java
Java
[]
null
[]
package com.example.fxplus.himetooplayer.activity.view; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; import com.example.fxplus.himetooplayer.R; import com.example.fxplus.himetooplayer.activity.activity.SearchActivity; //自定义标题栏 public class TitleBar extends LinearLayout implements View.OnClickListener { private View tv_search; private View rl_game; private View history; private Context context; //在代码中实例化改类的时候使用这个方法 public TitleBar(Context context) { this(context,null); } //当在布局文件中使用该类的时候,Android系统通过这个构造方法实例化该类 public TitleBar(Context context,AttributeSet attrs) { this(context, attrs,0); } //当需要使用设置样式的时候,可以使用该方法 public TitleBar(Context context,AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; } //当布局文件加载完成的时候回调这个方法 @Override protected void onFinishInflate() { super.onFinishInflate(); //得到孩子的实例 tv_search = getChildAt(1); rl_game = getChildAt(2); history = getChildAt(3); //设置点击事件 tv_search.setOnClickListener(this); rl_game.setOnClickListener(this); history.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.tv_search: // Toast.makeText(context,"搜索",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(context, SearchActivity.class); context.startActivity(intent); break; case R.id.rl_game: Toast.makeText(context,"游戏",Toast.LENGTH_SHORT).show(); break; case R.id.history: Toast.makeText(context,"历史记录",Toast.LENGTH_SHORT).show(); break; } } }
2,236
0.645274
0.643284
74
26.162163
21.649559
76
false
false
0
0
0
0
0
0
0.648649
false
false
4
4ba3618ac904f9e08e0c9f096722fe7bd45ea4ad
24,412,594,113,418
06f13fe4e80493873f7e293085de02a9b38f806c
/src/main/java/linkedLists/MergeLists.java
c594e0ea1300b6ccf4c2b8b3e108e222a5bfe576
[]
no_license
jy2981033857/EPI
https://github.com/jy2981033857/EPI
df883d0b95b7cace17c84a7143cd3ae3cd112f7c
ee9eb6504ce17250ecbcad7b6f1ce1c195fbc612
refs/heads/master
2022-12-08T20:26:46.457000
2020-09-07T09:59:37
2020-09-07T09:59:37
293,479,319
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package linkedLists; import java.util.Arrays; import java.util.List; import linkedLists.ListNode; public class MergeLists { //Problem 8.1 public static ListNode<Integer> Merge(ListNode<Integer> L1, ListNode<Integer> L2){ ListNode<Integer> dummyHead = new ListNode<Integer>(null, null); ListNode<Integer> current = dummyHead; ListNode<Integer> p1 = L1, p2 = L2; //Merge sorting while(p1 != null && p2 != null){ if(p1.data <= p2.data){ current.next = p1; p1 = p1.next; } else{ current.next = p2; p2 = p2.next; } current = current.next; } current.next = p1 != null ? p1 : p2; return dummyHead.next; } //Problem 8.10 public static ListNode<Integer> evenOddMerge(ListNode<Integer> L){ ListNode<Integer> dummyEvenHead = new ListNode<Integer>(0, null); ListNode<Integer> dummyOoddHead = new ListNode<Integer>(0, null); ListNode<Integer> current = L; List<ListNode<Integer>> tails = Arrays.asList(dummyEvenHead, dummyOoddHead); int turn = 0; //traverse L while(current != null){ tails.get(turn).next = current; tails.set(turn, tails.get(turn).next); turn ^= 1; //XOR flip current = current.next; } /*for(ListNode<Integer> current = L; current != null; current = current.next){ }*/ //merge the two lists tails.get(0).next = dummyOoddHead.next; tails.get(1).next = null; return dummyEvenHead.next; } }
UTF-8
Java
1,414
java
MergeLists.java
Java
[]
null
[]
package linkedLists; import java.util.Arrays; import java.util.List; import linkedLists.ListNode; public class MergeLists { //Problem 8.1 public static ListNode<Integer> Merge(ListNode<Integer> L1, ListNode<Integer> L2){ ListNode<Integer> dummyHead = new ListNode<Integer>(null, null); ListNode<Integer> current = dummyHead; ListNode<Integer> p1 = L1, p2 = L2; //Merge sorting while(p1 != null && p2 != null){ if(p1.data <= p2.data){ current.next = p1; p1 = p1.next; } else{ current.next = p2; p2 = p2.next; } current = current.next; } current.next = p1 != null ? p1 : p2; return dummyHead.next; } //Problem 8.10 public static ListNode<Integer> evenOddMerge(ListNode<Integer> L){ ListNode<Integer> dummyEvenHead = new ListNode<Integer>(0, null); ListNode<Integer> dummyOoddHead = new ListNode<Integer>(0, null); ListNode<Integer> current = L; List<ListNode<Integer>> tails = Arrays.asList(dummyEvenHead, dummyOoddHead); int turn = 0; //traverse L while(current != null){ tails.get(turn).next = current; tails.set(turn, tails.get(turn).next); turn ^= 1; //XOR flip current = current.next; } /*for(ListNode<Integer> current = L; current != null; current = current.next){ }*/ //merge the two lists tails.get(0).next = dummyOoddHead.next; tails.get(1).next = null; return dummyEvenHead.next; } }
1,414
0.661245
0.640028
60
22.566668
22.163307
83
false
false
0
0
0
0
0
0
2.366667
false
false
4
51642ae9c52fa41c460a024b36e366fec25847f1
33,200,097,256,041
957cdf7f38af4901a26f5bb59a3b04718812ef6c
/src/main/java/com/bjev/esb/entity/sysesb/TIfElementEntity.java
19a8e5e1cd33f663eaaeebae91e37bff9ebcf651
[ "MIT" ]
permissive
hankli1985/boot-code
https://github.com/hankli1985/boot-code
e7c2fe5d30e3c2b1ce55df854f7c03eae386a962
8e9d59a56a35e7a805c55a66e9716dff870ad7eb
refs/heads/master
2023-04-19T01:28:33.517000
2021-04-27T15:43:53
2021-04-27T15:43:53
362,133,623
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bjev.esb.entity.sysesb; import lombok.Data; @Data public class TIfElementEntity { private Long pkId; private String ifCode; private String elementName; private String tableId; private String fieldName; private String defaultValue; private String xmlAttr; private String creator; private Integer fieldType; private String userFieldType; private Integer maxLength; private Integer isActive; private Integer nullAble; private Integer insertAble; private Integer updateAble; private Integer sortNo; private String elementDesc; private String dataConvert; private String dataFormat; public TIfElementEntity(Long pkId) { this.pkId = pkId; } }
UTF-8
Java
699
java
TIfElementEntity.java
Java
[]
null
[]
package com.bjev.esb.entity.sysesb; import lombok.Data; @Data public class TIfElementEntity { private Long pkId; private String ifCode; private String elementName; private String tableId; private String fieldName; private String defaultValue; private String xmlAttr; private String creator; private Integer fieldType; private String userFieldType; private Integer maxLength; private Integer isActive; private Integer nullAble; private Integer insertAble; private Integer updateAble; private Integer sortNo; private String elementDesc; private String dataConvert; private String dataFormat; public TIfElementEntity(Long pkId) { this.pkId = pkId; } }
699
0.769671
0.769671
31
21.548388
11.575387
38
false
false
0
0
0
0
0
0
0.709677
false
false
4
5c18b43cc9bb027875267784a6b654d10554283c
35,296,041,266,311
8a032ea8d07c07587770978e1d3fef125b9ac003
/src/com/pipl/api/data/containers/Person.java
2287719e1cfd550fbc4db7c110256d46794be271
[ "Apache-2.0" ]
permissive
arulrajnet/piplapis-java
https://github.com/arulrajnet/piplapis-java
0d0965d96a79fdf9cc7f3e7b74f1887ed69223b5
9e1a44687cf37d4438277c5953661e2960e51e4f
refs/heads/master
2020-04-29T16:53:42.458000
2014-03-27T12:24:19
2014-03-27T12:24:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pipl.api.data.containers; import java.util.ArrayList; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.pipl.api.data.Source; import com.pipl.api.data.fields.Email; import com.pipl.api.data.fields.Field; import com.pipl.api.data.fields.Name; import com.pipl.api.data.fields.Phone; import com.pipl.api.data.fields.Username; /** * A Person object is all the data available on an individual. * <p/> * The Person object is essentially very similar in its structure to the Record * object, the main difference is that data about an individual can come from * multiple sources while a record is data from one source. * <p/> * The person's data comes as field objects (Name, Address, Email etc. see * piplapis.data.fields). Each type of field has its on container (note that * Person is a subclass of FieldsContainer). For example: * <p/> * <p> * <blockquote> * * <pre> * name = new Name(&quot;ccc&quot;, &quot;ddd&quot;); * email = new Email(&quot;t@v.com&quot;); * phone = new Phone(Long.parseLong(&quot;888888888&quot;)); * username = new Username(&quot;dddd&quot;); * address = new Address(&quot;fr&quot;, null, null); * dob = DOB.fromAgeRange(10, 55); * relationship = new Relationship(new Name(&quot;kkk&quot;, &quot;ggg&quot;)); * fields = new ArrayList&lt;Field&gt;(); * fields.add(name); * fields.add(email); * fields.add(phone); * fields.add(username); * fields.add(address); * fields.add(dob); * fields.add(relationship); * person = new Person(fields); * </pre> * * </blockquote> * <p/> * <p/> * Note that a person object is used in the Search API in two ways: - It might * come back as a result for a query (see SearchResponse). - It's possible to * build a person object with all the information you already have about the * person you're looking for and send this object as the query (see * SearchRequest). */ public class Person extends FieldsContainer { /** * */ private static final long serialVersionUID = 1L; @Expose private ArrayList<Source> sources; @SerializedName("@query_params_match") private Boolean queryParamsMatch; /** * @param fields * An ArrayList of <code>Field</code> objects * @param sources * A list of Source objects * @param queryParamsMatch * A bool value that indicates whether the record contains all * the params from the query or not. */ public Person(ArrayList<Field> fields, ArrayList<Source> sources, Boolean queryParamsMatch) { super(fields); setSources(sources); this.queryParamsMatch = queryParamsMatch; } private Person(Builder builder) { this(builder.fields, builder.sources, builder.queryParamsMatch); } public static class Builder { private ArrayList<Field> fields; private ArrayList<Source> sources; private Boolean queryParamsMatch; public Person build() { return new Person(this); } public Builder fields(ArrayList<Field> fields) { this.fields = fields; return this; } public Builder sources(ArrayList<Source> sources) { this.sources = sources; return this; } public Builder queryParamsMatch(Boolean queryParamsMatch) { this.queryParamsMatch = queryParamsMatch; return this; } } /** * @return A bool value that indicates whether the person has enough data * and can be sent as a query to the API. */ public boolean isSearchable() { for (Name name : getNames()) { if (name.isSearchable()) { return true; } } for (Email email : getEmails()) { if (email.isSearchable()) { return true; } } for (Phone phone : getPhones()) { if (phone.isSearchable()) { return true; } } for (Username username : getUsernames()) { if (username.isSearchable()) { return true; } } return false; } /** * @return A list of all the fields that can't be searched by. For example: * names/usernames that are too short, emails that are invalid etc. */ public ArrayList<Field> unsearchableFields() { ArrayList<Field> unSearchableList = new ArrayList<Field>(); for (Field field : allFields()) { if (!field.isSearchable()) { unSearchableList.add(field); } } return unSearchableList; } public ArrayList<Source> getSources() { return sources; } public void setSources(ArrayList<Source> sources) { if (null == sources) { this.sources = new ArrayList<Source>(); } else { this.sources = sources; } } public Boolean isQueryParamsMatch() { return queryParamsMatch; } public void setQueryParamsMatch(Boolean queryParamsMatch) { this.queryParamsMatch = queryParamsMatch; } }
UTF-8
Java
4,854
java
Person.java
Java
[ { "context": "t;, &quot;ddd&quot;);\r\n * email = new Email(&quot;t@v.com&quot;);\r\n * phone = new Phone(Long.parseLong(&quo", "end": 1067, "score": 0.9875757098197937, "start": 1060, "tag": "EMAIL", "value": "t@v.com" } ]
null
[]
package com.pipl.api.data.containers; import java.util.ArrayList; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.pipl.api.data.Source; import com.pipl.api.data.fields.Email; import com.pipl.api.data.fields.Field; import com.pipl.api.data.fields.Name; import com.pipl.api.data.fields.Phone; import com.pipl.api.data.fields.Username; /** * A Person object is all the data available on an individual. * <p/> * The Person object is essentially very similar in its structure to the Record * object, the main difference is that data about an individual can come from * multiple sources while a record is data from one source. * <p/> * The person's data comes as field objects (Name, Address, Email etc. see * piplapis.data.fields). Each type of field has its on container (note that * Person is a subclass of FieldsContainer). For example: * <p/> * <p> * <blockquote> * * <pre> * name = new Name(&quot;ccc&quot;, &quot;ddd&quot;); * email = new Email(&quot;<EMAIL>&quot;); * phone = new Phone(Long.parseLong(&quot;888888888&quot;)); * username = new Username(&quot;dddd&quot;); * address = new Address(&quot;fr&quot;, null, null); * dob = DOB.fromAgeRange(10, 55); * relationship = new Relationship(new Name(&quot;kkk&quot;, &quot;ggg&quot;)); * fields = new ArrayList&lt;Field&gt;(); * fields.add(name); * fields.add(email); * fields.add(phone); * fields.add(username); * fields.add(address); * fields.add(dob); * fields.add(relationship); * person = new Person(fields); * </pre> * * </blockquote> * <p/> * <p/> * Note that a person object is used in the Search API in two ways: - It might * come back as a result for a query (see SearchResponse). - It's possible to * build a person object with all the information you already have about the * person you're looking for and send this object as the query (see * SearchRequest). */ public class Person extends FieldsContainer { /** * */ private static final long serialVersionUID = 1L; @Expose private ArrayList<Source> sources; @SerializedName("@query_params_match") private Boolean queryParamsMatch; /** * @param fields * An ArrayList of <code>Field</code> objects * @param sources * A list of Source objects * @param queryParamsMatch * A bool value that indicates whether the record contains all * the params from the query or not. */ public Person(ArrayList<Field> fields, ArrayList<Source> sources, Boolean queryParamsMatch) { super(fields); setSources(sources); this.queryParamsMatch = queryParamsMatch; } private Person(Builder builder) { this(builder.fields, builder.sources, builder.queryParamsMatch); } public static class Builder { private ArrayList<Field> fields; private ArrayList<Source> sources; private Boolean queryParamsMatch; public Person build() { return new Person(this); } public Builder fields(ArrayList<Field> fields) { this.fields = fields; return this; } public Builder sources(ArrayList<Source> sources) { this.sources = sources; return this; } public Builder queryParamsMatch(Boolean queryParamsMatch) { this.queryParamsMatch = queryParamsMatch; return this; } } /** * @return A bool value that indicates whether the person has enough data * and can be sent as a query to the API. */ public boolean isSearchable() { for (Name name : getNames()) { if (name.isSearchable()) { return true; } } for (Email email : getEmails()) { if (email.isSearchable()) { return true; } } for (Phone phone : getPhones()) { if (phone.isSearchable()) { return true; } } for (Username username : getUsernames()) { if (username.isSearchable()) { return true; } } return false; } /** * @return A list of all the fields that can't be searched by. For example: * names/usernames that are too short, emails that are invalid etc. */ public ArrayList<Field> unsearchableFields() { ArrayList<Field> unSearchableList = new ArrayList<Field>(); for (Field field : allFields()) { if (!field.isSearchable()) { unSearchableList.add(field); } } return unSearchableList; } public ArrayList<Source> getSources() { return sources; } public void setSources(ArrayList<Source> sources) { if (null == sources) { this.sources = new ArrayList<Source>(); } else { this.sources = sources; } } public Boolean isQueryParamsMatch() { return queryParamsMatch; } public void setQueryParamsMatch(Boolean queryParamsMatch) { this.queryParamsMatch = queryParamsMatch; } }
4,854
0.662546
0.659662
176
25.579546
23.181459
79
false
false
0
0
0
0
0
0
1.579545
false
false
4
b843141da54b65dbbf31004f968de344051f81fc
31,361,851,245,902
5815d5ea36769d186bca7a52ca3877b4973647db
/src/main/java/org/barracasentertainment/javatesting/exceptions/IllegalCalculatorOperationException.java
9999446148ee43f034ee16c19f7be16c38b8bbec
[]
no_license
TheDreigon/JavaTesting_JUnit-Mockito_Practise
https://github.com/TheDreigon/JavaTesting_JUnit-Mockito_Practise
21a96563864e25a974ff89372dfca945407c2f2a
9d4be59d5d85fd0d96ea82211d5a29bb0d70d168
refs/heads/master
2020-04-26T14:00:05.004000
2019-03-03T16:13:09
2019-03-03T16:13:09
173,597,806
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.barracasentertainment.javatesting.exceptions; import org.barracasentertainment.javatesting.errors.ErrorMessage; public class IllegalCalculatorOperationException extends CalculatorException { public IllegalCalculatorOperationException () { super(ErrorMessage.INVALID_OPERATION); } }
UTF-8
Java
313
java
IllegalCalculatorOperationException.java
Java
[]
null
[]
package org.barracasentertainment.javatesting.exceptions; import org.barracasentertainment.javatesting.errors.ErrorMessage; public class IllegalCalculatorOperationException extends CalculatorException { public IllegalCalculatorOperationException () { super(ErrorMessage.INVALID_OPERATION); } }
313
0.821086
0.821086
10
30.299999
30.199503
78
false
false
0
0
0
0
0
0
0.3
false
false
4
bcd1650b989cd6c1252524a7d40e29e5b8604954
38,044,820,327,387
ca14764b0a81d050f5743a4085e60e156fe5a337
/Exercises/string/UsefulNumber.java
cd1055e083bc387804b746205c0228c22be77cbf
[]
no_license
zero-joke/algorithm
https://github.com/zero-joke/algorithm
2b1abe10461f1d002970b07c2a3a9acfb5b1651a
06e6c65f2e173f98b6dda22074a2c7e1f11e9c77
refs/heads/master
2023-01-16T08:09:45.207000
2020-11-26T11:30:27
2020-11-26T11:30:27
267,165,257
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Exercises.string; public class UsefulNumber { public boolean isNumber(String s) { s = s.trim(); int idxe = s.indexOf("e"); int idxE = s.indexOf("E"); if(idxe != -1 && idxE != -1) return false; idxe = idxe != -1 ? idxe : idxE; if(idxe == -1) { return isR(s, false); } else { if(idxe-1 < 0 || idxe+1 >= s.length()) return false; return isR(s.substring(0, idxe), false) && isR(s.substring(idxe+1), true); } } private boolean isR(String s, boolean mustInt) { int len = s.length(); boolean signed = false; boolean pointed = false; boolean useful = false; for(int i=0; i<len;i++) { char c = s.charAt(i); if(isSign(c)) { if(signed) return false; if(i+1 >= len) return false; signed = true; } else if(c == '.') { if(mustInt) return false; if(pointed) return false; if(!useful && (i+1 >= len || !Character.isDigit(s.charAt(i+1)))) return false; // 前后都没有数字 pointed = true; } else if(Character.isDigit(c)) { useful = true; } else return false; } return useful; } private boolean isSign(char c) { return c == '+' || c == '-'; } public static void main(String[] args) { UsefulNumber Main = new UsefulNumber(); System.out.println(Main.isNumber("2e0")); } }
UTF-8
Java
1,739
java
UsefulNumber.java
Java
[]
null
[]
package Exercises.string; public class UsefulNumber { public boolean isNumber(String s) { s = s.trim(); int idxe = s.indexOf("e"); int idxE = s.indexOf("E"); if(idxe != -1 && idxE != -1) return false; idxe = idxe != -1 ? idxe : idxE; if(idxe == -1) { return isR(s, false); } else { if(idxe-1 < 0 || idxe+1 >= s.length()) return false; return isR(s.substring(0, idxe), false) && isR(s.substring(idxe+1), true); } } private boolean isR(String s, boolean mustInt) { int len = s.length(); boolean signed = false; boolean pointed = false; boolean useful = false; for(int i=0; i<len;i++) { char c = s.charAt(i); if(isSign(c)) { if(signed) return false; if(i+1 >= len) return false; signed = true; } else if(c == '.') { if(mustInt) return false; if(pointed) return false; if(!useful && (i+1 >= len || !Character.isDigit(s.charAt(i+1)))) return false; // 前后都没有数字 pointed = true; } else if(Character.isDigit(c)) { useful = true; } else return false; } return useful; } private boolean isSign(char c) { return c == '+' || c == '-'; } public static void main(String[] args) { UsefulNumber Main = new UsefulNumber(); System.out.println(Main.isNumber("2e0")); } }
1,739
0.432464
0.423768
58
28.758621
15.940958
80
false
false
0
0
0
0
0
0
0.689655
false
false
4
3862ee94504cbff4615814c38bda5ad9bb497af0
10,505,490,055,642
03681a016e8fceee3d2c0b4012e0d45e4a41a8d0
/src/main/resources/mcpi/api/java/src-demos/pi/demo/TurtleDemo.java
c17fe2173cee159631be198221db35e81e927099
[ "Apache-2.0" ]
permissive
zhuowei/RaspberryJuice
https://github.com/zhuowei/RaspberryJuice
49a17210c40c5aa1b2b73a4f36fc276d3a75c2f1
e8ef1bcd5aa07a1851d25de847c02e0a171d8a20
refs/heads/master
2023-05-14T10:25:57.844000
2023-04-27T07:14:49
2023-04-27T07:14:49
7,324,594
326
152
NOASSERTION
false
2023-02-24T23:33:45
2012-12-26T07:46:37
2023-02-14T15:00:05
2023-02-24T23:33:44
790
290
131
26
Java
false
false
package pi.demo; import pi.*; import pi.tool.Turtle; import static pi.Block.*; /** * * @author Daniel Frisk, twitter:danfrisk */ public class TurtleDemo { public static void main(String[] args) { Turtle turtle = Minecraft.connect(args).tools.turtle; int width = 9, depth = 5, height = 3; drawHouse(turtle, width, depth, height); } /** * Draw a square house at turtle setHome * * @param turtle the turtle to use for drawing * @param width the width of the house * @param height the height of the walls */ private static void drawHouse(Turtle turtle, int width, int depth, int height) { width--; // Floor // Walls turtle.home().off().up(1).block(BRICK_BLOCK).on(); for (int i = 0; i < height; i++) { turtle.forward(depth).right(). forward(width).right(). forward(depth).right(). forward(width).right(); turtle.up(1); } // Roof turtle.jump(0, 0, -1).block(WOOD); for (int s = depth; s >= 0; s -= 2) { turtle.forward(s).right().forward(width + 2).right() .forward(s).right().forward(width + 2).right(); turtle.jump(1, 1, 0); } // Door turtle.home().block(AIR).off().up(1).right().forward(width / 2).on().up(1); } }
UTF-8
Java
1,420
java
TurtleDemo.java
Java
[ { "context": "rtle;\nimport static pi.Block.*;\n\n/**\n *\n * @author Daniel Frisk, twitter:danfrisk\n */\npublic class TurtleDemo {\n ", "end": 111, "score": 0.9998302459716797, "start": 99, "tag": "NAME", "value": "Daniel Frisk" }, { "context": "Block.*;\n\n/**\n *\n * @author Daniel Frisk, twitter:danfrisk\n */\npublic class TurtleDemo {\n public static v", "end": 129, "score": 0.9996599555015564, "start": 121, "tag": "USERNAME", "value": "danfrisk" } ]
null
[]
package pi.demo; import pi.*; import pi.tool.Turtle; import static pi.Block.*; /** * * @author <NAME>, twitter:danfrisk */ public class TurtleDemo { public static void main(String[] args) { Turtle turtle = Minecraft.connect(args).tools.turtle; int width = 9, depth = 5, height = 3; drawHouse(turtle, width, depth, height); } /** * Draw a square house at turtle setHome * * @param turtle the turtle to use for drawing * @param width the width of the house * @param height the height of the walls */ private static void drawHouse(Turtle turtle, int width, int depth, int height) { width--; // Floor // Walls turtle.home().off().up(1).block(BRICK_BLOCK).on(); for (int i = 0; i < height; i++) { turtle.forward(depth).right(). forward(width).right(). forward(depth).right(). forward(width).right(); turtle.up(1); } // Roof turtle.jump(0, 0, -1).block(WOOD); for (int s = depth; s >= 0; s -= 2) { turtle.forward(s).right().forward(width + 2).right() .forward(s).right().forward(width + 2).right(); turtle.jump(1, 1, 0); } // Door turtle.home().block(AIR).off().up(1).right().forward(width / 2).on().up(1); } }
1,414
0.524648
0.511268
52
26.307692
23.207706
84
false
false
0
0
0
0
0
0
0.615385
false
false
4
d1dff5fbfeebdc735b68db805cd97b7ae1e0270e
35,966,056,168,478
a93db87abd2ad3247b77d012d97e53a976e5ff43
/at/at-impl/src/main/java/com/at/service/security/SecurityLightWeightServiceImpl.java
1dc8094bc2decb9ba3ba7159b1a82e0bfd33bcd1
[]
no_license
slavgetman/mini-project
https://github.com/slavgetman/mini-project
4bc139aa28b1e029b33f31f98d5ce84aafbd28ab
dbf9df2c8a6b75ca9f7dc23886bf412c073995dd
refs/heads/master
2022-04-29T21:54:31.772000
2017-05-02T14:56:00
2017-05-02T14:56:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.at.service.security; import com.at.dto.factory.security.SecurityDTOFactory; import com.at.dto.out.security.SecurityInfoOutDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @Component public class SecurityLightWeightServiceImpl implements SecurityLightWeightService { @Autowired private SecurityDTOFactory securityDTOFactory; // ********************************************************************************************************** start // *** override SecurityLightWeightService methods *** @Override @Transactional(readOnly = true) public SecurityInfoOutDTO getUserSecurityDetails() { return securityDTOFactory.createOutDTO(); } // ********************************************************************************************************** end }
UTF-8
Java
953
java
SecurityLightWeightServiceImpl.java
Java
[]
null
[]
package com.at.service.security; import com.at.dto.factory.security.SecurityDTOFactory; import com.at.dto.out.security.SecurityInfoOutDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @Component public class SecurityLightWeightServiceImpl implements SecurityLightWeightService { @Autowired private SecurityDTOFactory securityDTOFactory; // ********************************************************************************************************** start // *** override SecurityLightWeightService methods *** @Override @Transactional(readOnly = true) public SecurityInfoOutDTO getUserSecurityDetails() { return securityDTOFactory.createOutDTO(); } // ********************************************************************************************************** end }
953
0.603358
0.603358
32
28.8125
34.211143
119
false
false
0
0
0
0
0
0
0.25
false
false
4
93af16deafbbeadc413ce3c1f3d2cffa3df18611
37,778,532,350,553
308cf11178f8034c1e64e9692d633dbf94d9edda
/examples/mslcli/client/src/main/java/mslcli/common/msg/MessageConfig.java
2a85b971585bdef800530864b6a4f0f6d3ed0355
[ "Apache-2.0" ]
permissive
firmangel8/msl
https://github.com/firmangel8/msl
9abd151c5b31254fba9ce4ea5a61939c7d262da7
78dfd67165533d97051ea6d828063eacc92de77a
refs/heads/master
2020-12-20T06:34:56.344000
2019-10-28T20:00:19
2019-10-28T20:00:19
235,989,131
1
0
Apache-2.0
true
2020-01-24T11:18:03
2020-01-24T11:18:03
2020-01-23T11:09:25
2019-10-28T20:00:25
17,188
0
0
0
null
false
false
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.common.msg; import mslcli.common.util.SharedUtil; /** * <p>MSL message security configuration data object.</p> * * @author Vadim Spector <vspector@netflix.com> */ public final class MessageConfig { /** whether message should be encrypted */ public boolean isEncrypted; /** whether message should be integrity protected */ public boolean isIntegrityProtected; /** whether message should be non-replayable */ public boolean isNonReplayable; @Override public String toString() { return String.format("%s{encrypted: %b, integrity protected: %b, non-replayable: %b}", SharedUtil.toString(this), isEncrypted, isIntegrityProtected, isNonReplayable); } }
UTF-8
Java
1,351
java
MessageConfig.java
Java
[ { "context": "urity configuration data object.</p>\n *\n * @author Vadim Spector <vspector@netflix.com>\n */\n\npublic final class Me", "end": 781, "score": 0.9998480081558228, "start": 768, "tag": "NAME", "value": "Vadim Spector" }, { "context": "ion data object.</p>\n *\n * @author Vadim Spector <vspector@netflix.com>\n */\n\npublic final class MessageConfig {\n /** ", "end": 803, "score": 0.9999299645423889, "start": 783, "tag": "EMAIL", "value": "vspector@netflix.com" } ]
null
[]
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.common.msg; import mslcli.common.util.SharedUtil; /** * <p>MSL message security configuration data object.</p> * * @author <NAME> <<EMAIL>> */ public final class MessageConfig { /** whether message should be encrypted */ public boolean isEncrypted; /** whether message should be integrity protected */ public boolean isIntegrityProtected; /** whether message should be non-replayable */ public boolean isNonReplayable; @Override public String toString() { return String.format("%s{encrypted: %b, integrity protected: %b, non-replayable: %b}", SharedUtil.toString(this), isEncrypted, isIntegrityProtected, isNonReplayable); } }
1,331
0.716506
0.710585
40
32.775002
28.678814
94
false
false
0
0
0
0
0
0
0.45
false
false
4
45a9b58be4520413c976862136cdd44045d82b1d
27,925,877,420,902
e35a2a54fafc6915ae6b251325e314dd9b9ead68
/src/main/java/com/gruuy/shejimoshi/behavior/order/Order.java
f7194c090c50adba31c59b95dc102980a046499d
[]
no_license
Gruuy/shejimoshi
https://github.com/Gruuy/shejimoshi
0d6dbe810b66fcaae18663a443cb4dd3c31fa8cd
5064be7967773d90ba5539d08809f45411705a5e
refs/heads/master
2022-07-16T08:54:17.522000
2019-10-17T03:14:18
2019-10-17T03:14:18
215,693,422
0
0
null
false
2022-06-17T02:34:39
2019-10-17T03:14:17
2019-10-17T03:14:38
2022-06-17T02:34:39
83
0
0
1
Java
false
false
package com.gruuy.shejimoshi.behavior.order; /** * @author: Gruuy * @remark: 命令抽象 * @date: Create in 11:48 2019/10/15 */ public abstract class Order { Geter g; abstract void execute(); public void setGeter(Geter entity){ g=entity; } }
UTF-8
Java
273
java
Order.java
Java
[ { "context": ".gruuy.shejimoshi.behavior.order;\n\n/**\n * @author: Gruuy\n * @remark: 命令抽象\n * @date: Create in 11:48 2019/1", "end": 67, "score": 0.9583683609962463, "start": 62, "tag": "USERNAME", "value": "Gruuy" } ]
null
[]
package com.gruuy.shejimoshi.behavior.order; /** * @author: Gruuy * @remark: 命令抽象 * @date: Create in 11:48 2019/10/15 */ public abstract class Order { Geter g; abstract void execute(); public void setGeter(Geter entity){ g=entity; } }
273
0.633962
0.588679
15
16.666666
14.68181
44
false
false
0
0
0
0
0
0
0.266667
false
false
4
12ab26573d98c2951bdb328ee5aa8f23d494497d
29,454,885,778,542
c813aa4c9563263f252f86169c231b9be88a1363
/SecondarySort/AdditionalAttrGroupingComparator.java
ca5b8178147c09e50c64237ab07658bcf2af5906
[]
no_license
onRoad2Happy/MapReduce-1
https://github.com/onRoad2Happy/MapReduce-1
c2cbd517b0a044970dec82478f52f2a2291cfc44
614bf530b625a71d8098b3e667fd073b27b549fd
refs/heads/master
2021-04-27T03:06:10.631000
2017-09-07T08:37:34
2017-09-07T08:37:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package util; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; public class AdditionalAttrGroupingComparator extends WritableComparator { protected AdditionalAttrGroupingComparator() { super(Text.class, true); } @Override public int compare(WritableComparable w1, WritableComparable w2) { Text k1 = (Text)w1; Text k2 = (Text)w2; String key1 =w1.toString(); String key2 =w2.toString(); int result = key1.split("-")[1].compareTo(key2.split("-")[1]); if(result==0) { String firstPartOfKey1 = key1.split("-")[0]; String firstPartOfKey2 = key2.split("-")[0]; result = Integer.valueOf(firstPartOfKey1).compareTo(Integer.valueOf(firstPartOfKey2)) ; } return result; } }
UTF-8
Java
948
java
AdditionalAttrGroupingComparator.java
Java
[]
null
[]
package util; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; public class AdditionalAttrGroupingComparator extends WritableComparator { protected AdditionalAttrGroupingComparator() { super(Text.class, true); } @Override public int compare(WritableComparable w1, WritableComparable w2) { Text k1 = (Text)w1; Text k2 = (Text)w2; String key1 =w1.toString(); String key2 =w2.toString(); int result = key1.split("-")[1].compareTo(key2.split("-")[1]); if(result==0) { String firstPartOfKey1 = key1.split("-")[0]; String firstPartOfKey2 = key2.split("-")[0]; result = Integer.valueOf(firstPartOfKey1).compareTo(Integer.valueOf(firstPartOfKey2)) ; } return result; } }
948
0.636076
0.611814
34
26.882353
25.982759
99
false
false
0
0
0
0
0
0
0.5
false
false
4
1f9b70e5b72328138a1cd0e5f8457492346215b6
38,543,036,522,531
0f36f5be721f1ed1416bb2538bde34f8c48dde8c
/app/src/main/java/edu/fsu/cs/mobile/hw5/ViewAdminEmployeeFragment.java
a403c4f48414cddfe8ed54a9b0aa2e21658def5d
[]
no_license
robertomr100/Android-ContentProvider
https://github.com/robertomr100/Android-ContentProvider
c58253f052dd12e3c1918dc79baebd51acbfd8a2
9b1fdf43597b38f550c1220e878e34fe91f8a47f
refs/heads/main
2023-03-07T07:55:39.474000
2021-02-20T23:43:23
2021-02-20T23:43:23
340,777,663
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.fsu.cs.mobile.hw5; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.app.Fragment; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterViewAnimator; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import java.security.PrivateKey; /** * A simple {@link Fragment} subclass. */ public class ViewAdminEmployeeFragment extends android.support.v4.app.Fragment { private Button button; private Cursor mCursor; private ListView mListview; public ViewAdminEmployeeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_view_admin_employee, container, false); button=(Button)view.findViewById(R.id.logout_admin); mListview=(ListView)view.findViewById(R.id.List); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); button=(Button)view.findViewById(R.id.logout_admin); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), MainActivity.class); startActivity(intent); } }); String[] mProjection = new String[]{ EmployeeContract.TransactionEntry._ID, EmployeeContract.TransactionEntry.LASTLOGIN, }; mCursor=getActivity().getContentResolver().query(EmployeeContract.CONTENT_URI,mProjection,null,null,null); Toast.makeText(getActivity(),Integer.toString(mCursor.getCount()),Toast.LENGTH_LONG).show(); String[] mListColumns= new String[] { EmployeeContract.TransactionEntry._ID, EmployeeContract.TransactionEntry.LASTLOGIN }; int[] mListItems= new int[] { R.id.ID_row, R.id.Time_row }; SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.display_user_row, mCursor,mListColumns,mListItems,0 ); mListview=(ListView)view.findViewById(R.id.List); mListview.setAdapter(adapter); } }
UTF-8
Java
2,877
java
ViewAdminEmployeeFragment.java
Java
[]
null
[]
package edu.fsu.cs.mobile.hw5; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.app.Fragment; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterViewAnimator; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import java.security.PrivateKey; /** * A simple {@link Fragment} subclass. */ public class ViewAdminEmployeeFragment extends android.support.v4.app.Fragment { private Button button; private Cursor mCursor; private ListView mListview; public ViewAdminEmployeeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_view_admin_employee, container, false); button=(Button)view.findViewById(R.id.logout_admin); mListview=(ListView)view.findViewById(R.id.List); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); button=(Button)view.findViewById(R.id.logout_admin); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), MainActivity.class); startActivity(intent); } }); String[] mProjection = new String[]{ EmployeeContract.TransactionEntry._ID, EmployeeContract.TransactionEntry.LASTLOGIN, }; mCursor=getActivity().getContentResolver().query(EmployeeContract.CONTENT_URI,mProjection,null,null,null); Toast.makeText(getActivity(),Integer.toString(mCursor.getCount()),Toast.LENGTH_LONG).show(); String[] mListColumns= new String[] { EmployeeContract.TransactionEntry._ID, EmployeeContract.TransactionEntry.LASTLOGIN }; int[] mListItems= new int[] { R.id.ID_row, R.id.Time_row }; SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.display_user_row, mCursor,mListColumns,mListItems,0 ); mListview=(ListView)view.findViewById(R.id.List); mListview.setAdapter(adapter); } }
2,877
0.653458
0.652416
82
33.085365
28.851259
140
false
false
0
0
0
0
0
0
0.719512
false
false
4
a85504fe9c1c992b7ef24ae653ccfd7a1fd307cb
28,613,072,194,780
33a9d0b44d2ab4a594df10f308806ced2fdd9b44
/CommandPatternsDerek/src/commandpatternsderek/DeviceButton.java
e97f4ea06e3c4dda6e7fef4084dc382b6be8165b
[]
no_license
1Raava1/Design-Patterns
https://github.com/1Raava1/Design-Patterns
64cd7bc3d8ace0c6f7a7212a69108c107143e5b6
4ab2e0d27917553a3a9f88a610dc5fd69eb7b09b
refs/heads/master
2016-09-16T23:42:36.899000
2016-07-07T00:06:45
2016-07-07T00:06:45
61,890,385
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 commandpatternsderek; /** * * @author raava */ //This is known as the invoker //It has a method press() that when executed //causes the execute method to be called //The execute method for the Command interface then calls //the method assigned in the class that implements the Command interface public class DeviceButton { Command theCommand; public DeviceButton(Command newCommand) { theCommand = newCommand; } public void press(){ theCommand.execute(); } //Now the remote can undo past commands public void pressUndo() { theCommand.undo(); } }
UTF-8
Java
799
java
DeviceButton.java
Java
[ { "context": "/\npackage commandpatternsderek;\n\n/**\n *\n * @author raava\n */\n\n//This is known as the invoker\n//It has a me", "end": 239, "score": 0.991538405418396, "start": 234, "tag": "USERNAME", "value": "raava" } ]
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 commandpatternsderek; /** * * @author raava */ //This is known as the invoker //It has a method press() that when executed //causes the execute method to be called //The execute method for the Command interface then calls //the method assigned in the class that implements the Command interface public class DeviceButton { Command theCommand; public DeviceButton(Command newCommand) { theCommand = newCommand; } public void press(){ theCommand.execute(); } //Now the remote can undo past commands public void pressUndo() { theCommand.undo(); } }
799
0.702128
0.702128
33
23.212122
22.15477
79
false
false
0
0
0
0
0
0
0.242424
false
false
4
72173f00f453ce5ebdcc9c30fb4b068fa3bd59b6
36,910,948,967,547
1257ff8c4c3155b954eca8f51fb7e2e122b387b5
/app/src/main/java/com/example/moss/SlaveMain.java
60455601e2260bef6552b304bc4813e3d119feef
[]
no_license
hamzakhalil10/FYP1-S20-10-D-MOSS-GitHubRepo
https://github.com/hamzakhalil10/FYP1-S20-10-D-MOSS-GitHubRepo
6257851d438e025e1d7d8d24f9eb8e5109c87a54
025597596260d011a827d33187b0dd4635ae81bc
refs/heads/master
2023-02-10T09:04:14.725000
2021-01-01T21:18:12
2021-01-01T21:18:12
271,609,123
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.moss; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.material.navigation.NavigationView; import com.google.firebase.auth.FirebaseAuth; 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 com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.squareup.picasso.Picasso; public class SlaveMain extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{ private LinearLayout fireButton; private LinearLayout intrusionButton; private Button logoutButton; private DrawerLayout drawer; private TextView userName_nav; private ImageView profilePic; FirebaseAuth fAuth; StorageReference storageReference; View mHeaderView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_slave_main); Toolbar toolbar = findViewById(R.id.toolbar_slave); setSupportActionBar(toolbar); //initializing firebase fAuth = FirebaseAuth.getInstance(); storageReference = FirebaseStorage.getInstance().getReference(); //displaying navigation drawer drawer = findViewById(R.id.drawer_layout_slave); NavigationView navigationView = findViewById(R.id.nav_view_slave); //initializing nav view variables mHeaderView = navigationView.getHeaderView(0); userName_nav = mHeaderView.findViewById(R.id.userName_nav_header_slave); profilePic = mHeaderView.findViewById(R.id.profilePic_slave); //fetching username in nav drawer from firebase DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Users").child(fAuth.getCurrentUser().getUid()); db.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ String name = dataSnapshot.child("Name").getValue(String.class); userName_nav.setText(name); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { userName_nav.setText("Name"); } }); //setting profile picture StorageReference profileRef = storageReference.child("users/"+fAuth.getCurrentUser().getUid()+"/profilePic.jpg"); profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { Picasso.get().load(uri).into(profilePic); } }); navigationView.setNavigationItemSelectedListener(this); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); //if fire button gets clicked fireButton = findViewById(R.id.fireButton); fireButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ openActivity(savedInstanceState); } }); //if intrusion button gets clicked intrusionButton = findViewById(R.id.IntrusionButton); intrusionButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ openActivity(savedInstanceState); } }); //if logout button gets clicked logoutButton = findViewById(R.id.Slave_LogOut); logoutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FirebaseAuth.getInstance().signOut(); Intent intent1 = new Intent(SlaveMain.this,SignIn.class); startActivity(intent1); finish(); } }); } public void openActivity(Bundle savedInstanceState){ if (null == savedInstanceState) { getFragmentManager() .beginTransaction() .replace(R.id.drawer_layout_slave, CameraActivity.newInstance()) .addToBackStack(null) .commit(); } } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.nav_switch: Intent intent = new Intent(this, MasterMainActivity.class); startActivity(intent); break; case R.id.nav_logout_slave: FirebaseAuth.getInstance().signOut(); Intent intent1 = new Intent(this, SignIn.class); startActivity(intent1); finish(); break; } drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onBackPressed(){ if(drawer.isDrawerOpen(GravityCompat.START)){ drawer.closeDrawer(GravityCompat.START); } else{ super.onBackPressed(); } } }
UTF-8
Java
6,171
java
SlaveMain.java
Java
[]
null
[]
package com.example.moss; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.material.navigation.NavigationView; import com.google.firebase.auth.FirebaseAuth; 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 com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.squareup.picasso.Picasso; public class SlaveMain extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{ private LinearLayout fireButton; private LinearLayout intrusionButton; private Button logoutButton; private DrawerLayout drawer; private TextView userName_nav; private ImageView profilePic; FirebaseAuth fAuth; StorageReference storageReference; View mHeaderView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_slave_main); Toolbar toolbar = findViewById(R.id.toolbar_slave); setSupportActionBar(toolbar); //initializing firebase fAuth = FirebaseAuth.getInstance(); storageReference = FirebaseStorage.getInstance().getReference(); //displaying navigation drawer drawer = findViewById(R.id.drawer_layout_slave); NavigationView navigationView = findViewById(R.id.nav_view_slave); //initializing nav view variables mHeaderView = navigationView.getHeaderView(0); userName_nav = mHeaderView.findViewById(R.id.userName_nav_header_slave); profilePic = mHeaderView.findViewById(R.id.profilePic_slave); //fetching username in nav drawer from firebase DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Users").child(fAuth.getCurrentUser().getUid()); db.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ String name = dataSnapshot.child("Name").getValue(String.class); userName_nav.setText(name); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { userName_nav.setText("Name"); } }); //setting profile picture StorageReference profileRef = storageReference.child("users/"+fAuth.getCurrentUser().getUid()+"/profilePic.jpg"); profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { Picasso.get().load(uri).into(profilePic); } }); navigationView.setNavigationItemSelectedListener(this); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); //if fire button gets clicked fireButton = findViewById(R.id.fireButton); fireButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ openActivity(savedInstanceState); } }); //if intrusion button gets clicked intrusionButton = findViewById(R.id.IntrusionButton); intrusionButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ openActivity(savedInstanceState); } }); //if logout button gets clicked logoutButton = findViewById(R.id.Slave_LogOut); logoutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FirebaseAuth.getInstance().signOut(); Intent intent1 = new Intent(SlaveMain.this,SignIn.class); startActivity(intent1); finish(); } }); } public void openActivity(Bundle savedInstanceState){ if (null == savedInstanceState) { getFragmentManager() .beginTransaction() .replace(R.id.drawer_layout_slave, CameraActivity.newInstance()) .addToBackStack(null) .commit(); } } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.nav_switch: Intent intent = new Intent(this, MasterMainActivity.class); startActivity(intent); break; case R.id.nav_logout_slave: FirebaseAuth.getInstance().signOut(); Intent intent1 = new Intent(this, SignIn.class); startActivity(intent1); finish(); break; } drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onBackPressed(){ if(drawer.isDrawerOpen(GravityCompat.START)){ drawer.closeDrawer(GravityCompat.START); } else{ super.onBackPressed(); } } }
6,171
0.66375
0.66294
169
35.514793
26.674923
151
false
false
0
0
0
0
0
0
0.556213
false
false
4
e1ec3d4258f12f64ee1767afef9b50453e601eec
28,802,050,691,446
5adfdfb4be0ec8564a9292ea97de0a40ac9b7500
/src/main/java/edu/uade/lib/security/Encriptor.java
4fca2bd310a71c345a4b414ccd8d8504b1d305d8
[]
no_license
mberrueta/uade_app_interact_tpo
https://github.com/mberrueta/uade_app_interact_tpo
38379eebdc9baa5f5d01b2dda81de7bdc1eb7c47
37fb837db56600e592081dce04194adb6d72d2a2
refs/heads/master
2021-04-15T05:16:18.042000
2018-07-01T18:10:54
2018-07-01T18:10:54
126,405,025
0
1
null
false
2018-06-29T05:05:54
2018-03-22T23:04:28
2018-06-26T00:44:22
2018-06-29T05:05:53
6,090
0
1
0
Java
false
null
package edu.uade.lib.security; import org.apache.log4j.Logger; public class Encriptor{ private static final Logger log = Logger.getLogger("Encriptor"); public static String encript(String md5) { if(md5 == null) return ""; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(md5.getBytes()); StringBuilder sb = new StringBuilder(); for (byte anArray : array) { sb.append(Integer.toHexString((anArray & 0xFF) | 0x100), 1, 3); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { log.error("error encrypting", e); } return null; } }
UTF-8
Java
785
java
Encriptor.java
Java
[]
null
[]
package edu.uade.lib.security; import org.apache.log4j.Logger; public class Encriptor{ private static final Logger log = Logger.getLogger("Encriptor"); public static String encript(String md5) { if(md5 == null) return ""; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(md5.getBytes()); StringBuilder sb = new StringBuilder(); for (byte anArray : array) { sb.append(Integer.toHexString((anArray & 0xFF) | 0x100), 1, 3); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { log.error("error encrypting", e); } return null; } }
785
0.578344
0.563057
24
31.75
25.637293
93
false
false
0
0
0
0
0
0
0.625
false
false
4
c6ac86f25849dda0a3e0e628b533004c04414178
28,802,050,690,951
4990a8821958fcc95fc1aa35d830fea7e1099e94
/Math Graphs/forTangentLineInParabola2/forTangentLineInParabola2.java
384dd390405eefb3519375a4ddee4528a2b900af
[]
no_license
sojharo/Processing-Java-Graph-Demos
https://github.com/sojharo/Processing-Java-Graph-Demos
70c3d208f22feaa01430924063d9861f61a1b89c
42b2276e8e2ec330215f415b936e8fcb83d42922
refs/heads/master
2020-05-17T22:38:11.634000
2014-09-13T16:18:08
2014-09-13T16:18:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import processing.core.*; import processing.xml.*; import java.applet.*; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.MouseEvent; import java.awt.event.KeyEvent; import java.awt.event.FocusEvent; import java.awt.Image; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import java.util.zip.*; import java.util.regex.*; public class forTangentLineInParabola2 extends PApplet { double py1; double py2; double px; double px2; public int screenX(double x) //scaling of x { return (int)(250+(x*8)); } public int screenY(double y) //scaling of y { return (int)(250-(y*8)); } public int screenX(int x) //scaling of x { return 250+(x*8); } public int screenY(int y) //scaling of y { return 250-(y*8); } public void setup() { size(500,500); smooth(); py1=0; py2=0; px=-16; px2=0; } public void draw() { fill(249,245,34); rect(0, 0, 500, 500); stroke(25,24,254,50); for(int i=-33; i<33; i++) line(screenX(i), -500, screenX(i), 500); for(int i=-33; i<33; i++) line(-500, screenY(i), 500, screenY(i)); noStroke(); for(double px=-16.01f; px<9.99f; px++) { px2=px+1; py1=(0.4f*px*px)+(2*px)-8; py2=(0.4f*px2*px2)+(2*px2)-8; stroke(141,85,244); line(screenX(px), screenY(py1), screenX(px2), screenY(py2)); strokeWeight(1); } px=px+0.05f; px2=px+0.01f; if(px>9) px=-16; py1=(0.4f*px*px)+(2*px)-8; py2=(0.4f*px2*px2)+(2*px2)-8; strokeWeight(1); stroke(1); double pvarx=px-10; double plny1=((py2-py1)/(px2-px))*(pvarx-px2)+py2; double plny2=((py2-py1)/(px2-px))*(pvarx+20-px2)+py2; line(screenX(pvarx), screenY(plny1), screenX(pvarx+20), screenY(plny2)); } static public void main(String args[]) { PApplet.main(new String[] { "--present", "--bgcolor=#666666", "--stop-color=#cccccc", "forTangentLineInParabola2" }); } }
UTF-8
Java
1,941
java
forTangentLineInParabola2.java
Java
[]
null
[]
import processing.core.*; import processing.xml.*; import java.applet.*; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.MouseEvent; import java.awt.event.KeyEvent; import java.awt.event.FocusEvent; import java.awt.Image; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import java.util.zip.*; import java.util.regex.*; public class forTangentLineInParabola2 extends PApplet { double py1; double py2; double px; double px2; public int screenX(double x) //scaling of x { return (int)(250+(x*8)); } public int screenY(double y) //scaling of y { return (int)(250-(y*8)); } public int screenX(int x) //scaling of x { return 250+(x*8); } public int screenY(int y) //scaling of y { return 250-(y*8); } public void setup() { size(500,500); smooth(); py1=0; py2=0; px=-16; px2=0; } public void draw() { fill(249,245,34); rect(0, 0, 500, 500); stroke(25,24,254,50); for(int i=-33; i<33; i++) line(screenX(i), -500, screenX(i), 500); for(int i=-33; i<33; i++) line(-500, screenY(i), 500, screenY(i)); noStroke(); for(double px=-16.01f; px<9.99f; px++) { px2=px+1; py1=(0.4f*px*px)+(2*px)-8; py2=(0.4f*px2*px2)+(2*px2)-8; stroke(141,85,244); line(screenX(px), screenY(py1), screenX(px2), screenY(py2)); strokeWeight(1); } px=px+0.05f; px2=px+0.01f; if(px>9) px=-16; py1=(0.4f*px*px)+(2*px)-8; py2=(0.4f*px2*px2)+(2*px2)-8; strokeWeight(1); stroke(1); double pvarx=px-10; double plny1=((py2-py1)/(px2-px))*(pvarx-px2)+py2; double plny2=((py2-py1)/(px2-px))*(pvarx+20-px2)+py2; line(screenX(pvarx), screenY(plny1), screenX(pvarx+20), screenY(plny2)); } static public void main(String args[]) { PApplet.main(new String[] { "--present", "--bgcolor=#666666", "--stop-color=#cccccc", "forTangentLineInParabola2" }); } }
1,941
0.611025
0.526017
110
16.645454
19.030878
121
false
false
0
0
0
0
0
0
0.772727
false
false
4
28096dbc2d48b7cef4e516aa38fac9091d888303
2,173,253,476,262
9647fb64eefac2cb29a6df8e9a44448a5715b3ae
/app/src/main/java/com/example/prikkie/RecipeListAdapter.java
9165cbd2b303b203ea1c14e7811ce45048193b92
[]
no_license
stefangrebenar/Prikkie
https://github.com/stefangrebenar/Prikkie
2d79f95437012481956005c0b28e7e6f649f7d70
3c21806ce0e6403ce26d13c9f3ff3a78b0e7fca7
refs/heads/master
2021-07-02T21:04:32.546000
2020-01-08T20:50:30
2020-01-08T20:50:30
215,262,890
0
0
null
false
2020-01-19T11:42:27
2019-10-15T09:46:00
2020-01-08T20:50:38
2020-01-19T11:42:26
1,236
0
0
1
Java
false
false
package com.example.prikkie; import android.app.Activity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.RecyclerView; import com.example.prikkie.Api.recipe_api.Recipe; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.RecipeListViewHolder> { private ArrayList<Recipe> m_recipes; private OnItemClickListener m_Listener; private MainActivity mainActivity; public void setRecipes(ArrayList<Recipe> recipes){ m_recipes = recipes; this.notifyDataSetChanged(); } public interface OnItemClickListener{ void onItemClick(int position); } public void setOnItemClickListener(OnItemClickListener listener){ m_Listener = listener; } public class RecipeListViewHolder extends RecyclerView.ViewHolder { public ImageView m_imageView; public TextView m_title; public TextView m_ingredients; public RecipeListViewHolder(View itemView, final OnItemClickListener listener) { super(itemView); m_imageView = itemView.findViewById(R.id.imageView); m_title = itemView.findViewById(R.id.recipeTitle); m_ingredients = itemView.findViewById(R.id.recipeIngredients); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { listener.onItemClick(position); RecipeDetails.setRecipe(m_recipes.get(position)); setFragment(RecipeDetails.getFragment()); } } } }); } } public void setFragment(Fragment fragment) { mainActivity.getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.frame_container, fragment).commit(); } public RecipeListAdapter(ArrayList<Recipe> recipes, Activity activity) { mainActivity = (MainActivity) activity; m_recipes = recipes; } @Override public RecipeListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item, parent, false); RecipeListViewHolder viewHolder = new RecipeListViewHolder(v, m_Listener); return viewHolder; } @Override public void onBindViewHolder(RecipeListViewHolder holder, int position) { Recipe currentItem = m_recipes.get(position); Picasso.get().load(currentItem.imagePath).into(holder.m_imageView); holder.m_title.setText(currentItem.title); holder.m_ingredients.setText(currentItem.ingredientsToString()); } @Override public int getItemCount() { if(m_recipes != null) { return m_recipes.size(); } return 0; } }
UTF-8
Java
3,395
java
RecipeListAdapter.java
Java
[]
null
[]
package com.example.prikkie; import android.app.Activity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.RecyclerView; import com.example.prikkie.Api.recipe_api.Recipe; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.RecipeListViewHolder> { private ArrayList<Recipe> m_recipes; private OnItemClickListener m_Listener; private MainActivity mainActivity; public void setRecipes(ArrayList<Recipe> recipes){ m_recipes = recipes; this.notifyDataSetChanged(); } public interface OnItemClickListener{ void onItemClick(int position); } public void setOnItemClickListener(OnItemClickListener listener){ m_Listener = listener; } public class RecipeListViewHolder extends RecyclerView.ViewHolder { public ImageView m_imageView; public TextView m_title; public TextView m_ingredients; public RecipeListViewHolder(View itemView, final OnItemClickListener listener) { super(itemView); m_imageView = itemView.findViewById(R.id.imageView); m_title = itemView.findViewById(R.id.recipeTitle); m_ingredients = itemView.findViewById(R.id.recipeIngredients); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { listener.onItemClick(position); RecipeDetails.setRecipe(m_recipes.get(position)); setFragment(RecipeDetails.getFragment()); } } } }); } } public void setFragment(Fragment fragment) { mainActivity.getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.frame_container, fragment).commit(); } public RecipeListAdapter(ArrayList<Recipe> recipes, Activity activity) { mainActivity = (MainActivity) activity; m_recipes = recipes; } @Override public RecipeListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item, parent, false); RecipeListViewHolder viewHolder = new RecipeListViewHolder(v, m_Listener); return viewHolder; } @Override public void onBindViewHolder(RecipeListViewHolder holder, int position) { Recipe currentItem = m_recipes.get(position); Picasso.get().load(currentItem.imagePath).into(holder.m_imageView); holder.m_title.setText(currentItem.title); holder.m_ingredients.setText(currentItem.ingredientsToString()); } @Override public int getItemCount() { if(m_recipes != null) { return m_recipes.size(); } return 0; } }
3,395
0.666274
0.665979
98
33.653061
30.666775
174
false
false
0
0
0
0
0
0
0.540816
false
false
4