blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
sequence
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
sequence
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
78de504f7fc178f5e4321c43af2fcf41c82ab368
33,947,421,509,662
3fd6dd3860d462c94e14bab69ea0676b9e8b3a1e
/src/jml/optimization/ProxLInfinity.java
dd1fe1e710d474b22fc6ab1d15839fcd198451cb
[ "Apache-2.0" ]
permissive
MingjieQian/JML
https://github.com/MingjieQian/JML
7c1ed9b3f2573967f6a5a1c470d947e2c5d74ac5
00afaa0e81fbfbdfbfbd7cfbbc6c0287bfb86eac
refs/heads/master
2020-03-30T23:59:30.257000
2015-12-05T04:46:20
2015-12-05T04:46:20
8,636,421
6
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package jml.optimization; import static jml.matlab.Matlab.abs; import static jml.matlab.Matlab.colon; import static jml.matlab.Matlab.display; import static jml.matlab.Matlab.min; import static jml.matlab.Matlab.sign; import static jml.matlab.Matlab.size; import static jml.matlab.Matlab.sort2; import static jml.matlab.Matlab.sumAll; import static jml.matlab.Matlab.times; import static jml.matlab.Matlab.zeros; import org.apache.commons.math.linear.BlockRealMatrix; import org.apache.commons.math.linear.RealMatrix; /** * Compute prox_th(X) where h = || X ||_{\infty}. * * @author Mingjie Qian * @version 1.0, Oct. 14th, 2013 */ public class ProxLInfinity implements ProximalMapping { /** * @param args */ public static void main(String[] args) { double[][] data = new double[][]{ {-3.5}, {2.4}, {1.2}, {-0.9} }; RealMatrix X = new BlockRealMatrix(data); double t = 1.5; display(new ProxLInfinity().compute(t, X)); } /** * Compute prox_th(X) where h = || X ||_{\infty}. * * @param t a nonnegative real scalar * * @param X a real column matrix * * @return prox_th(X) where h = || X ||_{\infty} * */ public RealMatrix compute(double t, RealMatrix X) { if (t < 0) { System.err.println("The first input should be a nonnegative real scalar."); System.exit(-1); } if (X.getColumnDimension() > 1) { System.err.println("The second input should be a vector."); System.exit(-1); } RealMatrix res = X.copy(); RealMatrix U = X.copy(); RealMatrix V = abs(X); if (sumAll(V) <= t) { res = zeros(size(V)); } int d = size(X)[0]; sort2(V); RealMatrix Delta = V.getSubMatrix(1, d - 1, 0, 0).subtract( V.getSubMatrix(0, d - 2, 0, 0)); RealMatrix S = times(Delta, colon(d - 1, -1, 1.0).transpose()); double a = V.getEntry(d - 1, 0); double n = 1; double sum = S.getEntry(d - 2, 0); for (int j = d - 1; j >= 1; j--) { if (sum < t) { if (j > 1) { sum += S.getEntry(j - 2, 0); } a += V.getEntry(j - 1, 0); n++; } else { break; } } double alpha = (a - t) / n; V = U; res = times(sign(V), min(alpha, abs(V))); return res; } }
UTF-8
Java
2,181
java
ProxLInfinity.java
Java
[ { "context": "x_th(X) where h = || X ||_{\\infty}.\n * \n * @author Mingjie Qian\n * @version 1.0, Oct. 14th, 2013\n */\npublic class", "end": 602, "score": 0.9998367428779602, "start": 590, "tag": "NAME", "value": "Mingjie Qian" } ]
null
[]
package jml.optimization; import static jml.matlab.Matlab.abs; import static jml.matlab.Matlab.colon; import static jml.matlab.Matlab.display; import static jml.matlab.Matlab.min; import static jml.matlab.Matlab.sign; import static jml.matlab.Matlab.size; import static jml.matlab.Matlab.sort2; import static jml.matlab.Matlab.sumAll; import static jml.matlab.Matlab.times; import static jml.matlab.Matlab.zeros; import org.apache.commons.math.linear.BlockRealMatrix; import org.apache.commons.math.linear.RealMatrix; /** * Compute prox_th(X) where h = || X ||_{\infty}. * * @author <NAME> * @version 1.0, Oct. 14th, 2013 */ public class ProxLInfinity implements ProximalMapping { /** * @param args */ public static void main(String[] args) { double[][] data = new double[][]{ {-3.5}, {2.4}, {1.2}, {-0.9} }; RealMatrix X = new BlockRealMatrix(data); double t = 1.5; display(new ProxLInfinity().compute(t, X)); } /** * Compute prox_th(X) where h = || X ||_{\infty}. * * @param t a nonnegative real scalar * * @param X a real column matrix * * @return prox_th(X) where h = || X ||_{\infty} * */ public RealMatrix compute(double t, RealMatrix X) { if (t < 0) { System.err.println("The first input should be a nonnegative real scalar."); System.exit(-1); } if (X.getColumnDimension() > 1) { System.err.println("The second input should be a vector."); System.exit(-1); } RealMatrix res = X.copy(); RealMatrix U = X.copy(); RealMatrix V = abs(X); if (sumAll(V) <= t) { res = zeros(size(V)); } int d = size(X)[0]; sort2(V); RealMatrix Delta = V.getSubMatrix(1, d - 1, 0, 0).subtract( V.getSubMatrix(0, d - 2, 0, 0)); RealMatrix S = times(Delta, colon(d - 1, -1, 1.0).transpose()); double a = V.getEntry(d - 1, 0); double n = 1; double sum = S.getEntry(d - 2, 0); for (int j = d - 1; j >= 1; j--) { if (sum < t) { if (j > 1) { sum += S.getEntry(j - 2, 0); } a += V.getEntry(j - 1, 0); n++; } else { break; } } double alpha = (a - t) / n; V = U; res = times(sign(V), min(alpha, abs(V))); return res; } }
2,175
0.605227
0.58276
95
21.957895
18.62365
78
false
false
0
0
0
0
0
0
2.326316
false
false
4
6feb54a61db5a7431877dd47390ce420e71d867d
29,454,885,733,364
5850ed6b619145a9d3990630d10ff977ccdc7731
/src/main/java/edu/training/task09/behavioral/observer/NewsPaper.java
5594d993274ad3b4f9d9b15dff43cd35c5a1d08c
[]
no_license
evgenijaZ/Training-labs
https://github.com/evgenijaZ/Training-labs
91bdc6da8fbd8dadb5abdbec7011dd86b7fcc8c9
3cb6bc046bee3d47a9e0e7daf1d6e11f95cda4dc
refs/heads/master
2020-03-31T13:22:47.661000
2018-12-10T11:58:14
2018-12-10T11:58:14
152,253,164
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.training.task09.behavioral.observer; public class NewsPaper { private String title; public NewsPaper(String title) { this.title = title; } }
UTF-8
Java
175
java
NewsPaper.java
Java
[]
null
[]
package edu.training.task09.behavioral.observer; public class NewsPaper { private String title; public NewsPaper(String title) { this.title = title; } }
175
0.685714
0.674286
9
18.444445
16.647396
48
false
false
0
0
0
0
0
0
0.333333
false
false
4
7fd82779c16ba96498dd1830c35d14a584aa4f9a
9,320,079,063,768
85f573af305c07112cf3296c4c9e26935b0350ad
/app/src/main/java/com/haoyigou/hyg/utils/DateTimeUtils.java
2aa3de7249abb5e53db4e3f74bbba6d67edbc2dc
[]
no_license
wuliang6661/Turuk
https://github.com/wuliang6661/Turuk
0cc8c483c4a8cb536874e7025437042dcbb00a11
4e3a4c0562f0f0f2e7bf9fd47166541550959d62
refs/heads/main
2023-07-20T17:58:56.764000
2021-09-03T14:26:18
2021-09-03T14:26:18
402,777,968
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.haoyigou.hyg.utils; import android.util.Log; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Created by kristain on 15/12/17. */ public class DateTimeUtils { /** * 日期格式:yyyy-MM-dd HH:mm:ss **/ public static final String DF_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; /** * 日期格式:yyyy-MM-dd HH:mm **/ public static final String DF_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm"; /** * 日期格式:yyyy-MM-dd **/ public static final String DF_YYYY_MM_DD = "yyyy-MM-dd"; /** * 日期格式:yyyy-MM-dd **/ public static final String DE_YYYY_MM_DD = "yyyyMMdd"; /** * 日期格式:HH:mm:ss **/ public static final String DF_HH_MM_SS = "HH:mm:ss"; /** * 日期格式:HH:mm **/ public static final String DF_HH_MM = "HH:mm"; /** * 日期格式:yyyy.MM.dd **/ public static final String YYYY_MM_DD = "yyyy.MM.dd"; public static final String YY_MM_DD = "yy.MM.dd"; public static final String MM_DD = "MM.dd"; public static final String YYYYMM = "yyyyMM"; public static final String YYYY_MM_DD_HH_MM = "yyyy.MM.dd HH:mm"; public static final String YYYY = "yyyy"; public static final String MM = "MM"; private final static long minute = 60 * 1000;// 1分钟 private final static long hour = 60 * minute;// 1小时 private final static long day = 24 * hour;// 1天 private final static long month = 31 * day;// 月 private final static long year = 12 * month;// 年 /** * Log输出标识 **/ private static final String TAG = DateTimeUtils.class.getSimpleName(); /** * 将日期格式化成友好的字符串:几分钟前、几小时前、几天前、几月前、几年前、刚刚 * * @param date * @return */ public static String formatFriendly1(long date) { if (date == 0) { return null; } long diff = weeHours(new Date(), 0).getTime() - date * 1000; // long diff = new Date().getTime()- date * 1000; long r = 0; if (diff > day) { r = (diff / day); if (r == 1) { return "昨天"; } if (r == 0) { return "今天"; } } return ""; } /** * 将日期信息转换成今天、明天、后天、星期 * * @param date * @return */ public static String getDateDetail(String date) { Calendar today = Calendar.getInstance(); Calendar target = Calendar.getInstance(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); try { today.setTime(df.parse(df.format(weeHours(new Date(), 0)))); today.set(Calendar.HOUR, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); target.setTime(df.parse(date)); target.set(Calendar.HOUR, 0); target.set(Calendar.MINUTE, 0); target.set(Calendar.SECOND, 0); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } long intervalMilli = target.getTimeInMillis() - today.getTimeInMillis(); int xcts = (int) (intervalMilli / day); if (xcts == 0) { return "今天"; } else if (xcts == 1) { return "明天"; } return ""; } /** * 将日期信息转换成今天、明天、后天、星期 * * @param date * @return */ public static String getDateDetail1(String date) { Calendar today = Calendar.getInstance(); Calendar target = Calendar.getInstance(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); try { today.setTime(df.parse(df.format(weeHours(new Date(), 1)))); today.set(Calendar.HOUR, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); target.setTime(df.parse(date)); target.set(Calendar.HOUR, 0); target.set(Calendar.MINUTE, 0); target.set(Calendar.SECOND, 0); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } long intervalMilli = target.getTimeInMillis() - today.getTimeInMillis(); int xcts = (int) (intervalMilli / day); if (xcts == -1) { return "昨天"; } if (xcts == 0) { return "今天"; } return ""; } /** * 凌晨 * * @param date * @return * @flag 0 返回yyyy-MM-dd 00:00:00日期<br> * 1 返回yyyy-MM-dd 23:59:59日期 */ public static Date weeHours(Date date, int flag) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); //时分秒(毫秒数) long millisecond = hour * 60 * 60 * 1000 + minute * 60 * 1000 + second * 1000; //凌晨00:00:00 cal.setTimeInMillis(cal.getTimeInMillis() - millisecond); if (flag == 0) { return cal.getTime(); } else if (flag == 1) { //凌晨23:59:59 cal.setTimeInMillis(cal.getTimeInMillis() + 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000); } return cal.getTime(); } /** * 2016-6-16转换成2016-6-16 00:00 凌晨 * flag=0 :是 * 将String类型的时间转换成 * * @param str */ public static String WeeDateToStirng(String str, int flag) { Date date = weeHours(parseDate(str, DF_YYYY_MM_DD), flag); return formatDateTime(date, DF_YYYY_MM_DD_HH_MM_SS); } public static void main(String[] str) { System.out.print(getFirstDayOfLastDayInMonth(2016, 2)); } /** * 获取离月底还有几天 * * @return */ public static int getDayOfMonth() { Calendar aCalendar = Calendar.getInstance(Locale.CHINA); int day_of_month = aCalendar.get(Calendar.DAY_OF_MONTH); int day = aCalendar.getActualMaximum(Calendar.DATE); return day - day_of_month + 1; } /** * 获取当前月份的第一天和最后一天 * * @return 第一天和最后一天 */ public static String getFirstDayOfLastDayInMonth() { String firstday, lastday; Calendar aCalendar = Calendar.getInstance(Locale.CHINA); aCalendar.add(Calendar.MONTH, 0); aCalendar.set(Calendar.DAY_OF_MONTH, 1); Calendar aCalendar1 = Calendar.getInstance(Locale.CHINA); aCalendar1.add(Calendar.MONTH, 1); aCalendar1.set(Calendar.DAY_OF_MONTH, 0); firstday = formatDateTime(aCalendar.getTime(), YYYY_MM_DD); lastday = formatDateTime(aCalendar1.getTime(), MM_DD); return firstday + "-" + lastday; } /** * 根据年月获取第一天和最后一天 */ public static String getFirstDayOfLastDayInMonth(int year, int month) { String firstday, lastday; Calendar aCalendar1 = Calendar.getInstance(Locale.CHINA); aCalendar1.set(Calendar.YEAR, year); aCalendar1.set(Calendar.MONTH, month - 1); aCalendar1.set(Calendar.DAY_OF_MONTH, aCalendar1.getMinimum(Calendar.DATE)); Calendar aCalendar = Calendar.getInstance(Locale.CHINA); aCalendar.set(Calendar.YEAR, year); aCalendar.set(Calendar.MONTH, month - 1); aCalendar.set(Calendar.DAY_OF_MONTH, aCalendar.getActualMaximum(Calendar.DATE)); firstday = formatDateTime(aCalendar1.getTime(), YYYY_MM_DD); lastday = formatDateTime(aCalendar.getTime(), MM_DD); return firstday + "-" + lastday; } /** * 将日期格式化成友好的字符串:几分钟前、几小时前、几天前、几月前、几年前、刚刚 * * @param date * @return */ public static String formatFriendly(long date) { if (date == 0) { return null; } long diff = new Date().getTime() - date * 1000; long r = 0; if (diff > year) { r = (diff / year); diff = diff - r * year; long m = 0; if (diff > month) { m = (diff / month); return r + "年" + m + "个月"; } return r + "年"; } if (diff > month) { r = (diff / month); return r + "个月"; } if (diff > day) { r = (diff / day); return r + "天"; } return "刚刚"; } /** * 将日期以yyyy-MM-dd HH:mm:ss格式化 * * @param dateL 日期 * @return */ public static String formatDateTime(long dateL) { SimpleDateFormat sdf = new SimpleDateFormat(DF_YYYY_MM_DD_HH_MM_SS); Date date = new Date(dateL); return sdf.format(date); } /** * 根据毫秒转日期 * * @param dateL * @return */ public static String formatDateByMill(long dateL) { TimeZone timeZone = null; if (StringUtils.isEmpty("GMT+8:00")) { timeZone = TimeZone.getDefault(); } else { timeZone = TimeZone.getTimeZone("GMT+8:00"); } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); df.setTimeZone(timeZone); return df.format(new Date(dateL * 1000)); } /** * 根据毫秒转日期 * * @param dateL * @return */ public static String formatDateByMill(long dateL, String fomate) { TimeZone timeZone = null; if (StringUtils.isEmpty("GMT+8:00")) { timeZone = TimeZone.getDefault(); } else { timeZone = TimeZone.getTimeZone("GMT+8:00"); } SimpleDateFormat df = new SimpleDateFormat(fomate); df.setTimeZone(timeZone); return df.format(new Date(dateL)); } /** * 将日期以yyyy-MM-dd HH:mm:ss格式化 * * @param dateL 日期 * @param formater * @return */ public static String formatDateTime(long dateL, String formater) { TimeZone timeZone = null; if (StringUtils.isEmpty("GMT+8:00")) { timeZone = TimeZone.getDefault(); } else { timeZone = TimeZone.getTimeZone("GMT+8:00"); } SimpleDateFormat sdf = new SimpleDateFormat(formater); sdf.setTimeZone(timeZone); return sdf.format(new Date(dateL)); } /** * 将日期以yyyy-MM-dd HH:mm:ss格式化 * * @param date 日期 * @param formater * @return */ public static String formatDateTime(Date date, String formater) { TimeZone timeZone = null; if (StringUtils.isEmpty("GMT+8:00")) { timeZone = TimeZone.getDefault(); } else { timeZone = TimeZone.getTimeZone("GMT+8:00"); } SimpleDateFormat sdf = new SimpleDateFormat(formater); sdf.setTimeZone(timeZone); return sdf.format(date); } /** * 将日期转为指定格式 * * @param date 日期 * @param formater * @return */ public static String formatTime(long date, String formater) { SimpleDateFormat sdf = new SimpleDateFormat(formater); return sdf.format(date); } /** * 将日期字符串转成日期 * * @param strDate 字符串日期 * @return java.util.date日期类型 */ public static Date parseDate(String strDate) { DateFormat dateFormat = new SimpleDateFormat(DF_YYYY_MM_DD_HH_MM_SS); Date returnDate = null; try { returnDate = dateFormat.parse(strDate); } catch (ParseException e) { Log.v(TAG, "parseDate failed !"); } return returnDate; } /** * 将日期字符串转成日期 * * @param strDate 字符串日期 * @return java.util.date日期类型 yyyyMMdd */ public static String parseDate1(String strDate) { try { SimpleDateFormat format = new SimpleDateFormat(DF_YYYY_MM_DD); Date date = format.parse(strDate);//有异常要捕获 format = new SimpleDateFormat(DE_YYYY_MM_DD); return format.format(date); } catch (ParseException e) { Log.v(TAG, "parseDate failed !"); } return strDate; } /** * 将日期字符串转成日期 * * @param strDate 字符串日期 * @return java.util.date日期类型 */ public static Date parseDate(String strDate, String format) { DateFormat dateFormat = new SimpleDateFormat(format); Date returnDate = null; try { returnDate = dateFormat.parse(strDate); } catch (ParseException e) { Log.v(TAG, "parseDate failed !"); } return returnDate; } /** * 获取系统当前日期 * * @return */ public static Date gainCurrentDate() { return new Date(); } /** * 获取系统当前日期 * * @return */ public static String gainCurrentDate(String formater) { return formatDateTime(new Date(), formater); } /** * 获取上一天 * * @return */ public static String getLastDate() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); String yesterday = new SimpleDateFormat("MM月dd日").format(cal.getTime()); return yesterday; } /** * 获取下一天 * * @param date * @return */ public static String getNextDate(String date) { return formatDateTime(addDateTime(parseDate(date, DF_YYYY_MM_DD), 24), DF_YYYY_MM_DD); } /** * 获取系统当前月份 * * @return */ public static String gainCurrentMonth() { return formatDateTime(new Date(), YYYYMM); } /** * 获取系统当前年 月 日 * 格式:yyyy.MM.dd * * @return */ public static String gainCurrentMonthforDay() { return formatDateTime(new Date(), YYYY_MM_DD); } /** * 获取系统当前年 月 日 * 格式:yyyy-MM-dd * * @return */ public static String getCurrentMonthforDay() { return formatDateTime(new Date(), DF_YYYY_MM_DD); } /** * 获取系统当前月份(不加年份) * * @return */ public static String gainCurrentMonth1() { return formatDateTime(new Date(), MM); } public static String gainCurrentMonth1(int position) { if (position < 10) { return "0" + position; } return position + ""; } /** * 获取系统当前年份 * * @return */ public static String gainCurrentYear() { return formatDateTime(new Date(), YYYY); } public static String gainCurrentMonth(int position) { String year = formatDateTime(new Date(), YYYY); if (position < 10) { return year + "0" + position; } return year + position; } /** * 获取当前月中一个月的天数 * * @return 一个月的天数 */ public static int getDayToMonth() { Calendar aCalendar = Calendar.getInstance(Locale.CHINA); int day = aCalendar.getActualMaximum(Calendar.DATE); return day; } /** * 获取上一月份日期 * * @param date * @return */ public static String getLastMonth(String date) { String year = date.substring(0, 4); String month = date.substring(4); if ("01".equals(month)) { return (Integer.parseInt(year) - 1) + "12"; } if ("10".equals(month)) { return year + "09"; } if ("11".equals(month)) { return year + "10"; } if ("12".equals(month)) { return year + "11"; } return year + "0" + (Integer.parseInt(month) - 1); } /** * 格式化月份 * * @param month * @return */ public static String formatMonth(int month) { if (month < 10) { return "0" + month; } return month + ""; } /** * 格式化日期 * * @param day * @return */ public static String formatDay(int day) { if (day < 10) { return "0" + day; } return day + ""; } /** * 获取下一月份日期 * * @param date * @return */ public static String getNextMonth(String date) { String year = date.substring(0, 4); String month = date.substring(4); if ("12".equals(month)) { return (Integer.parseInt(year) + 1) + "01"; } if ("09".equals(month)) { return year + "10"; } if ("10".equals(month) || "11".equals(month)) { return year + (Integer.parseInt(month) + 1); } return year + "0" + (Integer.parseInt(month) + 1); } /** * 验证日期是否比当前日期早 * * @param target1 比较时间1 * @param target2 比较时间2 * @return true 则代表target1比target2晚或等于target2,否则比target2早 */ public static boolean compareDate(Date target1, Date target2) { boolean flag = false; try { String target1DateTime = DateTimeUtils.formatDateTime(target1, DF_YYYY_MM_DD_HH_MM_SS); String target2DateTime = DateTimeUtils.formatDateTime(target2, DF_YYYY_MM_DD_HH_MM_SS); if (target1DateTime.compareTo(target2DateTime) <= 0) { flag = true; } } catch (Exception e1) { System.out.println("比较失败,原因:" + e1.getMessage()); } return flag; } /** * 获取当天晚上18点的时间 */ public static Date getSixHour() { Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 18); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); return c.getTime(); } /** * 获取昨日的时间 * * @return */ public static Date gethour() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 8); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); calendar.add(Calendar.DAY_OF_YEAR, -1); return calendar.getTime(); } /** * 对日期进行增加操作 * * @param target 需要进行运算的日期 * @param hour 小时 * @return */ public static Date addDateTime(Date target, double hour) { if (null == target || hour < 0) { return target; } return new Date(target.getTime() + (long) (hour * 60 * 60 * 1000)); } /** * 对日期进行相减操作 * * @param target 需要进行运算的日期 * @param hour 小时 * @return */ public static Date subDateTime(Date target, double hour) { if (null == target || hour < 0) { return target; } return new Date(target.getTime() - (long) (hour * 60 * 60 * 1000)); } /** * 获取合适型两个时间差 * <p>time0和time1格式都为yyyy-MM-dd HH:mm:ss</p> * * @param time0 时间字符串0 * @param time1 时间字符串1 * @param precision 精度 * <p>precision = 0,返回null</p> * <p>precision = 1,返回天</p> * <p>precision = 2,返回天和小时</p> * <p>precision = 3,返回天、小时和分钟</p> * <p>precision = 4,返回天、小时、分钟和秒</p> * <p>precision &gt;= 5,返回天、小时、分钟、秒和毫秒</p> * @return 合适型两个时间差 */ public static String getFitTimeSpan(String time0, String time1, int precision) { return ConvertUtils.millis2FitTimeSpan(Math.abs(string2Millis(time0, DF_YYYY_MM_DD_HH_MM_SS) - string2Millis(time1, DF_YYYY_MM_DD_HH_MM_SS)), precision); } /** * 将时间字符串转为时间戳 * <p>time格式为pattern</p> * * @param time 时间字符串 * @param pattern 时间格式 * @return 毫秒时间戳 */ public static long string2Millis(String time, String pattern) { try { return new SimpleDateFormat(pattern, Locale.getDefault()).parse(time).getTime(); } catch (ParseException e) { e.printStackTrace(); } return -1; } }
UTF-8
Java
21,345
java
DateTimeUtils.java
Java
[ { "context": "ale;\nimport java.util.TimeZone;\n\n/**\n * Created by kristain on 15/12/17.\n */\npublic class DateTimeUtils {\n\n\n ", "end": 285, "score": 0.999489963054657, "start": 277, "tag": "USERNAME", "value": "kristain" } ]
null
[]
package com.haoyigou.hyg.utils; import android.util.Log; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Created by kristain on 15/12/17. */ public class DateTimeUtils { /** * 日期格式:yyyy-MM-dd HH:mm:ss **/ public static final String DF_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; /** * 日期格式:yyyy-MM-dd HH:mm **/ public static final String DF_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm"; /** * 日期格式:yyyy-MM-dd **/ public static final String DF_YYYY_MM_DD = "yyyy-MM-dd"; /** * 日期格式:yyyy-MM-dd **/ public static final String DE_YYYY_MM_DD = "yyyyMMdd"; /** * 日期格式:HH:mm:ss **/ public static final String DF_HH_MM_SS = "HH:mm:ss"; /** * 日期格式:HH:mm **/ public static final String DF_HH_MM = "HH:mm"; /** * 日期格式:yyyy.MM.dd **/ public static final String YYYY_MM_DD = "yyyy.MM.dd"; public static final String YY_MM_DD = "yy.MM.dd"; public static final String MM_DD = "MM.dd"; public static final String YYYYMM = "yyyyMM"; public static final String YYYY_MM_DD_HH_MM = "yyyy.MM.dd HH:mm"; public static final String YYYY = "yyyy"; public static final String MM = "MM"; private final static long minute = 60 * 1000;// 1分钟 private final static long hour = 60 * minute;// 1小时 private final static long day = 24 * hour;// 1天 private final static long month = 31 * day;// 月 private final static long year = 12 * month;// 年 /** * Log输出标识 **/ private static final String TAG = DateTimeUtils.class.getSimpleName(); /** * 将日期格式化成友好的字符串:几分钟前、几小时前、几天前、几月前、几年前、刚刚 * * @param date * @return */ public static String formatFriendly1(long date) { if (date == 0) { return null; } long diff = weeHours(new Date(), 0).getTime() - date * 1000; // long diff = new Date().getTime()- date * 1000; long r = 0; if (diff > day) { r = (diff / day); if (r == 1) { return "昨天"; } if (r == 0) { return "今天"; } } return ""; } /** * 将日期信息转换成今天、明天、后天、星期 * * @param date * @return */ public static String getDateDetail(String date) { Calendar today = Calendar.getInstance(); Calendar target = Calendar.getInstance(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); try { today.setTime(df.parse(df.format(weeHours(new Date(), 0)))); today.set(Calendar.HOUR, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); target.setTime(df.parse(date)); target.set(Calendar.HOUR, 0); target.set(Calendar.MINUTE, 0); target.set(Calendar.SECOND, 0); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } long intervalMilli = target.getTimeInMillis() - today.getTimeInMillis(); int xcts = (int) (intervalMilli / day); if (xcts == 0) { return "今天"; } else if (xcts == 1) { return "明天"; } return ""; } /** * 将日期信息转换成今天、明天、后天、星期 * * @param date * @return */ public static String getDateDetail1(String date) { Calendar today = Calendar.getInstance(); Calendar target = Calendar.getInstance(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); try { today.setTime(df.parse(df.format(weeHours(new Date(), 1)))); today.set(Calendar.HOUR, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); target.setTime(df.parse(date)); target.set(Calendar.HOUR, 0); target.set(Calendar.MINUTE, 0); target.set(Calendar.SECOND, 0); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } long intervalMilli = target.getTimeInMillis() - today.getTimeInMillis(); int xcts = (int) (intervalMilli / day); if (xcts == -1) { return "昨天"; } if (xcts == 0) { return "今天"; } return ""; } /** * 凌晨 * * @param date * @return * @flag 0 返回yyyy-MM-dd 00:00:00日期<br> * 1 返回yyyy-MM-dd 23:59:59日期 */ public static Date weeHours(Date date, int flag) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); //时分秒(毫秒数) long millisecond = hour * 60 * 60 * 1000 + minute * 60 * 1000 + second * 1000; //凌晨00:00:00 cal.setTimeInMillis(cal.getTimeInMillis() - millisecond); if (flag == 0) { return cal.getTime(); } else if (flag == 1) { //凌晨23:59:59 cal.setTimeInMillis(cal.getTimeInMillis() + 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000); } return cal.getTime(); } /** * 2016-6-16转换成2016-6-16 00:00 凌晨 * flag=0 :是 * 将String类型的时间转换成 * * @param str */ public static String WeeDateToStirng(String str, int flag) { Date date = weeHours(parseDate(str, DF_YYYY_MM_DD), flag); return formatDateTime(date, DF_YYYY_MM_DD_HH_MM_SS); } public static void main(String[] str) { System.out.print(getFirstDayOfLastDayInMonth(2016, 2)); } /** * 获取离月底还有几天 * * @return */ public static int getDayOfMonth() { Calendar aCalendar = Calendar.getInstance(Locale.CHINA); int day_of_month = aCalendar.get(Calendar.DAY_OF_MONTH); int day = aCalendar.getActualMaximum(Calendar.DATE); return day - day_of_month + 1; } /** * 获取当前月份的第一天和最后一天 * * @return 第一天和最后一天 */ public static String getFirstDayOfLastDayInMonth() { String firstday, lastday; Calendar aCalendar = Calendar.getInstance(Locale.CHINA); aCalendar.add(Calendar.MONTH, 0); aCalendar.set(Calendar.DAY_OF_MONTH, 1); Calendar aCalendar1 = Calendar.getInstance(Locale.CHINA); aCalendar1.add(Calendar.MONTH, 1); aCalendar1.set(Calendar.DAY_OF_MONTH, 0); firstday = formatDateTime(aCalendar.getTime(), YYYY_MM_DD); lastday = formatDateTime(aCalendar1.getTime(), MM_DD); return firstday + "-" + lastday; } /** * 根据年月获取第一天和最后一天 */ public static String getFirstDayOfLastDayInMonth(int year, int month) { String firstday, lastday; Calendar aCalendar1 = Calendar.getInstance(Locale.CHINA); aCalendar1.set(Calendar.YEAR, year); aCalendar1.set(Calendar.MONTH, month - 1); aCalendar1.set(Calendar.DAY_OF_MONTH, aCalendar1.getMinimum(Calendar.DATE)); Calendar aCalendar = Calendar.getInstance(Locale.CHINA); aCalendar.set(Calendar.YEAR, year); aCalendar.set(Calendar.MONTH, month - 1); aCalendar.set(Calendar.DAY_OF_MONTH, aCalendar.getActualMaximum(Calendar.DATE)); firstday = formatDateTime(aCalendar1.getTime(), YYYY_MM_DD); lastday = formatDateTime(aCalendar.getTime(), MM_DD); return firstday + "-" + lastday; } /** * 将日期格式化成友好的字符串:几分钟前、几小时前、几天前、几月前、几年前、刚刚 * * @param date * @return */ public static String formatFriendly(long date) { if (date == 0) { return null; } long diff = new Date().getTime() - date * 1000; long r = 0; if (diff > year) { r = (diff / year); diff = diff - r * year; long m = 0; if (diff > month) { m = (diff / month); return r + "年" + m + "个月"; } return r + "年"; } if (diff > month) { r = (diff / month); return r + "个月"; } if (diff > day) { r = (diff / day); return r + "天"; } return "刚刚"; } /** * 将日期以yyyy-MM-dd HH:mm:ss格式化 * * @param dateL 日期 * @return */ public static String formatDateTime(long dateL) { SimpleDateFormat sdf = new SimpleDateFormat(DF_YYYY_MM_DD_HH_MM_SS); Date date = new Date(dateL); return sdf.format(date); } /** * 根据毫秒转日期 * * @param dateL * @return */ public static String formatDateByMill(long dateL) { TimeZone timeZone = null; if (StringUtils.isEmpty("GMT+8:00")) { timeZone = TimeZone.getDefault(); } else { timeZone = TimeZone.getTimeZone("GMT+8:00"); } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); df.setTimeZone(timeZone); return df.format(new Date(dateL * 1000)); } /** * 根据毫秒转日期 * * @param dateL * @return */ public static String formatDateByMill(long dateL, String fomate) { TimeZone timeZone = null; if (StringUtils.isEmpty("GMT+8:00")) { timeZone = TimeZone.getDefault(); } else { timeZone = TimeZone.getTimeZone("GMT+8:00"); } SimpleDateFormat df = new SimpleDateFormat(fomate); df.setTimeZone(timeZone); return df.format(new Date(dateL)); } /** * 将日期以yyyy-MM-dd HH:mm:ss格式化 * * @param dateL 日期 * @param formater * @return */ public static String formatDateTime(long dateL, String formater) { TimeZone timeZone = null; if (StringUtils.isEmpty("GMT+8:00")) { timeZone = TimeZone.getDefault(); } else { timeZone = TimeZone.getTimeZone("GMT+8:00"); } SimpleDateFormat sdf = new SimpleDateFormat(formater); sdf.setTimeZone(timeZone); return sdf.format(new Date(dateL)); } /** * 将日期以yyyy-MM-dd HH:mm:ss格式化 * * @param date 日期 * @param formater * @return */ public static String formatDateTime(Date date, String formater) { TimeZone timeZone = null; if (StringUtils.isEmpty("GMT+8:00")) { timeZone = TimeZone.getDefault(); } else { timeZone = TimeZone.getTimeZone("GMT+8:00"); } SimpleDateFormat sdf = new SimpleDateFormat(formater); sdf.setTimeZone(timeZone); return sdf.format(date); } /** * 将日期转为指定格式 * * @param date 日期 * @param formater * @return */ public static String formatTime(long date, String formater) { SimpleDateFormat sdf = new SimpleDateFormat(formater); return sdf.format(date); } /** * 将日期字符串转成日期 * * @param strDate 字符串日期 * @return java.util.date日期类型 */ public static Date parseDate(String strDate) { DateFormat dateFormat = new SimpleDateFormat(DF_YYYY_MM_DD_HH_MM_SS); Date returnDate = null; try { returnDate = dateFormat.parse(strDate); } catch (ParseException e) { Log.v(TAG, "parseDate failed !"); } return returnDate; } /** * 将日期字符串转成日期 * * @param strDate 字符串日期 * @return java.util.date日期类型 yyyyMMdd */ public static String parseDate1(String strDate) { try { SimpleDateFormat format = new SimpleDateFormat(DF_YYYY_MM_DD); Date date = format.parse(strDate);//有异常要捕获 format = new SimpleDateFormat(DE_YYYY_MM_DD); return format.format(date); } catch (ParseException e) { Log.v(TAG, "parseDate failed !"); } return strDate; } /** * 将日期字符串转成日期 * * @param strDate 字符串日期 * @return java.util.date日期类型 */ public static Date parseDate(String strDate, String format) { DateFormat dateFormat = new SimpleDateFormat(format); Date returnDate = null; try { returnDate = dateFormat.parse(strDate); } catch (ParseException e) { Log.v(TAG, "parseDate failed !"); } return returnDate; } /** * 获取系统当前日期 * * @return */ public static Date gainCurrentDate() { return new Date(); } /** * 获取系统当前日期 * * @return */ public static String gainCurrentDate(String formater) { return formatDateTime(new Date(), formater); } /** * 获取上一天 * * @return */ public static String getLastDate() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); String yesterday = new SimpleDateFormat("MM月dd日").format(cal.getTime()); return yesterday; } /** * 获取下一天 * * @param date * @return */ public static String getNextDate(String date) { return formatDateTime(addDateTime(parseDate(date, DF_YYYY_MM_DD), 24), DF_YYYY_MM_DD); } /** * 获取系统当前月份 * * @return */ public static String gainCurrentMonth() { return formatDateTime(new Date(), YYYYMM); } /** * 获取系统当前年 月 日 * 格式:yyyy.MM.dd * * @return */ public static String gainCurrentMonthforDay() { return formatDateTime(new Date(), YYYY_MM_DD); } /** * 获取系统当前年 月 日 * 格式:yyyy-MM-dd * * @return */ public static String getCurrentMonthforDay() { return formatDateTime(new Date(), DF_YYYY_MM_DD); } /** * 获取系统当前月份(不加年份) * * @return */ public static String gainCurrentMonth1() { return formatDateTime(new Date(), MM); } public static String gainCurrentMonth1(int position) { if (position < 10) { return "0" + position; } return position + ""; } /** * 获取系统当前年份 * * @return */ public static String gainCurrentYear() { return formatDateTime(new Date(), YYYY); } public static String gainCurrentMonth(int position) { String year = formatDateTime(new Date(), YYYY); if (position < 10) { return year + "0" + position; } return year + position; } /** * 获取当前月中一个月的天数 * * @return 一个月的天数 */ public static int getDayToMonth() { Calendar aCalendar = Calendar.getInstance(Locale.CHINA); int day = aCalendar.getActualMaximum(Calendar.DATE); return day; } /** * 获取上一月份日期 * * @param date * @return */ public static String getLastMonth(String date) { String year = date.substring(0, 4); String month = date.substring(4); if ("01".equals(month)) { return (Integer.parseInt(year) - 1) + "12"; } if ("10".equals(month)) { return year + "09"; } if ("11".equals(month)) { return year + "10"; } if ("12".equals(month)) { return year + "11"; } return year + "0" + (Integer.parseInt(month) - 1); } /** * 格式化月份 * * @param month * @return */ public static String formatMonth(int month) { if (month < 10) { return "0" + month; } return month + ""; } /** * 格式化日期 * * @param day * @return */ public static String formatDay(int day) { if (day < 10) { return "0" + day; } return day + ""; } /** * 获取下一月份日期 * * @param date * @return */ public static String getNextMonth(String date) { String year = date.substring(0, 4); String month = date.substring(4); if ("12".equals(month)) { return (Integer.parseInt(year) + 1) + "01"; } if ("09".equals(month)) { return year + "10"; } if ("10".equals(month) || "11".equals(month)) { return year + (Integer.parseInt(month) + 1); } return year + "0" + (Integer.parseInt(month) + 1); } /** * 验证日期是否比当前日期早 * * @param target1 比较时间1 * @param target2 比较时间2 * @return true 则代表target1比target2晚或等于target2,否则比target2早 */ public static boolean compareDate(Date target1, Date target2) { boolean flag = false; try { String target1DateTime = DateTimeUtils.formatDateTime(target1, DF_YYYY_MM_DD_HH_MM_SS); String target2DateTime = DateTimeUtils.formatDateTime(target2, DF_YYYY_MM_DD_HH_MM_SS); if (target1DateTime.compareTo(target2DateTime) <= 0) { flag = true; } } catch (Exception e1) { System.out.println("比较失败,原因:" + e1.getMessage()); } return flag; } /** * 获取当天晚上18点的时间 */ public static Date getSixHour() { Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 18); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); return c.getTime(); } /** * 获取昨日的时间 * * @return */ public static Date gethour() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 8); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); calendar.add(Calendar.DAY_OF_YEAR, -1); return calendar.getTime(); } /** * 对日期进行增加操作 * * @param target 需要进行运算的日期 * @param hour 小时 * @return */ public static Date addDateTime(Date target, double hour) { if (null == target || hour < 0) { return target; } return new Date(target.getTime() + (long) (hour * 60 * 60 * 1000)); } /** * 对日期进行相减操作 * * @param target 需要进行运算的日期 * @param hour 小时 * @return */ public static Date subDateTime(Date target, double hour) { if (null == target || hour < 0) { return target; } return new Date(target.getTime() - (long) (hour * 60 * 60 * 1000)); } /** * 获取合适型两个时间差 * <p>time0和time1格式都为yyyy-MM-dd HH:mm:ss</p> * * @param time0 时间字符串0 * @param time1 时间字符串1 * @param precision 精度 * <p>precision = 0,返回null</p> * <p>precision = 1,返回天</p> * <p>precision = 2,返回天和小时</p> * <p>precision = 3,返回天、小时和分钟</p> * <p>precision = 4,返回天、小时、分钟和秒</p> * <p>precision &gt;= 5,返回天、小时、分钟、秒和毫秒</p> * @return 合适型两个时间差 */ public static String getFitTimeSpan(String time0, String time1, int precision) { return ConvertUtils.millis2FitTimeSpan(Math.abs(string2Millis(time0, DF_YYYY_MM_DD_HH_MM_SS) - string2Millis(time1, DF_YYYY_MM_DD_HH_MM_SS)), precision); } /** * 将时间字符串转为时间戳 * <p>time格式为pattern</p> * * @param time 时间字符串 * @param pattern 时间格式 * @return 毫秒时间戳 */ public static long string2Millis(String time, String pattern) { try { return new SimpleDateFormat(pattern, Locale.getDefault()).parse(time).getTime(); } catch (ParseException e) { e.printStackTrace(); } return -1; } }
21,345
0.534622
0.518052
762
25.13517
22.08404
161
false
false
0
0
0
0
0
0
0.418635
false
false
4
3a1bfafd76803e3fa322f1d125c80a16436910c5
25,829,933,350,985
1d23cf8eb29f9e91c087b1fbccc44be19a53df90
/src/org/pmmsc/storagemonitor/task/DumpTask.java
1f47a7808830f72558f79ac120da0e521f9158b5
[]
no_license
pmmsc/storageminitor
https://github.com/pmmsc/storageminitor
987eec5d533536fd283a320e0102c4561d229d04
1ae3d83b3b341e8a639462a326846e5a7aed8a4a
refs/heads/master
2020-06-03T06:13:46.180000
2015-04-15T10:30:59
2015-04-15T10:30:59
33,980,148
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.pmmsc.storagemonitor.task; public class DumpTask extends Task { public DumpTask() { mCommand = "adb shell ls /sdcard/* -aR"; } public void run() { mOutputList.clear(); super.run(); } }
UTF-8
Java
211
java
DumpTask.java
Java
[]
null
[]
package org.pmmsc.storagemonitor.task; public class DumpTask extends Task { public DumpTask() { mCommand = "adb shell ls /sdcard/* -aR"; } public void run() { mOutputList.clear(); super.run(); } }
211
0.663507
0.663507
14
14.071428
15.167937
42
false
false
0
0
0
0
0
0
1
false
false
4
250a44e3b813891f0ccdf4a31da487e6d6eea91f
33,346,126,105,361
84deb6badb68ba3d30ed0fe7fba6f93f33589500
/inject/src/main/java/io/micronaut/inject/beans/visitor/IntrospectedTypeElementVisitor.java
2e5d095e388bdce43dfa98dded1ec3de53c9d797
[ "Apache-2.0" ]
permissive
rongbo-j/micronaut-core
https://github.com/rongbo-j/micronaut-core
eff5ae17914a9a466dc0b062c5869472d0bfd3ae
f7b0f3997c24efb253441073532921c0d0b39764
refs/heads/master
2020-08-01T20:17:47.843000
2019-09-24T16:47:25
2019-09-24T16:47:25
211,102,921
1
0
Apache-2.0
true
2019-09-26T14:01:24
2019-09-26T14:01:23
2019-09-26T13:59:59
2019-09-26T13:52:54
44,238
0
0
0
null
false
false
/* * Copyright 2017-2019 original 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 * * 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 io.micronaut.inject.beans.visitor; import io.micronaut.core.annotation.AnnotationClassValue; import io.micronaut.core.annotation.AnnotationValue; import io.micronaut.core.annotation.Internal; import io.micronaut.core.annotation.Introspected; import io.micronaut.core.util.ArrayUtils; import io.micronaut.core.util.CollectionUtils; import io.micronaut.core.util.StringUtils; import io.micronaut.inject.ast.ClassElement; import io.micronaut.inject.ast.ConstructorElement; import io.micronaut.inject.ast.ParameterElement; import io.micronaut.inject.ast.PropertyElement; import io.micronaut.inject.visitor.TypeElementVisitor; import io.micronaut.inject.visitor.VisitorContext; import io.micronaut.inject.writer.ClassGenerationException; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * A {@link TypeElementVisitor} that visits classes annotated with {@link Introspected} and produces * {@link io.micronaut.core.beans.BeanIntrospectionReference} instances at compilation time. * * @author graemerocher * @since 1.1 */ @Internal public class IntrospectedTypeElementVisitor implements TypeElementVisitor<Introspected, Object> { /** * The position of the visitor. */ public static final int POSITION = -100; private static final String JAVAX_VALIDATION_CONSTRAINT = "javax.validation.Constraint"; private static final AnnotationValue<Introspected.IndexedAnnotation> ANN_CONSTRAINT = AnnotationValue.builder(Introspected.IndexedAnnotation.class) .member("annotation", new AnnotationClassValue<>(JAVAX_VALIDATION_CONSTRAINT)) .build(); private static final String JAVAX_VALIDATION_VALID = "javax.validation.Valid"; private static final AnnotationValue<Introspected.IndexedAnnotation> ANN_VALID = AnnotationValue.builder(Introspected.IndexedAnnotation.class) .member("annotation", new AnnotationClassValue<>(JAVAX_VALIDATION_VALID)) .build(); private Map<String, BeanIntrospectionWriter> writers = new LinkedHashMap<>(10); @Override public int getOrder() { // lower precedence, all others to mutate metadata as necessary return POSITION; } @Override public void visitClass(ClassElement element, VisitorContext context) { final AnnotationValue<Introspected> introspected = element.getAnnotation(Introspected.class); if (introspected != null && !writers.containsKey(element.getName()) && !element.isAbstract()) { final String[] packages = introspected.get("packages", String[].class, StringUtils.EMPTY_STRING_ARRAY); final AnnotationClassValue[] classes = introspected.get("classes", AnnotationClassValue[].class, new AnnotationClassValue[0]); final boolean metadata = introspected.get("annotationMetadata", boolean.class, true); final Set<String> includes = CollectionUtils.setOf(introspected.get("includes", String[].class, StringUtils.EMPTY_STRING_ARRAY)); final Set<String> excludes = CollectionUtils.setOf(introspected.get("excludes", String[].class, StringUtils.EMPTY_STRING_ARRAY)); final Set<String> excludedAnnotations = CollectionUtils.setOf(introspected.get("excludedAnnotations", String[].class, StringUtils.EMPTY_STRING_ARRAY)); final Set<String> includedAnnotations = CollectionUtils.setOf(introspected.get("includedAnnotations", String[].class, StringUtils.EMPTY_STRING_ARRAY)); final Set<AnnotationValue> indexedAnnotations; final Set<AnnotationValue> toIndex = CollectionUtils.setOf(introspected.get("indexed", AnnotationValue[].class, new AnnotationValue[0])); if (CollectionUtils.isEmpty(toIndex)) { indexedAnnotations = CollectionUtils.setOf( ANN_CONSTRAINT, ANN_VALID ); } else { toIndex.addAll( CollectionUtils.setOf( ANN_CONSTRAINT, ANN_VALID ) ); indexedAnnotations = toIndex; } if (ArrayUtils.isNotEmpty(classes)) { AtomicInteger index = new AtomicInteger(0); for (AnnotationClassValue aClass : classes) { final Optional<ClassElement> classElement = context.getClassElement(aClass.getName()); classElement.ifPresent(ce -> { if (!ce.isAbstract() && ce.isPublic()) { final BeanIntrospectionWriter writer = new BeanIntrospectionWriter( element.getName(), index.getAndIncrement(), ce.getName(), metadata ? element.getAnnotationMetadata() : null ); processElement(context, metadata, includes, excludes, excludedAnnotations, indexedAnnotations, ce, writer); } }); } } else if (ArrayUtils.isNotEmpty(packages)) { if (includedAnnotations.isEmpty()) { context.fail("When specifying 'packages' you must also specify 'includedAnnotations' to limit scanning", element); } else { for (String aPackage : packages) { ClassElement[] elements = context.getClassElements(aPackage, includedAnnotations.toArray(new String[0])); int j = 0; for (ClassElement classElement : elements) { if (classElement.isAbstract() || !classElement.isPublic()) { continue; } final BeanIntrospectionWriter writer = new BeanIntrospectionWriter( element.getName(), j++, classElement.getName(), metadata ? element.getAnnotationMetadata() : null ); processElement(context, metadata, includes, excludes, excludedAnnotations, indexedAnnotations, classElement, writer); } } } } else { final BeanIntrospectionWriter writer = new BeanIntrospectionWriter( element.getName(), metadata ? element.getAnnotationMetadata() : null ); processElement(context, metadata, includes, excludes, excludedAnnotations, indexedAnnotations, element, writer); } } } @Override public void finish(VisitorContext visitorContext) { for (BeanIntrospectionWriter writer : writers.values()) { try { writer.accept(visitorContext); } catch (IOException e) { throw new ClassGenerationException("I/O error occurred during class generation: " + e.getMessage(), e); } } } private void processElement(VisitorContext context, boolean metadata, Set<String> includes, Set<String> excludes, Set<String> excludedAnnotations, Set<AnnotationValue> indexedAnnotations, ClassElement ce, BeanIntrospectionWriter writer) { final List<PropertyElement> beanProperties = ce.getBeanProperties(); Optional<ConstructorElement> constructorElement = ce.getPrimaryConstructor(); if (!constructorElement.isPresent()) { context.fail("Introspected types must have a single public constructor", ce); } else { final ConstructorElement constructor = constructorElement.get(); if (Arrays.stream(constructor.getParameters()).anyMatch(p -> p.getType() == null)) { context.fail("Introspected constructor includes unsupported argument types", ce); } else { process(constructor, writer, beanProperties, includes, excludes, excludedAnnotations, indexedAnnotations, metadata); } } } private void process( ConstructorElement constructorElement, BeanIntrospectionWriter writer, List<PropertyElement> beanProperties, Set<String> includes, Set<String> excludes, Set<String> ignored, Set<AnnotationValue> indexedAnnotations, boolean metadata) { final ParameterElement[] parameters = constructorElement.getParameters(); if (ArrayUtils.isNotEmpty(parameters)) { writer.visitConstructorArguments(parameters); } for (PropertyElement beanProperty : beanProperties) { final ClassElement type = beanProperty.getType(); if (type != null) { final String name = beanProperty.getName(); if (!includes.isEmpty() && !includes.contains(name)) { continue; } if (!excludes.isEmpty() && excludes.contains(name)) { continue; } if (!ignored.isEmpty() && ignored.stream().anyMatch(beanProperty::hasAnnotation)) { continue; } writer.visitProperty( type, name, beanProperty.getReadMethod().orElse(null), beanProperty.getWriteMethod().orElse(null), beanProperty.isReadOnly(), metadata ? beanProperty.getAnnotationMetadata() : null, beanProperty.getType().getTypeArguments() ); for (AnnotationValue<?> indexedAnnotation : indexedAnnotations) { indexedAnnotation.get("annotation", String.class).ifPresent(annotationName -> { if (beanProperty.hasStereotype(annotationName)) { writer.indexProperty( new AnnotationValue<>(annotationName), name, indexedAnnotation.get("member", String.class) .flatMap(m -> beanProperty.getValue(annotationName, m, String.class)).orElse(null) ); } }); } } } writers.put(writer.getBeanType().getClassName(), writer); } }
UTF-8
Java
11,322
java
IntrospectedTypeElementVisitor.java
Java
[ { "context": "ence} instances at compilation time.\n *\n * @author graemerocher\n * @since 1.1\n */\n@Internal\npublic class Introspe", "end": 1668, "score": 0.9988614916801453, "start": 1656, "tag": "USERNAME", "value": "graemerocher" } ]
null
[]
/* * Copyright 2017-2019 original 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 * * 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 io.micronaut.inject.beans.visitor; import io.micronaut.core.annotation.AnnotationClassValue; import io.micronaut.core.annotation.AnnotationValue; import io.micronaut.core.annotation.Internal; import io.micronaut.core.annotation.Introspected; import io.micronaut.core.util.ArrayUtils; import io.micronaut.core.util.CollectionUtils; import io.micronaut.core.util.StringUtils; import io.micronaut.inject.ast.ClassElement; import io.micronaut.inject.ast.ConstructorElement; import io.micronaut.inject.ast.ParameterElement; import io.micronaut.inject.ast.PropertyElement; import io.micronaut.inject.visitor.TypeElementVisitor; import io.micronaut.inject.visitor.VisitorContext; import io.micronaut.inject.writer.ClassGenerationException; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * A {@link TypeElementVisitor} that visits classes annotated with {@link Introspected} and produces * {@link io.micronaut.core.beans.BeanIntrospectionReference} instances at compilation time. * * @author graemerocher * @since 1.1 */ @Internal public class IntrospectedTypeElementVisitor implements TypeElementVisitor<Introspected, Object> { /** * The position of the visitor. */ public static final int POSITION = -100; private static final String JAVAX_VALIDATION_CONSTRAINT = "javax.validation.Constraint"; private static final AnnotationValue<Introspected.IndexedAnnotation> ANN_CONSTRAINT = AnnotationValue.builder(Introspected.IndexedAnnotation.class) .member("annotation", new AnnotationClassValue<>(JAVAX_VALIDATION_CONSTRAINT)) .build(); private static final String JAVAX_VALIDATION_VALID = "javax.validation.Valid"; private static final AnnotationValue<Introspected.IndexedAnnotation> ANN_VALID = AnnotationValue.builder(Introspected.IndexedAnnotation.class) .member("annotation", new AnnotationClassValue<>(JAVAX_VALIDATION_VALID)) .build(); private Map<String, BeanIntrospectionWriter> writers = new LinkedHashMap<>(10); @Override public int getOrder() { // lower precedence, all others to mutate metadata as necessary return POSITION; } @Override public void visitClass(ClassElement element, VisitorContext context) { final AnnotationValue<Introspected> introspected = element.getAnnotation(Introspected.class); if (introspected != null && !writers.containsKey(element.getName()) && !element.isAbstract()) { final String[] packages = introspected.get("packages", String[].class, StringUtils.EMPTY_STRING_ARRAY); final AnnotationClassValue[] classes = introspected.get("classes", AnnotationClassValue[].class, new AnnotationClassValue[0]); final boolean metadata = introspected.get("annotationMetadata", boolean.class, true); final Set<String> includes = CollectionUtils.setOf(introspected.get("includes", String[].class, StringUtils.EMPTY_STRING_ARRAY)); final Set<String> excludes = CollectionUtils.setOf(introspected.get("excludes", String[].class, StringUtils.EMPTY_STRING_ARRAY)); final Set<String> excludedAnnotations = CollectionUtils.setOf(introspected.get("excludedAnnotations", String[].class, StringUtils.EMPTY_STRING_ARRAY)); final Set<String> includedAnnotations = CollectionUtils.setOf(introspected.get("includedAnnotations", String[].class, StringUtils.EMPTY_STRING_ARRAY)); final Set<AnnotationValue> indexedAnnotations; final Set<AnnotationValue> toIndex = CollectionUtils.setOf(introspected.get("indexed", AnnotationValue[].class, new AnnotationValue[0])); if (CollectionUtils.isEmpty(toIndex)) { indexedAnnotations = CollectionUtils.setOf( ANN_CONSTRAINT, ANN_VALID ); } else { toIndex.addAll( CollectionUtils.setOf( ANN_CONSTRAINT, ANN_VALID ) ); indexedAnnotations = toIndex; } if (ArrayUtils.isNotEmpty(classes)) { AtomicInteger index = new AtomicInteger(0); for (AnnotationClassValue aClass : classes) { final Optional<ClassElement> classElement = context.getClassElement(aClass.getName()); classElement.ifPresent(ce -> { if (!ce.isAbstract() && ce.isPublic()) { final BeanIntrospectionWriter writer = new BeanIntrospectionWriter( element.getName(), index.getAndIncrement(), ce.getName(), metadata ? element.getAnnotationMetadata() : null ); processElement(context, metadata, includes, excludes, excludedAnnotations, indexedAnnotations, ce, writer); } }); } } else if (ArrayUtils.isNotEmpty(packages)) { if (includedAnnotations.isEmpty()) { context.fail("When specifying 'packages' you must also specify 'includedAnnotations' to limit scanning", element); } else { for (String aPackage : packages) { ClassElement[] elements = context.getClassElements(aPackage, includedAnnotations.toArray(new String[0])); int j = 0; for (ClassElement classElement : elements) { if (classElement.isAbstract() || !classElement.isPublic()) { continue; } final BeanIntrospectionWriter writer = new BeanIntrospectionWriter( element.getName(), j++, classElement.getName(), metadata ? element.getAnnotationMetadata() : null ); processElement(context, metadata, includes, excludes, excludedAnnotations, indexedAnnotations, classElement, writer); } } } } else { final BeanIntrospectionWriter writer = new BeanIntrospectionWriter( element.getName(), metadata ? element.getAnnotationMetadata() : null ); processElement(context, metadata, includes, excludes, excludedAnnotations, indexedAnnotations, element, writer); } } } @Override public void finish(VisitorContext visitorContext) { for (BeanIntrospectionWriter writer : writers.values()) { try { writer.accept(visitorContext); } catch (IOException e) { throw new ClassGenerationException("I/O error occurred during class generation: " + e.getMessage(), e); } } } private void processElement(VisitorContext context, boolean metadata, Set<String> includes, Set<String> excludes, Set<String> excludedAnnotations, Set<AnnotationValue> indexedAnnotations, ClassElement ce, BeanIntrospectionWriter writer) { final List<PropertyElement> beanProperties = ce.getBeanProperties(); Optional<ConstructorElement> constructorElement = ce.getPrimaryConstructor(); if (!constructorElement.isPresent()) { context.fail("Introspected types must have a single public constructor", ce); } else { final ConstructorElement constructor = constructorElement.get(); if (Arrays.stream(constructor.getParameters()).anyMatch(p -> p.getType() == null)) { context.fail("Introspected constructor includes unsupported argument types", ce); } else { process(constructor, writer, beanProperties, includes, excludes, excludedAnnotations, indexedAnnotations, metadata); } } } private void process( ConstructorElement constructorElement, BeanIntrospectionWriter writer, List<PropertyElement> beanProperties, Set<String> includes, Set<String> excludes, Set<String> ignored, Set<AnnotationValue> indexedAnnotations, boolean metadata) { final ParameterElement[] parameters = constructorElement.getParameters(); if (ArrayUtils.isNotEmpty(parameters)) { writer.visitConstructorArguments(parameters); } for (PropertyElement beanProperty : beanProperties) { final ClassElement type = beanProperty.getType(); if (type != null) { final String name = beanProperty.getName(); if (!includes.isEmpty() && !includes.contains(name)) { continue; } if (!excludes.isEmpty() && excludes.contains(name)) { continue; } if (!ignored.isEmpty() && ignored.stream().anyMatch(beanProperty::hasAnnotation)) { continue; } writer.visitProperty( type, name, beanProperty.getReadMethod().orElse(null), beanProperty.getWriteMethod().orElse(null), beanProperty.isReadOnly(), metadata ? beanProperty.getAnnotationMetadata() : null, beanProperty.getType().getTypeArguments() ); for (AnnotationValue<?> indexedAnnotation : indexedAnnotations) { indexedAnnotation.get("annotation", String.class).ifPresent(annotationName -> { if (beanProperty.hasStereotype(annotationName)) { writer.indexProperty( new AnnotationValue<>(annotationName), name, indexedAnnotation.get("member", String.class) .flatMap(m -> beanProperty.getValue(annotationName, m, String.class)).orElse(null) ); } }); } } } writers.put(writer.getBeanType().getClassName(), writer); } }
11,322
0.601837
0.599717
244
45.401638
40.807255
242
false
false
0
0
0
0
0
0
0.688525
false
false
4
a08e15ae7d0c6c4cc6283d2556e42ad2d867eb7d
31,267,361,928,578
3aefe36013d5ee0e4e3484789a5a484ee9bddd90
/src/com/anaadih/locationfinder/adapter/ReceiveRequestAdapter.java
a7b8cd201925093b397bf055e8e12939b5b86cde
[]
no_license
jogindersharma/locationfinder
https://github.com/jogindersharma/locationfinder
09bfa5ed3286ad36123c5a68902188c9f5708652
40ab05ab9212f8a5dab4fce0ff93be8dde17ff2d
refs/heads/master
2020-05-17T22:05:00.925000
2014-08-27T13:50:36
2014-08-27T13:50:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.anaadih.locationfinder.adapter; import java.util.List; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.anaadih.locationfinder.MyNetworkClass; import com.anaadih.locationfinder.R; import com.anaadih.locationfinder.dto.ReceiveRequestDto; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; public class ReceiveRequestAdapter extends BaseAdapter { private Context context ; private List<ReceiveRequestDto> rowItems ; private ImageLoader imageLoader ; private DisplayImageOptions options ; public interface OnViewButtonClickedListener { public void OnAdd(String id); } public ReceiveRequestAdapter(Context context, List<ReceiveRequestDto> rowItems) { super(); this.context = context; this.rowItems = rowItems; imageLoader = ImageLoader.getInstance(); imageLoader.init(ImageLoaderConfiguration.createDefault(context)); options = new DisplayImageOptions.Builder() .displayer(new RoundedBitmapDisplayer((int) 27.5f)) .showStubImage(R.drawable.ic_launcher) //this is the image that will be displayed if download fails .cacheInMemory() .cacheOnDisc() .build(); } @Override public int getCount() { // TODO Auto-generated method stub return rowItems.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return rowItems.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return rowItems.indexOf(getItem(position)); } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder = null; ReceiveRequestDto rowItem = rowItems.get(position); LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = mInflater.inflate(R.layout.receive_request_items, null); holder = new ViewHolder(); holder.tvreceiverequestName = (TextView) convertView.findViewById(R.id.tvreceiverequestName); holder.ivreceiverequestPic = (ImageView) convertView.findViewById(R.id.ivreceiverequestPic); holder.btnreceiverequestadd = (Button) convertView.findViewById(R.id.btnreceiverequestadd); holder.btnreceiverequestblock = (Button) convertView.findViewById(R.id.btnreceiverequestblock); holder.btnreceiverequestreject=(Button)convertView.findViewById(R.id.btnreceiverequestreject); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); holder.friendId = rowItem.getUserId(); holder.tvreceiverequestName.setText(rowItem.getName()); //holder.ivreceiverequestPic.setImageResource(R.drawable.bmw); imageLoader.displayImage(rowItem.getImage(), holder.ivreceiverequestPic, options); final ViewHolder fianlHolder = holder; holder.btnreceiverequestadd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MyNetworkClass.getInstance(context).requestResponse(fianlHolder.friendId, 3); } }); holder.btnreceiverequestreject.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MyNetworkClass.getInstance(context).requestResponse(fianlHolder.friendId, 4); } }); holder.btnreceiverequestblock.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MyNetworkClass.getInstance(context).requestResponse(fianlHolder.friendId, 5); } }); return convertView; } //private view holder class private class ViewHolder { ImageView ivreceiverequestPic ; TextView tvreceiverequestName ; Button btnreceiverequestadd ; Button btnreceiverequestblock; Button btnreceiverequestreject; int friendId; } }
UTF-8
Java
4,502
java
ReceiveRequestAdapter.java
Java
[]
null
[]
package com.anaadih.locationfinder.adapter; import java.util.List; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.anaadih.locationfinder.MyNetworkClass; import com.anaadih.locationfinder.R; import com.anaadih.locationfinder.dto.ReceiveRequestDto; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; public class ReceiveRequestAdapter extends BaseAdapter { private Context context ; private List<ReceiveRequestDto> rowItems ; private ImageLoader imageLoader ; private DisplayImageOptions options ; public interface OnViewButtonClickedListener { public void OnAdd(String id); } public ReceiveRequestAdapter(Context context, List<ReceiveRequestDto> rowItems) { super(); this.context = context; this.rowItems = rowItems; imageLoader = ImageLoader.getInstance(); imageLoader.init(ImageLoaderConfiguration.createDefault(context)); options = new DisplayImageOptions.Builder() .displayer(new RoundedBitmapDisplayer((int) 27.5f)) .showStubImage(R.drawable.ic_launcher) //this is the image that will be displayed if download fails .cacheInMemory() .cacheOnDisc() .build(); } @Override public int getCount() { // TODO Auto-generated method stub return rowItems.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return rowItems.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return rowItems.indexOf(getItem(position)); } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder = null; ReceiveRequestDto rowItem = rowItems.get(position); LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = mInflater.inflate(R.layout.receive_request_items, null); holder = new ViewHolder(); holder.tvreceiverequestName = (TextView) convertView.findViewById(R.id.tvreceiverequestName); holder.ivreceiverequestPic = (ImageView) convertView.findViewById(R.id.ivreceiverequestPic); holder.btnreceiverequestadd = (Button) convertView.findViewById(R.id.btnreceiverequestadd); holder.btnreceiverequestblock = (Button) convertView.findViewById(R.id.btnreceiverequestblock); holder.btnreceiverequestreject=(Button)convertView.findViewById(R.id.btnreceiverequestreject); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); holder.friendId = rowItem.getUserId(); holder.tvreceiverequestName.setText(rowItem.getName()); //holder.ivreceiverequestPic.setImageResource(R.drawable.bmw); imageLoader.displayImage(rowItem.getImage(), holder.ivreceiverequestPic, options); final ViewHolder fianlHolder = holder; holder.btnreceiverequestadd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MyNetworkClass.getInstance(context).requestResponse(fianlHolder.friendId, 3); } }); holder.btnreceiverequestreject.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MyNetworkClass.getInstance(context).requestResponse(fianlHolder.friendId, 4); } }); holder.btnreceiverequestblock.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MyNetworkClass.getInstance(context).requestResponse(fianlHolder.friendId, 5); } }); return convertView; } //private view holder class private class ViewHolder { ImageView ivreceiverequestPic ; TextView tvreceiverequestName ; Button btnreceiverequestadd ; Button btnreceiverequestblock; Button btnreceiverequestreject; int friendId; } }
4,502
0.736339
0.73323
132
33.10606
28.97707
108
false
false
0
0
0
0
0
0
1.833333
false
false
4
7451bf6a6601ad760715035cd114e4678348983c
25,331,717,175,483
c5b34c472a0a4895e228a7680ad269f3d78e71b3
/main/src/main/java/org/objenesis/instantiator/annotations/Typology.java
d5513df2a1cb24cf61d0aa2b8ad3516fea302837
[ "Apache-2.0" ]
permissive
easymock/objenesis
https://github.com/easymock/objenesis
4c0a2cf00f00e193aed1428ce89eac4665a88f3a
288ab48893630e4d7791fdc1dcd5988e5e6f7afb
refs/heads/master
2023-08-31T21:01:43.215000
2023-08-28T02:59:57
2023-08-28T12:23:12
11,453,959
554
109
Apache-2.0
false
2023-09-11T03:07:59
2013-07-16T16:08:53
2023-09-08T20:24:12
2023-09-11T03:07:58
3,746
563
94
10
Java
false
false
/* * Copyright 2006-2023 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 * * 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.objenesis.instantiator.annotations; /** * Possible types of instantiator * @author Henri Tremblay */ public enum Typology { /** * Mark an instantiator used for standard instantiation (not calling a constructor). */ STANDARD, /** * Mark an instantiator used for serialization. */ SERIALIZATION, /** * Mark an instantiator that doesn't behave like a {@link #STANDARD} nor a {@link #SERIALIZATION} (e.g. calls a constructor, fails * all the time, etc.) */ NOT_COMPLIANT, /** * No type specified on the instantiator class */ UNKNOWN }
UTF-8
Java
1,230
java
Typology.java
Java
[ { "context": "\n\n/**\n * Possible types of instantiator\n * @author Henri Tremblay\n */\npublic enum Typology {\n /**\n * Mark an i", "end": 732, "score": 0.9998576045036316, "start": 718, "tag": "NAME", "value": "Henri Tremblay" } ]
null
[]
/* * Copyright 2006-2023 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 * * 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.objenesis.instantiator.annotations; /** * Possible types of instantiator * @author <NAME> */ public enum Typology { /** * Mark an instantiator used for standard instantiation (not calling a constructor). */ STANDARD, /** * Mark an instantiator used for serialization. */ SERIALIZATION, /** * Mark an instantiator that doesn't behave like a {@link #STANDARD} nor a {@link #SERIALIZATION} (e.g. calls a constructor, fails * all the time, etc.) */ NOT_COMPLIANT, /** * No type specified on the instantiator class */ UNKNOWN }
1,222
0.696748
0.686992
43
27.60465
30.743605
133
false
false
0
0
0
0
0
0
0.255814
false
false
4
e52f938958986f7db5ee95372ccab47e4a21698a
5,257,040,019,503
9b6503f148049ff5a340e2dba980359872a6abb1
/tests/src/test/java/org/neo4j/graphalgo/core/utils/container/RelationshipContainerIntegrationTest.java
6afc3a3023ac07388af8e6149380ec5f6eeb271c
[ "Apache-2.0" ]
permissive
tomasonjo/neo4j-graph-algorithms
https://github.com/tomasonjo/neo4j-graph-algorithms
5687dd9efba61b53c9963792435a757dc92bbcbb
69ae9c335334bf2995fc48b9aefd31725b6fa280
refs/heads/3.1
2021-01-20T13:56:50.372000
2017-07-13T20:12:41
2017-07-13T20:12:41
90,540,549
0
1
null
true
2017-05-08T21:57:46
2017-05-07T14:58:58
2017-05-07T14:59:00
2017-05-08T21:57:46
574
0
0
0
Java
null
null
package org.neo4j.graphalgo.core.utils.container; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.neo4j.graphalgo.Neo4JTestCase; import org.neo4j.graphalgo.api.RelationshipConsumer; import org.neo4j.graphalgo.core.sources.LazyIdMapper; import org.neo4j.graphdb.Direction; import org.neo4j.kernel.internal.GraphDatabaseAPI; import static org.mockito.Mockito.*; /** * @author mknblch */ @RunWith(MockitoJUnitRunner.class) public class RelationshipContainerIntegrationTest extends Neo4JTestCase { private static RelationshipContainer container; private static int a, b, c; @Mock private RelationshipConsumer consumer; @BeforeClass public static void buildGraph() { a = newNode(); b = newNode(); c = newNode(); newRelation(a, b); newRelation(a, c); newRelation(b, c); final LazyIdMapper idMapper = new LazyIdMapper(3); container = RelationshipContainer.importer((GraphDatabaseAPI) db) .withIdMapping(idMapper) .withDirection(Direction.OUTGOING) .build(); a = idMapper.toMappedNodeId(a); b = idMapper.toMappedNodeId(b); c = idMapper.toMappedNodeId(c); } @AfterClass public static void tearDown() throws Exception { if (db!=null) db.shutdown(); } @Test public void testV0ForEach() throws Exception { container.forEach(a, consumer); verify(consumer, times(2)).accept(anyInt(), anyInt(), anyLong()); verify(consumer, times(1)).accept(eq(a), eq(b), eq(-1L)); verify(consumer, times(1)).accept(eq(a), eq(c), eq(-1L)); } @Test public void testV1ForEach() throws Exception { container.forEach(b, consumer); verify(consumer, times(1)).accept(anyInt(), anyInt(), anyLong()); verify(consumer, times(1)).accept(eq(b), eq(c), eq(-1L)); } @Test public void testVXForEach() throws Exception { container.forEach(42, consumer); verify(consumer, never()).accept(anyInt(), anyInt(), anyLong()); } }
UTF-8
Java
2,237
java
RelationshipContainerIntegrationTest.java
Java
[ { "context": "port static org.mockito.Mockito.*;\n\n/**\n * @author mknblch\n */\n@RunWith(MockitoJUnitRunner.class)\npublic cla", "end": 536, "score": 0.999603807926178, "start": 529, "tag": "USERNAME", "value": "mknblch" } ]
null
[]
package org.neo4j.graphalgo.core.utils.container; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.neo4j.graphalgo.Neo4JTestCase; import org.neo4j.graphalgo.api.RelationshipConsumer; import org.neo4j.graphalgo.core.sources.LazyIdMapper; import org.neo4j.graphdb.Direction; import org.neo4j.kernel.internal.GraphDatabaseAPI; import static org.mockito.Mockito.*; /** * @author mknblch */ @RunWith(MockitoJUnitRunner.class) public class RelationshipContainerIntegrationTest extends Neo4JTestCase { private static RelationshipContainer container; private static int a, b, c; @Mock private RelationshipConsumer consumer; @BeforeClass public static void buildGraph() { a = newNode(); b = newNode(); c = newNode(); newRelation(a, b); newRelation(a, c); newRelation(b, c); final LazyIdMapper idMapper = new LazyIdMapper(3); container = RelationshipContainer.importer((GraphDatabaseAPI) db) .withIdMapping(idMapper) .withDirection(Direction.OUTGOING) .build(); a = idMapper.toMappedNodeId(a); b = idMapper.toMappedNodeId(b); c = idMapper.toMappedNodeId(c); } @AfterClass public static void tearDown() throws Exception { if (db!=null) db.shutdown(); } @Test public void testV0ForEach() throws Exception { container.forEach(a, consumer); verify(consumer, times(2)).accept(anyInt(), anyInt(), anyLong()); verify(consumer, times(1)).accept(eq(a), eq(b), eq(-1L)); verify(consumer, times(1)).accept(eq(a), eq(c), eq(-1L)); } @Test public void testV1ForEach() throws Exception { container.forEach(b, consumer); verify(consumer, times(1)).accept(anyInt(), anyInt(), anyLong()); verify(consumer, times(1)).accept(eq(b), eq(c), eq(-1L)); } @Test public void testVXForEach() throws Exception { container.forEach(42, consumer); verify(consumer, never()).accept(anyInt(), anyInt(), anyLong()); } }
2,237
0.659365
0.649978
79
27.316456
23.0753
73
false
false
0
0
0
0
0
0
0.797468
false
false
4
7456f679893cbb1cdabbb483074eb24250b6ae72
730,144,475,237
86505462601eae6007bef6c9f0f4eeb9fcdd1e7b
/bin/modules/data-hub-adapter/datahubadapter/testsrc/com/hybris/datahub/core/tasks/ItemImportTaskRunnerUnitTest.java
b72d59dc06d0a4ecf3b138fe35f4e2973d9f944d
[]
no_license
jp-developer0/hybrisTrail
https://github.com/jp-developer0/hybrisTrail
82165c5b91352332a3d471b3414faee47bdb6cee
a0208ffee7fee5b7f83dd982e372276492ae83d4
refs/heads/master
2020-12-03T19:53:58.652000
2020-01-02T18:02:34
2020-01-02T18:02:34
231,430,332
0
4
null
false
2020-08-05T22:46:23
2020-01-02T17:39:15
2020-01-02T19:06:34
2020-08-05T22:46:21
1,073,803
0
1
2
null
false
false
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. * All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package com.hybris.datahub.core.tasks; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.session.SessionService; import de.hybris.platform.task.TaskModel; import de.hybris.platform.task.TaskService; import com.hybris.datahub.core.dto.ItemImportTaskData; import com.hybris.datahub.core.facades.ItemImportFacade; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; @UnitTest @RunWith(MockitoJUnitRunner.class) public class ItemImportTaskRunnerUnitTest { private static final String POOL_NAME = "testpool"; private static final Long PUBLICATION_ID = 1L; private static final String CALLBACK_URL = "http://localhost/callback"; private static final byte[] IMPEX_CONTENT = "INSERT_UPDATE value, value, value".getBytes(); private static final String USER = "user name"; private static final String LANGUAGE = "ja"; private final ItemImportTaskRunner taskRunner = new ItemImportTaskRunner(); @Mock private ItemImportFacade importFacade; @Mock private SessionService sessionService; @Mock private TaskModel taskModel; @Mock private TaskService taskService; @Before public void setup() { final Map<String, Serializable> sessionAttrs = new HashMap<>(); sessionAttrs.put("user", USER); sessionAttrs.put("language", LANGUAGE); final ItemImportTaskData taskData = new ItemImportTaskData(POOL_NAME, PUBLICATION_ID, CALLBACK_URL, IMPEX_CONTENT, sessionAttrs); doReturn(taskData).when(taskModel).getContext(); taskRunner.setImportFacade(importFacade); taskRunner.setSessionService(sessionService); } @Test public void testRunInitializesSessionUserBeforeTheItemImport() throws Exception { final InOrder callSeq = Mockito.inOrder(sessionService, importFacade); taskRunner.run(taskService, taskModel); callSeq.verify(sessionService).setAttribute("user", USER); callSeq.verify(importFacade).importItems((ItemImportTaskData) taskModel.getContext()); } @Test public void testRunInitializesSessionLanguageBeforeTheItemImport() throws Exception { final InOrder callSeq = Mockito.inOrder(sessionService, importFacade); taskRunner.run(taskService, taskModel); callSeq.verify(sessionService).setAttribute("language", LANGUAGE); callSeq.verify(importFacade).importItems((ItemImportTaskData) taskModel.getContext()); } @Test public void testRunClosesSessionAfterTheItemImport() throws Exception { final InOrder callSeq = Mockito.inOrder(sessionService, importFacade); taskRunner.run(taskService, taskModel); callSeq.verify(importFacade).importItems((ItemImportTaskData) taskModel.getContext()); callSeq.verify(sessionService).closeCurrentSession(); } @Test public void testRunHandlesImportItemsException() throws Exception { final IOException ioEx = new IOException(); doThrow(ioEx).when(importFacade).importItems(any(ItemImportTaskData.class)); assertThatThrownBy(() -> taskRunner.run(taskService, taskModel)) .isInstanceOf(RuntimeException.class) .hasCause(ioEx); } }
UTF-8
Java
3,831
java
ItemImportTaskRunnerUnitTest.java
Java
[ { "context": ".getBytes();\n\tprivate static final String USER = \"user name\";\n\tprivate static final String LANGUAGE = \"ja\";\n\n", "end": 1650, "score": 0.9994524121284485, "start": 1641, "tag": "USERNAME", "value": "user name" } ]
null
[]
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. * All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package com.hybris.datahub.core.tasks; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.servicelayer.session.SessionService; import de.hybris.platform.task.TaskModel; import de.hybris.platform.task.TaskService; import com.hybris.datahub.core.dto.ItemImportTaskData; import com.hybris.datahub.core.facades.ItemImportFacade; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; @UnitTest @RunWith(MockitoJUnitRunner.class) public class ItemImportTaskRunnerUnitTest { private static final String POOL_NAME = "testpool"; private static final Long PUBLICATION_ID = 1L; private static final String CALLBACK_URL = "http://localhost/callback"; private static final byte[] IMPEX_CONTENT = "INSERT_UPDATE value, value, value".getBytes(); private static final String USER = "user name"; private static final String LANGUAGE = "ja"; private final ItemImportTaskRunner taskRunner = new ItemImportTaskRunner(); @Mock private ItemImportFacade importFacade; @Mock private SessionService sessionService; @Mock private TaskModel taskModel; @Mock private TaskService taskService; @Before public void setup() { final Map<String, Serializable> sessionAttrs = new HashMap<>(); sessionAttrs.put("user", USER); sessionAttrs.put("language", LANGUAGE); final ItemImportTaskData taskData = new ItemImportTaskData(POOL_NAME, PUBLICATION_ID, CALLBACK_URL, IMPEX_CONTENT, sessionAttrs); doReturn(taskData).when(taskModel).getContext(); taskRunner.setImportFacade(importFacade); taskRunner.setSessionService(sessionService); } @Test public void testRunInitializesSessionUserBeforeTheItemImport() throws Exception { final InOrder callSeq = Mockito.inOrder(sessionService, importFacade); taskRunner.run(taskService, taskModel); callSeq.verify(sessionService).setAttribute("user", USER); callSeq.verify(importFacade).importItems((ItemImportTaskData) taskModel.getContext()); } @Test public void testRunInitializesSessionLanguageBeforeTheItemImport() throws Exception { final InOrder callSeq = Mockito.inOrder(sessionService, importFacade); taskRunner.run(taskService, taskModel); callSeq.verify(sessionService).setAttribute("language", LANGUAGE); callSeq.verify(importFacade).importItems((ItemImportTaskData) taskModel.getContext()); } @Test public void testRunClosesSessionAfterTheItemImport() throws Exception { final InOrder callSeq = Mockito.inOrder(sessionService, importFacade); taskRunner.run(taskService, taskModel); callSeq.verify(importFacade).importItems((ItemImportTaskData) taskModel.getContext()); callSeq.verify(sessionService).closeCurrentSession(); } @Test public void testRunHandlesImportItemsException() throws Exception { final IOException ioEx = new IOException(); doThrow(ioEx).when(importFacade).importItems(any(ItemImportTaskData.class)); assertThatThrownBy(() -> taskRunner.run(taskService, taskModel)) .isInstanceOf(RuntimeException.class) .hasCause(ioEx); } }
3,831
0.790655
0.78935
120
30.924999
28.37903
97
false
false
0
0
0
0
0
0
1.366667
false
false
4
05203c7e4eb79369be439a6dadd3a07098d21fae
34,445,637,721,004
5349cb35fb6fbbfdc688ff351a109ffb865d164b
/src/sservice/CartDelAction.java
7a402e5d62712be172874ef920bd6636ede9842d
[]
no_license
jaehyun8282/epl
https://github.com/jaehyun8282/epl
3e58cccf59c015ff987e6a713914b22911ce3235
58b72ff669fb57089f023170907a7d3add22ce74
refs/heads/master
2023-01-22T16:33:25.057000
2020-11-21T09:09:15
2020-11-21T09:09:15
314,771,326
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package epl.service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import epl.dao.CartDao; public class CartDelAction implements CommandProcess{ public String requestPro(HttpServletRequest request, HttpServletResponse response) { int cart_id = Integer.parseInt(request.getParameter("cart_id")); String pageNum = request.getParameter("pageNum"); CartDao cdo = CartDao.getInstance(); int result = cdo.delete(cart_id); request.setAttribute("pageNum", pageNum); request.setAttribute("result", result); return "cartDel"; } }
UTF-8
Java
621
java
CartDelAction.java
Java
[]
null
[]
package epl.service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import epl.dao.CartDao; public class CartDelAction implements CommandProcess{ public String requestPro(HttpServletRequest request, HttpServletResponse response) { int cart_id = Integer.parseInt(request.getParameter("cart_id")); String pageNum = request.getParameter("pageNum"); CartDao cdo = CartDao.getInstance(); int result = cdo.delete(cart_id); request.setAttribute("pageNum", pageNum); request.setAttribute("result", result); return "cartDel"; } }
621
0.7343
0.7343
18
32.5
27.560539
85
false
false
0
0
0
0
0
0
1.666667
false
false
4
4335ffee1aac4f0887e32f462caf76beecc36517
11,982,958,799,124
742765e939063533002d39be19ee216dbe7bee8f
/src/main/java/codesquad/domain/Answer.java
67ad24606afdc3f84748b6c9b9ff37a563af266f
[]
no_license
Gunju-Ko/java-qna
https://github.com/Gunju-Ko/java-qna
5435614e520a0901c06ca66cc7887d58c9b36151
07becd74a63111fbec3402fe6ea2f34dd43b9d7e
refs/heads/Gunju-Ko
2021-05-05T09:00:36.662000
2018-12-22T07:16:55
2018-12-22T07:16:55
119,136,524
0
0
null
true
2018-12-22T07:14:49
2018-01-27T05:38:37
2018-11-14T12:34:59
2018-12-22T07:14:48
574
0
0
0
Java
false
null
package codesquad.domain; import codesquad.common.exception.PermissionDeniedException; import codesquad.web.dto.AnswerDto; import lombok.AllArgsConstructor; import lombok.Builder; import support.domain.AbstractEntity; import support.domain.ApiUrlGeneratable; import support.domain.UrlGeneratable; import javax.persistence.Entity; import javax.persistence.ForeignKey; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.validation.constraints.Size; import java.net.URI; import java.time.LocalDateTime; @Builder @AllArgsConstructor @Entity public class Answer extends AbstractEntity implements UrlGeneratable, ApiUrlGeneratable { @ManyToOne @JoinColumn(foreignKey = @ForeignKey(name = "fk_answer_writer")) private User writer; @ManyToOne @JoinColumn(foreignKey = @ForeignKey(name = "fk_answer_to_question")) private Question question; @Size(min = 5) @Lob private String contents; private boolean deleted = false; public Answer() { } @Override public String generateUrl() { return String.format("%s/answers/%d", question.generateUrl(), getId()); } @Override public URI generateApiUri() { String apiUri = "/api" + generateUrl(); return URI.create(apiUri); } public Answer update(Answer updateAnswer) { if (!isOwner(updateAnswer.writer)) { throw new PermissionDeniedException(); } this.contents = updateAnswer.contents; return this; } public DeleteHistory delete(User loginUser) { if (!isOwner(loginUser)) { throw new PermissionDeniedException(); } this.deleted = true; return new DeleteHistory(ContentType.ANSWER, getId(), loginUser, LocalDateTime.now()); } public void checkAuthority(User loginUser) { if (!isOwner(loginUser)) { throw new PermissionDeniedException(); } } public boolean isOwner(User loginUser) { return writer.equals(loginUser); } public void writerBy(User writer) { if (this.writer != null && !this.writer.equals(writer)) { throw new IllegalStateException("Can not change writer"); } this.writer = writer; } public AnswerDto toAnswerDto() { AnswerDto.AnswerDtoBuilder builder = AnswerDto.builder() .id(getId()) .contents(this.contents) .formattedCreateDate(getFormattedCreateDate()) .deleted(this.isDeleted()); if (this.writer != null) { builder.writer(this.writer.toUserDto()); } return builder.build(); } public User getWriter() { return writer; } public Question getQuestion() { return question; } public void setQuestion(Question question) { if (this.question != null && !this.question.equals(question)) { throw new IllegalStateException("This answer already has a question"); } this.question = question; } public String getContents() { return contents; } public boolean isDeleted() { return deleted; } @Override public String toString() { return "Answer [id=" + getId() + ", writer=" + writer + ", contents=" + contents + "]"; } }
UTF-8
Java
3,528
java
Answer.java
Java
[]
null
[]
package codesquad.domain; import codesquad.common.exception.PermissionDeniedException; import codesquad.web.dto.AnswerDto; import lombok.AllArgsConstructor; import lombok.Builder; import support.domain.AbstractEntity; import support.domain.ApiUrlGeneratable; import support.domain.UrlGeneratable; import javax.persistence.Entity; import javax.persistence.ForeignKey; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.validation.constraints.Size; import java.net.URI; import java.time.LocalDateTime; @Builder @AllArgsConstructor @Entity public class Answer extends AbstractEntity implements UrlGeneratable, ApiUrlGeneratable { @ManyToOne @JoinColumn(foreignKey = @ForeignKey(name = "fk_answer_writer")) private User writer; @ManyToOne @JoinColumn(foreignKey = @ForeignKey(name = "fk_answer_to_question")) private Question question; @Size(min = 5) @Lob private String contents; private boolean deleted = false; public Answer() { } @Override public String generateUrl() { return String.format("%s/answers/%d", question.generateUrl(), getId()); } @Override public URI generateApiUri() { String apiUri = "/api" + generateUrl(); return URI.create(apiUri); } public Answer update(Answer updateAnswer) { if (!isOwner(updateAnswer.writer)) { throw new PermissionDeniedException(); } this.contents = updateAnswer.contents; return this; } public DeleteHistory delete(User loginUser) { if (!isOwner(loginUser)) { throw new PermissionDeniedException(); } this.deleted = true; return new DeleteHistory(ContentType.ANSWER, getId(), loginUser, LocalDateTime.now()); } public void checkAuthority(User loginUser) { if (!isOwner(loginUser)) { throw new PermissionDeniedException(); } } public boolean isOwner(User loginUser) { return writer.equals(loginUser); } public void writerBy(User writer) { if (this.writer != null && !this.writer.equals(writer)) { throw new IllegalStateException("Can not change writer"); } this.writer = writer; } public AnswerDto toAnswerDto() { AnswerDto.AnswerDtoBuilder builder = AnswerDto.builder() .id(getId()) .contents(this.contents) .formattedCreateDate(getFormattedCreateDate()) .deleted(this.isDeleted()); if (this.writer != null) { builder.writer(this.writer.toUserDto()); } return builder.build(); } public User getWriter() { return writer; } public Question getQuestion() { return question; } public void setQuestion(Question question) { if (this.question != null && !this.question.equals(question)) { throw new IllegalStateException("This answer already has a question"); } this.question = question; } public String getContents() { return contents; } public boolean isDeleted() { return deleted; } @Override public String toString() { return "Answer [id=" + getId() + ", writer=" + writer + ", contents=" + contents + "]"; } }
3,528
0.616497
0.616213
124
27.451612
24.958143
100
false
false
0
0
0
0
0
0
0.41129
false
false
4
10d3a869667c563ffbb8b235bfbced4b4b3570ca
14,035,953,190,739
20bb37b1e2bf4e76036dac7cd451174beba8675b
/src/com/icloudoor/cloudoor/MsgPagePopupWindow.java
4e83f94bbc072dcc2400c84463c7244b4e73af09
[]
no_license
carollifen/icloudoor_new_package
https://github.com/carollifen/icloudoor_new_package
368faea4b61ca94061407db9a05b36622d765a58
2b828d9e945a10b4d2a6dad2ec3be8e64786a29d
refs/heads/master
2020-05-17T19:11:57.133000
2015-08-31T03:16:18
2015-08-31T03:16:18
37,391,480
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.icloudoor.cloudoor; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.PopupWindow; public class MsgPagePopupWindow extends PopupWindow{ private View mPopupView; public MsgPagePopupWindow(final Activity context, OnClickListener itemsOnClick) { super(context); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mPopupView = inflater.inflate(R.layout.msg_popup_menu, null); this.setContentView(mPopupView); this.setFocusable(true); } }
UTF-8
Java
655
java
MsgPagePopupWindow.java
Java
[]
null
[]
package com.icloudoor.cloudoor; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.PopupWindow; public class MsgPagePopupWindow extends PopupWindow{ private View mPopupView; public MsgPagePopupWindow(final Activity context, OnClickListener itemsOnClick) { super(context); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mPopupView = inflater.inflate(R.layout.msg_popup_menu, null); this.setContentView(mPopupView); this.setFocusable(true); } }
655
0.80916
0.80916
22
28.818182
26.871134
103
false
false
0
0
0
0
0
0
1.454545
false
false
4
326afec088134345ca4c1b5a671daae7e29ac52b
28,939,489,689,590
932eb8f81b77b2a9bda42529798a3c4ffc9bc825
/Chapter5/src/main/java/com/course/testng/paramter/DataProviderTest.java
86e1564b942d6e1a994b3aa94189e50cdaa75208
[]
no_license
sansi0906/AutoTest
https://github.com/sansi0906/AutoTest
bf374868552dce8b78e436629bc166c99a6ae879
840a136412569ba66907ddacde4fb562150ae80c
refs/heads/master
2023-05-07T22:50:02.282000
2020-08-20T13:50:52
2020-08-20T13:50:52
284,739,837
0
0
null
false
2021-06-04T02:49:26
2020-08-03T15:42:38
2020-08-20T13:51:12
2021-06-04T02:49:26
5,686
0
0
1
HTML
false
false
package com.course.testng.paramter; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.lang.reflect.Method; public class DataProviderTest { @Test(dataProvider = "Person") public void getPersonMessage(String name, int age) { System.out.println("name = " + name + ",age =" + age); } @DataProvider(name = "Person") public Object[][] personData() { Object[][] pm = new Object[][]{ {"zhangsan", 14}, {"lisa", 15}, {"wangliu", 18} }; return pm; } @Test(dataProvider = "achievement") public void getGoodStu(String name, int grade) { System.out.println(name + ":" + grade); } @Test(dataProvider = "achievement") public void getBadStu(String name, int grade) { System.out.println(name + ":" + grade); } @DataProvider(name = "achievement") public Object[][] achievement(Method method) { Object[][] ach = null; if (method.getName().equals("getGoodStu")) { ach = new Object[][]{ {"xiaojiu", 96}, {"sanpang", 98} }; } else if (method.getName().equals("getBadStu")) { ach = new Object[][]{ {"sansi", 33} }; } return ach; } }
UTF-8
Java
1,362
java
DataProviderTest.java
Java
[ { "context": "Object[][] pm = new Object[][]{\n {\"zhangsan\", 14},\n {\"lisa\", 15},\n ", "end": 484, "score": 0.9994685649871826, "start": 476, "tag": "NAME", "value": "zhangsan" }, { "context": " {\"zhangsan\", 14},\n {\"lisa\", 15},\n {\"wangliu\", 18}\n };", "end": 514, "score": 0.9995775818824768, "start": 510, "tag": "NAME", "value": "lisa" }, { "context": ",\n {\"lisa\", 15},\n {\"wangliu\", 18}\n };\n return pm;\n }\n\n @T", "end": 547, "score": 0.9994617104530334, "start": 540, "tag": "NAME", "value": "wangliu" }, { "context": " ach = new Object[][]{\n {\"xiaojiu\", 96},\n {\"sanpang\", 98}\n ", "end": 1124, "score": 0.9553171992301941, "start": 1117, "tag": "NAME", "value": "xiaojiu" }, { "context": " {\"xiaojiu\", 96},\n {\"sanpang\", 98}\n };\n } else if (method.ge", "end": 1161, "score": 0.9923766255378723, "start": 1154, "tag": "NAME", "value": "sanpang" }, { "context": " ach = new Object[][]{\n {\"sansi\", 33}\n };\n }\n return ach", "end": 1303, "score": 0.9974870085716248, "start": 1298, "tag": "NAME", "value": "sansi" } ]
null
[]
package com.course.testng.paramter; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.lang.reflect.Method; public class DataProviderTest { @Test(dataProvider = "Person") public void getPersonMessage(String name, int age) { System.out.println("name = " + name + ",age =" + age); } @DataProvider(name = "Person") public Object[][] personData() { Object[][] pm = new Object[][]{ {"zhangsan", 14}, {"lisa", 15}, {"wangliu", 18} }; return pm; } @Test(dataProvider = "achievement") public void getGoodStu(String name, int grade) { System.out.println(name + ":" + grade); } @Test(dataProvider = "achievement") public void getBadStu(String name, int grade) { System.out.println(name + ":" + grade); } @DataProvider(name = "achievement") public Object[][] achievement(Method method) { Object[][] ach = null; if (method.getName().equals("getGoodStu")) { ach = new Object[][]{ {"xiaojiu", 96}, {"sanpang", 98} }; } else if (method.getName().equals("getBadStu")) { ach = new Object[][]{ {"sansi", 33} }; } return ach; } }
1,362
0.526432
0.517621
49
26.816326
18.611685
62
false
false
0
0
0
0
0
0
0.530612
false
false
4
444ab0c5a43df315d658a7df12f0c14e0ce1e23c
29,540,785,082,030
a8a4dd5cf3844881cd0b1996314f17165572551c
/restaurant-microservice/src/main/java/com/serveme/service/service/GeolocationService.java
02e28b35f37e9b721a2c8564b04ff0971df1b0c7
[]
no_license
DaveChains/Served-Microservices
https://github.com/DaveChains/Served-Microservices
8b8eeea206addd68d12d0860f75fcbacd2a55973
6ceab01167ba98cee461f681929eebda7af0d54f
refs/heads/master
2021-08-30T11:27:19.221000
2017-12-17T18:36:51
2017-12-17T18:36:51
114,554,712
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.serveme.service.service; import com.serveme.service.domain.CategoryDomain; import com.serveme.service.domain.DishDomain; import com.serveme.service.domain.RestaurantDomain; /** * Created by Davids-iMac on 26/10/15. */ public interface GeolocationService { Object getLocationByPostcode(String postcode); }
UTF-8
Java
326
java
GeolocationService.java
Java
[ { "context": "ervice.domain.RestaurantDomain;\n\n/**\n * Created by Davids-iMac on 26/10/15.\n */\npublic interface GeolocationServ", "end": 216, "score": 0.9259960651397705, "start": 205, "tag": "USERNAME", "value": "Davids-iMac" } ]
null
[]
package com.serveme.service.service; import com.serveme.service.domain.CategoryDomain; import com.serveme.service.domain.DishDomain; import com.serveme.service.domain.RestaurantDomain; /** * Created by Davids-iMac on 26/10/15. */ public interface GeolocationService { Object getLocationByPostcode(String postcode); }
326
0.794479
0.776074
13
24.076923
21.695309
51
false
false
0
0
0
0
0
0
0.384615
false
false
4
90db5a8404417f36df5079a98114cb9b31951843
29,540,785,083,439
818bfdd16b38028fdecd0edc662fca8e7401d168
/AccountManagementWebApplication/src/com/sapient/web/DeleteAccount.java
579bad975bbbc37e01f9de8a3a210f3f5ddd7ea6
[]
no_license
Akash01010/AccountManagementWebApplication
https://github.com/Akash01010/AccountManagementWebApplication
0a5e85804d5d654e8e1967666b77f384e89e388d
5a698fa5b66172a17040f7e29e3cc26f9eb3b08c
refs/heads/master
2020-07-01T01:56:47.426000
2019-08-07T07:49:36
2019-08-07T07:49:36
201,012,453
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sapient.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sapient.dao.AccountDAO; import com.sapient.dao.AccountDAOImpl; import com.sapient.model.Account; /** * Servlet implementation class DeleteAccount */ @WebServlet("/deleteAccount") public class DeleteAccount extends HttpServlet { private static final long serialVersionUID = 1L; private AccountDAO service=new AccountDAOImpl(); /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); try { System.out.println("Hi i'm deleting an account"); Integer accountNo=Integer.parseInt(request.getParameter("accountNo")); service.deleteAccount(accountNo); out.print("Account deleted Successfully\n"); }catch(Exception e) { response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,e.getMessage()); e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
UTF-8
Java
1,539
java
DeleteAccount.java
Java
[]
null
[]
package com.sapient.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sapient.dao.AccountDAO; import com.sapient.dao.AccountDAOImpl; import com.sapient.model.Account; /** * Servlet implementation class DeleteAccount */ @WebServlet("/deleteAccount") public class DeleteAccount extends HttpServlet { private static final long serialVersionUID = 1L; private AccountDAO service=new AccountDAOImpl(); /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); try { System.out.println("Hi i'm deleting an account"); Integer accountNo=Integer.parseInt(request.getParameter("accountNo")); service.deleteAccount(accountNo); out.print("Account deleted Successfully\n"); }catch(Exception e) { response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,e.getMessage()); e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
1,539
0.786875
0.786225
48
31.0625
29.826168
119
false
false
0
0
0
0
0
0
1.479167
false
false
4
9f44debc0c01f900a98d4a1ad8edafdac03be37d
31,026,843,766,972
d6ba22a8a9dd431921b8af8982edf115e0f84e01
/stroom-core/src/main/java/stroom/core/meta/MetaModule.java
32f1dd0abb103aed3e01e76493b3a92324f6d9d2
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0", "CDDL-1.0", "GPL-1.0-or-later", "LGPL-2.0-or-later", "MPL-1.0", "CC-BY-4.0", "LicenseRef-scancode-public-domain", "EPL-1.0" ]
permissive
gchq/stroom
https://github.com/gchq/stroom
15dc1d4a8527fe7888d060d39e639b48183ff8bd
759370c31d5d441444bca9d59c41c54bc42816f2
refs/heads/master
2023-09-05T01:40:41.773000
2023-09-04T16:40:12
2023-09-04T16:40:12
72,740,687
442
65
Apache-2.0
false
2023-09-14T12:12:28
2016-11-03T11:55:47
2023-09-01T18:33:25
2023-09-14T12:12:27
170,887
410
54
552
Java
false
false
package stroom.core.meta; import stroom.meta.shared.MetaFields; import stroom.suggestions.api.SuggestionsServiceBinder; import com.google.inject.AbstractModule; public class MetaModule extends AbstractModule { @Override protected void configure() { bind(MetaSuggestionsQueryHandler.class).to(MetaSuggestionsQueryHandlerImpl.class); SuggestionsServiceBinder.create(binder()) .bind(MetaFields.STREAM_STORE_TYPE, MetaSuggestionsQueryHandler.class); } }
UTF-8
Java
499
java
MetaModule.java
Java
[]
null
[]
package stroom.core.meta; import stroom.meta.shared.MetaFields; import stroom.suggestions.api.SuggestionsServiceBinder; import com.google.inject.AbstractModule; public class MetaModule extends AbstractModule { @Override protected void configure() { bind(MetaSuggestionsQueryHandler.class).to(MetaSuggestionsQueryHandlerImpl.class); SuggestionsServiceBinder.create(binder()) .bind(MetaFields.STREAM_STORE_TYPE, MetaSuggestionsQueryHandler.class); } }
499
0.763527
0.763527
17
28.352942
29.251328
90
false
false
0
0
0
0
0
0
0.411765
false
false
4
769eaed2e6f8ee558cb727a853cf443ce751166f
25,366,076,907,973
25460be363aea686fcecf563606fafebc7349374
/org.nor.tutorials.generic/src/main/java/org/nor/tutorials/java/generics/l/bridgeMethods/MyNode.java
05c83d0fb54b888f60efff9b8a6f13a99f4a9d07
[]
no_license
MakeADayLikeAYear/org.nor
https://github.com/MakeADayLikeAYear/org.nor
7a2f524f98255c04158b24a79f43087f16b638c2
a76e9d364634e1f80fc03284b0729e74873133d8
refs/heads/master
2023-03-19T03:08:57.147000
2023-03-11T15:08:02
2023-03-11T15:08:02
46,953,239
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.nor.tutorials.java.generics.l.bridgeMethods; public class MyNode extends Node<Integer> { public MyNode(Integer data) { super(data); } public void setData(Integer data) { System.out.println("MyNode.setData"); super.setData(data); } } /** * <pre> * public class MyNode extends Node { * * public MyNode(Integer data) { * super(data); * } * * // Bridge method generated by the compiler * public void setData(Object data) { * setData((Integer) data); * } * * public void setData(Integer data) { * System.out.println("MyNode.setData"); * super.setData(data); * } * } * * </pre> */
UTF-8
Java
696
java
MyNode.java
Java
[]
null
[]
package org.nor.tutorials.java.generics.l.bridgeMethods; public class MyNode extends Node<Integer> { public MyNode(Integer data) { super(data); } public void setData(Integer data) { System.out.println("MyNode.setData"); super.setData(data); } } /** * <pre> * public class MyNode extends Node { * * public MyNode(Integer data) { * super(data); * } * * // Bridge method generated by the compiler * public void setData(Object data) { * setData((Integer) data); * } * * public void setData(Integer data) { * System.out.println("MyNode.setData"); * super.setData(data); * } * } * * </pre> */
696
0.583333
0.583333
33
19.09091
17.394466
56
false
false
0
0
0
0
0
0
0.242424
false
false
4
f808a168508aaafd3b93b89445cc9d38562207d8
15,161,234,580,374
f225c284b0d141b40bacca3ddc87697120a78f30
/java/registry/src/main/java/io/opensaber/registry/model/DBConnectionInfoMgr.java
7c768665e8c90580c6eb71a32ace8582ad54282e
[ "MIT" ]
permissive
indrajra/teacher-registry
https://github.com/indrajra/teacher-registry
7a2386a3c63e89f0f8275ce0e4c6c19e979d8f15
d53c8006c4855ada27cd0bb3f2a336a2e0506fbf
refs/heads/master
2023-01-10T23:06:19.323000
2020-03-26T06:34:33
2020-03-26T06:34:33
241,092,143
1
1
MIT
false
2023-01-07T14:58:56
2020-02-17T11:34:04
2020-04-13T05:15:54
2023-01-07T14:58:55
2,303
0
1
46
Java
false
false
package io.opensaber.registry.model; import io.opensaber.registry.config.validation.ValidDatabaseConfig; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Component("dbConnectionInfoMgr") @ConfigurationProperties(prefix = "database") @Validated @ValidDatabaseConfig public class DBConnectionInfoMgr { /** * The value names the unique property to be used by this registry for * internal identification purposes. */ private String uuidPropertyName; /** * only one type of database provider as the target as of today. */ private String provider; /** * Only one property is allowed. */ private String shardProperty; /** * Each DBConnectionInfo is a shard connection information. */ private List<DBConnectionInfo> connectionInfo = new ArrayList<>(); /** * Instructs which advisor to pick up across each connectionInfo Only one * advisor allowed */ private String shardAdvisorClassName; private Map<String, String> shardLabelIdMap = new HashMap<>(); @PostConstruct public void init() { for (DBConnectionInfo connInfo : connectionInfo) { shardLabelIdMap.putIfAbsent(connInfo.getShardLabel(), connInfo.getShardId()); } } public List<DBConnectionInfo> getConnectionInfo() { return connectionInfo; } /** * To provide a connection info on based of a shard identifier(name) * * @param shardId * @return */ public DBConnectionInfo getDBConnectionInfo(String shardId) { for (DBConnectionInfo con : connectionInfo) { if (con.getShardId().equalsIgnoreCase(shardId)) return con; } return null; } public String getUuidPropertyName() { return uuidPropertyName; } public void setUuidPropertyName(String uuidPropertyName) { this.uuidPropertyName = uuidPropertyName; } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public void setShardProperty(String shardProperty) { this.shardProperty = shardProperty; } public String getShardProperty() { return this.shardProperty; } public void setConnectionInfo(List<DBConnectionInfo> connectionInfo) { this.connectionInfo = connectionInfo; } public String getShardAdvisorClassName() { return shardAdvisorClassName; } public void setShardAdvisorClassName(String shardAdvisorClassName) { this.shardAdvisorClassName = shardAdvisorClassName; } public String getShardId(String shardLabel) { return shardLabelIdMap.getOrDefault(shardLabel, null); } }
UTF-8
Java
2,745
java
DBConnectionInfoMgr.java
Java
[]
null
[]
package io.opensaber.registry.model; import io.opensaber.registry.config.validation.ValidDatabaseConfig; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Component("dbConnectionInfoMgr") @ConfigurationProperties(prefix = "database") @Validated @ValidDatabaseConfig public class DBConnectionInfoMgr { /** * The value names the unique property to be used by this registry for * internal identification purposes. */ private String uuidPropertyName; /** * only one type of database provider as the target as of today. */ private String provider; /** * Only one property is allowed. */ private String shardProperty; /** * Each DBConnectionInfo is a shard connection information. */ private List<DBConnectionInfo> connectionInfo = new ArrayList<>(); /** * Instructs which advisor to pick up across each connectionInfo Only one * advisor allowed */ private String shardAdvisorClassName; private Map<String, String> shardLabelIdMap = new HashMap<>(); @PostConstruct public void init() { for (DBConnectionInfo connInfo : connectionInfo) { shardLabelIdMap.putIfAbsent(connInfo.getShardLabel(), connInfo.getShardId()); } } public List<DBConnectionInfo> getConnectionInfo() { return connectionInfo; } /** * To provide a connection info on based of a shard identifier(name) * * @param shardId * @return */ public DBConnectionInfo getDBConnectionInfo(String shardId) { for (DBConnectionInfo con : connectionInfo) { if (con.getShardId().equalsIgnoreCase(shardId)) return con; } return null; } public String getUuidPropertyName() { return uuidPropertyName; } public void setUuidPropertyName(String uuidPropertyName) { this.uuidPropertyName = uuidPropertyName; } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public void setShardProperty(String shardProperty) { this.shardProperty = shardProperty; } public String getShardProperty() { return this.shardProperty; } public void setConnectionInfo(List<DBConnectionInfo> connectionInfo) { this.connectionInfo = connectionInfo; } public String getShardAdvisorClassName() { return shardAdvisorClassName; } public void setShardAdvisorClassName(String shardAdvisorClassName) { this.shardAdvisorClassName = shardAdvisorClassName; } public String getShardId(String shardLabel) { return shardLabelIdMap.getOrDefault(shardLabel, null); } }
2,745
0.765756
0.765756
111
23.729731
24.011238
80
false
false
0
0
0
0
0
0
1.18018
false
false
4
f7bf83d7716b768838118ad0fc79a4a61d5cf605
11,690,901,010,498
1d995894aa732932a4a6253936e2df20ca268d34
/src/EditMultipleObjects/DocEditor.java
c2edc357fecf25c4c2346a81eebc1eee0bc6b1b0
[ "MIT" ]
permissive
Medical-Devs/Open-GMAO
https://github.com/Medical-Devs/Open-GMAO
9a9f8fc6a902fd473248ec9a16ce3dc617b6db95
60107dde012eb5ef4e9c7245600c3280aad0409d
refs/heads/main
2023-07-30T14:44:08.832000
2021-09-03T17:21:35
2021-09-03T17:21:35
398,729,095
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package EditMultipleObjects; import javax.swing.JFrame; public class DocEditor extends JFrame { private static final long serialVersionUID = -8208268358136576156L; public DocEditor() { sferyx.administration.editors.HTMLEditor hTMLEditor1; hTMLEditor1 = new sferyx.administration.editors.HTMLEditor(); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); hTMLEditor1.setRemovedMenuItems(""); hTMLEditor1.setStatusMessage(""); hTMLEditor1.setTableItemsStatus(false); getContentPane().add(hTMLEditor1, java.awt.BorderLayout.CENTER); pack(); } public static void main(String[] args) { DocEditor z = new DocEditor(); z.setExtendedState(MAXIMIZED_BOTH); z.setBounds(0,0,1920,1080); z.setLocationRelativeTo(null); z.setVisible(true); z.setTitle("Editeur de Documents"); z.setResizable(true); } private void exitForm(java.awt.event.WindowEvent evt) { System.exit(0); } }
UTF-8
Java
1,134
java
DocEditor.java
Java
[]
null
[]
package EditMultipleObjects; import javax.swing.JFrame; public class DocEditor extends JFrame { private static final long serialVersionUID = -8208268358136576156L; public DocEditor() { sferyx.administration.editors.HTMLEditor hTMLEditor1; hTMLEditor1 = new sferyx.administration.editors.HTMLEditor(); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); hTMLEditor1.setRemovedMenuItems(""); hTMLEditor1.setStatusMessage(""); hTMLEditor1.setTableItemsStatus(false); getContentPane().add(hTMLEditor1, java.awt.BorderLayout.CENTER); pack(); } public static void main(String[] args) { DocEditor z = new DocEditor(); z.setExtendedState(MAXIMIZED_BOTH); z.setBounds(0,0,1920,1080); z.setLocationRelativeTo(null); z.setVisible(true); z.setTitle("Editeur de Documents"); z.setResizable(true); } private void exitForm(java.awt.event.WindowEvent evt) { System.exit(0); } }
1,134
0.66843
0.636684
46
23.673914
21.761608
72
false
false
0
0
0
0
0
0
1.173913
false
false
4
0260fe54c788bc49f967b0205c33dbdd75928a82
34,866,544,515,412
82b59048ecb8f3c27dc45a4939fe50d2c3b9f84f
/HazeSvrPersist/src/main/java/com/aurfy/haze/dao/conf/TerminalMfrMapper.java
bb9a3a4d8184bd4bf6e973d7c37627bb18a71edd
[]
no_license
hud125/Payment
https://github.com/hud125/Payment
fe357fd1aa30921a237f8f123090935dfb18174f
066272a7edbbf5b59368b3378618785f75082bd7
refs/heads/master
2021-01-20T00:56:49.345000
2015-04-21T02:25:48
2015-04-21T02:25:48
34,298,613
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aurfy.haze.dao.conf; import org.springframework.stereotype.Component; import com.aurfy.haze.dao.CRUDMapper; import com.aurfy.haze.dao.MapperEntity; import com.aurfy.haze.dao.conf.MapperConstant.AOP_MAPPER; import com.aurfy.haze.entity.TerminalMfrEntity; @Component(AOP_MAPPER.TERMINAL_MANUFACTURER_MAPPER) @MapperEntity(value = TerminalMfrEntity.class, CRUDBeanRequired = true) public interface TerminalMfrMapper extends CRUDMapper { }
UTF-8
Java
466
java
TerminalMfrMapper.java
Java
[]
null
[]
package com.aurfy.haze.dao.conf; import org.springframework.stereotype.Component; import com.aurfy.haze.dao.CRUDMapper; import com.aurfy.haze.dao.MapperEntity; import com.aurfy.haze.dao.conf.MapperConstant.AOP_MAPPER; import com.aurfy.haze.entity.TerminalMfrEntity; @Component(AOP_MAPPER.TERMINAL_MANUFACTURER_MAPPER) @MapperEntity(value = TerminalMfrEntity.class, CRUDBeanRequired = true) public interface TerminalMfrMapper extends CRUDMapper { }
466
0.802575
0.802575
14
31.285715
24.843592
71
false
false
0
0
0
0
0
0
0.5
false
false
4
4f496c999853571b4c2b74a0eb6430f6d9e5e76e
8,272,107,058,291
098c6eb270c5ba2d4170efd82c0e414add71ac0b
/src/model/dao/CommentDAO.java
e78cf0bbd0a3af78f2a0f42e4cfcd76d055c3984
[]
no_license
Group2BTB/VideoManagementFinal
https://github.com/Group2BTB/VideoManagementFinal
157fe737fcb157d455d54c9066abd852694ef336
5df0461bfe51b1b63f98e3f196dec07e166df7bf
refs/heads/master
2020-05-19T09:31:33.085000
2015-09-01T06:51:57
2015-09-01T06:51:57
39,873,846
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import utilities.DBConnection; import utilities.WorkWithDate; import utilities.WorkWithJson; import model.dto.Comment; public class CommentDAO { ResultSet rs = null; WorkWithJson wwj = new WorkWithJson(); WorkWithDate wwd = new WorkWithDate(); public String getAllComment(){ try(Connection con = new DBConnection().getConnection(); Statement stm = con.createStatement()){ rs = stm.executeQuery("select * from \"selectAllComment\";"); //execute the statement and assign to Resultset object return WorkWithJson.convertResultSetIntoJSON(rs).toString(); }catch(Exception ex){ ex.printStackTrace(); return null; } } public boolean insertComment(Comment cm){ /*Create try with resource*/ String str = "insert into tb_comment(description,user_id, video_id) values(?,?,?)"; if(cm.getParent_id() != 0) str = "insert into tb_comment(description, user_id, video_id, parent_id) values(?,?,?,?)"; try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement(str);){ /*To set data to preparedStatement from video's data*/ stm.setString(1, cm.getDescription()); stm.setLong(2, cm.getUserID()); stm.setLong(3, cm.getVideoID()); if(cm.getParent_id() != 0) stm.setLong(4, cm.getParent_id()); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public boolean updateComment(Comment cm){ /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement("update tb_comment set description=?, parent_id=?," + "user_id=?, video_id=? where comment_id=?")){ /*To set data to preparedStatement from video's data*/ stm.setString(1, cm.getDescription()); stm.setLong(2, cm.getParent_id()); stm.setLong(3, cm.getUserID()); stm.setLong(4, cm.getVideoID()); stm.setLong(5, cm.getId()); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public boolean upLike(long id){ /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement("update tb_comment set like = like+1 where comment_id=?")){ stm.setLong(1, id); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public boolean upUnlike(long id){ /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement("update tb_comment set unlike = unlike+1 where comment_id=?")){ stm.setLong(1, id); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public boolean upView(long id){ /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement("update tb_comment set view = 1 where comment_id=?")){ stm.setLong(1, id); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public int countComment() { try(Connection con = new DBConnection().getConnection(); Statement stm = con.createStatement()){ rs = stm.executeQuery("select count(*) from tb_comment where view=0;"); //execute the statement and assign to Resultset object while(rs.next()) return rs.getInt(1); }catch(Exception ex){ ex.printStackTrace(); return 0; } return 0; } public boolean deletComment(int id) { /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement("delete from tb_comment where comment_id=?")){ stm.setLong(1, id); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public String getCommentWithSub(long videoId){ /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); PreparedStatement stm = con.prepareStatement("select * from \"vComment\" where video_id=?");){ stm.setLong(1, videoId); rs = stm.executeQuery(); return WorkWithJson.convertCommentToJson(rs); }catch(Exception ex){ ex.printStackTrace(); return null; } } public static void main(String[] args) { System.out.println(new CommentDAO().getCommentWithSub(29)); } }
UTF-8
Java
5,537
java
CommentDAO.java
Java
[]
null
[]
package model.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import utilities.DBConnection; import utilities.WorkWithDate; import utilities.WorkWithJson; import model.dto.Comment; public class CommentDAO { ResultSet rs = null; WorkWithJson wwj = new WorkWithJson(); WorkWithDate wwd = new WorkWithDate(); public String getAllComment(){ try(Connection con = new DBConnection().getConnection(); Statement stm = con.createStatement()){ rs = stm.executeQuery("select * from \"selectAllComment\";"); //execute the statement and assign to Resultset object return WorkWithJson.convertResultSetIntoJSON(rs).toString(); }catch(Exception ex){ ex.printStackTrace(); return null; } } public boolean insertComment(Comment cm){ /*Create try with resource*/ String str = "insert into tb_comment(description,user_id, video_id) values(?,?,?)"; if(cm.getParent_id() != 0) str = "insert into tb_comment(description, user_id, video_id, parent_id) values(?,?,?,?)"; try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement(str);){ /*To set data to preparedStatement from video's data*/ stm.setString(1, cm.getDescription()); stm.setLong(2, cm.getUserID()); stm.setLong(3, cm.getVideoID()); if(cm.getParent_id() != 0) stm.setLong(4, cm.getParent_id()); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public boolean updateComment(Comment cm){ /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement("update tb_comment set description=?, parent_id=?," + "user_id=?, video_id=? where comment_id=?")){ /*To set data to preparedStatement from video's data*/ stm.setString(1, cm.getDescription()); stm.setLong(2, cm.getParent_id()); stm.setLong(3, cm.getUserID()); stm.setLong(4, cm.getVideoID()); stm.setLong(5, cm.getId()); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public boolean upLike(long id){ /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement("update tb_comment set like = like+1 where comment_id=?")){ stm.setLong(1, id); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public boolean upUnlike(long id){ /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement("update tb_comment set unlike = unlike+1 where comment_id=?")){ stm.setLong(1, id); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public boolean upView(long id){ /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement("update tb_comment set view = 1 where comment_id=?")){ stm.setLong(1, id); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public int countComment() { try(Connection con = new DBConnection().getConnection(); Statement stm = con.createStatement()){ rs = stm.executeQuery("select count(*) from tb_comment where view=0;"); //execute the statement and assign to Resultset object while(rs.next()) return rs.getInt(1); }catch(Exception ex){ ex.printStackTrace(); return 0; } return 0; } public boolean deletComment(int id) { /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); //get connection to database PreparedStatement stm = con.prepareStatement("delete from tb_comment where comment_id=?")){ stm.setLong(1, id); if(stm.executeUpdate()==0) //execute the statement and compare return false; return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } public String getCommentWithSub(long videoId){ /*Create try with resource*/ try(Connection con = new DBConnection().getConnection(); PreparedStatement stm = con.prepareStatement("select * from \"vComment\" where video_id=?");){ stm.setLong(1, videoId); rs = stm.executeQuery(); return WorkWithJson.convertCommentToJson(rs); }catch(Exception ex){ ex.printStackTrace(); return null; } } public static void main(String[] args) { System.out.println(new CommentDAO().getCommentWithSub(29)); } }
5,537
0.644031
0.638432
209
24.492823
27.45821
129
false
false
0
0
0
0
0
0
2.971292
false
false
4
cf3b9786f6ffa9c48ed521c457e2890d5a7d66c1
34,351,148,453,554
062e99cfabc1d6ce2b7ed7abdb43bc5012d33061
/src/main/java/com/example/CsvRead.java
47c81b01602a414bb05421372848c9f9f77e7ef9
[]
no_license
EliasW/GeoLocalization
https://github.com/EliasW/GeoLocalization
0a11b45ead59fd648ae1f63d6d710b0c2b1d82b8
2776d5af0e8834200f33bf16ad511c7b3d227d7b
refs/heads/master
2021-01-22T22:40:08.105000
2017-03-20T11:37:36
2017-03-20T11:37:36
85,570,438
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.example.CustomerService; @Component public class CsvRead { @Autowired CustomerService select = new CustomerService(); BufferedReader importBuffer = null; String line = ""; String cvsSplitBy = ","; public void CsvRead(String filename){ // return null; } }
UTF-8
Java
543
java
CsvRead.java
Java
[]
null
[]
package com.example; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.example.CustomerService; @Component public class CsvRead { @Autowired CustomerService select = new CustomerService(); BufferedReader importBuffer = null; String line = ""; String cvsSplitBy = ","; public void CsvRead(String filename){ // return null; } }
543
0.777164
0.777164
25
20.719999
17.605726
62
false
false
0
0
0
0
0
0
1.16
false
false
4
6b5173f060d8b60ee089afa586cbe9a733703af8
30,442,728,241,164
9c8cfffe5ad76f5975a0eccb2429ebffa5112895
/src/org/yyu/msi/activity/VideoPlayActivity.java
7377ffc5757f045cd98ead2f6e8891d9fea6e7dc
[ "Apache-2.0" ]
permissive
yswheye/OTGFileExplore
https://github.com/yswheye/OTGFileExplore
75c752564e1bafd2fe566e3fffec9700f50670d0
89877afea0d255b88c8c06baff14b769945d074c
refs/heads/master
2020-09-22T10:30:38.208000
2017-07-12T06:49:59
2017-07-12T06:49:59
66,950,196
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * @Project: MobileFileExplorer * @User: Android * @Description: 社区商服项目 * @Author: yan.yu * @Company:http://www.neldtv.org/ * @Date 2014-4-24 下午4:11:34 * @Version V1.0 */ package org.yyu.msi.activity; import org.yyu.msi.R; import org.yyu.msi.entity.Global; import org.yyu.msi.view.PowerImageView; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnPreparedListener; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.MediaController; import android.widget.VideoView; /** * @ClassName: VideoPlayActivity * @Description: TODO * @author yan.yu * @date 2014-4-24 下午4:11:34 */ public class VideoPlayActivity extends Activity implements OnClickListener { private VideoView videoView = null; private PowerImageView ivPlay = null; private Button btnPlay = null; private String fileUrl = null; /** *callbacks */ @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_play); videoView = (VideoView)findViewById(R.id.view_video_play); ivPlay = (PowerImageView)findViewById(R.id.iv_video_play); btnPlay = (Button)findViewById(R.id.btn_video_play); btnPlay.setOnClickListener(this); fileUrl = getIntent().getStringExtra("FILE_DIR"); videoView.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub ivPlay.setVisibility(View.VISIBLE); btnPlay.setVisibility(View.VISIBLE); } }); videoView.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub ivPlay.setVisibility(View.GONE); btnPlay.setVisibility(View.GONE); } }); } /** *callbacks */ @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); Global.imageWorker.openImageWorker(0); Global.imageWorker.loadBitmap(fileUrl, ivPlay); } /** *callbacks */ @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); Global.imageWorker.closeImageWorker(); } private void playVideo(String strPath) { if (strPath != null) { videoView.setVideoURI(Uri.parse(strPath)); videoView.setMediaController(new MediaController(VideoPlayActivity.this)); videoView.requestFocus(); videoView.start(); } } /** *callbacks */ @Override public void onClick(View v) { // TODO Auto-generated method stub if(v == btnPlay) { playVideo(fileUrl); } } /** *callbacks */ @Override protected void onDestroy() { videoView.destroyDrawingCache(); // TODO Auto-generated method stub super.onDestroy(); } }
UTF-8
Java
3,262
java
VideoPlayActivity.java
Java
[ { "context": "User: Android \r\n* @Description: 社区商服项目\r\n* @Author: yan.yu\r\n* @Company:http://www.neldtv.org/\r\n* @Date 2014-", "end": 99, "score": 0.9997978210449219, "start": 93, "tag": "NAME", "value": "yan.yu" }, { "context": "eoPlayActivity \r\n * @Description: TODO\r\n * @author yan.yu \r\n * @date 2014-4-24 下午4:11:34 \r\n */\r\npublic cla", "end": 813, "score": 0.9998345375061035, "start": 807, "tag": "NAME", "value": "yan.yu" } ]
null
[]
/* * @Project: MobileFileExplorer * @User: Android * @Description: 社区商服项目 * @Author: yan.yu * @Company:http://www.neldtv.org/ * @Date 2014-4-24 下午4:11:34 * @Version V1.0 */ package org.yyu.msi.activity; import org.yyu.msi.R; import org.yyu.msi.entity.Global; import org.yyu.msi.view.PowerImageView; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnPreparedListener; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.MediaController; import android.widget.VideoView; /** * @ClassName: VideoPlayActivity * @Description: TODO * @author yan.yu * @date 2014-4-24 下午4:11:34 */ public class VideoPlayActivity extends Activity implements OnClickListener { private VideoView videoView = null; private PowerImageView ivPlay = null; private Button btnPlay = null; private String fileUrl = null; /** *callbacks */ @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_play); videoView = (VideoView)findViewById(R.id.view_video_play); ivPlay = (PowerImageView)findViewById(R.id.iv_video_play); btnPlay = (Button)findViewById(R.id.btn_video_play); btnPlay.setOnClickListener(this); fileUrl = getIntent().getStringExtra("FILE_DIR"); videoView.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub ivPlay.setVisibility(View.VISIBLE); btnPlay.setVisibility(View.VISIBLE); } }); videoView.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub ivPlay.setVisibility(View.GONE); btnPlay.setVisibility(View.GONE); } }); } /** *callbacks */ @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); Global.imageWorker.openImageWorker(0); Global.imageWorker.loadBitmap(fileUrl, ivPlay); } /** *callbacks */ @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); Global.imageWorker.closeImageWorker(); } private void playVideo(String strPath) { if (strPath != null) { videoView.setVideoURI(Uri.parse(strPath)); videoView.setMediaController(new MediaController(VideoPlayActivity.this)); videoView.requestFocus(); videoView.start(); } } /** *callbacks */ @Override public void onClick(View v) { // TODO Auto-generated method stub if(v == btnPlay) { playVideo(fileUrl); } } /** *callbacks */ @Override protected void onDestroy() { videoView.destroyDrawingCache(); // TODO Auto-generated method stub super.onDestroy(); } }
3,262
0.663681
0.655343
148
19.858109
18.694561
85
false
false
0
0
0
0
0
0
1.486486
false
false
4
a82d352a421416f15b06afe211a02dc55e24d422
36,524,401,893,413
5b2d21006ea3021bacbdb8d8f19c472340803131
/planner/src/main/java/edu/planner/models/Curso.java
26bb84f365ca69361110e573b4121a491974d991
[]
no_license
vfsilva1/teachingPlanAPI
https://github.com/vfsilva1/teachingPlanAPI
e9c137e2dbba26c25fa88721a8aab225d2b6d4cf
fcaaeed442bf75c017cc18e496447fe7ef280041
refs/heads/master
2020-05-07T01:19:52.686000
2019-04-07T09:02:43
2019-04-07T09:02:43
180,269,849
0
0
null
true
2019-04-09T02:33:57
2019-04-09T02:33:56
2019-04-09T02:26:12
2019-04-09T02:26:10
100
0
0
0
null
false
false
package edu.planner.models; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; @Entity public class Curso implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column private String nome; // TODO Mapear item que não possue referencia dos dois lados @ManyToMany @JoinTable(name = "COORD_CURSO", joinColumns = @JoinColumn(name = "coordenador"), inverseJoinColumns = @JoinColumn(name = "id") ) private List<Usuario> coordenadores = new ArrayList<Usuario>(); @ManyToMany @JoinTable(name = "CURSO_DISCIPLINA", joinColumns = @JoinColumn(name = "disciplina"), inverseJoinColumns = @JoinColumn(name = "id") ) private List<Disciplina> disciplinas = new ArrayList<Disciplina>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public List<Usuario> getCoordenadores() { return coordenadores; } public void setCoordenadores(List<Usuario> coordenadores) { this.coordenadores = coordenadores; } public List<Disciplina> getDisciplinas() { return disciplinas; } public void setDisciplinas(List<Disciplina> disciplinas) { this.disciplinas = disciplinas; } }
UTF-8
Java
1,678
java
Curso.java
Java
[]
null
[]
package edu.planner.models; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; @Entity public class Curso implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column private String nome; // TODO Mapear item que não possue referencia dos dois lados @ManyToMany @JoinTable(name = "COORD_CURSO", joinColumns = @JoinColumn(name = "coordenador"), inverseJoinColumns = @JoinColumn(name = "id") ) private List<Usuario> coordenadores = new ArrayList<Usuario>(); @ManyToMany @JoinTable(name = "CURSO_DISCIPLINA", joinColumns = @JoinColumn(name = "disciplina"), inverseJoinColumns = @JoinColumn(name = "id") ) private List<Disciplina> disciplinas = new ArrayList<Disciplina>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public List<Usuario> getCoordenadores() { return coordenadores; } public void setCoordenadores(List<Usuario> coordenadores) { this.coordenadores = coordenadores; } public List<Disciplina> getDisciplinas() { return disciplinas; } public void setDisciplinas(List<Disciplina> disciplinas) { this.disciplinas = disciplinas; } }
1,678
0.745379
0.744782
78
20.512821
19.947203
68
false
false
0
0
0
0
0
0
1.141026
false
false
4
93925896f15d5392f3fdbe83d3c123e86b00bb15
34,411,277,997,920
3be985ffe1b436c6c78f33337696f3aee5bfa08d
/src/GUI/mainFrame.java
3ed459825ac8c916ce19c1f4a88f76c3cd63b8cc
[ "Apache-2.0" ]
permissive
tohai/ktxProjects
https://github.com/tohai/ktxProjects
d04d3877729f612b076c746e290b0bd7b8667a5e
e2318ae7811870d66ec9b2f0c7449cac37b2d929
refs/heads/master
2015-08-14T11:55:15.558000
2014-12-25T08:59:04
2014-12-25T08:59:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package GUI; @SuppressWarnings("serial") public class mainFrame extends javax.swing.JFrame { public mainFrame() { super("Quan Li KTX DHBKHN"); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); mPanel = new loginJpanel(mainFrame.this); add(mPanel); pack(); } @SuppressWarnings("unused") private void initComponents() { setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); pack(); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new mainFrame().setVisible(true); } }); } private loginJpanel mPanel; }
UTF-8
Java
1,244
java
mainFrame.java
Java
[ { "context": "e {\n\n \n public mainFrame() {\n super(\"Quan Li KTX DHBKHN\");\n setDefaultCloseOperation(EXIT_O", "end": 152, "score": 0.978834331035614, "start": 141, "tag": "NAME", "value": "Quan Li KTX" } ]
null
[]
package GUI; @SuppressWarnings("serial") public class mainFrame extends javax.swing.JFrame { public mainFrame() { super("<NAME> DHBKHN"); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); mPanel = new loginJpanel(mainFrame.this); add(mPanel); pack(); } @SuppressWarnings("unused") private void initComponents() { setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); pack(); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new mainFrame().setVisible(true); } }); } private loginJpanel mPanel; }
1,239
0.611736
0.605305
46
26.043478
24.176846
87
false
false
0
0
0
0
0
0
0.456522
false
false
4
65a96218e42b4a72863dc8f9519f1b4985d17876
35,141,422,422,014
506afcc7c8db16f89f0ff4e34c3a629e909fb4c9
/offical-network/src/main/java/com/cict/offical/network/controller/RecruitController.java
b7eecdddbc7ab5432fcaeef2f8e2443ffd7c35a7
[]
no_license
Karrys/test-ssh
https://github.com/Karrys/test-ssh
5172c21fad919d6e6c1c80119e98619697a87adc
e0cf42a498474f98bfa3f42876b15ed091844ef1
refs/heads/master
2020-03-30T01:06:17.744000
2018-09-28T00:05:42
2018-09-28T00:05:42
150,559,464
0
0
null
false
2018-09-28T07:08:35
2018-09-27T09:08:07
2018-09-28T00:07:29
2018-09-28T07:08:34
52
0
0
0
Java
false
null
package com.cict.offical.network.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.cict.offical.network.entity.Recruit; import com.cict.offical.network.service.RecruitService; @Controller @RequestMapping(value = "/recruit") public class RecruitController { @Autowired private RecruitService recruitService; @GetMapping(value = "/getAllRecruit") public @ResponseBody List<Recruit> getAllRecruit() { return recruitService.getAllRecruit(); } @PostMapping(value = "/addRecruit") public @ResponseBody Recruit addRecruit(@RequestBody Recruit recruit) { return recruitService.addRecruit(recruit); } @PostMapping(value = "/updateRecruit") public @ResponseBody Recruit updateRecruit(@RequestBody Recruit recruit) { return recruitService.updateRecruit(recruit); } @PostMapping(value = "/deleteRecruit") public @ResponseBody String deleteRecruit(Integer id) { recruitService.deleteRecruit(id); return ""; } }
UTF-8
Java
1,357
java
RecruitController.java
Java
[]
null
[]
package com.cict.offical.network.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.cict.offical.network.entity.Recruit; import com.cict.offical.network.service.RecruitService; @Controller @RequestMapping(value = "/recruit") public class RecruitController { @Autowired private RecruitService recruitService; @GetMapping(value = "/getAllRecruit") public @ResponseBody List<Recruit> getAllRecruit() { return recruitService.getAllRecruit(); } @PostMapping(value = "/addRecruit") public @ResponseBody Recruit addRecruit(@RequestBody Recruit recruit) { return recruitService.addRecruit(recruit); } @PostMapping(value = "/updateRecruit") public @ResponseBody Recruit updateRecruit(@RequestBody Recruit recruit) { return recruitService.updateRecruit(recruit); } @PostMapping(value = "/deleteRecruit") public @ResponseBody String deleteRecruit(Integer id) { recruitService.deleteRecruit(id); return ""; } }
1,357
0.797347
0.797347
44
29.84091
24.538414
75
false
false
0
0
0
0
0
0
1.159091
false
false
4
4f53e997ff0f16a9d3092620dd7ee2d38f4bc3b1
16,810,502,021,239
866aeb3737e24dd27017d1e206129ebbde6e8a4d
/src/Arrays/ThuatToanTK/SearchInt.java
8598653a8da8f750551538f46673dc84d01a2675
[]
no_license
hoanglinh1119/Module2
https://github.com/hoanglinh1119/Module2
958c7b0f2477176e9755256206c043700008d52c
ef820e085fd8f21cbe6238b8c0c69412763b563b
refs/heads/master
2020-11-26T19:37:40.501000
2020-02-20T14:55:50
2020-02-20T14:55:50
229,187,813
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package Arrays.ThuatToanTK; import java.util.Arrays; import java.util.Scanner; public class SearchInt { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("nhap do dai chuoi so cua ban "); int lengthInt=scanner.nextInt(); scanner.nextLine(); int[] arrayList=new int[lengthInt]; for (int i=0;i<arrayList.length;i++){ System.out.println("nhap so thu "+(i+1)+":"); arrayList[i]=scanner.nextInt(); } System.out.println("nhap so ban muon tim : "); int value=scanner.nextInt(); scanner.nextLine(); sortArrays(arrayList); if(binarySearch(0,arrayList.length-1,arrayList,value)){ System.out.println("tim thay"); } else { System.out.println("khong tim thay"); } } public static void sortArrays(int[] arr){ int temp; for (int i=0;i<arr.length;i++){ for (int j=0;j<arr.length;j++){ if(arr[i]<arr[j]){ temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } } public static boolean binarySearch(int low,int hight,int[] arr,int value ){ int mid=(hight+low)/2; if (hight>low){ if(arr[mid]==value){ return true; }else if (value>arr[mid]){ binarySearch(mid+1,hight,arr,value); }else { binarySearch(low,mid-1,arr,value); } } return false; } }
UTF-8
Java
1,579
java
SearchInt.java
Java
[]
null
[]
package Arrays.ThuatToanTK; import java.util.Arrays; import java.util.Scanner; public class SearchInt { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("nhap do dai chuoi so cua ban "); int lengthInt=scanner.nextInt(); scanner.nextLine(); int[] arrayList=new int[lengthInt]; for (int i=0;i<arrayList.length;i++){ System.out.println("nhap so thu "+(i+1)+":"); arrayList[i]=scanner.nextInt(); } System.out.println("nhap so ban muon tim : "); int value=scanner.nextInt(); scanner.nextLine(); sortArrays(arrayList); if(binarySearch(0,arrayList.length-1,arrayList,value)){ System.out.println("tim thay"); } else { System.out.println("khong tim thay"); } } public static void sortArrays(int[] arr){ int temp; for (int i=0;i<arr.length;i++){ for (int j=0;j<arr.length;j++){ if(arr[i]<arr[j]){ temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } } public static boolean binarySearch(int low,int hight,int[] arr,int value ){ int mid=(hight+low)/2; if (hight>low){ if(arr[mid]==value){ return true; }else if (value>arr[mid]){ binarySearch(mid+1,hight,arr,value); }else { binarySearch(low,mid-1,arr,value); } } return false; } }
1,579
0.521216
0.515516
53
28.792454
18.213989
79
false
false
0
0
0
0
0
0
0.811321
false
false
4
bf9a78423258ca87b03e944fa8d1d0a86440ffda
25,537,875,547,794
14bdf78d6b0cf43e1403259f18e4d1efac2d3fff
/app/src/main/java/com/abhijit/mobeng/activity/MainActivity.java
59095038d9fcff11399ab19597b21ed790b77969
[]
no_license
jitNukalapati/mobile-engineering
https://github.com/jitNukalapati/mobile-engineering
ca86fe8585f50c2d604f0c7f7704c699e288bfe8
e4cbb537302e9d814b92266cf585d8a358eab478
refs/heads/master
2020-12-13T20:55:20.330000
2014-04-21T03:52:45
2014-04-21T03:52:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.abhijit.mobeng.activity; import android.annotation.TargetApi; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import com.abhijit.mobeng.R; import com.abhijit.mobeng.adapter.DealsAdapter; import com.abhijit.mobeng.model.Deal; import com.abhijit.mobeng.util.JsonArrayRequest; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.Volley; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; public class MainActivity extends ActionBarActivity { @InjectView(R.id.deals_list_view) ListView vDealsListView; @InjectView(R.id.progress) ProgressBar mProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); setupListView(); dispatchVolleyRequest(getString(R.string.feed_url)); // fetch data } /** * Creates and initiates a volley GET request to retrieve json from the given url, using * {@link com.abhijit.mobeng.util.JsonArrayRequest} * * @param url url to retrieve the json from */ private void dispatchVolleyRequest(String url) { RequestQueue queue = Volley.newRequestQueue(this); JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JsonArray>() { @Override public void onResponse(JsonArray jsonArray) { hideProgressBar(); ArrayAdapter dealsArrayAdapter = (ArrayAdapter) vDealsListView.getAdapter(); dealsArrayAdapter.clear(); List<Deal> deals = new Gson().fromJson(jsonArray, new TypeToken<List<Deal>>() {}.getType()); bindDataToAdapter(dealsArrayAdapter, deals); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { hideProgressBar(); Toast.makeText(MainActivity.this, getString(R.string.error_retrieving_feed), Toast.LENGTH_LONG).show(); } } ); queue.add(jsonObjectRequest); showProgressBar(); } /** * Attaches a {@link com.abhijit.mobeng.adapter.DealsAdapter} and an {@link android.widget.AdapterView.OnItemClickListener} * to {@link #vDealsListView} */ private void setupListView() { vDealsListView.setAdapter(new DealsAdapter(MainActivity.this, R.layout.list_row, new ArrayList<Deal>())); vDealsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Deal deal = (Deal) vDealsListView.getAdapter().getItem(position); if(deal != null) { startBrowserIntent(deal.getHref()); } } }); } /** * Displays the content of the url in a web browser * @param url a String */ private void startBrowserIntent(String url){ Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } /** * Binds the given deals list to the adapter * @param adapter the adapter that will contain the data * @param deals a List */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void bindDataToAdapter(ArrayAdapter adapter, List<Deal> deals){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { adapter.addAll(deals); } else { for(Deal deal : deals) adapter.add(deal); } } private void showProgressBar(){ mProgressBar.setVisibility(View.VISIBLE); } private void hideProgressBar(){ mProgressBar.setVisibility(View.GONE); } }
UTF-8
Java
4,658
java
MainActivity.java
Java
[]
null
[]
package com.abhijit.mobeng.activity; import android.annotation.TargetApi; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import com.abhijit.mobeng.R; import com.abhijit.mobeng.adapter.DealsAdapter; import com.abhijit.mobeng.model.Deal; import com.abhijit.mobeng.util.JsonArrayRequest; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.Volley; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; public class MainActivity extends ActionBarActivity { @InjectView(R.id.deals_list_view) ListView vDealsListView; @InjectView(R.id.progress) ProgressBar mProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); setupListView(); dispatchVolleyRequest(getString(R.string.feed_url)); // fetch data } /** * Creates and initiates a volley GET request to retrieve json from the given url, using * {@link com.abhijit.mobeng.util.JsonArrayRequest} * * @param url url to retrieve the json from */ private void dispatchVolleyRequest(String url) { RequestQueue queue = Volley.newRequestQueue(this); JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JsonArray>() { @Override public void onResponse(JsonArray jsonArray) { hideProgressBar(); ArrayAdapter dealsArrayAdapter = (ArrayAdapter) vDealsListView.getAdapter(); dealsArrayAdapter.clear(); List<Deal> deals = new Gson().fromJson(jsonArray, new TypeToken<List<Deal>>() {}.getType()); bindDataToAdapter(dealsArrayAdapter, deals); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { hideProgressBar(); Toast.makeText(MainActivity.this, getString(R.string.error_retrieving_feed), Toast.LENGTH_LONG).show(); } } ); queue.add(jsonObjectRequest); showProgressBar(); } /** * Attaches a {@link com.abhijit.mobeng.adapter.DealsAdapter} and an {@link android.widget.AdapterView.OnItemClickListener} * to {@link #vDealsListView} */ private void setupListView() { vDealsListView.setAdapter(new DealsAdapter(MainActivity.this, R.layout.list_row, new ArrayList<Deal>())); vDealsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Deal deal = (Deal) vDealsListView.getAdapter().getItem(position); if(deal != null) { startBrowserIntent(deal.getHref()); } } }); } /** * Displays the content of the url in a web browser * @param url a String */ private void startBrowserIntent(String url){ Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } /** * Binds the given deals list to the adapter * @param adapter the adapter that will contain the data * @param deals a List */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void bindDataToAdapter(ArrayAdapter adapter, List<Deal> deals){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { adapter.addAll(deals); } else { for(Deal deal : deals) adapter.add(deal); } } private void showProgressBar(){ mProgressBar.setVisibility(View.VISIBLE); } private void hideProgressBar(){ mProgressBar.setVisibility(View.GONE); } }
4,658
0.639116
0.638901
136
33.25
28.4718
131
false
false
0
0
0
0
0
0
0.522059
false
false
4
5d7b2e37dcf42f1ea8ffdcc03a50cff5bebeeb71
2,396,591,782,134
adc94cfb66104a19893315248db1b5f8e82ded11
/core/algorithm/src/main/java/io/luffy/interview/algorithm/ReceiverScheduler.java
6ba0bc5eff99f3bd91a23e9afda73082a924c972
[]
no_license
Luffytse/JavaInterview
https://github.com/Luffytse/JavaInterview
45f80f5803e54d2482a78b95215db6165da14375
06a2ba28aed7eb49f011e7d9cc83a6d51786b7e1
refs/heads/master
2020-08-03T03:17:19.679000
2019-11-08T18:57:27
2019-11-08T18:57:27
211,608,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2019 Lufei Xie. */ package io.luffy.interview.algorithm; import static java.util.Collections.EMPTY_SET; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class ReceiverScheduler { /** * {userId: List<MessageIdInterval>} will be provided along with a stream of Message Id. {1: [[1, * 4], [7, 10]], 2: [[3, 8], [11, 12]]} user only interested message with Id in the interval. */ private IntervalTreeNode root; public ReceiverScheduler(Map<Integer, List<int[]>> userPreferences) { this.root = buildSegmentTree(userPreferences); } public Set<Integer> getInterestedUsers(int messageId) { IntervalTreeNode node = root; while (node != null) { if (messageId <= node.rightBound && messageId >= node.leftBound) { return node.interestedUsers; } else if (messageId > node.rightBound) { node = node.right; } else { node = node.left; } } return EMPTY_SET; } private IntervalTreeNode buildSegmentTree(Map<Integer, List<int[]>> userPreferences) { for (Map.Entry<Integer, List<int[]>> entry : userPreferences.entrySet()) { Set<Integer> users; for (int[] interval : entry.getValue()) { users = new HashSet<>(); users.add(entry.getKey()); root = insertTo(users, interval[0], interval[1], root); } } return root; } public static class IntervalTreeNode { Set<Integer> interestedUsers; int leftBound; int rightBound; IntervalTreeNode left; IntervalTreeNode right; public IntervalTreeNode(Set<Integer> interestedUsers, int leftBound, int rightBound) { this.interestedUsers = interestedUsers; this.leftBound = leftBound; this.rightBound = rightBound; } public IntervalTreeNode(int user, int leftBound, int rightBound) { this(new HashSet<>(), leftBound, rightBound); this.interestedUsers.add(user); } public IntervalTreeNode insert(Set<Integer> users, int newLeftBound, int newRightBound) { if (newLeftBound > this.rightBound) { return insertTo(users, newLeftBound, newRightBound, this.right); } else if (newRightBound < this.leftBound) { return insertTo(users, newLeftBound, newRightBound, this.left); } if (newLeftBound > this.leftBound) { this.left = insertTo(new HashSet<>(interestedUsers), this.leftBound, newLeftBound - 1, this.left); } else if (newLeftBound < this.leftBound) { this.left = insertTo(users, newLeftBound, this.leftBound - 1, this.left); } if (newRightBound > this.rightBound) { this.right = insertTo(users, this.rightBound + 1, newRightBound, this.right); } else if (newRightBound < this.rightBound) { this.right = insertTo( new HashSet<>(interestedUsers), newRightBound + 1, this.rightBound, this.right); } this.leftBound = Math.max(this.leftBound, newLeftBound); this.rightBound = Math.min(this.rightBound, newRightBound); this.interestedUsers.addAll(users); return this; } } private static IntervalTreeNode insertTo( Set<Integer> users, int newLeftBound, int newRightBound, IntervalTreeNode node) { if (node == null) { return new IntervalTreeNode(users, newLeftBound, newRightBound); } else { return node.insert(users, newLeftBound, newRightBound); } } }
UTF-8
Java
3,461
java
ReceiverScheduler.java
Java
[ { "context": "/*\n * Copyright 2019 Lufei Xie.\n */\npackage io.luffy.interview.algorithm;\n\nimpor", "end": 30, "score": 0.9998124241828918, "start": 21, "tag": "NAME", "value": "Lufei Xie" } ]
null
[]
/* * Copyright 2019 <NAME>. */ package io.luffy.interview.algorithm; import static java.util.Collections.EMPTY_SET; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class ReceiverScheduler { /** * {userId: List<MessageIdInterval>} will be provided along with a stream of Message Id. {1: [[1, * 4], [7, 10]], 2: [[3, 8], [11, 12]]} user only interested message with Id in the interval. */ private IntervalTreeNode root; public ReceiverScheduler(Map<Integer, List<int[]>> userPreferences) { this.root = buildSegmentTree(userPreferences); } public Set<Integer> getInterestedUsers(int messageId) { IntervalTreeNode node = root; while (node != null) { if (messageId <= node.rightBound && messageId >= node.leftBound) { return node.interestedUsers; } else if (messageId > node.rightBound) { node = node.right; } else { node = node.left; } } return EMPTY_SET; } private IntervalTreeNode buildSegmentTree(Map<Integer, List<int[]>> userPreferences) { for (Map.Entry<Integer, List<int[]>> entry : userPreferences.entrySet()) { Set<Integer> users; for (int[] interval : entry.getValue()) { users = new HashSet<>(); users.add(entry.getKey()); root = insertTo(users, interval[0], interval[1], root); } } return root; } public static class IntervalTreeNode { Set<Integer> interestedUsers; int leftBound; int rightBound; IntervalTreeNode left; IntervalTreeNode right; public IntervalTreeNode(Set<Integer> interestedUsers, int leftBound, int rightBound) { this.interestedUsers = interestedUsers; this.leftBound = leftBound; this.rightBound = rightBound; } public IntervalTreeNode(int user, int leftBound, int rightBound) { this(new HashSet<>(), leftBound, rightBound); this.interestedUsers.add(user); } public IntervalTreeNode insert(Set<Integer> users, int newLeftBound, int newRightBound) { if (newLeftBound > this.rightBound) { return insertTo(users, newLeftBound, newRightBound, this.right); } else if (newRightBound < this.leftBound) { return insertTo(users, newLeftBound, newRightBound, this.left); } if (newLeftBound > this.leftBound) { this.left = insertTo(new HashSet<>(interestedUsers), this.leftBound, newLeftBound - 1, this.left); } else if (newLeftBound < this.leftBound) { this.left = insertTo(users, newLeftBound, this.leftBound - 1, this.left); } if (newRightBound > this.rightBound) { this.right = insertTo(users, this.rightBound + 1, newRightBound, this.right); } else if (newRightBound < this.rightBound) { this.right = insertTo( new HashSet<>(interestedUsers), newRightBound + 1, this.rightBound, this.right); } this.leftBound = Math.max(this.leftBound, newLeftBound); this.rightBound = Math.min(this.rightBound, newRightBound); this.interestedUsers.addAll(users); return this; } } private static IntervalTreeNode insertTo( Set<Integer> users, int newLeftBound, int newRightBound, IntervalTreeNode node) { if (node == null) { return new IntervalTreeNode(users, newLeftBound, newRightBound); } else { return node.insert(users, newLeftBound, newRightBound); } } }
3,458
0.659347
0.652702
105
31.961905
28.822916
99
false
false
0
0
0
0
0
0
0.838095
false
false
4
f6031f756b5b9de74cc72567dd8eed4fc8384292
36,850,819,399,877
1a02077df08119d254a617a4dcc00e5ee18ab8f1
/每日一题/src/字符串/Main05.java
b06abce1731ae78912d19f058306043d67d23308
[]
no_license
yolotianer/yolo
https://github.com/yolotianer/yolo
28dd08cca258a752a762e48a10bbc55b7b42b210
6206fb08df5649576f59c11021a2938994193f7d
refs/heads/master
2022-07-08T22:10:28.279000
2020-02-24T13:03:26
2020-02-24T13:03:26
197,178,443
0
0
null
false
2022-06-21T02:36:24
2019-07-16T11:09:21
2020-02-24T13:03:42
2022-06-21T02:36:20
176,131
0
0
2
JavaScript
false
false
package 字符串; import java.util.Scanner; /** * @author yolo * @date 2019/11/15-20:59 * 题目描述 * 描述: * * 输入一个整数,将这个整数以字符串的形式逆序输出 * 程序不考虑负数的情况,若数字含有0,则逆序形式也含有0,如输入为100,则输出为001 * 输入描述: * 输入一个int整数 * * 输出描述: * 将这个整数以字符串的形式逆序输出 * * 示例1 * 复制 * 1516000 * 输出 * 0006151 */ public class Main05 { /*//方法一:利用计算 public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); while (n >0) { System.out.print(n%10); n=n/10; } }*/ //方法二:利用StringBuffer的常用方法reserve //注意:nextLine()的返回值是String类型,而String类型没有reserve // 但同时String又不可以直接强转为StringBuffer,因此需要借助StringBuffer的构造方法StringBuffer(String str) public static void main(String[] args) { Scanner input=new Scanner(System.in); String str=input.nextLine(); StringBuffer s=new StringBuffer(str); System.out.println(s.reverse()); } }
UTF-8
Java
1,263
java
Main05.java
Java
[ { "context": "ge 字符串;\n\nimport java.util.Scanner;\n\n/**\n * @author yolo\n * @date 2019/11/15-20:59\n * 题目描述\n * 描述:\n *\n * 输入", "end": 60, "score": 0.9996764659881592, "start": 56, "tag": "USERNAME", "value": "yolo" } ]
null
[]
package 字符串; import java.util.Scanner; /** * @author yolo * @date 2019/11/15-20:59 * 题目描述 * 描述: * * 输入一个整数,将这个整数以字符串的形式逆序输出 * 程序不考虑负数的情况,若数字含有0,则逆序形式也含有0,如输入为100,则输出为001 * 输入描述: * 输入一个int整数 * * 输出描述: * 将这个整数以字符串的形式逆序输出 * * 示例1 * 复制 * 1516000 * 输出 * 0006151 */ public class Main05 { /*//方法一:利用计算 public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); while (n >0) { System.out.print(n%10); n=n/10; } }*/ //方法二:利用StringBuffer的常用方法reserve //注意:nextLine()的返回值是String类型,而String类型没有reserve // 但同时String又不可以直接强转为StringBuffer,因此需要借助StringBuffer的构造方法StringBuffer(String str) public static void main(String[] args) { Scanner input=new Scanner(System.in); String str=input.nextLine(); StringBuffer s=new StringBuffer(str); System.out.println(s.reverse()); } }
1,263
0.629153
0.584137
44
20.204546
18.801088
89
false
false
0
0
0
0
0
0
0.227273
false
false
4
011d90b4eb6f9cc1701dc101926ed88ac1279846
9,242,769,688,096
04b37cd463d770729ed9950604352f80823ac444
/cloud-stream-rabbitmq-consumer8803/src/main/java/com/test/springcloud/StreamMqMain8803.java
ba2c59368356c1b5d3c95cb8e67c0ac96a5969c9
[]
no_license
SuperLaozhang/springcould-test
https://github.com/SuperLaozhang/springcould-test
a30624d942dcf8dd80051271d4cd0a7f45d2c6c6
597a721323b16e743283fe8227e318fbc41b8dd3
refs/heads/master
2023-03-28T07:37:29.486000
2021-03-30T03:45:22
2021-03-30T03:45:22
347,892,735
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.test.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Company: NanJing xinwang Technology Co.,Ltd * Copyright: 2019 Copyright(C). All rights Reserved * * @Title: com.test.springcloud.StreamMqMain8803 * @Description: * @author: ZhangZiWen * @CreateDate: 2021/3/22 22:41 * <p> * Modification History: * Date Author Discription * 2021/3/22 22:41 ZhangZiWen Create File. */ @SpringBootApplication public class StreamMqMain8803 { public static void main(String[] args) { SpringApplication.run(StreamMqMain8803.class,args); } }
UTF-8
Java
680
java
StreamMqMain8803.java
Java
[ { "context": "loud.StreamMqMain8803\n * @Description:\n * @author: ZhangZiWen\n * @CreateDate: 2021/3/22 22:41\n * <p>\n * Modific", "end": 347, "score": 0.9998784065246582, "start": 337, "tag": "NAME", "value": "ZhangZiWen" }, { "context": " Author Discription\n * 2021/3/22 22:41 ZhangZiWen Create File.\n */\n@SpringBootApplication\npublic", "end": 488, "score": 0.9809077382087708, "start": 478, "tag": "NAME", "value": "ZhangZiWen" } ]
null
[]
package com.test.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Company: NanJing xinwang Technology Co.,Ltd * Copyright: 2019 Copyright(C). All rights Reserved * * @Title: com.test.springcloud.StreamMqMain8803 * @Description: * @author: ZhangZiWen * @CreateDate: 2021/3/22 22:41 * <p> * Modification History: * Date Author Discription * 2021/3/22 22:41 ZhangZiWen Create File. */ @SpringBootApplication public class StreamMqMain8803 { public static void main(String[] args) { SpringApplication.run(StreamMqMain8803.class,args); } }
680
0.722714
0.666667
25
26.120001
21.319138
68
false
false
0
0
0
0
0
0
0.24
false
false
4
3ca5c0de6d5b040d31862dab508d907d41e41ea8
22,222,160,824,816
35f0250ae39097faae73252d98da3c6472282b7a
/src/main/java/com/github/wreulicke/dropwizard/MyConfiguration.java
6bf835e3d72c55d93ad6fdcde6cf20329c4e75a8
[ "MIT" ]
permissive
Wreulicke/dropwizard-sandbox
https://github.com/Wreulicke/dropwizard-sandbox
d27a24ac73320fbf9305ff9bf098cc11820074e1
33a0e6f874c691239f1035ab1f39b7ae2981de1d
refs/heads/master
2021-01-19T11:23:19.613000
2017-12-10T03:08:40
2017-12-10T03:08:40
87,963,488
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.wreulicke.dropwizard; import javax.validation.Valid; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.Configuration; import io.dropwizard.db.DataSourceFactory; public class MyConfiguration extends Configuration { @Valid @NotNull @JsonProperty("database") private DataSourceFactory dataSourceFactory = new DataSourceFactory(); /** * @return the dataSourceFactory */ public DataSourceFactory getDataSourceFactory() { return dataSourceFactory; } /** * @param dataSourceFactory the dataSourceFactory to set */ public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { this.dataSourceFactory = dataSourceFactory; } }
UTF-8
Java
766
java
MyConfiguration.java
Java
[ { "context": "package com.github.wreulicke.dropwizard;\n\nimport javax.validation.Valid;\nimpor", "end": 28, "score": 0.9971851110458374, "start": 19, "tag": "USERNAME", "value": "wreulicke" } ]
null
[]
package com.github.wreulicke.dropwizard; import javax.validation.Valid; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.Configuration; import io.dropwizard.db.DataSourceFactory; public class MyConfiguration extends Configuration { @Valid @NotNull @JsonProperty("database") private DataSourceFactory dataSourceFactory = new DataSourceFactory(); /** * @return the dataSourceFactory */ public DataSourceFactory getDataSourceFactory() { return dataSourceFactory; } /** * @param dataSourceFactory the dataSourceFactory to set */ public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { this.dataSourceFactory = dataSourceFactory; } }
766
0.776762
0.776762
34
21.529411
23.561228
73
false
false
0
0
0
0
0
0
0.264706
false
false
4
93686562ef4a41f0c53b0548918af1bd38868614
33,809,982,574,160
c20824a3be9864662d57f2a2a928c5bc5206c262
/src/com/zenorocha/modulo4/IElementoFolha.java
6e13e83640f07ef118dd5ab0ba9357b3ff6c2bf3
[]
no_license
rickeletro/Estudos-Java
https://github.com/rickeletro/Estudos-Java
e89fd1dec8ed198c46fdad28c39dfc758607fbaf
01a6191297590620c50d8bc9b8ff1357b4a9252e
refs/heads/master
2020-12-25T09:37:36.549000
2011-06-29T21:40:54
2011-06-29T21:40:54
20,357,844
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Módulo 4 * Projeto e Construção de Sistemas * Professor: Alexandre Correa * * Implementado por Zeno Rocha * Em 30/03/2011 * * -------------------------------------------------------------------------------------------- * * Programa Folha de Pagamento - Pessoas e Empresas * * Gere uma nova versão do programa anterior, considerando o seguinte design: As classes * Empregado* implementam uma interface IElementoFolha. A interface IElementoFolha * estende duas interfaces: IPagamento e INome. * A interface IPagamento possui a seguinte operação:getPagamentoLiquido e getRegime. * * • A operação getPagamentoLiquido retorna o pagamento líquido conforme as fórmulas * de cálculo definidas anteriormente. * • A operação getTipo retorna o tipo do elemento para impressão na folha (Horista, Assalariado, Bonificado). * * A interface INome possui a operação getNome. * Modifique também a classe FolhaPagamento de forma que o array não seja mais da * superclasse Empregado, mas sim um array de IElementoFolha, ou seja, de objetos que implementem esta interface. * Uma vez que a nova versão do programa esteja funcionando, agora com interfaces, faça a seguinte extensão: * Crie uma classe Empresa que também implementará a interface IElementoFolha, com * nome, um valor bruto, uma taxa de IR e uma taxa de ISS como descontos. * * O valor líquido de uma empresa é dado pela seguinte fórmula: Valor Bruto * (1 - taxaIR - taxaISS). * A implementação da operação getRegime de empresa deverá retornar o string "Pessoa Jurídica". * * Modifique a classe FolhaPagamento de forma a imprimir uma relação de pagamentos a * serem efetuados, considerando horistas, assalariados, bonificados e empresas. Para tal, * inicialize o vetor de elementos do tipo IElementoFolha definido em FolhaPagamento para * que tenha 3 elementos de cada tipo, ou seja, 3 horistas, 3 assalariados, 3 bonificados e 3 empresas. * */ package com.zenorocha.modulo4; public interface IElementoFolha extends INome, IPagamento { }
UTF-8
Java
2,096
java
IElementoFolha.java
Java
[ { "context": "\n * Projeto e Construção de Sistemas\n * Professor: Alexandre Correa\n * \n * Implementado por Zeno Rocha\n * Em 30/03/20", "end": 81, "score": 0.9998876452445984, "start": 65, "tag": "NAME", "value": "Alexandre Correa" }, { "context": "rofessor: Alexandre Correa\n * \n * Implementado por Zeno Rocha\n * Em 30/03/2011\n * \n * -------------------------", "end": 116, "score": 0.9998993873596191, "start": 106, "tag": "NAME", "value": "Zeno Rocha" } ]
null
[]
/* * Módulo 4 * Projeto e Construção de Sistemas * Professor: <NAME> * * Implementado por <NAME> * Em 30/03/2011 * * -------------------------------------------------------------------------------------------- * * Programa Folha de Pagamento - Pessoas e Empresas * * Gere uma nova versão do programa anterior, considerando o seguinte design: As classes * Empregado* implementam uma interface IElementoFolha. A interface IElementoFolha * estende duas interfaces: IPagamento e INome. * A interface IPagamento possui a seguinte operação:getPagamentoLiquido e getRegime. * * • A operação getPagamentoLiquido retorna o pagamento líquido conforme as fórmulas * de cálculo definidas anteriormente. * • A operação getTipo retorna o tipo do elemento para impressão na folha (Horista, Assalariado, Bonificado). * * A interface INome possui a operação getNome. * Modifique também a classe FolhaPagamento de forma que o array não seja mais da * superclasse Empregado, mas sim um array de IElementoFolha, ou seja, de objetos que implementem esta interface. * Uma vez que a nova versão do programa esteja funcionando, agora com interfaces, faça a seguinte extensão: * Crie uma classe Empresa que também implementará a interface IElementoFolha, com * nome, um valor bruto, uma taxa de IR e uma taxa de ISS como descontos. * * O valor líquido de uma empresa é dado pela seguinte fórmula: Valor Bruto * (1 - taxaIR - taxaISS). * A implementação da operação getRegime de empresa deverá retornar o string "Pessoa Jurídica". * * Modifique a classe FolhaPagamento de forma a imprimir uma relação de pagamentos a * serem efetuados, considerando horistas, assalariados, bonificados e empresas. Para tal, * inicialize o vetor de elementos do tipo IElementoFolha definido em FolhaPagamento para * que tenha 3 elementos de cada tipo, ou seja, 3 horistas, 3 assalariados, 3 bonificados e 3 empresas. * */ package com.zenorocha.modulo4; public interface IElementoFolha extends INome, IPagamento { }
2,082
0.724976
0.717201
43
46.860466
40.767395
114
false
false
0
0
0
0
0
0
1.069767
false
false
4
bf5b1143761c1857185f01fdc899621671ae7a8d
25,761,213,874,356
656f9d64b7eb7ed713022ed600bafc29fe63533c
/myCloud/src/commands/CommandUserinfo.java
15cab6eb96b5a24478e983ac977aa70c3c31375d
[ "MIT" ]
permissive
aachiritoaei/terminal-cloud-simulator
https://github.com/aachiritoaei/terminal-cloud-simulator
e0af0a4e159ebfaacba2ae43820552ba17d28b9f
c0dd2bb5323d54e9ff6db6c12b556175e3ea4df9
refs/heads/master
2021-05-04T10:43:14.345000
2018-09-09T19:39:10
2018-09-09T19:39:10
53,511,718
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package commands; import java.util.StringTokenizer; import repositories.*; import users.*; /* Get info about a user */ public class CommandUserinfo extends AbstractCommand { private String username; /* Set parameters and execute */ public void setParametersAndExecute(String arguments){ if(arguments.contains("-POO")){ // -POO parameter String splitted[] = arguments.split(" "); if(splitted.length == 1){// - only the -POO parameter was given myGUI.addUserinfoPOO(userManager.getCurrentUser()); return; } if(arguments.startsWith("-POO"))//parameter first username = splitted[1]; else username = splitted[0]; //parameter second for(User elem : allUsers){ if(elem.getUsername().equals(username)){ myGUI.addUserinfoPOO(elem); return; } } myGUI.addText("Username not found."); } else { // no POO parameter StringTokenizer str = new StringTokenizer(arguments, " "); if(str.hasMoreTokens()){ username = str.nextToken(); for(User elem : allUsers){ if(elem.getUsername().equals(username)){ myGUI.addText("Username : " + elem.getUsername() + "\nFirstname : " + elem.getFirstName() + "\nLastname : " + elem.getLastName() + "\nCreated : " + elem.getCreationDate() + "\nLast login : " + elem.getLastLogin()); return; } } myGUI.addText("Username not found."); } else { User elem = userManager.getCurrentUser(); myGUI.addText("Username : " + elem.getUsername() + "\nFirstname : " + elem.getFirstName() + "\nLastname : " + elem.getLastName() + "\nCreated : " + elem.getCreationDate() + "\nLast login : " + elem.getLastLogin()); } } } /* Execute */ public void execute(RepositoryClass rep) { rep.accept(this); } public void execute(Directory dir) {} public void execute(File file) {} }
UTF-8
Java
1,871
java
CommandUserinfo.java
Java
[]
null
[]
package commands; import java.util.StringTokenizer; import repositories.*; import users.*; /* Get info about a user */ public class CommandUserinfo extends AbstractCommand { private String username; /* Set parameters and execute */ public void setParametersAndExecute(String arguments){ if(arguments.contains("-POO")){ // -POO parameter String splitted[] = arguments.split(" "); if(splitted.length == 1){// - only the -POO parameter was given myGUI.addUserinfoPOO(userManager.getCurrentUser()); return; } if(arguments.startsWith("-POO"))//parameter first username = splitted[1]; else username = splitted[0]; //parameter second for(User elem : allUsers){ if(elem.getUsername().equals(username)){ myGUI.addUserinfoPOO(elem); return; } } myGUI.addText("Username not found."); } else { // no POO parameter StringTokenizer str = new StringTokenizer(arguments, " "); if(str.hasMoreTokens()){ username = str.nextToken(); for(User elem : allUsers){ if(elem.getUsername().equals(username)){ myGUI.addText("Username : " + elem.getUsername() + "\nFirstname : " + elem.getFirstName() + "\nLastname : " + elem.getLastName() + "\nCreated : " + elem.getCreationDate() + "\nLast login : " + elem.getLastLogin()); return; } } myGUI.addText("Username not found."); } else { User elem = userManager.getCurrentUser(); myGUI.addText("Username : " + elem.getUsername() + "\nFirstname : " + elem.getFirstName() + "\nLastname : " + elem.getLastName() + "\nCreated : " + elem.getCreationDate() + "\nLast login : " + elem.getLastLogin()); } } } /* Execute */ public void execute(RepositoryClass rep) { rep.accept(this); } public void execute(Directory dir) {} public void execute(File file) {} }
1,871
0.636558
0.634955
61
29.672131
19.40823
66
false
false
0
0
0
0
0
0
3.459016
false
false
4
56c1f89215c3ecf9f05018b8f8b27f8a13faefc7
35,631,048,691,189
cc3a159b31cb45cdbbc9f620a4b498b7e1905598
/demo/src/main/java/com/littlejie/demo/modules/base/notification/SimplestNotificationActivity.java
a05880a0e6a88d965172dfdba261cea4ea09bb92
[]
no_license
wuchuntao/AndroidCore
https://github.com/wuchuntao/AndroidCore
a11757744e206059ab566fca20c51238be1b52b6
25a3c1eae7fac17867d9639f1d9947b50177643e
refs/heads/master
2020-03-26T23:13:59.331000
2018-01-05T02:59:12
2018-01-05T02:59:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.littlejie.demo.modules.base.notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v4.app.NotificationCompat; import com.littlejie.core.base.BaseActivity; import com.littlejie.demo.R; import com.littlejie.demo.annotation.Description; import com.littlejie.demo.modules.MainActivity; import butterknife.OnClick; /** * 这是一个最简单的通知例子,该通知只有必要的三个属性: * 小图标、标题、内容 */ @Description(description = "一个最简单的Notification Demo") public class SimplestNotificationActivity extends BaseActivity{ private NotificationManager mNotifyManager; private Bitmap mLargeIcon; @Override protected int getPageLayoutID() { return R.layout.activity_simplest_notification; } @Override protected void initData() { mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mLargeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_fab_repair); } @Override protected void initView() { } @Override protected void initViewListener() { } void sendNotification() { //获取NotificationManager实例 NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); //实例化NotificationCompat.Builde并设置相关属性 NotificationCompat.Builder builder = new NotificationCompat.Builder(this) //设置小图标 .setSmallIcon(R.mipmap.icon_fab_repair) //设置通知标题 .setContentTitle("最简单的Notification") //设置通知内容 .setContentText("只有小图标、标题、内容"); //设置通知时间,默认为系统发出通知的时间,通常不用设置 //.setWhen(System.currentTimeMillis()); //通过builder.build()方法生成Notification对象,并发送通知,id=1 notifyManager.notify(1, builder.build()); } /** * 发送一个简单的通知,只带有小图标、标题、内容 */ @OnClick(R.id.btn_send_simplest_notification) void sendSimplestNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("最简单的Notification") .setContentIntent(null) .setContentText("只有小图标、标题、内容"); mNotifyManager.notify(1, builder.build()); } /** * 发送一个具有大图标的简单通知 * 当setSmallIcon与setLargeIcon同时存在时,smallIcon显示在通知的右下角,largeIcon显示在左侧 * 当只设置setSmallIcon时,smallIcon显示在左侧 */ @OnClick(R.id.btn_send_simplest_notification_with_large_icon) void sendSimplestNotificationWithLargeIcon() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("带大图标的Notification") .setContentText("有小图标、大图标、标题、内容") .setLargeIcon(mLargeIcon); mNotifyManager.notify(2, builder.build()); } /** * 发送一个点击跳转到MainActivity的消息 */ @OnClick(R.id.btn_send_simplest_notification_with_action) void sendSimplestNotificationWithAction() { //获取PendingIntent Intent mainIntent = new Intent(this, MainActivity.class); PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT); //创建 Notification.Builder 对象 NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) //点击通知后自动清除 .setAutoCancel(true) .setContentTitle("我是带Action的Notification") .setContentText("点我会打开MainActivity") .setContentIntent(mainPendingIntent); //发送通知 mNotifyManager.notify(3, builder.build()); } @Override protected void process() { } @Override protected void onDestroy() { super.onDestroy(); //回收bitmap if (mLargeIcon != null) { if (!mLargeIcon.isRecycled()) { mLargeIcon.recycle(); } mLargeIcon = null; } } }
UTF-8
Java
4,756
java
SimplestNotificationActivity.java
Java
[]
null
[]
package com.littlejie.demo.modules.base.notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v4.app.NotificationCompat; import com.littlejie.core.base.BaseActivity; import com.littlejie.demo.R; import com.littlejie.demo.annotation.Description; import com.littlejie.demo.modules.MainActivity; import butterknife.OnClick; /** * 这是一个最简单的通知例子,该通知只有必要的三个属性: * 小图标、标题、内容 */ @Description(description = "一个最简单的Notification Demo") public class SimplestNotificationActivity extends BaseActivity{ private NotificationManager mNotifyManager; private Bitmap mLargeIcon; @Override protected int getPageLayoutID() { return R.layout.activity_simplest_notification; } @Override protected void initData() { mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mLargeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_fab_repair); } @Override protected void initView() { } @Override protected void initViewListener() { } void sendNotification() { //获取NotificationManager实例 NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); //实例化NotificationCompat.Builde并设置相关属性 NotificationCompat.Builder builder = new NotificationCompat.Builder(this) //设置小图标 .setSmallIcon(R.mipmap.icon_fab_repair) //设置通知标题 .setContentTitle("最简单的Notification") //设置通知内容 .setContentText("只有小图标、标题、内容"); //设置通知时间,默认为系统发出通知的时间,通常不用设置 //.setWhen(System.currentTimeMillis()); //通过builder.build()方法生成Notification对象,并发送通知,id=1 notifyManager.notify(1, builder.build()); } /** * 发送一个简单的通知,只带有小图标、标题、内容 */ @OnClick(R.id.btn_send_simplest_notification) void sendSimplestNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("最简单的Notification") .setContentIntent(null) .setContentText("只有小图标、标题、内容"); mNotifyManager.notify(1, builder.build()); } /** * 发送一个具有大图标的简单通知 * 当setSmallIcon与setLargeIcon同时存在时,smallIcon显示在通知的右下角,largeIcon显示在左侧 * 当只设置setSmallIcon时,smallIcon显示在左侧 */ @OnClick(R.id.btn_send_simplest_notification_with_large_icon) void sendSimplestNotificationWithLargeIcon() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("带大图标的Notification") .setContentText("有小图标、大图标、标题、内容") .setLargeIcon(mLargeIcon); mNotifyManager.notify(2, builder.build()); } /** * 发送一个点击跳转到MainActivity的消息 */ @OnClick(R.id.btn_send_simplest_notification_with_action) void sendSimplestNotificationWithAction() { //获取PendingIntent Intent mainIntent = new Intent(this, MainActivity.class); PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT); //创建 Notification.Builder 对象 NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) //点击通知后自动清除 .setAutoCancel(true) .setContentTitle("我是带Action的Notification") .setContentText("点我会打开MainActivity") .setContentIntent(mainPendingIntent); //发送通知 mNotifyManager.notify(3, builder.build()); } @Override protected void process() { } @Override protected void onDestroy() { super.onDestroy(); //回收bitmap if (mLargeIcon != null) { if (!mLargeIcon.isRecycled()) { mLargeIcon.recycle(); } mLargeIcon = null; } } }
4,756
0.661932
0.660275
131
31.244274
25.705643
124
false
false
0
0
0
0
0
0
0.374046
false
false
4
42d945ed09027347e9da3eacb08672bfb3e86cf7
592,705,532,211
5e9562aafdb159b7bd4eb3a793ab0c8b9da23169
/neo4j/src/main/java/com/stackroute/neo4j/repository/SupplierRepository.java
31f4f9526dd62e7c099f38b48ba75f47a774523a
[ "Apache-2.0" ]
permissive
stackroute/ibm-wave7-online-fashion-retail
https://github.com/stackroute/ibm-wave7-online-fashion-retail
a1f3777dd92a1c8f9da5995213255d0a9fec2c26
ee94419ba56e5c57ab08371f6abfeb5e1b5d01d3
refs/heads/master
2023-01-28T07:33:13.747000
2019-09-06T04:50:33
2019-09-06T04:50:33
203,519,050
1
4
null
false
2023-01-07T09:19:08
2019-08-21T06:15:54
2019-09-06T04:51:21
2023-01-07T09:19:07
46,506
0
2
82
Java
false
false
package com.stackroute.neo4j.repository; import com.stackroute.neo4j.entity.Supplier; import org.springframework.data.neo4j.repository.Neo4jRepository; public interface SupplierRepository extends Neo4jRepository<Supplier,Long> { }
UTF-8
Java
233
java
SupplierRepository.java
Java
[]
null
[]
package com.stackroute.neo4j.repository; import com.stackroute.neo4j.entity.Supplier; import org.springframework.data.neo4j.repository.Neo4jRepository; public interface SupplierRepository extends Neo4jRepository<Supplier,Long> { }
233
0.849785
0.828326
7
32.285713
29.860218
76
false
false
0
0
0
0
0
0
0.571429
false
false
4
3ed5de4235a1f45f7914443d358d5d41518df080
34,729,105,580,978
4c6f0b967f5e69ac1db94668485071078b85f8e3
/src/main/java/mcjty/rftoolsbase/setup/RFToolsBaseMessages.java
43e89fdd0db4e197408038de160a8bc61a1562c5
[ "MIT" ]
permissive
McJtyMods/RFToolsBase
https://github.com/McJtyMods/RFToolsBase
95b83155e534aea8b9de47ad0fc43f591dbdff70
956cd1444e0b1df31bcd6c48685f6f0142fa0767
refs/heads/1.16
2023-08-23T12:12:26.205000
2022-06-10T02:58:18
2022-06-10T02:58:18
192,222,652
26
24
MIT
false
2022-08-06T05:48:44
2019-06-16T18:14:54
2022-05-09T23:34:56
2022-08-06T05:48:43
947
14
14
9
Java
false
false
package mcjty.rftoolsbase.setup; import mcjty.lib.network.*; import mcjty.lib.typed.TypedMap; import mcjty.rftoolsbase.RFToolsBase; import mcjty.rftoolsbase.compat.jei.PacketSendRecipe; import mcjty.rftoolsbase.modules.crafting.network.PacketItemNBTToServer; import mcjty.rftoolsbase.modules.crafting.network.PacketUpdateNBTItemCard; import mcjty.rftoolsbase.modules.informationscreen.network.PacketGetMonitorLog; import mcjty.rftoolsbase.modules.informationscreen.network.PacketMonitorLogReady; import mcjty.rftoolsbase.modules.filter.network.PacketSyncHandItem; import mcjty.rftoolsbase.modules.filter.network.PacketUpdateNBTItemFilter; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.network.NetworkDirection; import net.minecraftforge.fml.network.NetworkRegistry; import net.minecraftforge.fml.network.simple.SimpleChannel; import javax.annotation.Nonnull; public class RFToolsBaseMessages { public static SimpleChannel INSTANCE; private static int packetId = 0; private static int id() { return packetId++; } public static void registerMessages(String name) { SimpleChannel net = NetworkRegistry.ChannelBuilder .named(new ResourceLocation(RFToolsBase.MODID, name)) .networkProtocolVersion(() -> "1.0") .clientAcceptedVersions(s -> true) .serverAcceptedVersions(s -> true) .simpleChannel(); INSTANCE = net; net.registerMessage(id(), PacketItemNBTToServer.class, PacketItemNBTToServer::toBytes, PacketItemNBTToServer::new, PacketItemNBTToServer::handle); net.registerMessage(id(), PacketUpdateNBTItemCard.class, PacketUpdateNBTItemCard::toBytes, PacketUpdateNBTItemCard::new, PacketUpdateNBTItemCard::handle); net.registerMessage(id(), PacketSendRecipe.class, PacketSendRecipe::toBytes, PacketSendRecipe::new, PacketSendRecipe::handle); net.registerMessage(id(), PacketGetMonitorLog.class, PacketGetMonitorLog::toBytes, PacketGetMonitorLog::new, PacketGetMonitorLog::handle); net.registerMessage(id(), PacketMonitorLogReady.class, PacketMonitorLogReady::toBytes, PacketMonitorLogReady::new, PacketMonitorLogReady::handle); net.registerMessage(id(), PacketUpdateNBTItemFilter.class, PacketUpdateNBTItemFilter::toBytes, PacketUpdateNBTItemFilter::new, PacketUpdateNBTItemFilter::handle); net.registerMessage(id(), PacketSyncHandItem.class, PacketSyncHandItem::toBytes, PacketSyncHandItem::new, PacketSyncHandItem::handle); net.registerMessage(id(), PacketRequestDataFromServer.class, PacketRequestDataFromServer::toBytes, PacketRequestDataFromServer::new, new ChannelBoundHandler<>(net, PacketRequestDataFromServer::handle)); PacketHandler.registerStandardMessages(id(), net); } public static void sendToServer(String command, @Nonnull TypedMap.Builder argumentBuilder) { INSTANCE.sendToServer(new PacketSendServerCommand(RFToolsBase.MODID, command, argumentBuilder.build())); } public static void sendToServer(String command) { INSTANCE.sendToServer(new PacketSendServerCommand(RFToolsBase.MODID, command, TypedMap.EMPTY)); } public static void sendToClient(PlayerEntity player, String command, @Nonnull TypedMap.Builder argumentBuilder) { INSTANCE.sendTo(new PacketSendClientCommand(RFToolsBase.MODID, command, argumentBuilder.build()), ((ServerPlayerEntity) player).connection.connection, NetworkDirection.PLAY_TO_CLIENT); } public static void sendToClient(PlayerEntity player, String command) { INSTANCE.sendTo(new PacketSendClientCommand(RFToolsBase.MODID, command, TypedMap.EMPTY), ((ServerPlayerEntity) player).connection.connection, NetworkDirection.PLAY_TO_CLIENT); } }
UTF-8
Java
3,886
java
RFToolsBaseMessages.java
Java
[]
null
[]
package mcjty.rftoolsbase.setup; import mcjty.lib.network.*; import mcjty.lib.typed.TypedMap; import mcjty.rftoolsbase.RFToolsBase; import mcjty.rftoolsbase.compat.jei.PacketSendRecipe; import mcjty.rftoolsbase.modules.crafting.network.PacketItemNBTToServer; import mcjty.rftoolsbase.modules.crafting.network.PacketUpdateNBTItemCard; import mcjty.rftoolsbase.modules.informationscreen.network.PacketGetMonitorLog; import mcjty.rftoolsbase.modules.informationscreen.network.PacketMonitorLogReady; import mcjty.rftoolsbase.modules.filter.network.PacketSyncHandItem; import mcjty.rftoolsbase.modules.filter.network.PacketUpdateNBTItemFilter; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.network.NetworkDirection; import net.minecraftforge.fml.network.NetworkRegistry; import net.minecraftforge.fml.network.simple.SimpleChannel; import javax.annotation.Nonnull; public class RFToolsBaseMessages { public static SimpleChannel INSTANCE; private static int packetId = 0; private static int id() { return packetId++; } public static void registerMessages(String name) { SimpleChannel net = NetworkRegistry.ChannelBuilder .named(new ResourceLocation(RFToolsBase.MODID, name)) .networkProtocolVersion(() -> "1.0") .clientAcceptedVersions(s -> true) .serverAcceptedVersions(s -> true) .simpleChannel(); INSTANCE = net; net.registerMessage(id(), PacketItemNBTToServer.class, PacketItemNBTToServer::toBytes, PacketItemNBTToServer::new, PacketItemNBTToServer::handle); net.registerMessage(id(), PacketUpdateNBTItemCard.class, PacketUpdateNBTItemCard::toBytes, PacketUpdateNBTItemCard::new, PacketUpdateNBTItemCard::handle); net.registerMessage(id(), PacketSendRecipe.class, PacketSendRecipe::toBytes, PacketSendRecipe::new, PacketSendRecipe::handle); net.registerMessage(id(), PacketGetMonitorLog.class, PacketGetMonitorLog::toBytes, PacketGetMonitorLog::new, PacketGetMonitorLog::handle); net.registerMessage(id(), PacketMonitorLogReady.class, PacketMonitorLogReady::toBytes, PacketMonitorLogReady::new, PacketMonitorLogReady::handle); net.registerMessage(id(), PacketUpdateNBTItemFilter.class, PacketUpdateNBTItemFilter::toBytes, PacketUpdateNBTItemFilter::new, PacketUpdateNBTItemFilter::handle); net.registerMessage(id(), PacketSyncHandItem.class, PacketSyncHandItem::toBytes, PacketSyncHandItem::new, PacketSyncHandItem::handle); net.registerMessage(id(), PacketRequestDataFromServer.class, PacketRequestDataFromServer::toBytes, PacketRequestDataFromServer::new, new ChannelBoundHandler<>(net, PacketRequestDataFromServer::handle)); PacketHandler.registerStandardMessages(id(), net); } public static void sendToServer(String command, @Nonnull TypedMap.Builder argumentBuilder) { INSTANCE.sendToServer(new PacketSendServerCommand(RFToolsBase.MODID, command, argumentBuilder.build())); } public static void sendToServer(String command) { INSTANCE.sendToServer(new PacketSendServerCommand(RFToolsBase.MODID, command, TypedMap.EMPTY)); } public static void sendToClient(PlayerEntity player, String command, @Nonnull TypedMap.Builder argumentBuilder) { INSTANCE.sendTo(new PacketSendClientCommand(RFToolsBase.MODID, command, argumentBuilder.build()), ((ServerPlayerEntity) player).connection.connection, NetworkDirection.PLAY_TO_CLIENT); } public static void sendToClient(PlayerEntity player, String command) { INSTANCE.sendTo(new PacketSendClientCommand(RFToolsBase.MODID, command, TypedMap.EMPTY), ((ServerPlayerEntity) player).connection.connection, NetworkDirection.PLAY_TO_CLIENT); } }
3,886
0.78281
0.782038
67
57
54.710911
210
false
false
0
0
0
0
0
0
1.298507
false
false
4
277142421991701b3e8d9fa6c3aead42593c6058
35,321,811,060,816
1840307a316053f70892cf7fb1697575a15c64c2
/src/main/java/com/nikolayrybakov/optiontwo/Util.java
5992b00b72ac06fb28afc3e4df6cd244a43346d7
[]
no_license
Nutopzhe/WordAnalyzer
https://github.com/Nutopzhe/WordAnalyzer
0626cf40654eceec56bc717e902f6bdf04cd8c88
43ee7165f02afd7012e29836c3fd5151ad121fd2
refs/heads/master
2023-03-24T11:22:08.845000
2021-03-22T13:19:09
2021-03-22T13:19:09
350,343,461
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nikolayrybakov.optiontwo; import com.nikolayrybakov.optiontwo.model.Letter; import java.util.HashMap; import java.util.Map; public class Util { public static Letter searchLetter(String str) { Map<Character, Integer> lettersMap = new HashMap<>(); if (str.length() > 0) { char[] chars = str.toCharArray(); char letter = chars[0]; for (char c : chars) { if (!lettersMap.containsKey(c)) { lettersMap.put(c, 1); if (lettersMap.get(letter).equals(lettersMap.get(c))) { letter = c; } } else { lettersMap.put(c, lettersMap.get(c) + 1); if (lettersMap.get(c) >= lettersMap.get(letter)) { letter = c; } } } return new Letter(letter, lettersMap.get(letter)); } return null; } }
UTF-8
Java
998
java
Util.java
Java
[ { "context": "package com.nikolayrybakov.optiontwo;\n\nimport com.nikolayrybakov.op", "end": 17, "score": 0.722139835357666, "start": 15, "tag": "USERNAME", "value": "ol" }, { "context": "package com.nikolayrybakov.optiontwo;\n\nimport com.nikolayrybakov.optiontwo.model.Letter;\nimport java.util.HashMap;", "end": 64, "score": 0.8322572708129883, "start": 50, "tag": "USERNAME", "value": "nikolayrybakov" } ]
null
[]
package com.nikolayrybakov.optiontwo; import com.nikolayrybakov.optiontwo.model.Letter; import java.util.HashMap; import java.util.Map; public class Util { public static Letter searchLetter(String str) { Map<Character, Integer> lettersMap = new HashMap<>(); if (str.length() > 0) { char[] chars = str.toCharArray(); char letter = chars[0]; for (char c : chars) { if (!lettersMap.containsKey(c)) { lettersMap.put(c, 1); if (lettersMap.get(letter).equals(lettersMap.get(c))) { letter = c; } } else { lettersMap.put(c, lettersMap.get(c) + 1); if (lettersMap.get(c) >= lettersMap.get(letter)) { letter = c; } } } return new Letter(letter, lettersMap.get(letter)); } return null; } }
998
0.483968
0.47996
31
31.193548
21.073481
75
false
false
0
0
0
0
0
0
0.548387
false
false
4
0b5aeae65d22f8441b736d85dae35863e1f359a5
20,486,994,052,944
3d9672cdfb1fd5c472dc2cf3d9c696c16351aa6c
/src/test/java/com/rtbhouse/utils/avro/benchmark/FastSerdeBenchmarkSupport.java
fde30d371456a8ea793a93c6d00fc98e685b27ba
[ "Apache-2.0" ]
permissive
ppsysdev/avro-fastserde
https://github.com/ppsysdev/avro-fastserde
235387f6ba1d6a09273a63baaf9629bb5890b8f2
6c597331e06d54ca849ce30010fde7cd68bf2a1a
refs/heads/master
2022-12-27T13:58:05.999000
2020-06-15T14:09:19
2020-06-15T14:09:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rtbhouse.utils.avro.benchmark; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.avro.Schema; import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.DecoderFactory; import org.apache.avro.io.Encoder; import org.apache.avro.io.EncoderFactory; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificRecord; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomUtils; public final class FastSerdeBenchmarkSupport { public static final String NAMESPACE = "com.rtbhouse.utils.generated.avro.benchmark"; private FastSerdeBenchmarkSupport() { } public static String getRandomString() { return RandomStringUtils.randomAlphabetic(RandomUtils.nextInt(2, 40)); } public static Integer getRandomInteger() { return RandomUtils.nextInt(0, Integer.MAX_VALUE); } public static Long getRandomLong() { return RandomUtils.nextLong(0l, Long.MAX_VALUE); } public static Double getRandomDouble() { return RandomUtils.nextDouble(0, Double.MAX_VALUE); } public static Float getRandomFloat() { return RandomUtils.nextFloat(0f, Float.MAX_VALUE); } public static Boolean getRandomBoolean() { return RandomUtils.nextInt(0, 10) % 2 == 0 ? Boolean.TRUE : Boolean.FALSE; } public static ByteBuffer getRandomBytes() { return ByteBuffer.wrap(RandomUtils.nextBytes(RandomUtils.nextInt(1, 25))); } public static List<String> getRandomStringList() { return Stream.generate(FastSerdeBenchmarkSupport::getRandomString).limit(RandomUtils.nextInt(1, 10)) .collect(Collectors.toList()); } public static <T extends SpecificRecord> T toSpecificRecord(GenericData.Record record) throws IOException { GenericDatumWriter<GenericData.Record> datumWriter = new GenericDatumWriter<>(record.getSchema()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Encoder binaryEncoder = EncoderFactory.get().binaryEncoder(baos, null); datumWriter.write(record, binaryEncoder); binaryEncoder.flush(); SpecificDatumReader<T> datumReader = new SpecificDatumReader<>(record.getSchema()); return datumReader.read(null, DecoderFactory.get().binaryDecoder(baos.toByteArray(), null)); } public static Schema generateRandomRecordSchema(String name, int depth, int minNestedRecords, int maxNestedRecords, int fieldsNumber) { int nestedRecords = 0; if (depth != 0) { nestedRecords = RandomUtils.nextInt(minNestedRecords, maxNestedRecords + 1); } final Schema.Type[] types = new Schema.Type[] { Schema.Type.BOOLEAN, Schema.Type.INT, Schema.Type.LONG, Schema.Type.DOUBLE, Schema.Type.FLOAT, Schema.Type.BYTES, Schema.Type.STRING, Schema.Type.FIXED, Schema.Type.ENUM, Schema.Type.ARRAY, Schema.Type.MAP, Schema.Type.UNION, Schema.Type.UNION, Schema.Type.UNION, Schema.Type.UNION }; final Schema schema = Schema.createRecord(name, null, NAMESPACE, false); List<Schema.Field> fields = new ArrayList<>(); for (int i = 0; i < fieldsNumber; i++) { if (i < nestedRecords) { fields.add(new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomRecordSchema("NestedRecord" + RandomStringUtils.randomAlphabetic(5), depth - 1, minNestedRecords, maxNestedRecords, fieldsNumber), null, null, Schema.Field.Order.ASCENDING)); } else { final Schema.Type type = types[RandomUtils.nextInt(0, types.length)]; switch (type) { case ENUM: fields.add( new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomEnumSchema(), null, null, Schema.Field.Order.ASCENDING)); break; case FIXED: fields.add( new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomFixedSchema(), null, null, Schema.Field.Order.ASCENDING)); break; case UNION: fields.add( new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomUnionSchema(), null, null, Schema.Field.Order.ASCENDING)); break; case ARRAY: fields.add( new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomArraySchema(), null, null, Schema.Field.Order.ASCENDING)); break; case MAP: fields.add( new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomMapSchema(), null, null, Schema.Field.Order.ASCENDING)); break; default: fields.add(new Schema.Field(RandomStringUtils.randomAlphabetic(10), Schema.create(type), null, null, Schema.Field.Order.ASCENDING)); } } } Collections.shuffle(fields); schema.setFields(fields); return schema; } public static Schema generateRandomUnionSchema() { final Schema.Type[] types = new Schema.Type[] { Schema.Type.BOOLEAN, Schema.Type.INT, Schema.Type.LONG, Schema.Type.DOUBLE, Schema.Type.FLOAT, Schema.Type.BYTES, Schema.Type.STRING, Schema.Type.FIXED, Schema.Type.ENUM }; final Schema.Type type = types[RandomUtils.nextInt(0, types.length)]; Schema unionSchema = null; switch (type) { case ENUM: unionSchema = Schema .createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), generateRandomEnumSchema())); break; case FIXED: unionSchema = Schema .createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), generateRandomFixedSchema())); break; default: unionSchema = Schema.createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), Schema.create(type))); } return unionSchema; } public static Schema generateRandomArraySchema() { final Schema.Type[] types = new Schema.Type[] { Schema.Type.BOOLEAN, Schema.Type.INT, Schema.Type.LONG, Schema.Type.DOUBLE, Schema.Type.FLOAT, Schema.Type.BYTES, Schema.Type.STRING, Schema.Type.FIXED, Schema.Type.ENUM }; final Schema.Type type = types[RandomUtils.nextInt(0, types.length)]; Schema arraySchema = null; switch (type) { case ENUM: arraySchema = Schema .createArray(generateRandomEnumSchema()); break; case FIXED: arraySchema = Schema .createArray(generateRandomFixedSchema()); break; default: arraySchema = Schema.createArray(Schema.create(type)); } return arraySchema; } public static Schema generateRandomMapSchema() { final Schema.Type[] types = new Schema.Type[] { Schema.Type.BOOLEAN, Schema.Type.INT, Schema.Type.LONG, Schema.Type.DOUBLE, Schema.Type.FLOAT, Schema.Type.BYTES, Schema.Type.STRING, Schema.Type.FIXED, Schema.Type.ENUM }; final Schema.Type type = types[RandomUtils.nextInt(0, types.length)]; Schema mapSchema = null; switch (type) { case ENUM: mapSchema = Schema .createMap(generateRandomEnumSchema()); break; case FIXED: mapSchema = Schema .createMap(generateRandomFixedSchema()); break; default: mapSchema = Schema.createMap(Schema.create(type)); } return mapSchema; } public static Schema generateRandomEnumSchema() { return Schema.createEnum("Enum" + RandomStringUtils.randomAlphabetic(5), null, NAMESPACE, getRandomStringList()); } public static Schema generateRandomFixedSchema() { return Schema.createFixed("Fixed" + RandomStringUtils.randomAlphabetic(5), null, NAMESPACE, RandomUtils.nextInt(1, 10)); } public static GenericData.Record generateRandomRecordData(Schema schema) { if (!Schema.Type.RECORD.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be a record schema"); } final GenericData.Record record = new GenericData.Record(schema); for (Schema.Field field : schema.getFields()) { switch (field.schema().getType()) { case BOOLEAN: record.put(field.pos(), getRandomBoolean()); break; case INT: record.put(field.pos(), getRandomInteger()); break; case LONG: record.put(field.pos(), getRandomLong()); break; case DOUBLE: record.put(field.pos(), getRandomDouble()); break; case FLOAT: record.put(field.pos(), getRandomFloat()); break; case BYTES: record.put(field.pos(), getRandomBytes()); break; case STRING: record.put(field.pos(), getRandomString()); break; case RECORD: record.put(field.pos(), generateRandomRecordData(field.schema())); break; case ENUM: record.put(field.pos(), generateRandomEnumSymbol(field.schema())); break; case FIXED: record.put(field.pos(), generateRandomFixed(field.schema())); break; case UNION: record.put(field.pos(), generateRandomUnion(field.schema())); break; case ARRAY: record.put(field.pos(), generateRandomArray(field.schema())); break; case MAP: record.put(field.pos(), generateRandomMap(field.schema())); break; } } return record; } public static GenericData.EnumSymbol generateRandomEnumSymbol(Schema schema) { if (!Schema.Type.ENUM.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be an enum schema"); } return new GenericData.EnumSymbol(schema, schema.getEnumSymbols().get(RandomUtils.nextInt(0, schema.getEnumSymbols().size()))); } public static GenericData.Fixed generateRandomFixed(Schema schema) { if (!Schema.Type.FIXED.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be an fixed schema"); } return new GenericData.Fixed(schema, RandomUtils.nextBytes(schema.getFixedSize())); } public static Object generateRandomUnion(Schema schema) { if (!Schema.Type.UNION.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be an union schema"); } Object unionData = null; switch (schema.getTypes().get(1).getType()) { case BOOLEAN: unionData = getRandomBoolean(); break; case INT: unionData = getRandomInteger(); break; case LONG: unionData = getRandomLong(); break; case DOUBLE: unionData = getRandomDouble(); break; case FLOAT: unionData = getRandomFloat(); break; case BYTES: unionData = getRandomBytes(); break; case STRING: unionData = getRandomString(); break; case RECORD: unionData = generateRandomRecordData(schema.getTypes().get(1)); break; case ENUM: unionData = generateRandomEnumSymbol(schema.getTypes().get(1)); break; case FIXED: unionData = generateRandomFixed(schema.getTypes().get(1)); break; case UNION: unionData = generateRandomUnion(schema.getTypes().get(1)); } return unionData; } public static GenericData.Array<?> generateRandomArray(Schema schema) { if (!Schema.Type.ARRAY.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be an array schema"); } int elements = RandomUtils.nextInt(1, 11); GenericData.Array<Object> arrayData = new GenericData.Array<>(elements, schema); for (int i = 0; i < elements; i++) { switch (schema.getElementType().getType()) { case BOOLEAN: arrayData.add(getRandomBoolean()); break; case INT: arrayData.add(getRandomInteger()); break; case LONG: arrayData.add(getRandomLong()); break; case DOUBLE: arrayData.add(getRandomDouble()); break; case FLOAT: arrayData.add(getRandomFloat()); break; case BYTES: arrayData.add(getRandomBytes()); break; case STRING: arrayData.add(getRandomString()); break; case RECORD: arrayData.add(generateRandomRecordData(schema.getElementType())); break; case ENUM: arrayData.add(generateRandomEnumSymbol(schema.getElementType())); break; case FIXED: arrayData.add(generateRandomFixed(schema.getElementType())); break; } } return arrayData; } public static Map<String, ?> generateRandomMap(Schema schema) { if (!Schema.Type.MAP.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be an map schema"); } int elements = RandomUtils.nextInt(1, 11); Map<String, Object> mapData = new HashMap<>(); for (int i = 0; i < elements; i++) { switch (schema.getValueType().getType()) { case BOOLEAN: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomBoolean()); break; case INT: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomInteger()); break; case LONG: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomLong()); break; case DOUBLE: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomDouble()); break; case FLOAT: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomFloat()); break; case BYTES: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomBytes()); break; case STRING: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomString()); break; case RECORD: mapData.put(RandomStringUtils.randomAlphabetic(10), generateRandomRecordData(schema.getValueType())); break; case ENUM: mapData.put(RandomStringUtils.randomAlphabetic(10), generateRandomEnumSymbol(schema.getValueType())); break; case FIXED: mapData.put(RandomStringUtils.randomAlphabetic(10), generateRandomFixed(schema.getValueType())); break; } } return mapData; } public static void main(String[] args) throws IOException { if (args.length < 5) { System.err.println("Usage: FastBenchmarkSupport name depth minNestedRecords maxNestedRecords fieldsNumber"); System.exit(1); } String name = args[0]; int depth = Integer.parseInt(args[1]); int minNestedRecords = Integer.parseInt(args[2]); int maxNestedRecords = Integer.parseInt(args[3]); int fieldsNumber = Integer.parseInt(args[4]); Schema recordSchema = generateRandomRecordSchema(name, depth, minNestedRecords, maxNestedRecords, fieldsNumber); FileOutputStream avroFileOutputStream = new FileOutputStream(name + ".avsc"); avroFileOutputStream.write(recordSchema.toString(true).getBytes()); } }
UTF-8
Java
17,474
java
FastSerdeBenchmarkSupport.java
Java
[]
null
[]
package com.rtbhouse.utils.avro.benchmark; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.avro.Schema; import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.DecoderFactory; import org.apache.avro.io.Encoder; import org.apache.avro.io.EncoderFactory; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificRecord; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomUtils; public final class FastSerdeBenchmarkSupport { public static final String NAMESPACE = "com.rtbhouse.utils.generated.avro.benchmark"; private FastSerdeBenchmarkSupport() { } public static String getRandomString() { return RandomStringUtils.randomAlphabetic(RandomUtils.nextInt(2, 40)); } public static Integer getRandomInteger() { return RandomUtils.nextInt(0, Integer.MAX_VALUE); } public static Long getRandomLong() { return RandomUtils.nextLong(0l, Long.MAX_VALUE); } public static Double getRandomDouble() { return RandomUtils.nextDouble(0, Double.MAX_VALUE); } public static Float getRandomFloat() { return RandomUtils.nextFloat(0f, Float.MAX_VALUE); } public static Boolean getRandomBoolean() { return RandomUtils.nextInt(0, 10) % 2 == 0 ? Boolean.TRUE : Boolean.FALSE; } public static ByteBuffer getRandomBytes() { return ByteBuffer.wrap(RandomUtils.nextBytes(RandomUtils.nextInt(1, 25))); } public static List<String> getRandomStringList() { return Stream.generate(FastSerdeBenchmarkSupport::getRandomString).limit(RandomUtils.nextInt(1, 10)) .collect(Collectors.toList()); } public static <T extends SpecificRecord> T toSpecificRecord(GenericData.Record record) throws IOException { GenericDatumWriter<GenericData.Record> datumWriter = new GenericDatumWriter<>(record.getSchema()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Encoder binaryEncoder = EncoderFactory.get().binaryEncoder(baos, null); datumWriter.write(record, binaryEncoder); binaryEncoder.flush(); SpecificDatumReader<T> datumReader = new SpecificDatumReader<>(record.getSchema()); return datumReader.read(null, DecoderFactory.get().binaryDecoder(baos.toByteArray(), null)); } public static Schema generateRandomRecordSchema(String name, int depth, int minNestedRecords, int maxNestedRecords, int fieldsNumber) { int nestedRecords = 0; if (depth != 0) { nestedRecords = RandomUtils.nextInt(minNestedRecords, maxNestedRecords + 1); } final Schema.Type[] types = new Schema.Type[] { Schema.Type.BOOLEAN, Schema.Type.INT, Schema.Type.LONG, Schema.Type.DOUBLE, Schema.Type.FLOAT, Schema.Type.BYTES, Schema.Type.STRING, Schema.Type.FIXED, Schema.Type.ENUM, Schema.Type.ARRAY, Schema.Type.MAP, Schema.Type.UNION, Schema.Type.UNION, Schema.Type.UNION, Schema.Type.UNION }; final Schema schema = Schema.createRecord(name, null, NAMESPACE, false); List<Schema.Field> fields = new ArrayList<>(); for (int i = 0; i < fieldsNumber; i++) { if (i < nestedRecords) { fields.add(new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomRecordSchema("NestedRecord" + RandomStringUtils.randomAlphabetic(5), depth - 1, minNestedRecords, maxNestedRecords, fieldsNumber), null, null, Schema.Field.Order.ASCENDING)); } else { final Schema.Type type = types[RandomUtils.nextInt(0, types.length)]; switch (type) { case ENUM: fields.add( new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomEnumSchema(), null, null, Schema.Field.Order.ASCENDING)); break; case FIXED: fields.add( new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomFixedSchema(), null, null, Schema.Field.Order.ASCENDING)); break; case UNION: fields.add( new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomUnionSchema(), null, null, Schema.Field.Order.ASCENDING)); break; case ARRAY: fields.add( new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomArraySchema(), null, null, Schema.Field.Order.ASCENDING)); break; case MAP: fields.add( new Schema.Field(RandomStringUtils.randomAlphabetic(10), generateRandomMapSchema(), null, null, Schema.Field.Order.ASCENDING)); break; default: fields.add(new Schema.Field(RandomStringUtils.randomAlphabetic(10), Schema.create(type), null, null, Schema.Field.Order.ASCENDING)); } } } Collections.shuffle(fields); schema.setFields(fields); return schema; } public static Schema generateRandomUnionSchema() { final Schema.Type[] types = new Schema.Type[] { Schema.Type.BOOLEAN, Schema.Type.INT, Schema.Type.LONG, Schema.Type.DOUBLE, Schema.Type.FLOAT, Schema.Type.BYTES, Schema.Type.STRING, Schema.Type.FIXED, Schema.Type.ENUM }; final Schema.Type type = types[RandomUtils.nextInt(0, types.length)]; Schema unionSchema = null; switch (type) { case ENUM: unionSchema = Schema .createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), generateRandomEnumSchema())); break; case FIXED: unionSchema = Schema .createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), generateRandomFixedSchema())); break; default: unionSchema = Schema.createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), Schema.create(type))); } return unionSchema; } public static Schema generateRandomArraySchema() { final Schema.Type[] types = new Schema.Type[] { Schema.Type.BOOLEAN, Schema.Type.INT, Schema.Type.LONG, Schema.Type.DOUBLE, Schema.Type.FLOAT, Schema.Type.BYTES, Schema.Type.STRING, Schema.Type.FIXED, Schema.Type.ENUM }; final Schema.Type type = types[RandomUtils.nextInt(0, types.length)]; Schema arraySchema = null; switch (type) { case ENUM: arraySchema = Schema .createArray(generateRandomEnumSchema()); break; case FIXED: arraySchema = Schema .createArray(generateRandomFixedSchema()); break; default: arraySchema = Schema.createArray(Schema.create(type)); } return arraySchema; } public static Schema generateRandomMapSchema() { final Schema.Type[] types = new Schema.Type[] { Schema.Type.BOOLEAN, Schema.Type.INT, Schema.Type.LONG, Schema.Type.DOUBLE, Schema.Type.FLOAT, Schema.Type.BYTES, Schema.Type.STRING, Schema.Type.FIXED, Schema.Type.ENUM }; final Schema.Type type = types[RandomUtils.nextInt(0, types.length)]; Schema mapSchema = null; switch (type) { case ENUM: mapSchema = Schema .createMap(generateRandomEnumSchema()); break; case FIXED: mapSchema = Schema .createMap(generateRandomFixedSchema()); break; default: mapSchema = Schema.createMap(Schema.create(type)); } return mapSchema; } public static Schema generateRandomEnumSchema() { return Schema.createEnum("Enum" + RandomStringUtils.randomAlphabetic(5), null, NAMESPACE, getRandomStringList()); } public static Schema generateRandomFixedSchema() { return Schema.createFixed("Fixed" + RandomStringUtils.randomAlphabetic(5), null, NAMESPACE, RandomUtils.nextInt(1, 10)); } public static GenericData.Record generateRandomRecordData(Schema schema) { if (!Schema.Type.RECORD.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be a record schema"); } final GenericData.Record record = new GenericData.Record(schema); for (Schema.Field field : schema.getFields()) { switch (field.schema().getType()) { case BOOLEAN: record.put(field.pos(), getRandomBoolean()); break; case INT: record.put(field.pos(), getRandomInteger()); break; case LONG: record.put(field.pos(), getRandomLong()); break; case DOUBLE: record.put(field.pos(), getRandomDouble()); break; case FLOAT: record.put(field.pos(), getRandomFloat()); break; case BYTES: record.put(field.pos(), getRandomBytes()); break; case STRING: record.put(field.pos(), getRandomString()); break; case RECORD: record.put(field.pos(), generateRandomRecordData(field.schema())); break; case ENUM: record.put(field.pos(), generateRandomEnumSymbol(field.schema())); break; case FIXED: record.put(field.pos(), generateRandomFixed(field.schema())); break; case UNION: record.put(field.pos(), generateRandomUnion(field.schema())); break; case ARRAY: record.put(field.pos(), generateRandomArray(field.schema())); break; case MAP: record.put(field.pos(), generateRandomMap(field.schema())); break; } } return record; } public static GenericData.EnumSymbol generateRandomEnumSymbol(Schema schema) { if (!Schema.Type.ENUM.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be an enum schema"); } return new GenericData.EnumSymbol(schema, schema.getEnumSymbols().get(RandomUtils.nextInt(0, schema.getEnumSymbols().size()))); } public static GenericData.Fixed generateRandomFixed(Schema schema) { if (!Schema.Type.FIXED.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be an fixed schema"); } return new GenericData.Fixed(schema, RandomUtils.nextBytes(schema.getFixedSize())); } public static Object generateRandomUnion(Schema schema) { if (!Schema.Type.UNION.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be an union schema"); } Object unionData = null; switch (schema.getTypes().get(1).getType()) { case BOOLEAN: unionData = getRandomBoolean(); break; case INT: unionData = getRandomInteger(); break; case LONG: unionData = getRandomLong(); break; case DOUBLE: unionData = getRandomDouble(); break; case FLOAT: unionData = getRandomFloat(); break; case BYTES: unionData = getRandomBytes(); break; case STRING: unionData = getRandomString(); break; case RECORD: unionData = generateRandomRecordData(schema.getTypes().get(1)); break; case ENUM: unionData = generateRandomEnumSymbol(schema.getTypes().get(1)); break; case FIXED: unionData = generateRandomFixed(schema.getTypes().get(1)); break; case UNION: unionData = generateRandomUnion(schema.getTypes().get(1)); } return unionData; } public static GenericData.Array<?> generateRandomArray(Schema schema) { if (!Schema.Type.ARRAY.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be an array schema"); } int elements = RandomUtils.nextInt(1, 11); GenericData.Array<Object> arrayData = new GenericData.Array<>(elements, schema); for (int i = 0; i < elements; i++) { switch (schema.getElementType().getType()) { case BOOLEAN: arrayData.add(getRandomBoolean()); break; case INT: arrayData.add(getRandomInteger()); break; case LONG: arrayData.add(getRandomLong()); break; case DOUBLE: arrayData.add(getRandomDouble()); break; case FLOAT: arrayData.add(getRandomFloat()); break; case BYTES: arrayData.add(getRandomBytes()); break; case STRING: arrayData.add(getRandomString()); break; case RECORD: arrayData.add(generateRandomRecordData(schema.getElementType())); break; case ENUM: arrayData.add(generateRandomEnumSymbol(schema.getElementType())); break; case FIXED: arrayData.add(generateRandomFixed(schema.getElementType())); break; } } return arrayData; } public static Map<String, ?> generateRandomMap(Schema schema) { if (!Schema.Type.MAP.equals(schema.getType())) { throw new IllegalArgumentException("input schema must be an map schema"); } int elements = RandomUtils.nextInt(1, 11); Map<String, Object> mapData = new HashMap<>(); for (int i = 0; i < elements; i++) { switch (schema.getValueType().getType()) { case BOOLEAN: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomBoolean()); break; case INT: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomInteger()); break; case LONG: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomLong()); break; case DOUBLE: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomDouble()); break; case FLOAT: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomFloat()); break; case BYTES: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomBytes()); break; case STRING: mapData.put(RandomStringUtils.randomAlphabetic(10), getRandomString()); break; case RECORD: mapData.put(RandomStringUtils.randomAlphabetic(10), generateRandomRecordData(schema.getValueType())); break; case ENUM: mapData.put(RandomStringUtils.randomAlphabetic(10), generateRandomEnumSymbol(schema.getValueType())); break; case FIXED: mapData.put(RandomStringUtils.randomAlphabetic(10), generateRandomFixed(schema.getValueType())); break; } } return mapData; } public static void main(String[] args) throws IOException { if (args.length < 5) { System.err.println("Usage: FastBenchmarkSupport name depth minNestedRecords maxNestedRecords fieldsNumber"); System.exit(1); } String name = args[0]; int depth = Integer.parseInt(args[1]); int minNestedRecords = Integer.parseInt(args[2]); int maxNestedRecords = Integer.parseInt(args[3]); int fieldsNumber = Integer.parseInt(args[4]); Schema recordSchema = generateRandomRecordSchema(name, depth, minNestedRecords, maxNestedRecords, fieldsNumber); FileOutputStream avroFileOutputStream = new FileOutputStream(name + ".avsc"); avroFileOutputStream.write(recordSchema.toString(true).getBytes()); } }
17,474
0.588646
0.583495
446
38.179371
31.959534
126
false
false
0
0
0
0
0
0
0.789238
false
false
4
00bb33330c5ab439444ac20e66a7c6f7832c1326
33,878,702,063,690
cb6e2a59f0fdcd4f23965d3bd911150070656860
/app/src/main/java/com/incode_it/spychat/alarm/AlarmReceiverIndividual.java
3ffda55dfa2cf836fc77ab5931c3dd1aace6661f
[]
no_license
NTRsolutions/SpyChat
https://github.com/NTRsolutions/SpyChat
e2da68213308ee0e1f90f51eff31844ef04d3825
6c77f1d01fcd6d302fa78a009cc2c4b326742a17
refs/heads/master
2020-03-27T08:45:13.249000
2017-03-01T08:05:56
2017-03-01T08:05:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.incode_it.spychat.alarm; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v4.content.WakefulBroadcastReceiver; import com.incode_it.spychat.C; import com.incode_it.spychat.Message; import com.incode_it.spychat.data_base.MyDbHelper; import java.io.File; public class AlarmReceiverIndividual extends WakefulBroadcastReceiver { private static final String TAG = "myserv"; @Override public void onReceive(Context context, Intent intent) { int mId = intent.getIntExtra(C.ID_TO_DELETE, 0); Message message = MyDbHelper.readMessage(new MyDbHelper(context).getReadableDatabase(), mId, context); if (message.messageType != Message.MY_MESSAGE_TEXT && message.messageType != Message.NOT_MY_MESSAGE_TEXT) { File file = new File(message.getMessage()); file.delete(); } MyDbHelper.removeMessageFromIndividualTimer(new MyDbHelper(context).getWritableDatabase(), mId); Intent serviceIntent = new Intent(context, UpdateUIService.class); serviceIntent.putExtra(C.ID_TO_DELETE, mId); startWakefulService(context, serviceIntent); } public void setAlarm(Context context, long removalTime, int mId) { AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmReceiverIndividual.class); intent.putExtra(C.ID_TO_DELETE, mId); PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mId, intent, 0); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { alarmMgr.setExact(AlarmManager.RTC_WAKEUP, removalTime, alarmIntent); } else { alarmMgr.set(AlarmManager.RTC_WAKEUP, removalTime, alarmIntent); } // Enable {@code SampleBootReceiver} to automatically restart the alarm when the // device is rebooted. /*ComponentName receiver = new ComponentName(context, BootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);*/ } public void cancelAlarm(Context context, int mId) { AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmReceiverIndividual.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, mId, intent, 0); alarmMgr.cancel(pendingIntent); // Disable {@code SampleBootReceiver} so that it doesn't automatically restart the // alarm when the device is rebooted. /*ComponentName receiver = new ComponentName(context, BootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);*/ } }
UTF-8
Java
3,167
java
AlarmReceiverIndividual.java
Java
[]
null
[]
package com.incode_it.spychat.alarm; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v4.content.WakefulBroadcastReceiver; import com.incode_it.spychat.C; import com.incode_it.spychat.Message; import com.incode_it.spychat.data_base.MyDbHelper; import java.io.File; public class AlarmReceiverIndividual extends WakefulBroadcastReceiver { private static final String TAG = "myserv"; @Override public void onReceive(Context context, Intent intent) { int mId = intent.getIntExtra(C.ID_TO_DELETE, 0); Message message = MyDbHelper.readMessage(new MyDbHelper(context).getReadableDatabase(), mId, context); if (message.messageType != Message.MY_MESSAGE_TEXT && message.messageType != Message.NOT_MY_MESSAGE_TEXT) { File file = new File(message.getMessage()); file.delete(); } MyDbHelper.removeMessageFromIndividualTimer(new MyDbHelper(context).getWritableDatabase(), mId); Intent serviceIntent = new Intent(context, UpdateUIService.class); serviceIntent.putExtra(C.ID_TO_DELETE, mId); startWakefulService(context, serviceIntent); } public void setAlarm(Context context, long removalTime, int mId) { AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmReceiverIndividual.class); intent.putExtra(C.ID_TO_DELETE, mId); PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mId, intent, 0); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { alarmMgr.setExact(AlarmManager.RTC_WAKEUP, removalTime, alarmIntent); } else { alarmMgr.set(AlarmManager.RTC_WAKEUP, removalTime, alarmIntent); } // Enable {@code SampleBootReceiver} to automatically restart the alarm when the // device is rebooted. /*ComponentName receiver = new ComponentName(context, BootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);*/ } public void cancelAlarm(Context context, int mId) { AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmReceiverIndividual.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, mId, intent, 0); alarmMgr.cancel(pendingIntent); // Disable {@code SampleBootReceiver} so that it doesn't automatically restart the // alarm when the device is rebooted. /*ComponentName receiver = new ComponentName(context, BootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);*/ } }
3,167
0.700979
0.699716
80
38.599998
33.242519
113
false
false
0
0
0
0
0
0
0.825
false
false
4
c3eaec9e84acc4c5d59e8a6f28f3e2c5a6237774
19,069,654,853,431
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_9fd4c2e8d33a4e4fb03ab37705f2db273783c87f/SymLinkFileReporter/2_9fd4c2e8d33a4e4fb03ab37705f2db273783c87f_SymLinkFileReporter_t.java
eae049e55dea71c29b5db84ada3e62bce274ce11
[]
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
/* * Copyright (C) 2011 SeqWare * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.sourceforge.seqware.pipeline.plugins; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import net.sourceforge.seqware.common.hibernate.FindAllTheFiles; import net.sourceforge.seqware.common.model.Study; import net.sourceforge.seqware.common.module.FileMetadata; import net.sourceforge.seqware.common.module.ReturnValue; import net.sourceforge.seqware.pipeline.plugin.Plugin; import net.sourceforge.seqware.pipeline.plugin.PluginInterface; import org.openide.util.lookup.ServiceProvider; /** * <p>SymLinkFileReporter class.</p> * * @author mtaschuk * @version $Id: $Id */ @ServiceProvider(service = PluginInterface.class) public class SymLinkFileReporter extends Plugin { ReturnValue ret = new ReturnValue(); private final String LINKTYPE_SYM = "s"; private String fileType = FindAllTheFiles.FILETYPE_ALL; private String linkType = LINKTYPE_SYM; private String csvFileName = null; private BufferedWriter writer; /** * <p>Constructor for SymLinkFileReporter.</p> */ public SymLinkFileReporter() { super(); parser.acceptsAll(Arrays.asList("study"), "Make symlinks for a study").withRequiredArg(); parser.acceptsAll(Arrays.asList("sample"), "Make symlinks for a sample").withRequiredArg(); //FIXME: SymLinking using SequencerRuns is not working properly yet, so it is disabled for now. parser.acceptsAll(Arrays.asList("sequencer-run"), "Make symlinks for a sequencerRun").withRequiredArg(); parser.acceptsAll(Arrays.asList("file-type", "f"), "Optional: The file type to filter on. Only this type will be linked. Default is all files. Permissible file metatypes can found on our website under 'Module Conventions'").withRequiredArg(); parser.acceptsAll(Arrays.asList("workflow-accession", "w"), "Optional: List all workflow runs with this workflow accession").withRequiredArg(); parser.acceptsAll(Arrays.asList("link", "l"), "Optional: make hard links (P) or symlinks (s). Default is symlinks.").withRequiredArg(); parser.acceptsAll(Arrays.asList("prod-format"), "Optional: print the directories in prod format"); parser.acceptsAll(Arrays.asList("duplicates"), "Optional: Allow duplications at the file path level"); parser.acceptsAll(Arrays.asList("dump-all"), "Optional: Dumps all of the studies in the database to one file."); parser.acceptsAll(Arrays.asList("no-links"), "Optional: Create only the CSV file, not the symlinked directories."); parser.acceptsAll(Arrays.asList("output-filename"), "Optional: Name of the output CSV file (without the extension)").withRequiredArg(); parser.acceptsAll(Arrays.asList("show-failed-and-running"), "Show all of the files regardless of the workflow run status. Default shows only successful runs."); parser.acceptsAll(Arrays.asList("show-status"), "Show the workflow run status in the output CSV."); ret.setExitStatus(ReturnValue.SUCCESS); } /** {@inheritDoc} */ @Override public ReturnValue init() { return ret; } /** {@inheritDoc} */ @Override public ReturnValue do_test() { return ret; } /** {@inheritDoc} */ @Override public ReturnValue do_run() { String currentDir = new File(".").getAbsolutePath(); fileType = getFileType(); linkType = getLinkType(); try { if (options.has("study")) { String study = (String) options.valueOf("study"); initWriter(currentDir, study); // printHeader(); reportOnStudy(study, currentDir); } else if (options.has("sample")) { String sample = (String) options.valueOf("sample"); initWriter(currentDir, sample); // printHeader(); ret = reportOnSample(sample, currentDir); } else if (options.has("sequencer-run")) { String sequencerRun = (String) options.valueOf("sequencer-run"); initWriter(currentDir, sequencerRun); // printHeader(); ret = reportOnSequencerRun(sequencerRun, currentDir); } else if (options.has("dump-all")) { initWriter(currentDir, "all"); // printHeader(); ret = reportAll(currentDir); } else { println("Combination of parameters not recognized!"); println(this.get_syntax()); ret.setExitStatus(ReturnValue.INVALIDPARAMETERS); } } catch (IOException e) { e.printStackTrace(); ret.setExitStatus(ReturnValue.FILENOTREADABLE); ret.setDescription(e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException ex) { Logger.getLogger(SymLinkFileReporter.class.getName()).log(Level.SEVERE, null, ex); } } } return ret; } private void initWriter(String currentDir, String string) throws IOException { String filename = new Date().toString().replace(" ", "_") + "__" + string; if (options.has("output-filename")) { filename = (String) options.valueOf("output-filename"); } csvFileName = currentDir + File.separator + filename + ".csv"; writer = new BufferedWriter(new FileWriter(csvFileName, true)); } private ReturnValue reportOnStudy(String studyName, String rootDirectory) throws IOException { println("Searching for study with title: " + studyName); List<ReturnValue> returnValues = metadata.findFilesAssociatedWithAStudy(studyName); okGo(returnValues, rootDirectory, studyName); return ret; } private ReturnValue reportOnSample(String sampleName, String rootDirectory) throws IOException { println("Searching for sample with title: " + sampleName); List<ReturnValue> returnValues = metadata.findFilesAssociatedWithASample(sampleName); okGo(returnValues, rootDirectory, null); return ret; } private ReturnValue reportOnSequencerRun(String sequencerRun, String rootDirectory) throws IOException { println("Searching for sequencer run with name: " + sequencerRun); List<ReturnValue> returnValues = metadata.findFilesAssociatedWithASequencerRun(sequencerRun); okGo(returnValues, rootDirectory, null); return ret; } private ReturnValue reportAll(String rootDirectory) throws IOException { println("Dumping all studies to file"); List<Study> studies = metadata.getAllStudies(); for (Study study : studies) { String name = study.getTitle(); println("Dumping study: " + name); List<ReturnValue> returnValues = metadata.findFilesAssociatedWithAStudy(name); okGo(returnValues, rootDirectory, name); } return ret; } private void okGo(List<ReturnValue> returnValues, String rootDirectory, String studyName) throws IOException { println("There are " + returnValues.size() + " returnValues in total before filtering"); println("Saving symlinks and creating CSV file"); returnValues = FindAllTheFiles.filterReturnValues(returnValues, studyName, fileType, options.has("duplicates"), options.has("show-failed-and-running"), options.has("show-status")); FindAllTheFiles.printTSVFile(writer, options.has("show-status"), returnValues, studyName); for (ReturnValue rv : returnValues) { StringBuilder directory = new StringBuilder(); directory.append(rootDirectory).append(File.separator); //First pull all of the required information out of the ReturnValue String studySwa = rv.getAttribute(FindAllTheFiles.STUDY_SWA); String parentSampleName = rv.getAttribute(FindAllTheFiles.PARENT_SAMPLE_NAME); String parentSampleSwa = rv.getAttribute(FindAllTheFiles.PARENT_SAMPLE_SWA); String sampleName = rv.getAttribute(FindAllTheFiles.SAMPLE_NAME); String sampleSwa = rv.getAttribute(FindAllTheFiles.SAMPLE_SWA); String iusSwa = rv.getAttribute(FindAllTheFiles.IUS_SWA); String iusTag = rv.getAttribute(FindAllTheFiles.IUS_TAG); String laneNum = rv.getAttribute(FindAllTheFiles.LANE_NUM); String sequencerRunName = rv.getAttribute(FindAllTheFiles.SEQUENCER_RUN_NAME); String sequencerRunSwa = rv.getAttribute(FindAllTheFiles.SEQUENCER_RUN_SWA); String workflowRunName = rv.getAttribute(FindAllTheFiles.WORKFLOW_RUN_NAME); String workflowRunSwa = rv.getAttribute(FindAllTheFiles.WORKFLOW_RUN_SWA); String workflowName = rv.getAttribute(FindAllTheFiles.WORKFLOW_NAME); String workflowSwa = rv.getAttribute(FindAllTheFiles.WORKFLOW_SWA); String workflowVersion = rv.getAttribute(FindAllTheFiles.WORKFLOW_VERSION); if (!options.has("no-links")) { ///Save in the format requested if (options.has("prod-format")) { saveProdFileName(directory, studyName, studySwa, parentSampleName, parentSampleSwa, rv, workflowName, workflowVersion, sampleName, sampleSwa); } else { if (studyName != null && studySwa != null) { directory.append(studyName).append("-").append(studySwa); directory.append(File.separator); } directory.append(parentSampleName).append("-").append(parentSampleSwa); directory.append(File.separator); directory.append(sampleName).append("-").append(sampleSwa); saveSeqwareFileName(directory.toString(), workflowName, workflowSwa, workflowRunName, workflowRunSwa, sequencerRunName, sequencerRunSwa, laneNum, iusTag, iusSwa, sampleName, sampleSwa, rv); } } } } /** * Links files in a loose interpretation of the Production format. * * @param directory the base directory to build the hierarchical structure * @param studyName * @param studySwa study seqware accession * @param parentSampleName * @param parentSampleSwa parent sample seqware accession * @param rv the ReturnValue where all the attributes are stored * @param workflowName * @param workflowVersion * @param sampleName * @param sampleSwa */ private void saveProdFileName(StringBuilder directory, String studyName, String studySwa, String parentSampleName, String parentSampleSwa, ReturnValue rv, String workflowName, String workflowVersion, String sampleName, String sampleSwa) { if (studyName != null && studySwa != null) { directory.append(studyName).append("-").append(studySwa); directory.append(File.separator); } directory.append(parentSampleName).append("-").append(parentSampleSwa); directory.append(File.separator); directory.append(parentSampleName); directory.append(rv.getAttribute(FindAllTheFiles.SAMPLE_TAG_PREFIX + "geo_tissue_type")); directory.append(File.separator); directory.append(rv.getAttribute(FindAllTheFiles.SAMPLE_TAG_PREFIX + "geo_library_source_template_type")); directory.append(File.separator); directory.append(rv.getAlgorithm()); directory.append(File.separator); directory.append(workflowName).append("-").append(workflowVersion); directory.append(File.separator); directory.append(sampleName).append("-").append(sampleSwa); saveFiles(rv.getFiles(), "", directory.toString()); } /** * Links files in the SeqWare file format and directory hierarchy. * * @param directory * @param workflowName * @param workflowSwa * @param workflowRunName * @param workflowRunSwa * @param sequencerRunName * @param sequencerRunSwa * @param laneNum * @param iusTag * @param iusSwa * @param sampleName * @param sampleSwa * @param rv */ private void saveSeqwareFileName(String directory, String workflowName, String workflowSwa, String workflowRunName, String workflowRunSwa, String sequencerRunName, String sequencerRunSwa, String laneNum, String iusTag, String iusSwa, String sampleName, String sampleSwa, ReturnValue rv) { StringBuilder fileNamePrefix = new StringBuilder(); fileNamePrefix.append(workflowName).append("-"); fileNamePrefix.append(workflowSwa).append("__"); fileNamePrefix.append(workflowRunName).append("-"); fileNamePrefix.append(workflowRunSwa).append("__"); fileNamePrefix.append(sequencerRunName).append("-"); fileNamePrefix.append(sequencerRunSwa).append("__"); fileNamePrefix.append(laneNum).append("__"); fileNamePrefix.append(iusTag).append("-"); fileNamePrefix.append(iusSwa).append("__"); fileNamePrefix.append(sampleName).append("-"); fileNamePrefix.append(sampleSwa).append("__"); saveFiles(rv.getFiles(), fileNamePrefix.toString(), directory); } /** * Link some files and creates a directory structure. * * @param files a list of the files * @param fileNamePrefix the prefix of the files * @param directory the directory in which to link the files */ private void saveFiles(List<FileMetadata> files, String fileNamePrefix, String directory) { for (FileMetadata fm : files) { if (fm.getMetaType().equals(fileType) || fileType.equals(FindAllTheFiles.FILETYPE_ALL)) { String[] pathArr = fm.getFilePath().split(File.separator); String filename = fileNamePrefix.toString() + pathArr[pathArr.length - 1]; //Filenames have a max size of 144 chars on Ubuntu, believe it or not. if (filename.length() >= 143) { String pieces = fm.getDescription() + pathArr[pathArr.length - 1]; String ext = "." + fm.getMetaType().replace("/", "."); if (pieces.length() > 143 - ext.length()) { filename = pieces.substring(0, 143 - ext.length()) + ext; } } try { (new File(directory)).mkdirs(); Process process = Runtime.getRuntime().exec( new String[]{"ln", "-" + linkType, fm.getFilePath(), directory + File.separator + filename}); process.waitFor(); } catch (InterruptedException ex) { Logger.getLogger(SymLinkFileReporter.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SymLinkFileReporter.class.getName()).log(Level.SEVERE, null, ex); } } } } private String getFileType() { if (options.has("file-type")) { return (String) options.valueOf("file-type"); } else { return FindAllTheFiles.FILETYPE_ALL; } } private String getLinkType() { if (options.has("link")) { return (String) options.valueOf("link"); } else { return LINKTYPE_SYM; } } /** {@inheritDoc} */ @Override public ReturnValue clean_up() { return ret; } /** {@inheritDoc} */ @Override public String get_description() { return "Create a nested tree structure of all of the output files from a " + "particular sample, or all of the samples in a study by using " + "the SymLinkFileReporter plugin. This plugin also creates a CSV " + "file with all of the accompanying information for every file. " + "For more information, see " + "see http://seqware.github.com/docs/21-study-reporter/"; } }
UTF-8
Java
17,898
java
2_9fd4c2e8d33a4e4fb03ab37705f2db273783c87f_SymLinkFileReporter_t.java
Java
[ { "context": " <p>SymLinkFileReporter class.</p>\n *\n * @author mtaschuk\n * @version $Id: $Id\n */\n @ServiceProvider(serv", "end": 1430, "score": 0.9991016983985901, "start": 1422, "tag": "USERNAME", "value": "mtaschuk" } ]
null
[]
/* * Copyright (C) 2011 SeqWare * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.sourceforge.seqware.pipeline.plugins; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import net.sourceforge.seqware.common.hibernate.FindAllTheFiles; import net.sourceforge.seqware.common.model.Study; import net.sourceforge.seqware.common.module.FileMetadata; import net.sourceforge.seqware.common.module.ReturnValue; import net.sourceforge.seqware.pipeline.plugin.Plugin; import net.sourceforge.seqware.pipeline.plugin.PluginInterface; import org.openide.util.lookup.ServiceProvider; /** * <p>SymLinkFileReporter class.</p> * * @author mtaschuk * @version $Id: $Id */ @ServiceProvider(service = PluginInterface.class) public class SymLinkFileReporter extends Plugin { ReturnValue ret = new ReturnValue(); private final String LINKTYPE_SYM = "s"; private String fileType = FindAllTheFiles.FILETYPE_ALL; private String linkType = LINKTYPE_SYM; private String csvFileName = null; private BufferedWriter writer; /** * <p>Constructor for SymLinkFileReporter.</p> */ public SymLinkFileReporter() { super(); parser.acceptsAll(Arrays.asList("study"), "Make symlinks for a study").withRequiredArg(); parser.acceptsAll(Arrays.asList("sample"), "Make symlinks for a sample").withRequiredArg(); //FIXME: SymLinking using SequencerRuns is not working properly yet, so it is disabled for now. parser.acceptsAll(Arrays.asList("sequencer-run"), "Make symlinks for a sequencerRun").withRequiredArg(); parser.acceptsAll(Arrays.asList("file-type", "f"), "Optional: The file type to filter on. Only this type will be linked. Default is all files. Permissible file metatypes can found on our website under 'Module Conventions'").withRequiredArg(); parser.acceptsAll(Arrays.asList("workflow-accession", "w"), "Optional: List all workflow runs with this workflow accession").withRequiredArg(); parser.acceptsAll(Arrays.asList("link", "l"), "Optional: make hard links (P) or symlinks (s). Default is symlinks.").withRequiredArg(); parser.acceptsAll(Arrays.asList("prod-format"), "Optional: print the directories in prod format"); parser.acceptsAll(Arrays.asList("duplicates"), "Optional: Allow duplications at the file path level"); parser.acceptsAll(Arrays.asList("dump-all"), "Optional: Dumps all of the studies in the database to one file."); parser.acceptsAll(Arrays.asList("no-links"), "Optional: Create only the CSV file, not the symlinked directories."); parser.acceptsAll(Arrays.asList("output-filename"), "Optional: Name of the output CSV file (without the extension)").withRequiredArg(); parser.acceptsAll(Arrays.asList("show-failed-and-running"), "Show all of the files regardless of the workflow run status. Default shows only successful runs."); parser.acceptsAll(Arrays.asList("show-status"), "Show the workflow run status in the output CSV."); ret.setExitStatus(ReturnValue.SUCCESS); } /** {@inheritDoc} */ @Override public ReturnValue init() { return ret; } /** {@inheritDoc} */ @Override public ReturnValue do_test() { return ret; } /** {@inheritDoc} */ @Override public ReturnValue do_run() { String currentDir = new File(".").getAbsolutePath(); fileType = getFileType(); linkType = getLinkType(); try { if (options.has("study")) { String study = (String) options.valueOf("study"); initWriter(currentDir, study); // printHeader(); reportOnStudy(study, currentDir); } else if (options.has("sample")) { String sample = (String) options.valueOf("sample"); initWriter(currentDir, sample); // printHeader(); ret = reportOnSample(sample, currentDir); } else if (options.has("sequencer-run")) { String sequencerRun = (String) options.valueOf("sequencer-run"); initWriter(currentDir, sequencerRun); // printHeader(); ret = reportOnSequencerRun(sequencerRun, currentDir); } else if (options.has("dump-all")) { initWriter(currentDir, "all"); // printHeader(); ret = reportAll(currentDir); } else { println("Combination of parameters not recognized!"); println(this.get_syntax()); ret.setExitStatus(ReturnValue.INVALIDPARAMETERS); } } catch (IOException e) { e.printStackTrace(); ret.setExitStatus(ReturnValue.FILENOTREADABLE); ret.setDescription(e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException ex) { Logger.getLogger(SymLinkFileReporter.class.getName()).log(Level.SEVERE, null, ex); } } } return ret; } private void initWriter(String currentDir, String string) throws IOException { String filename = new Date().toString().replace(" ", "_") + "__" + string; if (options.has("output-filename")) { filename = (String) options.valueOf("output-filename"); } csvFileName = currentDir + File.separator + filename + ".csv"; writer = new BufferedWriter(new FileWriter(csvFileName, true)); } private ReturnValue reportOnStudy(String studyName, String rootDirectory) throws IOException { println("Searching for study with title: " + studyName); List<ReturnValue> returnValues = metadata.findFilesAssociatedWithAStudy(studyName); okGo(returnValues, rootDirectory, studyName); return ret; } private ReturnValue reportOnSample(String sampleName, String rootDirectory) throws IOException { println("Searching for sample with title: " + sampleName); List<ReturnValue> returnValues = metadata.findFilesAssociatedWithASample(sampleName); okGo(returnValues, rootDirectory, null); return ret; } private ReturnValue reportOnSequencerRun(String sequencerRun, String rootDirectory) throws IOException { println("Searching for sequencer run with name: " + sequencerRun); List<ReturnValue> returnValues = metadata.findFilesAssociatedWithASequencerRun(sequencerRun); okGo(returnValues, rootDirectory, null); return ret; } private ReturnValue reportAll(String rootDirectory) throws IOException { println("Dumping all studies to file"); List<Study> studies = metadata.getAllStudies(); for (Study study : studies) { String name = study.getTitle(); println("Dumping study: " + name); List<ReturnValue> returnValues = metadata.findFilesAssociatedWithAStudy(name); okGo(returnValues, rootDirectory, name); } return ret; } private void okGo(List<ReturnValue> returnValues, String rootDirectory, String studyName) throws IOException { println("There are " + returnValues.size() + " returnValues in total before filtering"); println("Saving symlinks and creating CSV file"); returnValues = FindAllTheFiles.filterReturnValues(returnValues, studyName, fileType, options.has("duplicates"), options.has("show-failed-and-running"), options.has("show-status")); FindAllTheFiles.printTSVFile(writer, options.has("show-status"), returnValues, studyName); for (ReturnValue rv : returnValues) { StringBuilder directory = new StringBuilder(); directory.append(rootDirectory).append(File.separator); //First pull all of the required information out of the ReturnValue String studySwa = rv.getAttribute(FindAllTheFiles.STUDY_SWA); String parentSampleName = rv.getAttribute(FindAllTheFiles.PARENT_SAMPLE_NAME); String parentSampleSwa = rv.getAttribute(FindAllTheFiles.PARENT_SAMPLE_SWA); String sampleName = rv.getAttribute(FindAllTheFiles.SAMPLE_NAME); String sampleSwa = rv.getAttribute(FindAllTheFiles.SAMPLE_SWA); String iusSwa = rv.getAttribute(FindAllTheFiles.IUS_SWA); String iusTag = rv.getAttribute(FindAllTheFiles.IUS_TAG); String laneNum = rv.getAttribute(FindAllTheFiles.LANE_NUM); String sequencerRunName = rv.getAttribute(FindAllTheFiles.SEQUENCER_RUN_NAME); String sequencerRunSwa = rv.getAttribute(FindAllTheFiles.SEQUENCER_RUN_SWA); String workflowRunName = rv.getAttribute(FindAllTheFiles.WORKFLOW_RUN_NAME); String workflowRunSwa = rv.getAttribute(FindAllTheFiles.WORKFLOW_RUN_SWA); String workflowName = rv.getAttribute(FindAllTheFiles.WORKFLOW_NAME); String workflowSwa = rv.getAttribute(FindAllTheFiles.WORKFLOW_SWA); String workflowVersion = rv.getAttribute(FindAllTheFiles.WORKFLOW_VERSION); if (!options.has("no-links")) { ///Save in the format requested if (options.has("prod-format")) { saveProdFileName(directory, studyName, studySwa, parentSampleName, parentSampleSwa, rv, workflowName, workflowVersion, sampleName, sampleSwa); } else { if (studyName != null && studySwa != null) { directory.append(studyName).append("-").append(studySwa); directory.append(File.separator); } directory.append(parentSampleName).append("-").append(parentSampleSwa); directory.append(File.separator); directory.append(sampleName).append("-").append(sampleSwa); saveSeqwareFileName(directory.toString(), workflowName, workflowSwa, workflowRunName, workflowRunSwa, sequencerRunName, sequencerRunSwa, laneNum, iusTag, iusSwa, sampleName, sampleSwa, rv); } } } } /** * Links files in a loose interpretation of the Production format. * * @param directory the base directory to build the hierarchical structure * @param studyName * @param studySwa study seqware accession * @param parentSampleName * @param parentSampleSwa parent sample seqware accession * @param rv the ReturnValue where all the attributes are stored * @param workflowName * @param workflowVersion * @param sampleName * @param sampleSwa */ private void saveProdFileName(StringBuilder directory, String studyName, String studySwa, String parentSampleName, String parentSampleSwa, ReturnValue rv, String workflowName, String workflowVersion, String sampleName, String sampleSwa) { if (studyName != null && studySwa != null) { directory.append(studyName).append("-").append(studySwa); directory.append(File.separator); } directory.append(parentSampleName).append("-").append(parentSampleSwa); directory.append(File.separator); directory.append(parentSampleName); directory.append(rv.getAttribute(FindAllTheFiles.SAMPLE_TAG_PREFIX + "geo_tissue_type")); directory.append(File.separator); directory.append(rv.getAttribute(FindAllTheFiles.SAMPLE_TAG_PREFIX + "geo_library_source_template_type")); directory.append(File.separator); directory.append(rv.getAlgorithm()); directory.append(File.separator); directory.append(workflowName).append("-").append(workflowVersion); directory.append(File.separator); directory.append(sampleName).append("-").append(sampleSwa); saveFiles(rv.getFiles(), "", directory.toString()); } /** * Links files in the SeqWare file format and directory hierarchy. * * @param directory * @param workflowName * @param workflowSwa * @param workflowRunName * @param workflowRunSwa * @param sequencerRunName * @param sequencerRunSwa * @param laneNum * @param iusTag * @param iusSwa * @param sampleName * @param sampleSwa * @param rv */ private void saveSeqwareFileName(String directory, String workflowName, String workflowSwa, String workflowRunName, String workflowRunSwa, String sequencerRunName, String sequencerRunSwa, String laneNum, String iusTag, String iusSwa, String sampleName, String sampleSwa, ReturnValue rv) { StringBuilder fileNamePrefix = new StringBuilder(); fileNamePrefix.append(workflowName).append("-"); fileNamePrefix.append(workflowSwa).append("__"); fileNamePrefix.append(workflowRunName).append("-"); fileNamePrefix.append(workflowRunSwa).append("__"); fileNamePrefix.append(sequencerRunName).append("-"); fileNamePrefix.append(sequencerRunSwa).append("__"); fileNamePrefix.append(laneNum).append("__"); fileNamePrefix.append(iusTag).append("-"); fileNamePrefix.append(iusSwa).append("__"); fileNamePrefix.append(sampleName).append("-"); fileNamePrefix.append(sampleSwa).append("__"); saveFiles(rv.getFiles(), fileNamePrefix.toString(), directory); } /** * Link some files and creates a directory structure. * * @param files a list of the files * @param fileNamePrefix the prefix of the files * @param directory the directory in which to link the files */ private void saveFiles(List<FileMetadata> files, String fileNamePrefix, String directory) { for (FileMetadata fm : files) { if (fm.getMetaType().equals(fileType) || fileType.equals(FindAllTheFiles.FILETYPE_ALL)) { String[] pathArr = fm.getFilePath().split(File.separator); String filename = fileNamePrefix.toString() + pathArr[pathArr.length - 1]; //Filenames have a max size of 144 chars on Ubuntu, believe it or not. if (filename.length() >= 143) { String pieces = fm.getDescription() + pathArr[pathArr.length - 1]; String ext = "." + fm.getMetaType().replace("/", "."); if (pieces.length() > 143 - ext.length()) { filename = pieces.substring(0, 143 - ext.length()) + ext; } } try { (new File(directory)).mkdirs(); Process process = Runtime.getRuntime().exec( new String[]{"ln", "-" + linkType, fm.getFilePath(), directory + File.separator + filename}); process.waitFor(); } catch (InterruptedException ex) { Logger.getLogger(SymLinkFileReporter.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SymLinkFileReporter.class.getName()).log(Level.SEVERE, null, ex); } } } } private String getFileType() { if (options.has("file-type")) { return (String) options.valueOf("file-type"); } else { return FindAllTheFiles.FILETYPE_ALL; } } private String getLinkType() { if (options.has("link")) { return (String) options.valueOf("link"); } else { return LINKTYPE_SYM; } } /** {@inheritDoc} */ @Override public ReturnValue clean_up() { return ret; } /** {@inheritDoc} */ @Override public String get_description() { return "Create a nested tree structure of all of the output files from a " + "particular sample, or all of the samples in a study by using " + "the SymLinkFileReporter plugin. This plugin also creates a CSV " + "file with all of the accompanying information for every file. " + "For more information, see " + "see http://seqware.github.com/docs/21-study-reporter/"; } }
17,898
0.612191
0.610962
381
45.973755
33.986633
250
false
false
0
0
0
0
0
0
0.729659
false
false
4
4d3816e286ccf237bdf2ed6af23a0030caa2b730
36,472,862,293,392
5b82e2f7c720c49dff236970aacd610e7c41a077
/QueryReformulation-master 2/data/processed/LightweightDecoratorTestCase.java
8b2558be49dada903ab57213cef628cb923b064f
[]
no_license
shy942/EGITrepoOnlineVersion
https://github.com/shy942/EGITrepoOnlineVersion
4b157da0f76dc5bbf179437242d2224d782dd267
f88fb20497dcc30ff1add5fe359cbca772142b09
refs/heads/master
2021-01-20T16:04:23.509000
2016-07-21T20:43:22
2016-07-21T20:43:22
63,737,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/***/ package org.eclipse.ui.tests.decorators; import org.eclipse.jface.viewers.ILabelProviderListener; /** * @version 1.0 */ public class LightweightDecoratorTestCase extends DecoratorEnablementTestCase implements ILabelProviderListener { /** * Constructor for DecoratorTestCase. * * @param testName */ public LightweightDecoratorTestCase(String testName) { super(testName); } /** * Refresh the test decorator. */ public void testRefreshContributor() { updated = false; getDecoratorManager().clearCaches(); definition.setEnabled(true); getDecoratorManager().updateForEnablementChange(); assertTrue("Got an update", updated); updated = false; } }
UTF-8
Java
732
java
LightweightDecoratorTestCase.java
Java
[]
null
[]
/***/ package org.eclipse.ui.tests.decorators; import org.eclipse.jface.viewers.ILabelProviderListener; /** * @version 1.0 */ public class LightweightDecoratorTestCase extends DecoratorEnablementTestCase implements ILabelProviderListener { /** * Constructor for DecoratorTestCase. * * @param testName */ public LightweightDecoratorTestCase(String testName) { super(testName); } /** * Refresh the test decorator. */ public void testRefreshContributor() { updated = false; getDecoratorManager().clearCaches(); definition.setEnabled(true); getDecoratorManager().updateForEnablementChange(); assertTrue("Got an update", updated); updated = false; } }
732
0.693989
0.691257
31
22.612904
25.441492
113
false
false
0
0
0
0
0
0
0.322581
false
false
4
ddf67a638833be56ffb39b5b259475d33fe93f31
33,689,723,510,984
0917a6cefcc3c3d6766080e58e83cd027522d0a8
/src/main/java/example/GetFoldFileNames.java
cf7406b4ccf67302c74bbdffd26d2fb65c83b98b
[]
no_license
lyk4411/untitled1_intellij
https://github.com/lyk4411/untitled1_intellij
19bb583c8e631c4fab5826573fe30a61dff9d2d4
7a3e9ff784faa03c04a40cfdc0ba53af3344bb09
refs/heads/master
2022-12-22T13:58:32.218000
2020-01-22T08:58:04
2020-01-22T08:58:04
62,300,156
0
0
null
false
2022-12-16T03:16:30
2016-06-30T09:56:05
2020-01-22T08:58:20
2022-12-16T03:16:27
5,280
0
0
7
Java
false
false
package example; import java.io.File; /** * Created by lyk on 2017-11-2. * Package name: example * Porject name: untitled1 */ public class GetFoldFileNames { /** * * @author zdz8207 */ public static void main(String[] args) { getFileName(); } public static void getFileName() { String path = "F:\\cfets风险管理部\\审计与检查\\AuditandInspect\\2018年安全运行监督检查\\检查材料\\调阅材料\\工程运行部"; // 路径 File f = new File(path); if (!f.exists()) { System.out.println(path + " not exists"); return; } File fa[] = f.listFiles(); for (int i = 0; i < fa.length; i++) { File fs = fa[i]; if (fs.isDirectory()) { System.out.println(fs.getName() + " [目录]"); } else { System.out.println(fs.getName()); } } } }
UTF-8
Java
955
java
GetFoldFileNames.java
Java
[ { "context": " example;\n\nimport java.io.File;\n\n/**\n * Created by lyk on 2017-11-2.\n * Package name: example\n * Porject", "end": 61, "score": 0.9995166659355164, "start": 58, "tag": "USERNAME", "value": "lyk" }, { "context": " GetFoldFileNames {\n\n /**\n *\n * @author zdz8207\n */\n public static void main(String[] args", "end": 202, "score": 0.9996086955070496, "start": 195, "tag": "USERNAME", "value": "zdz8207" } ]
null
[]
package example; import java.io.File; /** * Created by lyk on 2017-11-2. * Package name: example * Porject name: untitled1 */ public class GetFoldFileNames { /** * * @author zdz8207 */ public static void main(String[] args) { getFileName(); } public static void getFileName() { String path = "F:\\cfets风险管理部\\审计与检查\\AuditandInspect\\2018年安全运行监督检查\\检查材料\\调阅材料\\工程运行部"; // 路径 File f = new File(path); if (!f.exists()) { System.out.println(path + " not exists"); return; } File fa[] = f.listFiles(); for (int i = 0; i < fa.length; i++) { File fs = fa[i]; if (fs.isDirectory()) { System.out.println(fs.getName() + " [目录]"); } else { System.out.println(fs.getName()); } } } }
955
0.498301
0.479049
38
22.236841
21.07185
103
false
false
0
0
0
0
0
0
0.342105
false
false
4
ba370b1d45ecdc6ec5c5dd96f911a7ddf4c02fb9
37,546,604,103,341
fcc2266c23628bc32b48e9760dd72d3c5bdb523a
/app/src/main/java/com/example/news/Adapters/baseArticles.java
3470e10c4d06c2f862a64d7fa25d924deb21206d
[]
no_license
Kareem20/News-Feed
https://github.com/Kareem20/News-Feed
097d0b98bca6186e027abaf36acf01873193305f
a464e967cd5f89470088bc5b428270de61b46879
refs/heads/master
2023-01-16T02:47:53.663000
2020-11-28T14:12:29
2020-11-28T14:12:29
316,308,729
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.news.Adapters; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.example.news.R; import com.example.news.apiFactory.newsLoader; import com.example.news.modals.newsList; import java.util.ArrayList; import java.util.List; /* * Class for the base structure for any article fragment. * */ public class baseArticles extends Fragment implements androidx.loader.app.LoaderManager.LoaderCallbacks<List<newsList>>, SwipeRefreshLayout.OnRefreshListener { /** * Constant value for the news loader ID. */ private static final int NEWS_LOADER_ID = 1; /** * Adapter for the list of news */ private NewsAdapter mAdapter; /** * TextView that is displayed when the recycler view is empty */ private TextView mEmptyStateTextView; /** * The {@link SwipeRefreshLayout} that detects swipe gestures and * triggers callbacks in the app. */ private SwipeRefreshLayout mSwipeRefreshLayout; //image for no internet connection. private ImageView imageView; /** * Loading indicator that is displayed before the first load is completed */ private View loadingIndicator; /*Empty constructor*/ public baseArticles() { } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment, container, false); //find a reference to the image of no internet connection. imageView = rootView.findViewById(R.id.no_internet); //find a reference to the progress bar. loadingIndicator = rootView.findViewById(R.id.prograss_bar); // find a reference to the listView. EmptyRecyclerView listViewRecycler = rootView.findViewById(R.id.list_recycler); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); listViewRecycler.setHasFixedSize(true); // Set the layoutManager on the {@link RecyclerView} listViewRecycler.setLayoutManager(layoutManager); // find a reference to the textView(NO NEWS FOUND). mEmptyStateTextView = rootView.findViewById(R.id.empty_text); listViewRecycler.setEmptyView(mEmptyStateTextView); // find a reference to the Swipe for refresh. mSwipeRefreshLayout = rootView.findViewById(R.id.swiperefresh); mSwipeRefreshLayout.setOnRefreshListener(this); // Create a new adapter {@link ArrayAdapter} of news mAdapter = new NewsAdapter(getActivity(), new ArrayList<newsList>()); // Set the adapter on the {@link ListView} // so the list can be populated in the user interface listViewRecycler.setAdapter(mAdapter); boolean internetConnection = checkInternet(); if (internetConnection) { androidx.loader.app.LoaderManager loaderManager = getLoaderManager(); //fetching the data. loaderManager.initLoader(NEWS_LOADER_ID, null, this); //disappear image of no Internet Connection. imageView.setVisibility(View.GONE); } else { //if there is no Internet Connection // appear the image of no internet connection and return false.. loadingIndicator.setVisibility(View.GONE); imageView.setVisibility(View.VISIBLE); mEmptyStateTextView.setText(R.string.no_internet_connection); } return rootView; } /* * method to check if there is internet connection of not * if yes return true * if not return false. * */ private boolean checkInternet() { // get a reference to the connectivityManager to check state of network connectivity. ConnectivityManager comMang = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); //get details on the currently active defualt data network. NetworkInfo networkInfo = comMang.getActiveNetworkInfo(); // if there is a network connection , fetch data return networkInfo != null && networkInfo.isConnected(); } /* * three implementation method to get data from api * and do this action in separate thread. * * onCreateLoader for the fetching data. * onLoadFinished for the action after fetching data. * onLoaderReset for the re-fetching the data. * */ @NonNull @Override public androidx.loader.content.Loader<List<newsList>> onCreateLoader(int id, @Nullable Bundle args) { Uri.Builder uriBuilder = articlesUriBuilder.getPreferredUri(getContext()); return new newsLoader(getActivity(), uriBuilder.toString()); } @Override public void onLoadFinished(@NonNull androidx.loader.content.Loader<List<newsList>> loader, List<newsList> data) { loadingIndicator.setVisibility(View.GONE); mEmptyStateTextView.setText(R.string.no_News); mAdapter.clear(); // If there is a valid list of {@link Earthquake}s, then add them to the adapter's // data set. This will trigger the ListView to update. if (data != null && !data.isEmpty()) { mAdapter.addAll(data); } } @Override public void onLoaderReset(@NonNull androidx.loader.content.Loader<List<newsList>> loader) { // Loader reset, so we can clear out our existing data. mAdapter.clear(); } /* * method is called when user refresh the fragments. * and called the the process of fetching data again from api. * */ @Override public void onRefresh() { mSwipeRefreshLayout.setRefreshing(true); //check internet Connection first. if (checkInternet()) { imageView.setVisibility(View.GONE); // if there is internet Connection,then fetch the data. androidx.loader.app.LoaderManager loaderManager = getLoaderManager(); //fetching the data. loaderManager.initLoader(NEWS_LOADER_ID, null, this); Toast.makeText(getActivity(), "Articles is Updated.", Toast.LENGTH_SHORT).show(); } else { // if there is internet Connection,then check if there is data on // the fragment or not. if (mAdapter.getItemCount() == 0) { // if not ,then show "no Internet Connection" message. imageView.setVisibility(View.VISIBLE); mEmptyStateTextView.setText(R.string.No_Internet_Connection); } else { //if there is data , then don't show "no Internet Connection" message. imageView.setVisibility(View.GONE); mEmptyStateTextView.setText(""); } //And show the Toast. Toast.makeText(getActivity(), "No Internet Connection.", Toast.LENGTH_LONG).show(); } mSwipeRefreshLayout.setRefreshing(false); } }
UTF-8
Java
7,529
java
baseArticles.java
Java
[]
null
[]
package com.example.news.Adapters; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.example.news.R; import com.example.news.apiFactory.newsLoader; import com.example.news.modals.newsList; import java.util.ArrayList; import java.util.List; /* * Class for the base structure for any article fragment. * */ public class baseArticles extends Fragment implements androidx.loader.app.LoaderManager.LoaderCallbacks<List<newsList>>, SwipeRefreshLayout.OnRefreshListener { /** * Constant value for the news loader ID. */ private static final int NEWS_LOADER_ID = 1; /** * Adapter for the list of news */ private NewsAdapter mAdapter; /** * TextView that is displayed when the recycler view is empty */ private TextView mEmptyStateTextView; /** * The {@link SwipeRefreshLayout} that detects swipe gestures and * triggers callbacks in the app. */ private SwipeRefreshLayout mSwipeRefreshLayout; //image for no internet connection. private ImageView imageView; /** * Loading indicator that is displayed before the first load is completed */ private View loadingIndicator; /*Empty constructor*/ public baseArticles() { } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment, container, false); //find a reference to the image of no internet connection. imageView = rootView.findViewById(R.id.no_internet); //find a reference to the progress bar. loadingIndicator = rootView.findViewById(R.id.prograss_bar); // find a reference to the listView. EmptyRecyclerView listViewRecycler = rootView.findViewById(R.id.list_recycler); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); listViewRecycler.setHasFixedSize(true); // Set the layoutManager on the {@link RecyclerView} listViewRecycler.setLayoutManager(layoutManager); // find a reference to the textView(NO NEWS FOUND). mEmptyStateTextView = rootView.findViewById(R.id.empty_text); listViewRecycler.setEmptyView(mEmptyStateTextView); // find a reference to the Swipe for refresh. mSwipeRefreshLayout = rootView.findViewById(R.id.swiperefresh); mSwipeRefreshLayout.setOnRefreshListener(this); // Create a new adapter {@link ArrayAdapter} of news mAdapter = new NewsAdapter(getActivity(), new ArrayList<newsList>()); // Set the adapter on the {@link ListView} // so the list can be populated in the user interface listViewRecycler.setAdapter(mAdapter); boolean internetConnection = checkInternet(); if (internetConnection) { androidx.loader.app.LoaderManager loaderManager = getLoaderManager(); //fetching the data. loaderManager.initLoader(NEWS_LOADER_ID, null, this); //disappear image of no Internet Connection. imageView.setVisibility(View.GONE); } else { //if there is no Internet Connection // appear the image of no internet connection and return false.. loadingIndicator.setVisibility(View.GONE); imageView.setVisibility(View.VISIBLE); mEmptyStateTextView.setText(R.string.no_internet_connection); } return rootView; } /* * method to check if there is internet connection of not * if yes return true * if not return false. * */ private boolean checkInternet() { // get a reference to the connectivityManager to check state of network connectivity. ConnectivityManager comMang = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); //get details on the currently active defualt data network. NetworkInfo networkInfo = comMang.getActiveNetworkInfo(); // if there is a network connection , fetch data return networkInfo != null && networkInfo.isConnected(); } /* * three implementation method to get data from api * and do this action in separate thread. * * onCreateLoader for the fetching data. * onLoadFinished for the action after fetching data. * onLoaderReset for the re-fetching the data. * */ @NonNull @Override public androidx.loader.content.Loader<List<newsList>> onCreateLoader(int id, @Nullable Bundle args) { Uri.Builder uriBuilder = articlesUriBuilder.getPreferredUri(getContext()); return new newsLoader(getActivity(), uriBuilder.toString()); } @Override public void onLoadFinished(@NonNull androidx.loader.content.Loader<List<newsList>> loader, List<newsList> data) { loadingIndicator.setVisibility(View.GONE); mEmptyStateTextView.setText(R.string.no_News); mAdapter.clear(); // If there is a valid list of {@link Earthquake}s, then add them to the adapter's // data set. This will trigger the ListView to update. if (data != null && !data.isEmpty()) { mAdapter.addAll(data); } } @Override public void onLoaderReset(@NonNull androidx.loader.content.Loader<List<newsList>> loader) { // Loader reset, so we can clear out our existing data. mAdapter.clear(); } /* * method is called when user refresh the fragments. * and called the the process of fetching data again from api. * */ @Override public void onRefresh() { mSwipeRefreshLayout.setRefreshing(true); //check internet Connection first. if (checkInternet()) { imageView.setVisibility(View.GONE); // if there is internet Connection,then fetch the data. androidx.loader.app.LoaderManager loaderManager = getLoaderManager(); //fetching the data. loaderManager.initLoader(NEWS_LOADER_ID, null, this); Toast.makeText(getActivity(), "Articles is Updated.", Toast.LENGTH_SHORT).show(); } else { // if there is internet Connection,then check if there is data on // the fragment or not. if (mAdapter.getItemCount() == 0) { // if not ,then show "no Internet Connection" message. imageView.setVisibility(View.VISIBLE); mEmptyStateTextView.setText(R.string.No_Internet_Connection); } else { //if there is data , then don't show "no Internet Connection" message. imageView.setVisibility(View.GONE); mEmptyStateTextView.setText(""); } //And show the Toast. Toast.makeText(getActivity(), "No Internet Connection.", Toast.LENGTH_LONG).show(); } mSwipeRefreshLayout.setRefreshing(false); } }
7,529
0.67499
0.674724
201
36.45771
30.096519
159
false
false
0
0
0
0
0
0
0.467662
false
false
4
861a7778d0b3804b251edf42fcdb5dd29c94c2b0
38,276,748,549,611
d7b7eedfa1c24e53b4665b44bb0814abeec72c09
/11/11.2/FlowLayoutTest.java
40b3fd90c4186411d8e7da71fe2da124031d1a91
[]
no_license
lefeudelavie/CreazyJavaLearn
https://github.com/lefeudelavie/CreazyJavaLearn
a2e01e47952405c42f7d2826c2fb09367e8022e2
507ef0066b101f3bc0a02379df6763ce68b03c45
refs/heads/master
2021-06-07T18:17:10.730000
2021-05-11T15:52:17
2021-05-11T15:52:17
159,046,456
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.*; public class FlowLayoutTest { public static void main(String[] args) { Frame f = new Frame("²âÊÔ´°¿Ú"); f.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 5)); for (int i = 0 ; i < 10 ;i++) { f.add(new Button("°´Å¥" + i)); } f.pack(); f.setVisible(true); } }
WINDOWS-1252
Java
368
java
FlowLayoutTest.java
Java
[]
null
[]
import java.awt.*; public class FlowLayoutTest { public static void main(String[] args) { Frame f = new Frame("²âÊÔ´°¿Ú"); f.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 5)); for (int i = 0 ; i < 10 ;i++) { f.add(new Button("°´Å¥" + i)); } f.pack(); f.setVisible(true); } }
368
0.488764
0.469101
16
21.25
17.953064
60
false
false
0
0
0
0
0
0
0.625
false
false
4
cf196c16ed43942cda61f91d0d6d8a09bcff8e1c
35,450,660,091,995
07baab13e41a13c0ff02f8241db59c30bce556d6
/rpi/src/test/java/cz/pojd/rpi/system/RuntimeExecutorImplTestCase.java
5ff0e8eb75d4c6ce4721819fccadd04bf1dbaef0
[ "MIT" ]
permissive
anhdenday/hawa
https://github.com/anhdenday/hawa
5a7c303a503a5c0167e668e9250e2214713e0446
e7353c87246b843263dd937a054bc396e43b96f3
refs/heads/master
2021-01-17T01:18:53.428000
2016-03-09T21:20:34
2016-03-09T21:20:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.pojd.rpi.system; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Iterator; import java.util.List; import mockit.Expectations; import mockit.Mock; import mockit.MockUp; import mockit.Mocked; import mockit.NonStrictExpectations; import org.junit.Before; import org.junit.Test; public class RuntimeExecutorImplTestCase { private RuntimeExecutorImpl runtimeExecutor; private Runtime runtime; @Mocked private Process process; @Mocked private InputStreamReader streamReader; @Mocked private BufferedReader bufferedReader; @Before public void setup() { runtime = Runtime.getRuntime(); runtimeExecutor = new RuntimeExecutorImpl(); runtimeExecutor.setRuntime(runtime); new MockUp<Runtime>() { @Mock public Process exec(String[] str) { assertEquals(3, str.length); assertEquals("Some command", str[2]); return process; } @Mock public int availableProcessors() { return 55; } }; new NonStrictExpectations() { { new BufferedReader(withInstanceOf(InputStreamReader.class)); result = bufferedReader; } }; } @Test public void testGetCpuCount() { new Expectations() { { runtime.availableProcessors(); } }; assertEquals(55, runtimeExecutor.getCpuCount()); } @Test public void testExecuteOneLineOK() throws IOException, InterruptedException { new NonStrictExpectations() { { bufferedReader.readLine(); // error stream first, then 1 line OK and null again to close it off returns(null, "12345", null); } }; List<Double> result = runtimeExecutor.executeDouble("Some command"); assertNotNull(result); Iterator<Double> it = result.iterator(); assertTrue(it.hasNext()); Double value = it.next(); assertEquals(12345., value.doubleValue(), 0.001); assertFalse(it.hasNext()); } @Test public void testExecuteMoreLinesOK() throws IOException, InterruptedException { new NonStrictExpectations() { { bufferedReader.readLine(); // error stream first, then 1 line OK and null again to close it off returns(null, "1", "2", "3.23", null); } }; List<Double> result = runtimeExecutor.executeDouble("Some command"); assertNotNull(result); Iterator<Double> it = result.iterator(); assertTrue(it.hasNext()); assertEquals(1., it.next().doubleValue(), 0.001); assertTrue(it.hasNext()); assertEquals(2., it.next().doubleValue(), 0.001); assertTrue(it.hasNext()); assertEquals(3.23, it.next().doubleValue(), 0.001); assertFalse(it.hasNext()); } @Test public void testExecuteError() throws IOException { new NonStrictExpectations() { { bufferedReader.readLine(); returns("Some error ocurred", null, null); } }; // error returned should force not to fail, but return empty list instead List<Double> result = runtimeExecutor.executeDouble("Some command"); assertTrue(result.isEmpty()); } }
UTF-8
Java
3,149
java
RuntimeExecutorImplTestCase.java
Java
[]
null
[]
package cz.pojd.rpi.system; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Iterator; import java.util.List; import mockit.Expectations; import mockit.Mock; import mockit.MockUp; import mockit.Mocked; import mockit.NonStrictExpectations; import org.junit.Before; import org.junit.Test; public class RuntimeExecutorImplTestCase { private RuntimeExecutorImpl runtimeExecutor; private Runtime runtime; @Mocked private Process process; @Mocked private InputStreamReader streamReader; @Mocked private BufferedReader bufferedReader; @Before public void setup() { runtime = Runtime.getRuntime(); runtimeExecutor = new RuntimeExecutorImpl(); runtimeExecutor.setRuntime(runtime); new MockUp<Runtime>() { @Mock public Process exec(String[] str) { assertEquals(3, str.length); assertEquals("Some command", str[2]); return process; } @Mock public int availableProcessors() { return 55; } }; new NonStrictExpectations() { { new BufferedReader(withInstanceOf(InputStreamReader.class)); result = bufferedReader; } }; } @Test public void testGetCpuCount() { new Expectations() { { runtime.availableProcessors(); } }; assertEquals(55, runtimeExecutor.getCpuCount()); } @Test public void testExecuteOneLineOK() throws IOException, InterruptedException { new NonStrictExpectations() { { bufferedReader.readLine(); // error stream first, then 1 line OK and null again to close it off returns(null, "12345", null); } }; List<Double> result = runtimeExecutor.executeDouble("Some command"); assertNotNull(result); Iterator<Double> it = result.iterator(); assertTrue(it.hasNext()); Double value = it.next(); assertEquals(12345., value.doubleValue(), 0.001); assertFalse(it.hasNext()); } @Test public void testExecuteMoreLinesOK() throws IOException, InterruptedException { new NonStrictExpectations() { { bufferedReader.readLine(); // error stream first, then 1 line OK and null again to close it off returns(null, "1", "2", "3.23", null); } }; List<Double> result = runtimeExecutor.executeDouble("Some command"); assertNotNull(result); Iterator<Double> it = result.iterator(); assertTrue(it.hasNext()); assertEquals(1., it.next().doubleValue(), 0.001); assertTrue(it.hasNext()); assertEquals(2., it.next().doubleValue(), 0.001); assertTrue(it.hasNext()); assertEquals(3.23, it.next().doubleValue(), 0.001); assertFalse(it.hasNext()); } @Test public void testExecuteError() throws IOException { new NonStrictExpectations() { { bufferedReader.readLine(); returns("Some error ocurred", null, null); } }; // error returned should force not to fail, but return empty list instead List<Double> result = runtimeExecutor.executeDouble("Some command"); assertTrue(result.isEmpty()); } }
3,149
0.710067
0.696094
125
24.191999
20.449234
83
false
false
0
0
0
0
0
0
1.36
false
false
4
a2281e241f0ea10cbfe13257c3cc6df16dee28af
34,823,594,851,139
7d505e3b8c84b4ced04be94656b30684aef2cb5a
/crawler-log-service/src/main/java/org/solar/crawlerlog/web/api/LogNotFoundExceptionAdvice.java
c5063c4fcca3ba6d95557a9ff1645450250509fc
[]
no_license
tadovas/homework
https://github.com/tadovas/homework
f91fd0eac50bb48196317d630c63de2426044245
68570c14d3baa2266e4e2751e18d30e787c60466
refs/heads/master
2021-07-10T03:09:29.890000
2017-10-05T13:43:02
2017-10-05T13:43:02
105,374,604
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.solar.crawlerlog.web.api; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.solar.crawlerlog.domain.service.CrawlerLogNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerAdvice public class LogNotFoundExceptionAdvice { private Logger logger = LoggerFactory.getLogger(this.getClass()); @ExceptionHandler(CrawlerLogNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public void handeException(CrawlerLogNotFoundException exception) { logger.error("Caught exception", exception); } }
UTF-8
Java
757
java
LogNotFoundExceptionAdvice.java
Java
[]
null
[]
package org.solar.crawlerlog.web.api; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.solar.crawlerlog.domain.service.CrawlerLogNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerAdvice public class LogNotFoundExceptionAdvice { private Logger logger = LoggerFactory.getLogger(this.getClass()); @ExceptionHandler(CrawlerLogNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public void handeException(CrawlerLogNotFoundException exception) { logger.error("Caught exception", exception); } }
757
0.832232
0.82959
22
33.409092
26.326031
71
false
false
0
0
0
0
0
0
0.5
false
false
4
7726311d5b38413312ff010e9cbdc458f9586b4d
37,082,747,638,619
9049eabb2562cd3e854781dea6bd0a5e395812d3
/sources/com/google/android/location/network/NetworkLocationProvider.java
178c20ab4a2542065592245da07d57ea0a809454
[]
no_license
Romern/gms_decompiled
https://github.com/Romern/gms_decompiled
4c75449feab97321da23ecbaac054c2303150076
a9c245404f65b8af456b7b3440f48d49313600ba
refs/heads/master
2022-07-17T23:22:00.441000
2020-05-17T18:26:16
2020-05-17T18:26:16
264,227,100
2
5
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.android.location.network; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.WorkSource; import com.android.location.provider.LocationProviderBase; import com.android.location.provider.ProviderPropertiesUnbundled; import com.android.location.provider.ProviderRequestUnbundled; /* compiled from: :com.google.android.gms@201515033@20.15.15 (120300-306758586) */ public class NetworkLocationProvider extends LocationProviderBase { /* renamed from: k */ private static final ProviderPropertiesUnbundled f150823k = ProviderPropertiesUnbundled.create(false, false, false, false, true, true, true, 1, 2); /* renamed from: a */ public final Context f150824a; /* renamed from: b */ public final Handler f150825b; /* renamed from: c */ public final aeri f150826c; /* renamed from: d */ public final bhca f150827d; /* renamed from: e */ public final bhbx f150828e = new bhbx(); /* renamed from: f */ public final aerh f150829f; /* renamed from: g */ public final aerc f150830g; /* renamed from: h */ public boolean f150831h = false; /* renamed from: i */ public ProviderRequestUnbundled f150832i = null; /* renamed from: j */ public WorkSource f150833j = null; /* renamed from: l */ private long f150834l = Long.MAX_VALUE; public NetworkLocationProvider(Context context) { super("NLP", f150823k); this.f150824a = context; this.f150825b = new adzt(Looper.getMainLooper()); this.f150826c = aeri.m52441e(context); this.f150827d = new bhca(context, new bgfe(this), this.f150825b.getLooper()); this.f150829f = new bgff(this); this.f150830g = new bgfg(this); } /* renamed from: a */ public final void mo70879a() { mo70880a(aeri.m52434a(this.f150824a)); } /* JADX WARNING: Removed duplicated region for block: B:29:0x0095 */ /* JADX WARNING: Removed duplicated region for block: B:32:? A[RETURN, SYNTHETIC] */ /* renamed from: b */ public final void mo70881b(boolean z) { long j; bxbi bxbi; boolean z2 = true; bmxy.m108600b(Looper.myLooper() == this.f150825b.getLooper()); ProviderRequestUnbundled providerRequestUnbundled = this.f150832i; if (providerRequestUnbundled != null) { long interval = providerRequestUnbundled.getInterval(); boolean z3 = interval > this.f150834l; this.f150834l = interval; if (interval < 20000) { interval = 20000; } if (this.f150831h) { long c = cesq.m138193c(); if (interval < c) { j = c; if (!z || !this.f150828e.mo63541a(j, z3)) { z2 = false; } Context context = this.f150824a; Intent intent = new Intent(); intent.setComponent(new ComponentName(context, "com.google.android.location.network.NetworkLocationService")); PendingIntent service = PendingIntent.getService(context, 0, intent, 134217728); bxbi = new bxbi(this.f150824a.getPackageName()); bxbi.mo73558c(z2); bxbi.mo73550a(j, j, service, "NetworkLocationProvider"); bxbi.mo73552a(this.f150833j); int i = Build.VERSION.SDK_INT; bxbi.mo73556b(this.f150832i.isLocationSettingsIgnored()); if (bxbi.mo73549a(this.f150824a) != null) { service.cancel(); return; } return; } } j = interval; z2 = false; Context context2 = this.f150824a; Intent intent2 = new Intent(); intent2.setComponent(new ComponentName(context2, "com.google.android.location.network.NetworkLocationService")); PendingIntent service2 = PendingIntent.getService(context2, 0, intent2, 134217728); bxbi = new bxbi(this.f150824a.getPackageName()); bxbi.mo73558c(z2); bxbi.mo73550a(j, j, service2, "NetworkLocationProvider"); bxbi.mo73552a(this.f150833j); int i2 = Build.VERSION.SDK_INT; try { bxbi.mo73556b(this.f150832i.isLocationSettingsIgnored()); } catch (NoSuchMethodError e) { } if (bxbi.mo73549a(this.f150824a) != null) { } } } public final void onDisable() { } public final void onEnable() { int i = Build.VERSION.SDK_INT; } public final int onGetStatus(Bundle bundle) { return 2; } public final long onGetStatusUpdateTime() { return 0; } /* access modifiers changed from: protected */ public final void onInit() { this.f150825b.post(new bgfh(this)); } public final void onSetRequest(ProviderRequestUnbundled providerRequestUnbundled, WorkSource workSource) { this.f150825b.post(new bgfi(this, providerRequestUnbundled, workSource)); } /* renamed from: a */ public final void mo70880a(boolean z) { bmxy.m108600b(Looper.myLooper() == this.f150825b.getLooper()); setEnabled(z); } public final void setEnabled(boolean z) { int i = Build.VERSION.SDK_INT; try { NetworkLocationProvider.super.setEnabled(z); } catch (NoSuchMethodError e) { if (z) { int i2 = Build.VERSION.SDK_INT; return; } sdo.m34959a(aerk.ALLOWED); int i3 = Build.VERSION.SDK_INT; throw new UnsupportedOperationException("providers may not be controlled from Q and above"); } } }
UTF-8
Java
6,101
java
NetworkLocationProvider.java
Java
[]
null
[]
package com.google.android.location.network; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.WorkSource; import com.android.location.provider.LocationProviderBase; import com.android.location.provider.ProviderPropertiesUnbundled; import com.android.location.provider.ProviderRequestUnbundled; /* compiled from: :com.google.android.gms@201515033@20.15.15 (120300-306758586) */ public class NetworkLocationProvider extends LocationProviderBase { /* renamed from: k */ private static final ProviderPropertiesUnbundled f150823k = ProviderPropertiesUnbundled.create(false, false, false, false, true, true, true, 1, 2); /* renamed from: a */ public final Context f150824a; /* renamed from: b */ public final Handler f150825b; /* renamed from: c */ public final aeri f150826c; /* renamed from: d */ public final bhca f150827d; /* renamed from: e */ public final bhbx f150828e = new bhbx(); /* renamed from: f */ public final aerh f150829f; /* renamed from: g */ public final aerc f150830g; /* renamed from: h */ public boolean f150831h = false; /* renamed from: i */ public ProviderRequestUnbundled f150832i = null; /* renamed from: j */ public WorkSource f150833j = null; /* renamed from: l */ private long f150834l = Long.MAX_VALUE; public NetworkLocationProvider(Context context) { super("NLP", f150823k); this.f150824a = context; this.f150825b = new adzt(Looper.getMainLooper()); this.f150826c = aeri.m52441e(context); this.f150827d = new bhca(context, new bgfe(this), this.f150825b.getLooper()); this.f150829f = new bgff(this); this.f150830g = new bgfg(this); } /* renamed from: a */ public final void mo70879a() { mo70880a(aeri.m52434a(this.f150824a)); } /* JADX WARNING: Removed duplicated region for block: B:29:0x0095 */ /* JADX WARNING: Removed duplicated region for block: B:32:? A[RETURN, SYNTHETIC] */ /* renamed from: b */ public final void mo70881b(boolean z) { long j; bxbi bxbi; boolean z2 = true; bmxy.m108600b(Looper.myLooper() == this.f150825b.getLooper()); ProviderRequestUnbundled providerRequestUnbundled = this.f150832i; if (providerRequestUnbundled != null) { long interval = providerRequestUnbundled.getInterval(); boolean z3 = interval > this.f150834l; this.f150834l = interval; if (interval < 20000) { interval = 20000; } if (this.f150831h) { long c = cesq.m138193c(); if (interval < c) { j = c; if (!z || !this.f150828e.mo63541a(j, z3)) { z2 = false; } Context context = this.f150824a; Intent intent = new Intent(); intent.setComponent(new ComponentName(context, "com.google.android.location.network.NetworkLocationService")); PendingIntent service = PendingIntent.getService(context, 0, intent, 134217728); bxbi = new bxbi(this.f150824a.getPackageName()); bxbi.mo73558c(z2); bxbi.mo73550a(j, j, service, "NetworkLocationProvider"); bxbi.mo73552a(this.f150833j); int i = Build.VERSION.SDK_INT; bxbi.mo73556b(this.f150832i.isLocationSettingsIgnored()); if (bxbi.mo73549a(this.f150824a) != null) { service.cancel(); return; } return; } } j = interval; z2 = false; Context context2 = this.f150824a; Intent intent2 = new Intent(); intent2.setComponent(new ComponentName(context2, "com.google.android.location.network.NetworkLocationService")); PendingIntent service2 = PendingIntent.getService(context2, 0, intent2, 134217728); bxbi = new bxbi(this.f150824a.getPackageName()); bxbi.mo73558c(z2); bxbi.mo73550a(j, j, service2, "NetworkLocationProvider"); bxbi.mo73552a(this.f150833j); int i2 = Build.VERSION.SDK_INT; try { bxbi.mo73556b(this.f150832i.isLocationSettingsIgnored()); } catch (NoSuchMethodError e) { } if (bxbi.mo73549a(this.f150824a) != null) { } } } public final void onDisable() { } public final void onEnable() { int i = Build.VERSION.SDK_INT; } public final int onGetStatus(Bundle bundle) { return 2; } public final long onGetStatusUpdateTime() { return 0; } /* access modifiers changed from: protected */ public final void onInit() { this.f150825b.post(new bgfh(this)); } public final void onSetRequest(ProviderRequestUnbundled providerRequestUnbundled, WorkSource workSource) { this.f150825b.post(new bgfi(this, providerRequestUnbundled, workSource)); } /* renamed from: a */ public final void mo70880a(boolean z) { bmxy.m108600b(Looper.myLooper() == this.f150825b.getLooper()); setEnabled(z); } public final void setEnabled(boolean z) { int i = Build.VERSION.SDK_INT; try { NetworkLocationProvider.super.setEnabled(z); } catch (NoSuchMethodError e) { if (z) { int i2 = Build.VERSION.SDK_INT; return; } sdo.m34959a(aerk.ALLOWED); int i3 = Build.VERSION.SDK_INT; throw new UnsupportedOperationException("providers may not be controlled from Q and above"); } } }
6,101
0.598263
0.526307
174
34.063217
27.723627
151
false
false
0
0
0
0
0
0
0.666667
false
false
4
7f530d4d04203568df021d72112e6f98c326c034
8,272,107,078,094
9b21279fb5cd00166fc0e0c86ab6e9a5e922a847
/src/test/java/com/workscape/vehicleidentifier/VehicleIdentifierTestTest.java
e3fb7a5f1740bbbe059556e6ac66cd3b528f1b27
[]
no_license
malviyarahuljayendra/vehicleIdentifier_adp
https://github.com/malviyarahuljayendra/vehicleIdentifier_adp
fd2d3d4fc1ce4a47c6b7bdae5ee742a60db4fc1b
b7664e1fa823b14c2b6ed6f10edf559d626ffc54
refs/heads/master
2021-01-22T19:03:59.604000
2017-03-16T04:15:29
2017-03-16T04:15:29
85,151,275
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.workscape.vehicleidentifier; import static junit.framework.Assert.fail; import org.junit.Test; /** * Unit test for simple App. */ public class VehicleIdentifierTestTest { /** * Rigorous Test :-) */ @Test public void testApp() { fail("Replace me with tests"); } }
UTF-8
Java
292
java
VehicleIdentifierTestTest.java
Java
[]
null
[]
package com.workscape.vehicleidentifier; import static junit.framework.Assert.fail; import org.junit.Test; /** * Unit test for simple App. */ public class VehicleIdentifierTestTest { /** * Rigorous Test :-) */ @Test public void testApp() { fail("Replace me with tests"); } }
292
0.688356
0.688356
20
13.6
15.272197
42
false
false
0
0
0
0
0
0
0.6
false
false
4
e96d3f4006f0f4db12d1e649168df3b7912c467c
37,761,352,480,020
8b8f5d8da9df7641a1690f8d06ec96e277006db1
/Web/src/main/java/by/gourianova/apptrainer/action/user/AddMoneyAction.java
aaca2d029d082ee3566fae241d8f8476c209c37a
[]
no_license
cscTournament/AppTrainer
https://github.com/cscTournament/AppTrainer
852272bcd4d1ff1e3e16cc7da4ea7d27c8fb9700
dc8b9556ea891b1375b2b92a8aad819f5234e10c
refs/heads/main
2023-04-05T16:13:54.093000
2021-04-28T19:30:35
2021-04-28T19:30:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.gourianova.apptrainer.action.user; import by.gourianova.apptrainer.action.Action; import by.gourianova.apptrainer.controller.Router; import by.gourianova.apptrainer.entity.Role; import by.gourianova.apptrainer.entity.User; import by.gourianova.apptrainer.exception.ServiceException; import by.gourianova.apptrainer.service.RoleService; import by.gourianova.apptrainer.service.UserService; import by.gourianova.apptrainer.util.PageConstant; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import static by.gourianova.apptrainer.util.PageConstant.ONE_USER; //import static jdk.nashorn.internal.runtime.regexp.joni.Config.log; public class AddMoneyAction implements Action { private final static String USER_BALANCE = "balance"; // private final static String USER = "user"; private final static String USER_ID = "userId"; private final static String MESSAGE = "message"; private final static String USER = "userOne"; private final static String ROLES_LIST = "rolesList"; private UserService userService = new UserService(); private RoleService roleService = new RoleService(); @Override public Router execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Router router = new Router(); // User user = (User) request.getSession().getAttribute(USER); BigDecimal balance = new BigDecimal(request.getParameter(USER_BALANCE)); int userId = Integer.parseInt(request.getParameter(USER_ID)); try { User user = userService.findUserById(userId); user = userService.updateBalance(user, balance); request.getSession().setAttribute(USER, user); // ArrayList<Role> rolesList; // rolesList = roleService.findAll(); // request.setAttribute(ROLES_LIST, rolesList); userService.updateUser(user); ArrayList<Role> rolesList; rolesList = roleService.findAll(); request.setAttribute(ROLES_LIST, rolesList); RequestDispatcher requestDispatcher = request.getRequestDispatcher(ONE_USER); requestDispatcher.forward(request, response); router.setPagePath(ONE_USER); router.setRoute(Router.RouteType.REDIRECT); } catch (ServiceException e) { request.getSession().setAttribute(MESSAGE, e.getMessage()); router.setPagePath(PageConstant.ERROR_PAGE); router.setRoute(Router.RouteType.REDIRECT); } return router; } }
UTF-8
Java
2,831
java
AddMoneyAction.java
Java
[ { "context": "ce\";\r\n // private final static String USER = \"user\";\r\n private final static String USER_ID = \"use", "end": 1028, "score": 0.987590491771698, "start": 1024, "tag": "USERNAME", "value": "user" }, { "context": "essage\";\r\n private final static String USER = \"userOne\";\r\n private final static String ROLES_LIST = \"", "end": 1186, "score": 0.9991708993911743, "start": 1179, "tag": "USERNAME", "value": "userOne" } ]
null
[]
package by.gourianova.apptrainer.action.user; import by.gourianova.apptrainer.action.Action; import by.gourianova.apptrainer.controller.Router; import by.gourianova.apptrainer.entity.Role; import by.gourianova.apptrainer.entity.User; import by.gourianova.apptrainer.exception.ServiceException; import by.gourianova.apptrainer.service.RoleService; import by.gourianova.apptrainer.service.UserService; import by.gourianova.apptrainer.util.PageConstant; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import static by.gourianova.apptrainer.util.PageConstant.ONE_USER; //import static jdk.nashorn.internal.runtime.regexp.joni.Config.log; public class AddMoneyAction implements Action { private final static String USER_BALANCE = "balance"; // private final static String USER = "user"; private final static String USER_ID = "userId"; private final static String MESSAGE = "message"; private final static String USER = "userOne"; private final static String ROLES_LIST = "rolesList"; private UserService userService = new UserService(); private RoleService roleService = new RoleService(); @Override public Router execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Router router = new Router(); // User user = (User) request.getSession().getAttribute(USER); BigDecimal balance = new BigDecimal(request.getParameter(USER_BALANCE)); int userId = Integer.parseInt(request.getParameter(USER_ID)); try { User user = userService.findUserById(userId); user = userService.updateBalance(user, balance); request.getSession().setAttribute(USER, user); // ArrayList<Role> rolesList; // rolesList = roleService.findAll(); // request.setAttribute(ROLES_LIST, rolesList); userService.updateUser(user); ArrayList<Role> rolesList; rolesList = roleService.findAll(); request.setAttribute(ROLES_LIST, rolesList); RequestDispatcher requestDispatcher = request.getRequestDispatcher(ONE_USER); requestDispatcher.forward(request, response); router.setPagePath(ONE_USER); router.setRoute(Router.RouteType.REDIRECT); } catch (ServiceException e) { request.getSession().setAttribute(MESSAGE, e.getMessage()); router.setPagePath(PageConstant.ERROR_PAGE); router.setRoute(Router.RouteType.REDIRECT); } return router; } }
2,831
0.705404
0.705404
62
43.661289
23.755436
122
false
false
0
0
0
0
0
0
0.903226
false
false
4
e4958abd887ba1cbc1f8fc38ca0a11bfc6e052ce
34,376,918,275,655
9507f740bf3570d5365fbbf7661ad43a5956e06d
/app/src/main/java/com/StartupBBSR/competo/Activity/TeamChatDetailActivity.java
61607c5e636d50e58f79dc07fa0e63eb5fa70a6b
[]
no_license
Aayush-Vats/Competo
https://github.com/Aayush-Vats/Competo
caa3f1f8e20c43bcde94683a23aaa484790c07f9
35ca7bdc04750e4e7611a0d8536ba5e547491611
refs/heads/master
2023-06-27T00:09:01.645000
2021-07-30T09:00:51
2021-07-30T09:00:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.StartupBBSR.competo.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.StartupBBSR.competo.Adapters.TeamChatAdapter; import com.StartupBBSR.competo.Fragments.AddTeamBottomSheetDialog; import com.StartupBBSR.competo.Models.EventPalModel; import com.StartupBBSR.competo.Models.TeamMessageModel; import com.StartupBBSR.competo.R; import com.StartupBBSR.competo.Utils.Constant; import com.StartupBBSR.competo.databinding.ActivityTeamChatDetailBinding; import com.StartupBBSR.competo.databinding.ViewmembersAlertLayoutBinding; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FieldValue; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Date; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class TeamChatDetailActivity extends AppCompatActivity implements AddTeamBottomSheetDialog.AddMemberBottomSheetListener { private ActivityTeamChatDetailBinding binding; private String teamName, teamImage, teamID, teamCreatorID; private List<String> teamMembers; private TeamMessageModel teamMessageModel; private Constant constant; private FirebaseAuth firebaseAuth; private FirebaseFirestore firestoreDB; private String userID, userName; private final int limit = 15; private DocumentSnapshot lastVisible; private boolean isScrolling = false; private boolean isLastItemReached = false; private TeamChatAdapter teamChatAdapter; private RecyclerView recyclerView; private List<TeamMessageModel> mMessage; private CollectionReference collectionReference; private DocumentReference teamReference, documentReference; private List<String> memberNameList = new ArrayList<>(); private ArrayAdapter<String> memberNameListAdapter; private ListView memberNameListView; private AddTeamBottomSheetDialog addTeamBottomSheetDialog; public static final String TAG = "teamChat"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityTeamChatDetailBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); firebaseAuth = FirebaseAuth.getInstance(); firestoreDB = FirebaseFirestore.getInstance(); userID = firebaseAuth.getUid(); constant = new Constant(); teamName = getIntent().getStringExtra("teamName"); teamImage = getIntent().getStringExtra("teamImage"); teamID = getIntent().getStringExtra("teamID"); teamCreatorID = getIntent().getStringExtra("teamCreatorID"); teamMembers = getIntent().getStringArrayListExtra("teamMembers"); updateTeamInfo(teamName, teamImage); collectionReference = firestoreDB.collection(constant.getTeamChats()) .document(teamID) .collection(constant.getTeamMessages()); teamReference = firestoreDB.collection(constant.getTeams()).document(teamID); documentReference = firestoreDB.collection(constant.getUsers()).document(userID); documentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot snapshot = task.getResult(); if (snapshot.exists()) { userName = snapshot.getString(constant.getUserNameField()); } } } }); // Loading the creator name into the toolbar DocumentReference adminDocRef = firestoreDB.collection(constant.getUsers()).document(teamCreatorID); adminDocRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot snapshot = task.getResult(); if (snapshot.exists()) { binding.teamCreatorName.setText("Created by " + snapshot.getString(constant.getUserNameField())); } } } }); getTeamUpdates(); status("Online"); binding.btnSendChat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!binding.etMessage.getText().toString().equals("")) { String message = binding.etMessage.getText().toString().trim(); String messageID = collectionReference.document().getId(); String senderID = userID; String senderName = userName; long messageTime = new Date().getTime(); teamMessageModel = new TeamMessageModel(message, messageID, senderID, senderName, messageTime); binding.etMessage.setText(""); collectionReference.document(messageID).set(teamMessageModel) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { // Message sent } }); } } }); // Setting the menu. /*if (teamCreatorID.equals(userID)) { binding.toolbar2.getMenu().add(Menu.NONE, 1, Menu.NONE, "Add Members"); }*/ binding.toolbar2.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.viewMembers: viewMembers(); return true; case R.id.exitTeam: exitTeam(); return true; /*case 1: addMembers(); return true;*/ default: return false; } } }); /*initData(); initRecyclerview();*/ initNewRecycler(); getMembers(); } private void updateTeamInfo(String teamName, String teamImage) { binding.teamName.setText(teamName); if (teamImage != null){ Glide.with(getApplicationContext()).load(Uri.parse(teamImage)).into(binding.teamImage); } else { Glide.with(getApplicationContext()) .load(R.drawable.ic_baseline_person_24) .into(binding.teamImage); } } private void getTeamUpdates() { teamReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { if (error != null) { return; } String teamName = value.getString("teamName"); String teamImage = value.getString("teamImage"); teamMembers = (List<String>) value.get("teamMembers"); updateTeamInfo(teamName, teamImage); } }); } /* private void initData() { Query query = collectionReference.orderBy("timestamp"); options = new FirestoreRecyclerOptions.Builder<TeamMessageModel>() .setQuery(query, TeamMessageModel.class) .build(); } private void initRecyclerview() { RecyclerView chatRecyclerView = binding.teamChatRecyclerView; chatRecyclerView.setLayoutManager(new LinearLayoutManager(this)); chatRecyclerView.setHasFixedSize(true); adapter = new TeamChatAdapter(options, this); chatRecyclerView.setAdapter(adapter); } */ private void initNewRecycler() { recyclerView = binding.teamChatRecyclerView; recyclerView.setHasFixedSize(true); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); linearLayoutManager.setStackFromEnd(false); linearLayoutManager.setReverseLayout(true); recyclerView.setLayoutManager(linearLayoutManager); } private void readMessage() { mMessage = new ArrayList<>(); collectionReference.orderBy("timestamp", Query.Direction.DESCENDING).limit(limit) .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { mMessage.clear(); for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots) { TeamMessageModel model = snapshot.toObject(TeamMessageModel.class); mMessage.add(model); teamChatAdapter = new TeamChatAdapter(TeamChatDetailActivity.this, mMessage); recyclerView.setAdapter(teamChatAdapter); // Pagination lastVisible = queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1); RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { isScrolling = true; } } @Override public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); LinearLayoutManager linearLayoutManager = ((LinearLayoutManager) recyclerView.getLayoutManager()); int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition(); int visibleItemCount = linearLayoutManager.getChildCount(); int totalItemCount = linearLayoutManager.getItemCount(); if (isScrolling && (firstVisibleItemPosition + visibleItemCount == totalItemCount) && !isLastItemReached) { isScrolling = false; Query nextQuery = collectionReference.orderBy("timestamp", Query.Direction.DESCENDING).startAfter(lastVisible).limit(limit); nextQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> t) { if (t.isSuccessful()) { for (DocumentSnapshot d : t.getResult()) { TeamMessageModel messageModel = d.toObject(TeamMessageModel.class); mMessage.add(messageModel); } teamChatAdapter.notifyDataSetChanged(); if (t.getResult().size() - 1 >= 0) { lastVisible = t.getResult().getDocuments().get(t.getResult().size() - 1); } if (t.getResult().size() < limit) { isLastItemReached = true; } } } }); } } }; recyclerView.addOnScrollListener(onScrollListener); } } }); } private void getMembers() { for (String id : teamMembers) { DocumentReference documentReference = firestoreDB.collection(constant.getUsers()).document(id); documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot snapshot) { if (snapshot.exists()) { memberNameList.add(snapshot.getString(constant.getUserNameField())); } } }); } } private void viewMembers() { AlertDialog.Builder builder = new AlertDialog.Builder(TeamChatDetailActivity.this); builder.setTitle("Team members"); ViewmembersAlertLayoutBinding viewmembersAlertLayoutBinding = ViewmembersAlertLayoutBinding.inflate(getLayoutInflater()); View view = viewmembersAlertLayoutBinding.getRoot(); memberNameListView = viewmembersAlertLayoutBinding.membersListView; memberNameListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, memberNameList); memberNameListView.setAdapter(memberNameListAdapter); memberNameListAdapter.notifyDataSetChanged(); builder.setView(view); builder.show(); } private void exitTeam() { AlertDialog.Builder builder = new AlertDialog.Builder(TeamChatDetailActivity.this); builder.setTitle("Exit Team"); builder.setMessage("Are you sure to exit the team?\n-You will not be able to access or read previous messages"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ProgressDialog dialog = new ProgressDialog(TeamChatDetailActivity.this); dialog.setMessage("Exiting..."); dialog.show(); DocumentReference connectionRef = firestoreDB.collection(constant.getChatConnections()).document(userID); connectionRef.update(constant.getTeamConnections(), FieldValue.arrayRemove(teamID)) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { DocumentReference teamRef = firestoreDB.collection(constant.getTeams()).document(teamID); teamRef.update(constant.getTeamMemberField(), FieldValue.arrayRemove(userID)) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(TeamChatDetailActivity.this, "Exit Successful", Toast.LENGTH_SHORT).show(); dialog.dismiss(); finish(); } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { dialog.dismiss(); Toast.makeText(TeamChatDetailActivity.this, "Exit Failed", Toast.LENGTH_SHORT).show(); } }); } }).setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }).show(); } private void addMembers() { ProgressDialog dialog = new ProgressDialog(TeamChatDetailActivity.this); dialog.setMessage("Loading"); dialog.show(); firestoreDB.collection(constant.getTeams()).document(teamID) .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull @NotNull Task<DocumentSnapshot> task) { DocumentSnapshot snapshot = task.getResult(); List<String> membersIDs = (List<String>) snapshot.get("teamMembers"); Log.d(TAG, "onComplete: " + membersIDs); dialog.dismiss(); if (membersIDs.size() < 6) { addTeamBottomSheetDialog = new AddTeamBottomSheetDialog(TeamChatDetailActivity.this, membersIDs); addTeamBottomSheetDialog.show(getSupportFragmentManager(), "AddMemberBottomSheet"); } else { Toast.makeText(TeamChatDetailActivity.this, "Cannot add more members", Toast.LENGTH_SHORT).show(); } } }); } @Override protected void onStart() { super.onStart(); collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) { if (error != null) { Log.e("error", "onEvent: ", error); return; } readMessage(); } }); } @Override protected void onPause() { super.onPause(); status("Offline"); Log.d("status", "onPauseChat: Offline"); } @Override protected void onResume() { super.onResume(); status("Online"); Log.d("status", "onResumeChat: Online"); } private void status(String status) { documentReference.update("status", status); } @Override public void onAddMembersButtonClicked(List<EventPalModel> selectedMembers) { CollectionReference teamCollectionRef = firestoreDB.collection(constant.getChatConnections()); for (EventPalModel model : selectedMembers) { // Updating team members list teamReference.update("teamMembers", FieldValue.arrayUnion(model.getUserID())); // Updating chat connection teamCollectionRef.document(model.getUserID()).update(constant.getTeamConnections(), FieldValue.arrayUnion(teamID)); Toast.makeText(TeamChatDetailActivity.this, "Team Updated", Toast.LENGTH_SHORT).show(); } } }
UTF-8
Java
20,289
java
TeamChatDetailActivity.java
Java
[ { "context": " = userID;\n String senderName = userName;\n long messageTime = new Date(", "end": 6156, "score": 0.9922849535942078, "start": 6148, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.StartupBBSR.competo.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.StartupBBSR.competo.Adapters.TeamChatAdapter; import com.StartupBBSR.competo.Fragments.AddTeamBottomSheetDialog; import com.StartupBBSR.competo.Models.EventPalModel; import com.StartupBBSR.competo.Models.TeamMessageModel; import com.StartupBBSR.competo.R; import com.StartupBBSR.competo.Utils.Constant; import com.StartupBBSR.competo.databinding.ActivityTeamChatDetailBinding; import com.StartupBBSR.competo.databinding.ViewmembersAlertLayoutBinding; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FieldValue; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Date; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class TeamChatDetailActivity extends AppCompatActivity implements AddTeamBottomSheetDialog.AddMemberBottomSheetListener { private ActivityTeamChatDetailBinding binding; private String teamName, teamImage, teamID, teamCreatorID; private List<String> teamMembers; private TeamMessageModel teamMessageModel; private Constant constant; private FirebaseAuth firebaseAuth; private FirebaseFirestore firestoreDB; private String userID, userName; private final int limit = 15; private DocumentSnapshot lastVisible; private boolean isScrolling = false; private boolean isLastItemReached = false; private TeamChatAdapter teamChatAdapter; private RecyclerView recyclerView; private List<TeamMessageModel> mMessage; private CollectionReference collectionReference; private DocumentReference teamReference, documentReference; private List<String> memberNameList = new ArrayList<>(); private ArrayAdapter<String> memberNameListAdapter; private ListView memberNameListView; private AddTeamBottomSheetDialog addTeamBottomSheetDialog; public static final String TAG = "teamChat"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityTeamChatDetailBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); firebaseAuth = FirebaseAuth.getInstance(); firestoreDB = FirebaseFirestore.getInstance(); userID = firebaseAuth.getUid(); constant = new Constant(); teamName = getIntent().getStringExtra("teamName"); teamImage = getIntent().getStringExtra("teamImage"); teamID = getIntent().getStringExtra("teamID"); teamCreatorID = getIntent().getStringExtra("teamCreatorID"); teamMembers = getIntent().getStringArrayListExtra("teamMembers"); updateTeamInfo(teamName, teamImage); collectionReference = firestoreDB.collection(constant.getTeamChats()) .document(teamID) .collection(constant.getTeamMessages()); teamReference = firestoreDB.collection(constant.getTeams()).document(teamID); documentReference = firestoreDB.collection(constant.getUsers()).document(userID); documentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot snapshot = task.getResult(); if (snapshot.exists()) { userName = snapshot.getString(constant.getUserNameField()); } } } }); // Loading the creator name into the toolbar DocumentReference adminDocRef = firestoreDB.collection(constant.getUsers()).document(teamCreatorID); adminDocRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot snapshot = task.getResult(); if (snapshot.exists()) { binding.teamCreatorName.setText("Created by " + snapshot.getString(constant.getUserNameField())); } } } }); getTeamUpdates(); status("Online"); binding.btnSendChat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!binding.etMessage.getText().toString().equals("")) { String message = binding.etMessage.getText().toString().trim(); String messageID = collectionReference.document().getId(); String senderID = userID; String senderName = userName; long messageTime = new Date().getTime(); teamMessageModel = new TeamMessageModel(message, messageID, senderID, senderName, messageTime); binding.etMessage.setText(""); collectionReference.document(messageID).set(teamMessageModel) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { // Message sent } }); } } }); // Setting the menu. /*if (teamCreatorID.equals(userID)) { binding.toolbar2.getMenu().add(Menu.NONE, 1, Menu.NONE, "Add Members"); }*/ binding.toolbar2.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.viewMembers: viewMembers(); return true; case R.id.exitTeam: exitTeam(); return true; /*case 1: addMembers(); return true;*/ default: return false; } } }); /*initData(); initRecyclerview();*/ initNewRecycler(); getMembers(); } private void updateTeamInfo(String teamName, String teamImage) { binding.teamName.setText(teamName); if (teamImage != null){ Glide.with(getApplicationContext()).load(Uri.parse(teamImage)).into(binding.teamImage); } else { Glide.with(getApplicationContext()) .load(R.drawable.ic_baseline_person_24) .into(binding.teamImage); } } private void getTeamUpdates() { teamReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { if (error != null) { return; } String teamName = value.getString("teamName"); String teamImage = value.getString("teamImage"); teamMembers = (List<String>) value.get("teamMembers"); updateTeamInfo(teamName, teamImage); } }); } /* private void initData() { Query query = collectionReference.orderBy("timestamp"); options = new FirestoreRecyclerOptions.Builder<TeamMessageModel>() .setQuery(query, TeamMessageModel.class) .build(); } private void initRecyclerview() { RecyclerView chatRecyclerView = binding.teamChatRecyclerView; chatRecyclerView.setLayoutManager(new LinearLayoutManager(this)); chatRecyclerView.setHasFixedSize(true); adapter = new TeamChatAdapter(options, this); chatRecyclerView.setAdapter(adapter); } */ private void initNewRecycler() { recyclerView = binding.teamChatRecyclerView; recyclerView.setHasFixedSize(true); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); linearLayoutManager.setStackFromEnd(false); linearLayoutManager.setReverseLayout(true); recyclerView.setLayoutManager(linearLayoutManager); } private void readMessage() { mMessage = new ArrayList<>(); collectionReference.orderBy("timestamp", Query.Direction.DESCENDING).limit(limit) .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { mMessage.clear(); for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots) { TeamMessageModel model = snapshot.toObject(TeamMessageModel.class); mMessage.add(model); teamChatAdapter = new TeamChatAdapter(TeamChatDetailActivity.this, mMessage); recyclerView.setAdapter(teamChatAdapter); // Pagination lastVisible = queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1); RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { isScrolling = true; } } @Override public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); LinearLayoutManager linearLayoutManager = ((LinearLayoutManager) recyclerView.getLayoutManager()); int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition(); int visibleItemCount = linearLayoutManager.getChildCount(); int totalItemCount = linearLayoutManager.getItemCount(); if (isScrolling && (firstVisibleItemPosition + visibleItemCount == totalItemCount) && !isLastItemReached) { isScrolling = false; Query nextQuery = collectionReference.orderBy("timestamp", Query.Direction.DESCENDING).startAfter(lastVisible).limit(limit); nextQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> t) { if (t.isSuccessful()) { for (DocumentSnapshot d : t.getResult()) { TeamMessageModel messageModel = d.toObject(TeamMessageModel.class); mMessage.add(messageModel); } teamChatAdapter.notifyDataSetChanged(); if (t.getResult().size() - 1 >= 0) { lastVisible = t.getResult().getDocuments().get(t.getResult().size() - 1); } if (t.getResult().size() < limit) { isLastItemReached = true; } } } }); } } }; recyclerView.addOnScrollListener(onScrollListener); } } }); } private void getMembers() { for (String id : teamMembers) { DocumentReference documentReference = firestoreDB.collection(constant.getUsers()).document(id); documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot snapshot) { if (snapshot.exists()) { memberNameList.add(snapshot.getString(constant.getUserNameField())); } } }); } } private void viewMembers() { AlertDialog.Builder builder = new AlertDialog.Builder(TeamChatDetailActivity.this); builder.setTitle("Team members"); ViewmembersAlertLayoutBinding viewmembersAlertLayoutBinding = ViewmembersAlertLayoutBinding.inflate(getLayoutInflater()); View view = viewmembersAlertLayoutBinding.getRoot(); memberNameListView = viewmembersAlertLayoutBinding.membersListView; memberNameListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, memberNameList); memberNameListView.setAdapter(memberNameListAdapter); memberNameListAdapter.notifyDataSetChanged(); builder.setView(view); builder.show(); } private void exitTeam() { AlertDialog.Builder builder = new AlertDialog.Builder(TeamChatDetailActivity.this); builder.setTitle("Exit Team"); builder.setMessage("Are you sure to exit the team?\n-You will not be able to access or read previous messages"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ProgressDialog dialog = new ProgressDialog(TeamChatDetailActivity.this); dialog.setMessage("Exiting..."); dialog.show(); DocumentReference connectionRef = firestoreDB.collection(constant.getChatConnections()).document(userID); connectionRef.update(constant.getTeamConnections(), FieldValue.arrayRemove(teamID)) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { DocumentReference teamRef = firestoreDB.collection(constant.getTeams()).document(teamID); teamRef.update(constant.getTeamMemberField(), FieldValue.arrayRemove(userID)) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(TeamChatDetailActivity.this, "Exit Successful", Toast.LENGTH_SHORT).show(); dialog.dismiss(); finish(); } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { dialog.dismiss(); Toast.makeText(TeamChatDetailActivity.this, "Exit Failed", Toast.LENGTH_SHORT).show(); } }); } }).setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }).show(); } private void addMembers() { ProgressDialog dialog = new ProgressDialog(TeamChatDetailActivity.this); dialog.setMessage("Loading"); dialog.show(); firestoreDB.collection(constant.getTeams()).document(teamID) .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull @NotNull Task<DocumentSnapshot> task) { DocumentSnapshot snapshot = task.getResult(); List<String> membersIDs = (List<String>) snapshot.get("teamMembers"); Log.d(TAG, "onComplete: " + membersIDs); dialog.dismiss(); if (membersIDs.size() < 6) { addTeamBottomSheetDialog = new AddTeamBottomSheetDialog(TeamChatDetailActivity.this, membersIDs); addTeamBottomSheetDialog.show(getSupportFragmentManager(), "AddMemberBottomSheet"); } else { Toast.makeText(TeamChatDetailActivity.this, "Cannot add more members", Toast.LENGTH_SHORT).show(); } } }); } @Override protected void onStart() { super.onStart(); collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) { if (error != null) { Log.e("error", "onEvent: ", error); return; } readMessage(); } }); } @Override protected void onPause() { super.onPause(); status("Offline"); Log.d("status", "onPauseChat: Offline"); } @Override protected void onResume() { super.onResume(); status("Online"); Log.d("status", "onResumeChat: Online"); } private void status(String status) { documentReference.update("status", status); } @Override public void onAddMembersButtonClicked(List<EventPalModel> selectedMembers) { CollectionReference teamCollectionRef = firestoreDB.collection(constant.getChatConnections()); for (EventPalModel model : selectedMembers) { // Updating team members list teamReference.update("teamMembers", FieldValue.arrayUnion(model.getUserID())); // Updating chat connection teamCollectionRef.document(model.getUserID()).update(constant.getTeamConnections(), FieldValue.arrayUnion(teamID)); Toast.makeText(TeamChatDetailActivity.this, "Team Updated", Toast.LENGTH_SHORT).show(); } } }
20,289
0.596037
0.595347
478
41.447701
33.631531
156
false
false
0
0
0
0
0
0
0.575314
false
false
4
e421bfa0857a27a58644b123d43eb59221dcc593
12,017,318,560,314
b8704edf4d1fe7dd27667fdfb4bfa2064a736e14
/DesignPattern/app/src/main/java/com/example/designpattern/FacadePattern/MainFacadePattern.java
e44069b1f4061670ae6e70bdecd2caa7ae4c7945
[]
no_license
philong07712/AndroidWorking
https://github.com/philong07712/AndroidWorking
1d52101f86ebefc47735ba631cea482dc3c04f8f
3f52a7f8b06edf0938d1ff439195bb26a79a43a9
refs/heads/master
2022-04-17T22:58:35.685000
2020-04-19T16:55:28
2020-04-19T16:55:28
254,662,655
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.designpattern.FacadePattern; import android.util.Log; import com.example.designpattern.IPattern; public class MainFacadePattern implements IPattern { public static final String FACADETAG = "FacadePattern"; @Override public void run() { BankFacade bank = new BankFacade(12345678,1234); bank.deposit(1000); bank.withdraw(30); bank.withdraw(900); Log.d(FACADETAG, Double.toString(bank.getAccountMoney())); } }
UTF-8
Java
486
java
MainFacadePattern.java
Java
[]
null
[]
package com.example.designpattern.FacadePattern; import android.util.Log; import com.example.designpattern.IPattern; public class MainFacadePattern implements IPattern { public static final String FACADETAG = "FacadePattern"; @Override public void run() { BankFacade bank = new BankFacade(12345678,1234); bank.deposit(1000); bank.withdraw(30); bank.withdraw(900); Log.d(FACADETAG, Double.toString(bank.getAccountMoney())); } }
486
0.701646
0.658436
17
27.588236
22.016193
66
false
false
0
0
0
0
0
0
0.647059
false
false
4
d5e27ba857603a64fa9d657dbb0ec3c8b988e312
687,194,826,821
d34da06c904ab0fe654712a1e39b763e1b6f9158
/src/com/eulee/audiorecorder/AppLog.java
e20bb6fd3fe56a61d63c6854f3abd965d511219c
[]
no_license
euleeteh/audiorecorder
https://github.com/euleeteh/audiorecorder
2f8961c00617aea58c18bad7c50c118844336dfb
9e7bb0e98f416542a91639ff80ca67186cbf43c8
refs/heads/master
2020-04-06T03:40:04.432000
2014-01-29T00:59:28
2014-01-29T00:59:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eulee.audiorecorder; //Audio recorder/encoder obtained from: //http://www.devlper.com/2010/12/android-audio-recording-part-2/ //Edited by Eu-Lee Teh 2013 import android.util.Log; public class AppLog { private static final String APP_TAG = "AudioRecorder"; public static int logString(String message){ return Log.i(APP_TAG,message); } }
UTF-8
Java
359
java
AppLog.java
Java
[ { "context": "010/12/android-audio-recording-part-2/\n//Edited by Eu-Lee Teh 2013\n\n\nimport android.util.Log;\n\npublic class App", "end": 161, "score": 0.9998688101768494, "start": 151, "tag": "NAME", "value": "Eu-Lee Teh" } ]
null
[]
package com.eulee.audiorecorder; //Audio recorder/encoder obtained from: //http://www.devlper.com/2010/12/android-audio-recording-part-2/ //Edited by <NAME> 2013 import android.util.Log; public class AppLog { private static final String APP_TAG = "AudioRecorder"; public static int logString(String message){ return Log.i(APP_TAG,message); } }
355
0.749304
0.718663
16
21.4375
21.08604
64
false
false
0
0
0
0
0
0
0.6875
false
false
4
b74d29eda06697ac790eaaa071e40092db5f51f1
13,151,189,914,385
f767d0d675bef5bf36ef9acc10e88591b79a57a0
/Developpement/Noiroroo/src/informations/Competence.java
c75298e5c96a04172b52462a6bbb9907067e5329
[]
no_license
exopole/Noiroroo
https://github.com/exopole/Noiroroo
f2497c16fa073c4b1757d417a5f10b29e6379dfd
90716dee2a0342ddbc5bd8ff9279760c2d27e326
refs/heads/master
2020-12-12T16:43:00.311000
2016-08-04T19:41:03
2016-08-04T19:41:03
35,986,890
1
1
null
false
2016-04-04T08:23:05
2015-05-21T02:44:15
2016-03-07T03:25:59
2016-03-25T21:53:53
23,374
0
0
0
Java
null
null
package informations; import java.io.File; import java.util.Vector; import javafx.beans.property.DoubleProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; /** * Classe presentant une competence * * @author exopole * */ public class Competence { /** * Nom de la competence */ private final StringProperty nom; /** * Description de la competence */ private final StringProperty description; /** * Type de la competence */ private final StringProperty type; /** * Nature de la competence */ private final StringProperty nature; /** * Level maximum que peut atteindre la competence */ private final IntegerProperty levelMax; /** * Temps necessaire a l'incantation de la competence */ private final DoubleProperty tempsIncantation; /** * Level maximum que peut atteindre la competence */ private final IntegerProperty exp; /** * Constructeur permettant d'instancier toutes les valeurs * @param nom * @param description * @param type * @param nature * @param levelMax * @param tempsIncantation */ public Competence(String nom, String description, String type, String nature, int levelMax, Double tempsIncantation) { this.nom = new SimpleStringProperty(nom); this.description = new SimpleStringProperty(description); this.type = new SimpleStringProperty(type); this.nature = new SimpleStringProperty(nature); this.levelMax = new SimpleIntegerProperty(levelMax); this.tempsIncantation = new SimpleDoubleProperty(tempsIncantation); this.exp = null; } /** * Constructeur permettant d'instancier toutes les valeurs via un chaine de caractere * @param listComp */ public Competence(String listComp) { String[] stringSplit = listComp.split(";"); nom = new SimpleStringProperty(stringSplit[0]); description = new SimpleStringProperty(stringSplit[1]); type = new SimpleStringProperty(stringSplit[2]); nature = new SimpleStringProperty(stringSplit[3]); levelMax = new SimpleIntegerProperty(Integer.parseInt(stringSplit[4])) ; tempsIncantation = new SimpleDoubleProperty(Double.parseDouble(stringSplit[5])); this.exp = null; } /** * Constructeur permettant d'instancier toutes les valeurs via un chaine de caractere * @param listComp */ public Competence(String listComp, int exp) { String[] stringSplit = listComp.split(";"); nom = new SimpleStringProperty(stringSplit[0]); description = new SimpleStringProperty(stringSplit[1]); type = new SimpleStringProperty(stringSplit[2]); nature = new SimpleStringProperty(stringSplit[3]); levelMax = new SimpleIntegerProperty(Integer.parseInt(stringSplit[4])) ; tempsIncantation = new SimpleDoubleProperty(Double.parseDouble(stringSplit[5])); this.exp = new SimpleIntegerProperty(exp) ; } /** * Constructeur permettant d'instancier toutes les valeurs via un chaine de caractere * @param listComp */ public Competence(Competence comp, int exp) { nom = comp.nom; description = comp.description; type = comp.type; nature = comp.nature; levelMax = comp.levelMax ; tempsIncantation = comp.tempsIncantation; this.exp = new SimpleIntegerProperty(exp) ; } /** * Retourne le nom * @return String */ public String getNom() { return nom.get(); } public StringProperty getNomProperty() { return nom; } /** * Retourne la description de la competence * @return String */ public String getDescription() { return description.get(); } /** * Retourne la description de la competence * @return String */ public StringProperty getDescriptionProperty() { return description; } /** * Retourne le type de la competence * @return String */ public StringProperty getTypeProperty() { return type; } /** * Retourne le type de la competence * @return String */ public String getType() { return type.get(); } /** * Retourne la nature de la competence * @return String */ public StringProperty getNatureProperty() { return nature; } /** * Retourne la nature de la competence * @return String */ public String getNature() { return nature.get(); } /** * Retourne le level max pouvant atteindre la competence * @return int */ public IntegerProperty getLevelMaxProperty() { return levelMax; } /** * Retourne le level max pouvant atteindre la competence * @return int */ public int getLevelMax() { return levelMax.get(); } /** * @return the exp */ public IntegerProperty getExpProperty() { return exp; } /** * @return the exp */ public int getExp() { return exp.get(); } /** * Retourne le temps d'incantation necessaire pour lancer la competence * @return Double */ public DoubleProperty getTempsIncantationProperty() { return tempsIncantation; } public Double getTempsIncantation() { return tempsIncantation.get(); } /** * @param exp the exp to set */ public void setExp(int exp) { this.exp.set(exp); } /** * @param nom the nom to set */ public void setNom(String nom) { this.nom.set(nom); } /** * @param description the description to set */ public void setDescription(String description) { this.description.set(description); } /** * @param type the type to set */ public void setType(String type) { this.type.set(type); } /** * @param nature the nature to set */ public void setNature(String nature) { this.nature.set(nature); } /** * @param levelMax the levelMax to set */ public void setLevelMax(int levelMax) { this.levelMax.set(levelMax); } /** * @param tempsIncantation the tempsIncantation to set */ public void setTempsIncantation(double tempsIncantation) { this.tempsIncantation.set(tempsIncantation); } }
UTF-8
Java
5,923
java
Competence.java
Java
[ { "context": " * Classe presentant une competence\n * \n * @author exopole\n *\n */\npublic class Competence {\n\t\n\t/**\n\t * Nom d", "end": 422, "score": 0.9996421337127686, "start": 415, "tag": "USERNAME", "value": "exopole" } ]
null
[]
package informations; import java.io.File; import java.util.Vector; import javafx.beans.property.DoubleProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; /** * Classe presentant une competence * * @author exopole * */ public class Competence { /** * Nom de la competence */ private final StringProperty nom; /** * Description de la competence */ private final StringProperty description; /** * Type de la competence */ private final StringProperty type; /** * Nature de la competence */ private final StringProperty nature; /** * Level maximum que peut atteindre la competence */ private final IntegerProperty levelMax; /** * Temps necessaire a l'incantation de la competence */ private final DoubleProperty tempsIncantation; /** * Level maximum que peut atteindre la competence */ private final IntegerProperty exp; /** * Constructeur permettant d'instancier toutes les valeurs * @param nom * @param description * @param type * @param nature * @param levelMax * @param tempsIncantation */ public Competence(String nom, String description, String type, String nature, int levelMax, Double tempsIncantation) { this.nom = new SimpleStringProperty(nom); this.description = new SimpleStringProperty(description); this.type = new SimpleStringProperty(type); this.nature = new SimpleStringProperty(nature); this.levelMax = new SimpleIntegerProperty(levelMax); this.tempsIncantation = new SimpleDoubleProperty(tempsIncantation); this.exp = null; } /** * Constructeur permettant d'instancier toutes les valeurs via un chaine de caractere * @param listComp */ public Competence(String listComp) { String[] stringSplit = listComp.split(";"); nom = new SimpleStringProperty(stringSplit[0]); description = new SimpleStringProperty(stringSplit[1]); type = new SimpleStringProperty(stringSplit[2]); nature = new SimpleStringProperty(stringSplit[3]); levelMax = new SimpleIntegerProperty(Integer.parseInt(stringSplit[4])) ; tempsIncantation = new SimpleDoubleProperty(Double.parseDouble(stringSplit[5])); this.exp = null; } /** * Constructeur permettant d'instancier toutes les valeurs via un chaine de caractere * @param listComp */ public Competence(String listComp, int exp) { String[] stringSplit = listComp.split(";"); nom = new SimpleStringProperty(stringSplit[0]); description = new SimpleStringProperty(stringSplit[1]); type = new SimpleStringProperty(stringSplit[2]); nature = new SimpleStringProperty(stringSplit[3]); levelMax = new SimpleIntegerProperty(Integer.parseInt(stringSplit[4])) ; tempsIncantation = new SimpleDoubleProperty(Double.parseDouble(stringSplit[5])); this.exp = new SimpleIntegerProperty(exp) ; } /** * Constructeur permettant d'instancier toutes les valeurs via un chaine de caractere * @param listComp */ public Competence(Competence comp, int exp) { nom = comp.nom; description = comp.description; type = comp.type; nature = comp.nature; levelMax = comp.levelMax ; tempsIncantation = comp.tempsIncantation; this.exp = new SimpleIntegerProperty(exp) ; } /** * Retourne le nom * @return String */ public String getNom() { return nom.get(); } public StringProperty getNomProperty() { return nom; } /** * Retourne la description de la competence * @return String */ public String getDescription() { return description.get(); } /** * Retourne la description de la competence * @return String */ public StringProperty getDescriptionProperty() { return description; } /** * Retourne le type de la competence * @return String */ public StringProperty getTypeProperty() { return type; } /** * Retourne le type de la competence * @return String */ public String getType() { return type.get(); } /** * Retourne la nature de la competence * @return String */ public StringProperty getNatureProperty() { return nature; } /** * Retourne la nature de la competence * @return String */ public String getNature() { return nature.get(); } /** * Retourne le level max pouvant atteindre la competence * @return int */ public IntegerProperty getLevelMaxProperty() { return levelMax; } /** * Retourne le level max pouvant atteindre la competence * @return int */ public int getLevelMax() { return levelMax.get(); } /** * @return the exp */ public IntegerProperty getExpProperty() { return exp; } /** * @return the exp */ public int getExp() { return exp.get(); } /** * Retourne le temps d'incantation necessaire pour lancer la competence * @return Double */ public DoubleProperty getTempsIncantationProperty() { return tempsIncantation; } public Double getTempsIncantation() { return tempsIncantation.get(); } /** * @param exp the exp to set */ public void setExp(int exp) { this.exp.set(exp); } /** * @param nom the nom to set */ public void setNom(String nom) { this.nom.set(nom); } /** * @param description the description to set */ public void setDescription(String description) { this.description.set(description); } /** * @param type the type to set */ public void setType(String type) { this.type.set(type); } /** * @param nature the nature to set */ public void setNature(String nature) { this.nature.set(nature); } /** * @param levelMax the levelMax to set */ public void setLevelMax(int levelMax) { this.levelMax.set(levelMax); } /** * @param tempsIncantation the tempsIncantation to set */ public void setTempsIncantation(double tempsIncantation) { this.tempsIncantation.set(tempsIncantation); } }
5,923
0.706736
0.70471
274
20.616789
21.792885
119
false
false
0
0
0
0
0
0
1.324818
false
false
4
ed47112dc006baa52ad3f3e7e04a1c94ff3b12a7
3,659,312,145,223
6700a6f1e5b318367b584c210d7f21152bf96d5d
/app/src/main/java/com/coe/kku/ac/nursetalk/game/vocab/VocabPool.java
21ff897b8daabe4d4ac9233954173f873deb96c5
[]
no_license
teema15135/nurse-talk-java
https://github.com/teema15135/nurse-talk-java
8631e0734d5cb779b932cde108d0724f326de25d
02c2dc071bfca0d7fa255ee1c9526f00ad5b404c
refs/heads/master
2020-07-29T20:54:33.729000
2019-10-22T10:22:31
2019-10-22T10:22:31
209,955,712
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.coe.kku.ac.nursetalk.game.vocab; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class VocabPool { private static final String TAG = "VocabPool"; private static ArrayList<HashMap> words; private static boolean wordLoaded = false; public static void loadVocabPool() { words = new ArrayList<>(); // Symptom vocab words.add(new HashMap<String, String>() {{ put("answer", "Constipation"); put("word", "C_n_t_p_t___"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Dyspepsia"); put("word", "D_s_e_s__"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Dehydration"); put("word", "D___d__t___"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Sprain"); put("word", "S____n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Heartburn"); put("word", "H___tb__n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Toothache"); put("word", "_oo___c__"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Stomachache"); put("word", "___ma____he"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Eyestrain"); put("word", "E___tr___"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Insomnia"); put("word", "I____ni_"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Crick"); put("word", "Cr___"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Sore throat"); put("word", "S__e t___at"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Nose bleed"); put("word", "N___ bl__d"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Convulsion"); put("word", "C__vu____n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Fracture"); put("word", "F___t__e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Broken bone"); put("word", "___ken b__e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Burn"); put("word", "___n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Blister"); put("word", "_l__ter"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Conjunctivitis"); put("word", "__n___ct__it_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Nauseous"); put("word", "_a_s_o_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Vomit"); put("word", "V__it"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Bleeding"); put("word", "_l__di__"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Misshapen"); put("word", "M___h_p_n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Bruise"); put("word", "_ru__e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Cough"); put("word", "___gh"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Inflame"); put("word", "__f__me"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Runny nose"); put("word", "___ny n__e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Phlegm"); put("word", "P___gm"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Swollen"); put("word", "Sw____n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Pus"); put("word", "P_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Purulent"); put("word", "_u__l_nt"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Chronic"); put("word", "Chr__i_"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Hiccup"); put("word", "H__c_p"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Perspire"); put("word", "_e__pir_"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Rash"); put("word", "Ra__"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Short of breath"); put("word", "_h_rt o_ _r_a_h"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Itchy"); put("word", "_t_cy"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Dizzy"); put("word", "__z_y"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Fever"); put("word", "_e_er"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Backache"); put("word", "_a_k_c_e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Earache"); put("word", "__rac_e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Ache"); put("word", "A__e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Acute"); put("word", "A___e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Faint"); put("word", "___nt"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Fatigue"); put("word", "_a_i_u_"); }}); // Disease vocab words.add(new HashMap<String, String>() {{ put("answer", "Gout"); put("word", "G___"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Hemorrhoids"); put("word", "__m___ho__s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Pneumonia"); put("word", "P__umo__a"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Gastritis"); put("word", "_a_t_i_is"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Enteritis"); put("word", "E__e_i__s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Food poisoning"); put("word", "F__d p__so___g"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Diarrhea"); put("word", "_i_r_h_a"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Jaundice"); put("word", "_a_n_i_e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Cirrhosis"); put("word", "__r_h_s_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Gallstones"); put("word", "_a__s__nes"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Diabetes"); put("word", "D__be__s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Tonsillitis"); put("word", "_o__i__i_is"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Measles"); put("word", "_e_s_es"); }}); words.add(new HashMap<String, String>() {{ put("answer", "German measles"); put("word", "_e_m_n _e_s_es"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Rubella"); put("word", "_u_e_la"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Cancer"); put("word", "C_n_er"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Chicken pox"); put("word", "C_i_k_n _ox"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Dengue fever"); put("word", "_e_g_e f_v_r"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Heart disease"); put("word", "_e_rt _i_e_se"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Whooping cough"); put("word", "_h_op_ng c_u_h"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Pertussis"); put("word", "_e_t___is"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Diphtheria"); put("word", "_i_h__e_ia"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Tetanus"); put("word", "T_t_n_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Asthmatic"); put("word", "A__hm_t_c"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Sinusitis"); put("word", "S_n_s___s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Laryngitis"); put("word", "_a_y_g_t_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Allergy"); put("word", "___er_y"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Depression"); put("word", "_e_r_s__on"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Cold"); put("word", "C__d"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Chronic"); put("word", "__ron_c"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Tuberculosis"); put("word", "__b_r_u_os_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Appendicitis"); put("word", "A__e_d_c_t_s"); }}); wordLoaded = true; } public static HashMap<String, String> getRandomWord() { if (!wordLoaded) { Log.d(TAG, "getRandomWord: Please loadVocabPool() first!"); return null; } return words.get((new Random()).nextInt(words.size())); } }
UTF-8
Java
11,603
java
VocabPool.java
Java
[]
null
[]
package com.coe.kku.ac.nursetalk.game.vocab; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class VocabPool { private static final String TAG = "VocabPool"; private static ArrayList<HashMap> words; private static boolean wordLoaded = false; public static void loadVocabPool() { words = new ArrayList<>(); // Symptom vocab words.add(new HashMap<String, String>() {{ put("answer", "Constipation"); put("word", "C_n_t_p_t___"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Dyspepsia"); put("word", "D_s_e_s__"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Dehydration"); put("word", "D___d__t___"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Sprain"); put("word", "S____n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Heartburn"); put("word", "H___tb__n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Toothache"); put("word", "_oo___c__"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Stomachache"); put("word", "___ma____he"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Eyestrain"); put("word", "E___tr___"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Insomnia"); put("word", "I____ni_"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Crick"); put("word", "Cr___"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Sore throat"); put("word", "S__e t___at"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Nose bleed"); put("word", "N___ bl__d"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Convulsion"); put("word", "C__vu____n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Fracture"); put("word", "F___t__e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Broken bone"); put("word", "___ken b__e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Burn"); put("word", "___n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Blister"); put("word", "_l__ter"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Conjunctivitis"); put("word", "__n___ct__it_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Nauseous"); put("word", "_a_s_o_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Vomit"); put("word", "V__it"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Bleeding"); put("word", "_l__di__"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Misshapen"); put("word", "M___h_p_n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Bruise"); put("word", "_ru__e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Cough"); put("word", "___gh"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Inflame"); put("word", "__f__me"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Runny nose"); put("word", "___ny n__e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Phlegm"); put("word", "P___gm"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Swollen"); put("word", "Sw____n"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Pus"); put("word", "P_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Purulent"); put("word", "_u__l_nt"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Chronic"); put("word", "Chr__i_"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Hiccup"); put("word", "H__c_p"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Perspire"); put("word", "_e__pir_"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Rash"); put("word", "Ra__"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Short of breath"); put("word", "_h_rt o_ _r_a_h"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Itchy"); put("word", "_t_cy"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Dizzy"); put("word", "__z_y"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Fever"); put("word", "_e_er"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Backache"); put("word", "_a_k_c_e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Earache"); put("word", "__rac_e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Ache"); put("word", "A__e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Acute"); put("word", "A___e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Faint"); put("word", "___nt"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Fatigue"); put("word", "_a_i_u_"); }}); // Disease vocab words.add(new HashMap<String, String>() {{ put("answer", "Gout"); put("word", "G___"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Hemorrhoids"); put("word", "__m___ho__s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Pneumonia"); put("word", "P__umo__a"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Gastritis"); put("word", "_a_t_i_is"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Enteritis"); put("word", "E__e_i__s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Food poisoning"); put("word", "F__d p__so___g"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Diarrhea"); put("word", "_i_r_h_a"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Jaundice"); put("word", "_a_n_i_e"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Cirrhosis"); put("word", "__r_h_s_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Gallstones"); put("word", "_a__s__nes"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Diabetes"); put("word", "D__be__s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Tonsillitis"); put("word", "_o__i__i_is"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Measles"); put("word", "_e_s_es"); }}); words.add(new HashMap<String, String>() {{ put("answer", "German measles"); put("word", "_e_m_n _e_s_es"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Rubella"); put("word", "_u_e_la"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Cancer"); put("word", "C_n_er"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Chicken pox"); put("word", "C_i_k_n _ox"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Dengue fever"); put("word", "_e_g_e f_v_r"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Heart disease"); put("word", "_e_rt _i_e_se"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Whooping cough"); put("word", "_h_op_ng c_u_h"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Pertussis"); put("word", "_e_t___is"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Diphtheria"); put("word", "_i_h__e_ia"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Tetanus"); put("word", "T_t_n_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Asthmatic"); put("word", "A__hm_t_c"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Sinusitis"); put("word", "S_n_s___s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Laryngitis"); put("word", "_a_y_g_t_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Allergy"); put("word", "___er_y"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Depression"); put("word", "_e_r_s__on"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Cold"); put("word", "C__d"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Chronic"); put("word", "__ron_c"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Tuberculosis"); put("word", "__b_r_u_os_s"); }}); words.add(new HashMap<String, String>() {{ put("answer", "Appendicitis"); put("word", "A__e_d_c_t_s"); }}); wordLoaded = true; } public static HashMap<String, String> getRandomWord() { if (!wordLoaded) { Log.d(TAG, "getRandomWord: Please loadVocabPool() first!"); return null; } return words.get((new Random()).nextInt(words.size())); } }
11,603
0.422046
0.422046
338
33.328403
15.443211
71
false
false
0
0
0
0
0
0
1.393491
false
false
2
6b6759b7c3bb340e890e4404131ac6a878044a9a
29,463,475,657,252
777deba40a48722f9c9f4035d8c7cd779aaa35e4
/src/main/java/edu/brown/cs/dnd/Generate/GenerateEncounterHandler.java
7f5a9029d09c1c67e98a13701b86cfa3de3e4a69
[]
no_license
heyyyjude42/mysterydungeon
https://github.com/heyyyjude42/mysterydungeon
8e00502497ac1292804bccddcf01a40235011c5c
26a29aba2ef521a1204c5839e447cf368bcb6d5c
refs/heads/master
2020-08-02T17:13:11.208000
2019-09-18T05:30:37
2019-09-18T05:30:37
211,441,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.brown.cs.dnd.Generate; import edu.brown.cs.dnd.Data.Database; import edu.brown.cs.dnd.Data.Monster; import edu.brown.cs.dnd.Data.Result; import edu.brown.cs.dnd.Data.ReturnType; import edu.brown.cs.dnd.REPL.Command; import edu.brown.cs.dnd.REPL.Handler; import edu.brown.cs.dnd.REPL.CommandHandler; import edu.brown.cs.dnd.REPL.InvalidInputException; import edu.brown.cs.dnd.REPL.CommandFailedException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Class representing a handler to support generating an encounter based on * user input. */ public class GenerateEncounterHandler implements Handler { /** * A Constructor for a GenerateEncounterHandler. */ public GenerateEncounterHandler() { Database.load("data/srd.db"); } @Override public void registerCommands(CommandHandler handler) { handler.register("generate-encounter", new GenerateEncounter()); } /** * Class representing the generate-encounter command. */ private class GenerateEncounter implements Command { @Override public Result run(String[] args) throws InvalidInputException, CommandFailedException { if (args.length != 2) { throw new InvalidInputException("ERROR: Must specify the sum of the " + "party's levels."); } int partyLevel = 0; try { partyLevel = Integer.parseInt(args[1]); } catch (NumberFormatException e) { throw new InvalidInputException("ERROR: combined party level is not a" + " number"); } List<Monster> encounter = createEncounter(partyLevel); return new Result(ReturnType.ENCOUNTER, encounter); } /** * Method creates an encounter with the size specified by partyLevel. * * @param partyLevel An int that is the sum of the party's levels. * @return A List of Monsters that is the encounter appropriate for the * level sum. */ List<Monster> createEncounter(int partyLevel) throws CommandFailedException { PreparedStatement prep; Connection conn = Database.getConnection(); try { List<Integer> monsterCR = getEncounterMonsterCRs(partyLevel, new ArrayList<>()); List<Monster> encounter = new ArrayList<>(); for (Integer i : monsterCR) { prep = conn.prepareStatement("SELECT * FROM monsters WHERE cr = " + i + " ORDER BY " + "Random() LIMIT ?;"); prep.setInt(1, i); ResultSet rs = prep.executeQuery(); List<Monster> monster = GenerateNPCHandler.extractMonsterResult(rs); encounter.add(monster.get(0)); rs.close(); } return encounter; } catch (SQLException e) { System.out.println(e.getMessage()); throw new CommandFailedException("ERROR: Could not create encounter"); } } /** * Divides up a number into a sum of smaller, random numbers. * * @param partyLevel Combined party level of the group. * @param currCR The current list of CRs to add to. * @return A List of Integers that are the monster crs */ private List<Integer> getEncounterMonsterCRs(int partyLevel, List<Integer> currCR) { if (partyLevel == 0) { return currCR; } int nextCR = (int) (Math.random() * partyLevel + 1); if (nextCR > partyLevel) { nextCR = partyLevel; } final int twentyFour = 24; if (nextCR > twentyFour) { nextCR = twentyFour; } currCR.add(nextCR); return getEncounterMonsterCRs(partyLevel - nextCR, currCR); } } }
UTF-8
Java
3,829
java
GenerateEncounterHandler.java
Java
[]
null
[]
package edu.brown.cs.dnd.Generate; import edu.brown.cs.dnd.Data.Database; import edu.brown.cs.dnd.Data.Monster; import edu.brown.cs.dnd.Data.Result; import edu.brown.cs.dnd.Data.ReturnType; import edu.brown.cs.dnd.REPL.Command; import edu.brown.cs.dnd.REPL.Handler; import edu.brown.cs.dnd.REPL.CommandHandler; import edu.brown.cs.dnd.REPL.InvalidInputException; import edu.brown.cs.dnd.REPL.CommandFailedException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Class representing a handler to support generating an encounter based on * user input. */ public class GenerateEncounterHandler implements Handler { /** * A Constructor for a GenerateEncounterHandler. */ public GenerateEncounterHandler() { Database.load("data/srd.db"); } @Override public void registerCommands(CommandHandler handler) { handler.register("generate-encounter", new GenerateEncounter()); } /** * Class representing the generate-encounter command. */ private class GenerateEncounter implements Command { @Override public Result run(String[] args) throws InvalidInputException, CommandFailedException { if (args.length != 2) { throw new InvalidInputException("ERROR: Must specify the sum of the " + "party's levels."); } int partyLevel = 0; try { partyLevel = Integer.parseInt(args[1]); } catch (NumberFormatException e) { throw new InvalidInputException("ERROR: combined party level is not a" + " number"); } List<Monster> encounter = createEncounter(partyLevel); return new Result(ReturnType.ENCOUNTER, encounter); } /** * Method creates an encounter with the size specified by partyLevel. * * @param partyLevel An int that is the sum of the party's levels. * @return A List of Monsters that is the encounter appropriate for the * level sum. */ List<Monster> createEncounter(int partyLevel) throws CommandFailedException { PreparedStatement prep; Connection conn = Database.getConnection(); try { List<Integer> monsterCR = getEncounterMonsterCRs(partyLevel, new ArrayList<>()); List<Monster> encounter = new ArrayList<>(); for (Integer i : monsterCR) { prep = conn.prepareStatement("SELECT * FROM monsters WHERE cr = " + i + " ORDER BY " + "Random() LIMIT ?;"); prep.setInt(1, i); ResultSet rs = prep.executeQuery(); List<Monster> monster = GenerateNPCHandler.extractMonsterResult(rs); encounter.add(monster.get(0)); rs.close(); } return encounter; } catch (SQLException e) { System.out.println(e.getMessage()); throw new CommandFailedException("ERROR: Could not create encounter"); } } /** * Divides up a number into a sum of smaller, random numbers. * * @param partyLevel Combined party level of the group. * @param currCR The current list of CRs to add to. * @return A List of Integers that are the monster crs */ private List<Integer> getEncounterMonsterCRs(int partyLevel, List<Integer> currCR) { if (partyLevel == 0) { return currCR; } int nextCR = (int) (Math.random() * partyLevel + 1); if (nextCR > partyLevel) { nextCR = partyLevel; } final int twentyFour = 24; if (nextCR > twentyFour) { nextCR = twentyFour; } currCR.add(nextCR); return getEncounterMonsterCRs(partyLevel - nextCR, currCR); } } }
3,829
0.639854
0.637503
131
28.229008
24.521236
78
false
false
0
0
0
0
0
0
0.40458
false
false
2
2941ce0039b1bb7446d089a9e3dcba40e0454cb9
29,463,475,656,035
5df536459692e0a965714ce54582674ca6eaa0d8
/jpa-exercise12/src/main/java/com/abouzidi/jpa/Phone.java
5b8a5dab270353a89445d1264995c66023a6ea2f
[]
no_license
AfifBouzidi/JPA-REPOSITORY
https://github.com/AfifBouzidi/JPA-REPOSITORY
cd26b0d8fe735be7628d71b6f9c91a6d4bfbaa0b
5a5a72bce5d8b0f924393f8619ed9e92b8d7e1e3
refs/heads/master
2021-01-24T16:34:12.814000
2018-03-01T02:03:03
2018-03-01T02:03:03
123,008,393
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.abouzidi.jpa; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.SequenceGenerator; @Entity public class Phone { @SequenceGenerator(name = "phone_gen", sequenceName = "phone_seq") @Id @GeneratedValue(generator = "phone_gen") private long id; @Enumerated(EnumType.STRING) private PhoneType type; public Phone() { } public Phone(PhoneType type) { this.type = type; } public long getId() { return id; } public void setId(long id) { this.id = id; } public PhoneType getType() { return type; } public void setType(PhoneType type) { this.type = type; } } enum PhoneType { SAMSUNG, NOKIA }
UTF-8
Java
833
java
Phone.java
Java
[]
null
[]
package com.abouzidi.jpa; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.SequenceGenerator; @Entity public class Phone { @SequenceGenerator(name = "phone_gen", sequenceName = "phone_seq") @Id @GeneratedValue(generator = "phone_gen") private long id; @Enumerated(EnumType.STRING) private PhoneType type; public Phone() { } public Phone(PhoneType type) { this.type = type; } public long getId() { return id; } public void setId(long id) { this.id = id; } public PhoneType getType() { return type; } public void setType(PhoneType type) { this.type = type; } } enum PhoneType { SAMSUNG, NOKIA }
833
0.683073
0.683073
48
15.354167
15.819937
67
false
false
0
0
0
0
0
0
0.9375
false
false
2
0e68ffbb18d63319af7b2d4cfa32702584d82cb3
12,128,987,653,595
13f38e9e4f7781d830e4a62bf19868eae77954b5
/test/org/pathwayeditor/testfixture/NotationSubsystemFixture.java
47d57e6cc6de669d050ae09e3947690dea85c985
[ "Apache-2.0" ]
permissive
vijayvani/VisualLanguageToolkit
https://github.com/vijayvani/VisualLanguageToolkit
5dc3adc80badb2d9442cac2be7d6d39bfebf6d5b
0ab4fd7faab655388762c8f3c9f7eb14244981c8
refs/heads/master
2020-05-16T08:34:44.576000
2012-07-17T18:58:07
2012-07-17T18:58:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Licensed to the Court of the University of Edinburgh (UofE) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The UofE 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.pathwayeditor.testfixture; import static org.hamcrest.Matchers.isOneOf; import static org.hamcrest.Matchers.not; import org.hamcrest.Description; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.Action; import org.jmock.api.Invocation; import org.pathwayeditor.businessobjects.drawingprimitives.attributes.Version; import org.pathwayeditor.businessobjects.drawingprimitives.properties.IPlainTextAnnotationProperty; import org.pathwayeditor.businessobjects.drawingprimitives.properties.IPlainTextPropertyDefinition; import org.pathwayeditor.businessobjects.drawingprimitives.properties.IPropertyBuilder; import org.pathwayeditor.businessobjects.drawingprimitives.properties.IPropertyDefinition; import org.pathwayeditor.businessobjects.notationsubsystem.INotation; import org.pathwayeditor.businessobjects.notationsubsystem.INotationSubsystem; import org.pathwayeditor.businessobjects.notationsubsystem.INotationSyntaxService; import org.pathwayeditor.businessobjects.typedefn.IAnchorNodeObjectType; import org.pathwayeditor.businessobjects.typedefn.ILabelObjectType; import org.pathwayeditor.businessobjects.typedefn.ILinkObjectType; import org.pathwayeditor.businessobjects.typedefn.IObjectTypeParentingRules; import org.pathwayeditor.businessobjects.typedefn.IRootObjectType; import org.pathwayeditor.businessobjects.typedefn.IShapeObjectType; /** * @author Stuart Moodie * */ public class NotationSubsystemFixture { public static final int ROOT_TYPE_ID = 0; public static final int SHAPE_TYPE_A_ID = 1; public static final int SHAPE_TYPE_B_ID = 2; public static final int SHAPE_TYPE_C_ID = 3; public static final int LINK_TYPE_D_ID = 4; public static final int LINK_TYPE_E_ID = 5; public static final int LABEL_TYPE_ID = 6; public static final String SHAPE_TYPE_A_PROP_NAME = "shapeTypeAName"; public static final String SHAPE_TYPE_B_PROP_NAME = "shapeTypeBName"; public static final int ANCHOR_NODE_TYPE_ID = 7; private final Mockery mockery; private INotationSubsystem notationSubsystem; private INotationSyntaxService syntaxService; private IRootObjectType rootType; private IShapeObjectType shapeTypeA; private IShapeObjectType shapeTypeB; private IShapeObjectType shapeTypeC; private ILinkObjectType linkTypeD; private ILinkObjectType linkTypeE; private IObjectTypeParentingRules rootTypeParenting; private INotation notation; private ILabelObjectType labelObjectType; private IAnchorNodeObjectType anchorNodeType; public static class CreatePropertyAction implements Action { // private IPlainTextPropertyDefinition defn; public CreatePropertyAction(){ // this.defn = builder; } @Override public void describeTo(Description descn) { descn.appendText("get removal state"); } @Override public IPlainTextAnnotationProperty invoke(Invocation invocation) throws Throwable { IPropertyBuilder builder = (IPropertyBuilder)invocation.getParameter(0); IPlainTextPropertyDefinition testPropDefn = (IPlainTextPropertyDefinition)invocation.getInvokedObject(); IPlainTextAnnotationProperty retVal = builder.createPlainTextProperty(testPropDefn); return retVal; } } public static Action buildTextProperty(){ return new CreatePropertyAction(); } public NotationSubsystemFixture(Mockery mockery){ this.mockery = mockery; } public Mockery getMockery(){ return this.mockery; } public void buildFixture(){ this.notationSubsystem = mockery.mock(INotationSubsystem.class, "notationSubsystem"); this.syntaxService = mockery.mock(INotationSyntaxService.class, "syntaxService"); this.rootType = mockery.mock(IRootObjectType.class, "rootType"); this.rootTypeParenting = mockery.mock(IObjectTypeParentingRules.class, "rootTypeParenting"); this.notation = mockery.mock(INotation.class, "notation"); MockShapeObjectTypeBuilder showObjectTypeABuilder = new MockShapeObjectTypeBuilder(mockery, syntaxService, SHAPE_TYPE_A_ID, "shapeTypeA"); showObjectTypeABuilder.addTextProperty(SHAPE_TYPE_A_PROP_NAME, "PropNameAValue", true, true); showObjectTypeABuilder.build(); this.shapeTypeA = showObjectTypeABuilder.getObjectType(); MockShapeObjectTypeBuilder showObjectTypeBBuilder = new MockShapeObjectTypeBuilder(mockery, syntaxService, SHAPE_TYPE_B_ID, "shapeTypeB"); showObjectTypeBBuilder.addTextProperty(SHAPE_TYPE_B_PROP_NAME, "PropNameBValue", true, false); showObjectTypeBBuilder.build(); this.shapeTypeB = showObjectTypeBBuilder.getObjectType(); MockShapeObjectTypeBuilder showObjectTypeCBuilder = new MockShapeObjectTypeBuilder(mockery, syntaxService, SHAPE_TYPE_C_ID, "shapeTypeC"); showObjectTypeCBuilder.build(); this.shapeTypeC = showObjectTypeCBuilder.getObjectType(); showObjectTypeABuilder.buildParentingRules(shapeTypeA, shapeTypeC); showObjectTypeBBuilder.buildParentingRules(shapeTypeA, shapeTypeB); showObjectTypeCBuilder.buildParentingRules(); MockLinkObjectTypeBuilder linkTypeDBuilder = new MockLinkObjectTypeBuilder(mockery, syntaxService, LINK_TYPE_D_ID, "linkTypeD"); linkTypeDBuilder.build(); this.linkTypeD = linkTypeDBuilder.getObjectType(); MockLinkObjectTypeBuilder linkTypeEBuilder = new MockLinkObjectTypeBuilder(mockery, syntaxService, LINK_TYPE_E_ID, "linkTypeE"); linkTypeEBuilder.build(); this.linkTypeE = linkTypeEBuilder.getObjectType(); MockLabelObjectTypeBuilder labelTypeBuilder = new MockLabelObjectTypeBuilder(mockery, syntaxService, LABEL_TYPE_ID, "labelType"); labelTypeBuilder.build(); this.labelObjectType = labelTypeBuilder.getObjectType(); MockAnchorNodeObjectTypeBuilder anchorNodeTypeBuilder = new MockAnchorNodeObjectTypeBuilder(mockery, syntaxService, ANCHOR_NODE_TYPE_ID, "anchorNodeType"); anchorNodeTypeBuilder.build(); this.anchorNodeType = anchorNodeTypeBuilder.getObjectType(); linkTypeDBuilder.buildParentingRules(this.anchorNodeType); linkTypeDBuilder.setSources(this.shapeTypeA, this.anchorNodeType); linkTypeDBuilder.setTargets(this.shapeTypeA, this.shapeTypeB); linkTypeDBuilder.buildConnectionRules(); linkTypeEBuilder.buildParentingRules(this.anchorNodeType); linkTypeEBuilder.setSources(this.shapeTypeB); linkTypeEBuilder.setTargets(this.shapeTypeA); linkTypeEBuilder.buildConnectionRules(); this.mockery.checking(new Expectations(){{ allowing(notationSubsystem).getNotation(); will(returnValue(notation)); allowing(notationSubsystem).getSyntaxService(); will(returnValue(syntaxService)); allowing(syntaxService).getNotationSubsystem(); will(returnValue(notationSubsystem)); allowing(syntaxService).getRootObjectType(); will(returnValue(rootType)); allowing(syntaxService).getShapeObjectType(SHAPE_TYPE_A_ID); will(returnValue(shapeTypeA)); allowing(syntaxService).getShapeObjectType(SHAPE_TYPE_B_ID); will(returnValue(shapeTypeB)); allowing(syntaxService).getShapeObjectType(SHAPE_TYPE_C_ID); will(returnValue(shapeTypeC)); allowing(syntaxService).getLinkObjectType(LINK_TYPE_D_ID); will(returnValue(linkTypeD)); allowing(syntaxService).getLinkObjectType(LINK_TYPE_E_ID); will(returnValue(linkTypeE)); allowing(syntaxService).getAnchorNodeObjectType(ANCHOR_NODE_TYPE_ID); will(returnValue(anchorNodeType)); allowing(syntaxService).getObjectType(ROOT_TYPE_ID); will(returnValue(rootType)); allowing(syntaxService).getObjectType(SHAPE_TYPE_A_ID); will(returnValue(shapeTypeA)); allowing(syntaxService).getObjectType(SHAPE_TYPE_B_ID); will(returnValue(shapeTypeB)); allowing(syntaxService).getObjectType(SHAPE_TYPE_C_ID); will(returnValue(shapeTypeC)); allowing(syntaxService).getObjectType(LINK_TYPE_D_ID); will(returnValue(linkTypeD)); allowing(syntaxService).getObjectType(LINK_TYPE_E_ID); will(returnValue(linkTypeE)); allowing(syntaxService).getObjectType(ANCHOR_NODE_TYPE_ID); will(returnValue(anchorNodeType)); allowing(syntaxService).objectTypeIterator(); will(returnIterator(rootType, shapeTypeA, shapeTypeB, shapeTypeC, linkTypeD, linkTypeE, anchorNodeType)); allowing(syntaxService).getNotation(); will(returnValue(notation)); allowing(syntaxService).getLabelObjectType(LABEL_TYPE_ID); will(returnValue(labelObjectType)); allowing(syntaxService).getLabelObjectTypeByProperty(with(any(IPropertyDefinition.class))); will(returnValue(labelObjectType)); allowing(syntaxService).isVisualisableProperty(with(any(IPropertyDefinition.class))); will(returnValue(true)); allowing(notation).getDescription(); will(returnValue("Test Fixture Notation")); allowing(notation).getDisplayName(); will(returnValue("Fixture Notation")); allowing(notation).getQualifiedName(); will(returnValue("org.pathwayeditor.businessobjects.notation.testfixture")); allowing(notation).getVersion(); will(returnValue(new Version(1, 0, 0))); allowing(rootType).getUniqueId(); will(returnValue(ROOT_TYPE_ID)); allowing(rootType).getSyntaxService(); will(returnValue(syntaxService)); allowing(rootType).getName(); will(returnValue("rootName")); allowing(rootType).getDescription(); will(returnValue("Descn")); allowing(rootType).getParentingRules(); will(returnValue(rootTypeParenting)); allowing(rootTypeParenting).getObjectType(); will(returnValue(rootType)); allowing(rootTypeParenting).isValidChild(with(not(isOneOf(shapeTypeA, shapeTypeB, shapeTypeC)))); will(returnValue(false)); allowing(rootTypeParenting).isValidChild(with(isOneOf(shapeTypeA, shapeTypeB, shapeTypeC))); will(returnValue(true)); }}); } public INotationSubsystem getNotationSubsystem(){ return this.notationSubsystem; } }
UTF-8
Java
10,361
java
NotationSubsystemFixture.java
Java
[ { "context": "objects.typedefn.IShapeObjectType;\n\n/**\n * @author Stuart Moodie\n *\n */\npublic class NotationSubsystemFixture {\n\tp", "end": 2219, "score": 0.9997557401657104, "start": 2206, "tag": "NAME", "value": "Stuart Moodie" } ]
null
[]
/* Licensed to the Court of the University of Edinburgh (UofE) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The UofE 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.pathwayeditor.testfixture; import static org.hamcrest.Matchers.isOneOf; import static org.hamcrest.Matchers.not; import org.hamcrest.Description; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.Action; import org.jmock.api.Invocation; import org.pathwayeditor.businessobjects.drawingprimitives.attributes.Version; import org.pathwayeditor.businessobjects.drawingprimitives.properties.IPlainTextAnnotationProperty; import org.pathwayeditor.businessobjects.drawingprimitives.properties.IPlainTextPropertyDefinition; import org.pathwayeditor.businessobjects.drawingprimitives.properties.IPropertyBuilder; import org.pathwayeditor.businessobjects.drawingprimitives.properties.IPropertyDefinition; import org.pathwayeditor.businessobjects.notationsubsystem.INotation; import org.pathwayeditor.businessobjects.notationsubsystem.INotationSubsystem; import org.pathwayeditor.businessobjects.notationsubsystem.INotationSyntaxService; import org.pathwayeditor.businessobjects.typedefn.IAnchorNodeObjectType; import org.pathwayeditor.businessobjects.typedefn.ILabelObjectType; import org.pathwayeditor.businessobjects.typedefn.ILinkObjectType; import org.pathwayeditor.businessobjects.typedefn.IObjectTypeParentingRules; import org.pathwayeditor.businessobjects.typedefn.IRootObjectType; import org.pathwayeditor.businessobjects.typedefn.IShapeObjectType; /** * @author <NAME> * */ public class NotationSubsystemFixture { public static final int ROOT_TYPE_ID = 0; public static final int SHAPE_TYPE_A_ID = 1; public static final int SHAPE_TYPE_B_ID = 2; public static final int SHAPE_TYPE_C_ID = 3; public static final int LINK_TYPE_D_ID = 4; public static final int LINK_TYPE_E_ID = 5; public static final int LABEL_TYPE_ID = 6; public static final String SHAPE_TYPE_A_PROP_NAME = "shapeTypeAName"; public static final String SHAPE_TYPE_B_PROP_NAME = "shapeTypeBName"; public static final int ANCHOR_NODE_TYPE_ID = 7; private final Mockery mockery; private INotationSubsystem notationSubsystem; private INotationSyntaxService syntaxService; private IRootObjectType rootType; private IShapeObjectType shapeTypeA; private IShapeObjectType shapeTypeB; private IShapeObjectType shapeTypeC; private ILinkObjectType linkTypeD; private ILinkObjectType linkTypeE; private IObjectTypeParentingRules rootTypeParenting; private INotation notation; private ILabelObjectType labelObjectType; private IAnchorNodeObjectType anchorNodeType; public static class CreatePropertyAction implements Action { // private IPlainTextPropertyDefinition defn; public CreatePropertyAction(){ // this.defn = builder; } @Override public void describeTo(Description descn) { descn.appendText("get removal state"); } @Override public IPlainTextAnnotationProperty invoke(Invocation invocation) throws Throwable { IPropertyBuilder builder = (IPropertyBuilder)invocation.getParameter(0); IPlainTextPropertyDefinition testPropDefn = (IPlainTextPropertyDefinition)invocation.getInvokedObject(); IPlainTextAnnotationProperty retVal = builder.createPlainTextProperty(testPropDefn); return retVal; } } public static Action buildTextProperty(){ return new CreatePropertyAction(); } public NotationSubsystemFixture(Mockery mockery){ this.mockery = mockery; } public Mockery getMockery(){ return this.mockery; } public void buildFixture(){ this.notationSubsystem = mockery.mock(INotationSubsystem.class, "notationSubsystem"); this.syntaxService = mockery.mock(INotationSyntaxService.class, "syntaxService"); this.rootType = mockery.mock(IRootObjectType.class, "rootType"); this.rootTypeParenting = mockery.mock(IObjectTypeParentingRules.class, "rootTypeParenting"); this.notation = mockery.mock(INotation.class, "notation"); MockShapeObjectTypeBuilder showObjectTypeABuilder = new MockShapeObjectTypeBuilder(mockery, syntaxService, SHAPE_TYPE_A_ID, "shapeTypeA"); showObjectTypeABuilder.addTextProperty(SHAPE_TYPE_A_PROP_NAME, "PropNameAValue", true, true); showObjectTypeABuilder.build(); this.shapeTypeA = showObjectTypeABuilder.getObjectType(); MockShapeObjectTypeBuilder showObjectTypeBBuilder = new MockShapeObjectTypeBuilder(mockery, syntaxService, SHAPE_TYPE_B_ID, "shapeTypeB"); showObjectTypeBBuilder.addTextProperty(SHAPE_TYPE_B_PROP_NAME, "PropNameBValue", true, false); showObjectTypeBBuilder.build(); this.shapeTypeB = showObjectTypeBBuilder.getObjectType(); MockShapeObjectTypeBuilder showObjectTypeCBuilder = new MockShapeObjectTypeBuilder(mockery, syntaxService, SHAPE_TYPE_C_ID, "shapeTypeC"); showObjectTypeCBuilder.build(); this.shapeTypeC = showObjectTypeCBuilder.getObjectType(); showObjectTypeABuilder.buildParentingRules(shapeTypeA, shapeTypeC); showObjectTypeBBuilder.buildParentingRules(shapeTypeA, shapeTypeB); showObjectTypeCBuilder.buildParentingRules(); MockLinkObjectTypeBuilder linkTypeDBuilder = new MockLinkObjectTypeBuilder(mockery, syntaxService, LINK_TYPE_D_ID, "linkTypeD"); linkTypeDBuilder.build(); this.linkTypeD = linkTypeDBuilder.getObjectType(); MockLinkObjectTypeBuilder linkTypeEBuilder = new MockLinkObjectTypeBuilder(mockery, syntaxService, LINK_TYPE_E_ID, "linkTypeE"); linkTypeEBuilder.build(); this.linkTypeE = linkTypeEBuilder.getObjectType(); MockLabelObjectTypeBuilder labelTypeBuilder = new MockLabelObjectTypeBuilder(mockery, syntaxService, LABEL_TYPE_ID, "labelType"); labelTypeBuilder.build(); this.labelObjectType = labelTypeBuilder.getObjectType(); MockAnchorNodeObjectTypeBuilder anchorNodeTypeBuilder = new MockAnchorNodeObjectTypeBuilder(mockery, syntaxService, ANCHOR_NODE_TYPE_ID, "anchorNodeType"); anchorNodeTypeBuilder.build(); this.anchorNodeType = anchorNodeTypeBuilder.getObjectType(); linkTypeDBuilder.buildParentingRules(this.anchorNodeType); linkTypeDBuilder.setSources(this.shapeTypeA, this.anchorNodeType); linkTypeDBuilder.setTargets(this.shapeTypeA, this.shapeTypeB); linkTypeDBuilder.buildConnectionRules(); linkTypeEBuilder.buildParentingRules(this.anchorNodeType); linkTypeEBuilder.setSources(this.shapeTypeB); linkTypeEBuilder.setTargets(this.shapeTypeA); linkTypeEBuilder.buildConnectionRules(); this.mockery.checking(new Expectations(){{ allowing(notationSubsystem).getNotation(); will(returnValue(notation)); allowing(notationSubsystem).getSyntaxService(); will(returnValue(syntaxService)); allowing(syntaxService).getNotationSubsystem(); will(returnValue(notationSubsystem)); allowing(syntaxService).getRootObjectType(); will(returnValue(rootType)); allowing(syntaxService).getShapeObjectType(SHAPE_TYPE_A_ID); will(returnValue(shapeTypeA)); allowing(syntaxService).getShapeObjectType(SHAPE_TYPE_B_ID); will(returnValue(shapeTypeB)); allowing(syntaxService).getShapeObjectType(SHAPE_TYPE_C_ID); will(returnValue(shapeTypeC)); allowing(syntaxService).getLinkObjectType(LINK_TYPE_D_ID); will(returnValue(linkTypeD)); allowing(syntaxService).getLinkObjectType(LINK_TYPE_E_ID); will(returnValue(linkTypeE)); allowing(syntaxService).getAnchorNodeObjectType(ANCHOR_NODE_TYPE_ID); will(returnValue(anchorNodeType)); allowing(syntaxService).getObjectType(ROOT_TYPE_ID); will(returnValue(rootType)); allowing(syntaxService).getObjectType(SHAPE_TYPE_A_ID); will(returnValue(shapeTypeA)); allowing(syntaxService).getObjectType(SHAPE_TYPE_B_ID); will(returnValue(shapeTypeB)); allowing(syntaxService).getObjectType(SHAPE_TYPE_C_ID); will(returnValue(shapeTypeC)); allowing(syntaxService).getObjectType(LINK_TYPE_D_ID); will(returnValue(linkTypeD)); allowing(syntaxService).getObjectType(LINK_TYPE_E_ID); will(returnValue(linkTypeE)); allowing(syntaxService).getObjectType(ANCHOR_NODE_TYPE_ID); will(returnValue(anchorNodeType)); allowing(syntaxService).objectTypeIterator(); will(returnIterator(rootType, shapeTypeA, shapeTypeB, shapeTypeC, linkTypeD, linkTypeE, anchorNodeType)); allowing(syntaxService).getNotation(); will(returnValue(notation)); allowing(syntaxService).getLabelObjectType(LABEL_TYPE_ID); will(returnValue(labelObjectType)); allowing(syntaxService).getLabelObjectTypeByProperty(with(any(IPropertyDefinition.class))); will(returnValue(labelObjectType)); allowing(syntaxService).isVisualisableProperty(with(any(IPropertyDefinition.class))); will(returnValue(true)); allowing(notation).getDescription(); will(returnValue("Test Fixture Notation")); allowing(notation).getDisplayName(); will(returnValue("Fixture Notation")); allowing(notation).getQualifiedName(); will(returnValue("org.pathwayeditor.businessobjects.notation.testfixture")); allowing(notation).getVersion(); will(returnValue(new Version(1, 0, 0))); allowing(rootType).getUniqueId(); will(returnValue(ROOT_TYPE_ID)); allowing(rootType).getSyntaxService(); will(returnValue(syntaxService)); allowing(rootType).getName(); will(returnValue("rootName")); allowing(rootType).getDescription(); will(returnValue("Descn")); allowing(rootType).getParentingRules(); will(returnValue(rootTypeParenting)); allowing(rootTypeParenting).getObjectType(); will(returnValue(rootType)); allowing(rootTypeParenting).isValidChild(with(not(isOneOf(shapeTypeA, shapeTypeB, shapeTypeC)))); will(returnValue(false)); allowing(rootTypeParenting).isValidChild(with(isOneOf(shapeTypeA, shapeTypeB, shapeTypeC))); will(returnValue(true)); }}); } public INotationSubsystem getNotationSubsystem(){ return this.notationSubsystem; } }
10,354
0.808899
0.807355
197
51.59391
37.023075
157
false
false
0
0
0
0
0
0
2.568528
false
false
2
7c784a9bd3721618f53888316ef2b7d23f8470d9
13,623,636,274,624
a6e9d2061c18799961c3981a5a9c868cfcbcc016
/src/main/java/com/edward/algorithm/sort/insert/InsertSort2.java
bc309b087a5adaaef045867c41dec8491bc4a30d
[]
no_license
MrEdward2546/java_practice
https://github.com/MrEdward2546/java_practice
423fe5526cc5a16cb8b325221f123a121686a847
8122214bc1cd3294da4535fba8f8791ef3946134
refs/heads/master
2022-06-22T23:40:42.370000
2020-05-14T11:06:22
2020-05-14T11:06:22
263,890,684
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2018. 天津小多科技有限公司. * Site: http://xiaoduo.io * Email: shj@xiaoduo.io * FileName: InsertSort2 * CreationDate: 2020/4/2 * Author edward */ package com.edward.algorithm.sort.insert; import com.edward.algorithm.sort.Sort; /** * TODO * * @author edward * @see * @since */ public class InsertSort2<E extends Comparable<E>> implements Sort<E> { public static void main(String[] args) { Integer[] data = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; new InsertSort2<Integer>().sort(data); for (Integer datum : data) { System.out.println(datum); } } @Override public void sort(E[] data) { sort2(data); } private void sort1(E[] data) { for (int i = 1; i < data.length; i++) { for (int j = i; j > 0 && data[j].compareTo(data[j - 1]) > 0; j--) { E temp = data[j]; data[j] = data[j - 1]; data[j - 1] = temp; } } } private void sort2(E[] data) { for (int i = 1; i < data.length; i++) { E temp = data[i]; int j = i; for (; j > 0 && data[j - 1].compareTo(temp) < 0; j--) { data[j] = data[j-1]; } data[j] = temp; } } }
UTF-8
Java
1,343
java
InsertSort2.java
Java
[ { "context": "* Site: http://xiaoduo.io\n * Email: shj@xiaoduo.io\n * FileName: InsertSort2\n * CreationDate: 202", "end": 105, "score": 0.9999229907989502, "start": 91, "tag": "EMAIL", "value": "shj@xiaoduo.io" }, { "context": " InsertSort2\n * CreationDate: 2020/4/2\n * Author edward\n */\npackage com.edward.algorithm.sort.insert;\n\nim", "end": 177, "score": 0.995469331741333, "start": 171, "tag": "NAME", "value": "edward" }, { "context": "rd.algorithm.sort.Sort;\n\n/**\n * TODO\n *\n * @author edward\n * @see\n * @since\n */\npublic class InsertSort2<E ", "end": 297, "score": 0.9958346486091614, "start": 291, "tag": "NAME", "value": "edward" } ]
null
[]
/* * Copyright (c) 2018. 天津小多科技有限公司. * Site: http://xiaoduo.io * Email: <EMAIL> * FileName: InsertSort2 * CreationDate: 2020/4/2 * Author edward */ package com.edward.algorithm.sort.insert; import com.edward.algorithm.sort.Sort; /** * TODO * * @author edward * @see * @since */ public class InsertSort2<E extends Comparable<E>> implements Sort<E> { public static void main(String[] args) { Integer[] data = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; new InsertSort2<Integer>().sort(data); for (Integer datum : data) { System.out.println(datum); } } @Override public void sort(E[] data) { sort2(data); } private void sort1(E[] data) { for (int i = 1; i < data.length; i++) { for (int j = i; j > 0 && data[j].compareTo(data[j - 1]) > 0; j--) { E temp = data[j]; data[j] = data[j - 1]; data[j - 1] = temp; } } } private void sort2(E[] data) { for (int i = 1; i < data.length; i++) { E temp = data[i]; int j = i; for (; j > 0 && data[j - 1].compareTo(temp) < 0; j--) { data[j] = data[j-1]; } data[j] = temp; } } }
1,336
0.472411
0.4452
55
23.054546
20.132668
79
false
false
0
0
0
0
0
0
0.527273
false
false
2
7f0b0607013c69cca754a0b1f80b024333457a95
33,225,867,013,663
0bd31f8d82adc091495be18397601e09cab85193
/guard-server/src/main/java/com/demkada/guard/server/commons/utils/GuardLogLayout.java
1f179e65402ed8f801c589449116b43263ebe689
[ "Apache-2.0" ]
permissive
gitter-badger/guard
https://github.com/gitter-badger/guard
c6ad6964e5967156ef5cb9258d67dd59cd51290f
6cf330b36b619be1b3d878786bfc94e2962c29cf
refs/heads/master
2020-05-22T19:34:19.391000
2019-05-13T12:09:45
2019-05-13T12:09:45
186,492,687
1
0
null
true
2019-05-13T20:43:01
2019-05-13T20:43:00
2019-05-13T12:09:48
2019-05-13T12:09:46
7,405
0
0
0
null
false
false
package com.demkada.guard.server.commons.utils; /* * Copyright 2019 DEMKADA. * * 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. * * @author <a href="mailto:kad@demkada.com">Kad D.</a> */ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.contrib.json.classic.JsonLayout; import io.vertx.core.json.JsonObject; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Map; import java.util.Objects; public class GuardLogLayout extends JsonLayout { @SuppressWarnings("unchecked") @Override protected Map toJsonMap(ILoggingEvent event) { Map map = super.toJsonMap(event); map.remove(MDC_ATTR_NAME); map.remove(FORMATTED_MESSAGE_ATTR_NAME); try { map.put("content", new JsonObject(event.getFormattedMessage())); } catch (Exception e) { map.put("content", event.getFormattedMessage()); } event.getMDCPropertyMap().forEach(map::put); if (!map.containsKey("type")) { map.put(Constant.TYPE, "LOG"); } final String source = "source"; if (Objects.nonNull(System.getenv("GUARD_INSTANCE_NAME"))) { map.put(source, System.getenv("GUARD_INSTANCE_NAME")); } if (!map.containsKey(source)){ try { map.put(source, InetAddress.getLocalHost().getCanonicalHostName()); } catch (UnknownHostException e) { return map; } } return map; } }
UTF-8
Java
2,038
java
GuardLogLayout.java
Java
[ { "context": " under the License.\n *\n * @author <a href=\"mailto:kad@demkada.com\">Kad D.</a>\n*/\n\n\nimport ch.qos.logback.classic.sp", "end": 678, "score": 0.9999288320541382, "start": 663, "tag": "EMAIL", "value": "kad@demkada.com" }, { "context": "e.\n *\n * @author <a href=\"mailto:kad@demkada.com\">Kad D.</a>\n*/\n\n\nimport ch.qos.logback.classic.spi.ILogging", "end": 685, "score": 0.9859315156936646, "start": 680, "tag": "NAME", "value": "Kad D" } ]
null
[]
package com.demkada.guard.server.commons.utils; /* * Copyright 2019 DEMKADA. * * 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. * * @author <a href="mailto:<EMAIL>"><NAME>.</a> */ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.contrib.json.classic.JsonLayout; import io.vertx.core.json.JsonObject; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Map; import java.util.Objects; public class GuardLogLayout extends JsonLayout { @SuppressWarnings("unchecked") @Override protected Map toJsonMap(ILoggingEvent event) { Map map = super.toJsonMap(event); map.remove(MDC_ATTR_NAME); map.remove(FORMATTED_MESSAGE_ATTR_NAME); try { map.put("content", new JsonObject(event.getFormattedMessage())); } catch (Exception e) { map.put("content", event.getFormattedMessage()); } event.getMDCPropertyMap().forEach(map::put); if (!map.containsKey("type")) { map.put(Constant.TYPE, "LOG"); } final String source = "source"; if (Objects.nonNull(System.getenv("GUARD_INSTANCE_NAME"))) { map.put(source, System.getenv("GUARD_INSTANCE_NAME")); } if (!map.containsKey(source)){ try { map.put(source, InetAddress.getLocalHost().getCanonicalHostName()); } catch (UnknownHostException e) { return map; } } return map; } }
2,031
0.652601
0.648675
63
31.349207
24.657114
83
false
false
0
0
0
0
0
0
0.47619
false
false
2
207278fe682e64eb51e449aa5bec44cbe237f99e
27,023,934,236,573
a3143d3412fc174d7554f3a955ce301719baaa0f
/zhoukaolianxi01/src/main/java/com/example/zhoukaolianxi01/fragment/LeftFragmnet.java
eae04c963bfc4790e9c9b228156416d0d42c2305
[]
no_license
houhou1349010738/github
https://github.com/houhou1349010738/github
f7d76c7907c7a84198184a739dbae10da7a5d029
4d9b7e4c46af9f1937cafd3f45bf8f30ff33d3cb
refs/heads/master
2021-01-19T08:13:18.821000
2017-05-12T13:49:53
2017-05-12T13:49:53
87,612,591
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.zhoukaolianxi01.fragment; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.example.zhoukaolianxi01.Bean.Jsonbean; import com.example.zhoukaolianxi01.Httputlis.MyHttp; import com.example.zhoukaolianxi01.R; import com.example.zhoukaolianxi01.UrlUtils.Myurl; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; /** * Created by sus on 2017/4/15. */ public class LeftFragmnet extends Fragment { private ListView list; private TextView tv; private Onclicklisten oncli; private List<String> name= new ArrayList<>(); private Handler han = new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what==1){ String str = (String) msg.obj; Gson gson = new Gson(); Jsonbean jsonbean = gson.fromJson(str, Jsonbean.class); List<Jsonbean.DataBean> data = jsonbean.getData(); for (Jsonbean.DataBean d:data) { name.add(d.getName()); } list.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_expandable_list_item_1,name)); } } }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.laftffrag,container,false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); new MyHttp(han,Myurl.path).start(); list = (ListView) getView().findViewById(R.id.list); tv = (TextView) getView().findViewById(R.id.title_tv); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { oncli.getinpo(name.get(position),position); } }); } public interface Onclicklisten{ public void getinpo(String title,int older); } public void huidiao(Onclicklisten on){ this.oncli=on; } }
UTF-8
Java
2,587
java
LeftFragmnet.java
Java
[ { "context": "ayList;\nimport java.util.List;\n\n\n/**\n * Created by sus on 2017/4/15.\n */\n\npublic class LeftFragmnet exte", "end": 736, "score": 0.97798752784729, "start": 733, "tag": "USERNAME", "value": "sus" } ]
null
[]
package com.example.zhoukaolianxi01.fragment; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.example.zhoukaolianxi01.Bean.Jsonbean; import com.example.zhoukaolianxi01.Httputlis.MyHttp; import com.example.zhoukaolianxi01.R; import com.example.zhoukaolianxi01.UrlUtils.Myurl; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; /** * Created by sus on 2017/4/15. */ public class LeftFragmnet extends Fragment { private ListView list; private TextView tv; private Onclicklisten oncli; private List<String> name= new ArrayList<>(); private Handler han = new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what==1){ String str = (String) msg.obj; Gson gson = new Gson(); Jsonbean jsonbean = gson.fromJson(str, Jsonbean.class); List<Jsonbean.DataBean> data = jsonbean.getData(); for (Jsonbean.DataBean d:data) { name.add(d.getName()); } list.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_expandable_list_item_1,name)); } } }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.laftffrag,container,false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); new MyHttp(han,Myurl.path).start(); list = (ListView) getView().findViewById(R.id.list); tv = (TextView) getView().findViewById(R.id.title_tv); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { oncli.getinpo(name.get(position),position); } }); } public interface Onclicklisten{ public void getinpo(String title,int older); } public void huidiao(Onclicklisten on){ this.oncli=on; } }
2,587
0.672207
0.664476
85
29.435293
26.764528
125
false
false
0
0
0
0
0
0
0.635294
false
false
2
b7a75545d3fc5dd99d1f89f6f72325c26c6278d7
28,415,503,642,994
664ba811edec9f178904a91869d00123498e9a2e
/src/main/java/me/changchao/springcloud/springcloudstreamgh1858/InputStream.java
ae2bd5f6b05a977ffc174c5a88d5de868ac428bd
[]
no_license
chang-chao/spring-cloud-stream-gh1858
https://github.com/chang-chao/spring-cloud-stream-gh1858
807f4fe91b5120886413c081e6b49254937e1f79
dba25203c6df98d7074bc191ea152e56aa720c10
refs/heads/master
2020-09-27T12:47:25.186000
2019-12-08T02:02:47
2019-12-08T02:02:47
226,519,793
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.changchao.springcloud.springcloudstreamgh1858; import org.springframework.cloud.stream.annotation.Input; import org.springframework.messaging.SubscribableChannel; public interface InputStream { @Input("foo") SubscribableChannel subscribe(); }
UTF-8
Java
260
java
InputStream.java
Java
[]
null
[]
package me.changchao.springcloud.springcloudstreamgh1858; import org.springframework.cloud.stream.annotation.Input; import org.springframework.messaging.SubscribableChannel; public interface InputStream { @Input("foo") SubscribableChannel subscribe(); }
260
0.830769
0.815385
9
27.888889
23.63822
57
false
false
0
0
0
0
0
0
0.444444
false
false
2
e465dcda1abbfded61eaf177b3e7698536d738d3
35,845,797,095,141
90a9e9baf2178cd8ac4a002c5592af66fc5ca454
/BiddingSystem/src/main/java/com/bidding/application/exception/UserNotLoggedInException.java
85c12c8c5a967a0f220664a8a2b51509b9203fab
[ "Apache-2.0" ]
permissive
ayushmishra2/BiddingSystem
https://github.com/ayushmishra2/BiddingSystem
bc1a02456f234ed644695a883aadc1219be696e0
5a71bce8307b8795b3ad579f993ff086a67a2f3e
refs/heads/master
2022-12-08T18:29:17.082000
2020-09-15T20:26:03
2020-09-15T20:26:03
295,818,675
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bidding.application.exception; public class UserNotLoggedInException extends RuntimeException { private static final long serialVersionUID = -2979274025291047508L; public UserNotLoggedInException() { super("User Not Logged In"); } }
UTF-8
Java
254
java
UserNotLoggedInException.java
Java
[]
null
[]
package com.bidding.application.exception; public class UserNotLoggedInException extends RuntimeException { private static final long serialVersionUID = -2979274025291047508L; public UserNotLoggedInException() { super("User Not Logged In"); } }
254
0.799213
0.724409
11
22.09091
25.790958
68
false
false
0
0
0
0
0
0
0.727273
false
false
2
a362dd3c5025b084071ee3e99681b0f12c50a2ee
12,128,987,661,050
2fb4adb074f65df4dab34e920aebfc70882204a8
/game-engine/src/main/java/com/xl/game/mina/code/ProtocolEncoderImpl.java
4f8f72d768a77e381f28687595ed53e2cef0ef21
[]
no_license
Ox0400/game-fish-springboot
https://github.com/Ox0400/game-fish-springboot
e6cf69112c503935fa9a986334e69929ab09bfb1
e4f914d88b5574f23f97b96d127bb15579017142
refs/heads/master
2023-03-18T05:45:40.493000
2020-01-10T11:40:31
2020-01-10T11:40:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xl.game.mina.code; import com.google.protobuf.Message; import com.xl.game.message.IDMessage; import com.xl.game.util.MsgUtil; import lombok.extern.slf4j.Slf4j; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import sun.misc.MessageUtils; import java.util.function.Predicate; /** * 消息编码 * * @author xuliang * @date 2019-12-07 * QQ:359135103 */ @Slf4j public class ProtocolEncoderImpl implements ProtocolEncoder { /** * 允许的最大堆积未发送消息条数 */ protected int maxScheduledWriteMessages = 256; /** * 当超过设置的最大堆积消息条数时的处理 */ protected Predicate<IoSession> overScheduledWriteBytesHandler; /** * 编码,格式:数据长度|数据部分 * * @param session * @param obj * @param out * @throws Exception */ @Override public void encode(IoSession session, Object obj, ProtocolEncoderOutput out) throws Exception { if (getOverScheduledWriteBytesHandler() != null && session.getScheduledWriteMessages() > getMaxScheduledWriteMessages() && getOverScheduledWriteBytesHandler().test(session)) { return; } IoBuffer buf = null; if (obj instanceof Message) { buf = MsgUtil.toIoBuffer((Message) obj); } else if (obj instanceof IDMessage) { buf = MsgUtil.toIobuffer((IDMessage) obj); } else if (obj instanceof IoBuffer) {//必须符合完整的编码格式 buf = (IoBuffer) obj; } else if (obj instanceof byte[]) {//必须符合除去消息长度后的编码格式 byte[] data = (byte[]) obj; buf = IoBuffer.allocate(data.length + 4); buf.putInt(data.length); buf.put(data); } else { log.info("未知的数据类型:{}",obj); return; } if (buf != null && session.isConnected()) { buf.rewind(); // log.warn("发送的数据byte[]{}",IntUtil.BytesToStr(buf.array())); out.write(buf); out.flush(); } } @Override public void dispose(IoSession ioSession) throws Exception { } public int getMaxScheduledWriteMessages() { return maxScheduledWriteMessages; } public void setMaxScheduledWriteMessages(int maxScheduledWriteMessages) { this.maxScheduledWriteMessages = maxScheduledWriteMessages; } public Predicate<IoSession> getOverScheduledWriteBytesHandler() { return overScheduledWriteBytesHandler; } public void setOverScheduledWriteBytesHandler(Predicate<IoSession> overScheduledWriteBytesHandler) { this.overScheduledWriteBytesHandler = overScheduledWriteBytesHandler; } }
UTF-8
Java
2,923
java
ProtocolEncoderImpl.java
Java
[ { "context": "il.function.Predicate;\n\n\n/**\n * 消息编码\n *\n * @author xuliang\n * @date 2019-12-07\n * QQ:359135103\n */\n@Slf4j\npu", "end": 480, "score": 0.9996595978736877, "start": 473, "tag": "USERNAME", "value": "xuliang" } ]
null
[]
package com.xl.game.mina.code; import com.google.protobuf.Message; import com.xl.game.message.IDMessage; import com.xl.game.util.MsgUtil; import lombok.extern.slf4j.Slf4j; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import sun.misc.MessageUtils; import java.util.function.Predicate; /** * 消息编码 * * @author xuliang * @date 2019-12-07 * QQ:359135103 */ @Slf4j public class ProtocolEncoderImpl implements ProtocolEncoder { /** * 允许的最大堆积未发送消息条数 */ protected int maxScheduledWriteMessages = 256; /** * 当超过设置的最大堆积消息条数时的处理 */ protected Predicate<IoSession> overScheduledWriteBytesHandler; /** * 编码,格式:数据长度|数据部分 * * @param session * @param obj * @param out * @throws Exception */ @Override public void encode(IoSession session, Object obj, ProtocolEncoderOutput out) throws Exception { if (getOverScheduledWriteBytesHandler() != null && session.getScheduledWriteMessages() > getMaxScheduledWriteMessages() && getOverScheduledWriteBytesHandler().test(session)) { return; } IoBuffer buf = null; if (obj instanceof Message) { buf = MsgUtil.toIoBuffer((Message) obj); } else if (obj instanceof IDMessage) { buf = MsgUtil.toIobuffer((IDMessage) obj); } else if (obj instanceof IoBuffer) {//必须符合完整的编码格式 buf = (IoBuffer) obj; } else if (obj instanceof byte[]) {//必须符合除去消息长度后的编码格式 byte[] data = (byte[]) obj; buf = IoBuffer.allocate(data.length + 4); buf.putInt(data.length); buf.put(data); } else { log.info("未知的数据类型:{}",obj); return; } if (buf != null && session.isConnected()) { buf.rewind(); // log.warn("发送的数据byte[]{}",IntUtil.BytesToStr(buf.array())); out.write(buf); out.flush(); } } @Override public void dispose(IoSession ioSession) throws Exception { } public int getMaxScheduledWriteMessages() { return maxScheduledWriteMessages; } public void setMaxScheduledWriteMessages(int maxScheduledWriteMessages) { this.maxScheduledWriteMessages = maxScheduledWriteMessages; } public Predicate<IoSession> getOverScheduledWriteBytesHandler() { return overScheduledWriteBytesHandler; } public void setOverScheduledWriteBytesHandler(Predicate<IoSession> overScheduledWriteBytesHandler) { this.overScheduledWriteBytesHandler = overScheduledWriteBytesHandler; } }
2,923
0.654645
0.645902
96
27.59375
29.286152
183
false
false
0
0
0
0
0
0
0.385417
false
false
2
07baeebbfc6ac1a77539491c03666fd96e46216a
5,420,248,741,798
28f226e711f0c921dbd17c4ef4f1b0acff93f0c4
/src/main/java/om2m/monitor/timeComparator.java
d615c58b373933bc53b2b43f25bd363e3521fef0
[]
no_license
namnguyen5497/om2m-monitoring
https://github.com/namnguyen5497/om2m-monitoring
8abd38004fdfaeb3c314c29dedc954bf3bba6f62
169ffd4b0ef11d7dde7636aff4a655744faaa881
refs/heads/master
2022-07-07T12:43:35.979000
2019-11-29T05:57:14
2019-11-29T06:04:46
224,784,816
0
0
null
false
2022-06-29T17:48:42
2019-11-29T05:45:59
2019-11-29T06:05:27
2022-06-29T17:48:42
13
0
0
1
Java
false
false
package om2m.monitor; import java.sql.Timestamp; public class timeComparator { private static Timestamp latest; private String[] buffer; public timeComparator(String[] buffer, Timestamp latest){ this.latest = latest; this.buffer = buffer; } //get the index of CSE whose messsage got printed public int indexSheetWithOutputMess(){ int indexSheetWithOutputMess = 0; //check if buffer is null boolean isNull = true; for(int i = 0; i< buffer.length; i++){ if(buffer[i] != null) isNull = false; } if(isNull){ indexSheetWithOutputMess = -1; } //find 1st non-null element and set min value Timestamp timeStamp; long min_diff = 0; for(int i = 0; i<buffer.length; i++){ if(buffer[i] != null){ timeStamp =Timestamp.valueOf(buffer[i].split("\\|")[0]); min_diff = timeStamp.getTime() - latest.getTime(); break; } } long diff; // fine diff time of all elements and compare to min diff for(int i = 0; i<buffer.length; i++){ if(buffer[i] != null){ timeStamp = Timestamp.valueOf(buffer[i].split("\\|")[0]); diff = timeStamp.getTime() - latest.getTime(); if(diff <= min_diff){ min_diff = diff; indexSheetWithOutputMess = i; } } } if(indexSheetWithOutputMess != -1){ setLatestTimestamp(Timestamp.valueOf(buffer[indexSheetWithOutputMess].split("\\|")[0])); } return indexSheetWithOutputMess; } public void setLatestTimestamp(Timestamp timeStamp){ latest = timeStamp; } public Timestamp getLatestTimestamp(){ return latest; } }
UTF-8
Java
1,627
java
timeComparator.java
Java
[]
null
[]
package om2m.monitor; import java.sql.Timestamp; public class timeComparator { private static Timestamp latest; private String[] buffer; public timeComparator(String[] buffer, Timestamp latest){ this.latest = latest; this.buffer = buffer; } //get the index of CSE whose messsage got printed public int indexSheetWithOutputMess(){ int indexSheetWithOutputMess = 0; //check if buffer is null boolean isNull = true; for(int i = 0; i< buffer.length; i++){ if(buffer[i] != null) isNull = false; } if(isNull){ indexSheetWithOutputMess = -1; } //find 1st non-null element and set min value Timestamp timeStamp; long min_diff = 0; for(int i = 0; i<buffer.length; i++){ if(buffer[i] != null){ timeStamp =Timestamp.valueOf(buffer[i].split("\\|")[0]); min_diff = timeStamp.getTime() - latest.getTime(); break; } } long diff; // fine diff time of all elements and compare to min diff for(int i = 0; i<buffer.length; i++){ if(buffer[i] != null){ timeStamp = Timestamp.valueOf(buffer[i].split("\\|")[0]); diff = timeStamp.getTime() - latest.getTime(); if(diff <= min_diff){ min_diff = diff; indexSheetWithOutputMess = i; } } } if(indexSheetWithOutputMess != -1){ setLatestTimestamp(Timestamp.valueOf(buffer[indexSheetWithOutputMess].split("\\|")[0])); } return indexSheetWithOutputMess; } public void setLatestTimestamp(Timestamp timeStamp){ latest = timeStamp; } public Timestamp getLatestTimestamp(){ return latest; } }
1,627
0.629994
0.622618
68
21.92647
20.328419
91
false
false
0
0
0
0
0
0
2.5
false
false
2
8b9cdb71de55de642efa9fe7064b7c4d013bb400
438,086,681,184
3ba2ed425257130688225e31452290fa7f418429
/src/main/java/com/xylope/sogobot/domain/authorize/advice/AuthorizeAdvice.java
1669ff93d4ecbfc4d46614d034b09675e91b660a
[]
no_license
key-del-jeeinho/sogobot
https://github.com/key-del-jeeinho/sogobot
69d1c902869f22d7df511ac0ac482bd5acd33f0b
0288b376a9d21c4c6de616cd6740f5d983d27056
refs/heads/master
2023-08-14T21:43:00.286000
2021-10-04T23:44:14
2021-10-04T23:44:14
401,511,802
1
0
null
false
2021-09-05T08:57:56
2021-08-30T23:18:24
2021-09-03T01:26:49
2021-09-05T08:57:55
110
1
0
0
Java
false
false
package com.xylope.sogobot.domain.authorize.advice; import com.xylope.sogobot.domain.authorize.exception.AlreadyEnrolledException; import com.xylope.sogobot.infra.exception.EmailSendingFailureException; import com.xylope.sogobot.infra.service.MailSenderService; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.JwtException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.thymeleaf.context.Context; import org.thymeleaf.spring5.SpringTemplateEngine; import javax.mail.MessagingException; import java.sql.SQLIntegrityConstraintViolationException; import java.util.Arrays; @ControllerAdvice ("com.xylope.sogobot.domain.authorize")@Slf4j @RequiredArgsConstructor public class AuthorizeAdvice { private final MailSenderService mailSenderService; private final SpringTemplateEngine templateEngine; @Value("${bot.admin-email") private String adminEmail; @ExceptionHandler(ExpiredJwtException.class) public String handleTokenExpiredError() { return "error/authorize-token-expired"; } @ExceptionHandler(JwtException.class) public String handleJwtException() { return "error/wrong-token"; } @ExceptionHandler(AlreadyEnrolledException.class) public String alreadyEnrolledException() { return "/error/already-enrolled"; } @ExceptionHandler(Exception.class) public void handleUnexpectedException(Exception e) { log.warn("예상치못한 예외가 발생하였습니다!\n" + e.getLocalizedMessage()); Context context = new Context(); context.setVariable("exception-class", e.getClass().getSimpleName()); context.setVariable("exception-reason", e.getLocalizedMessage()); context.setVariable("exception-stack-trace", Arrays.toString(e.getStackTrace())); String content = templateEngine.process("fatal-error-mail-template", context); try { mailSenderService.sendHtmlEmail(adminEmail, "[소고봇] 오류가 발생하였습니다!", content); } catch (MessagingException ex) { throw new EmailSendingFailureException(ex); } } }
UTF-8
Java
2,346
java
AuthorizeAdvice.java
Java
[]
null
[]
package com.xylope.sogobot.domain.authorize.advice; import com.xylope.sogobot.domain.authorize.exception.AlreadyEnrolledException; import com.xylope.sogobot.infra.exception.EmailSendingFailureException; import com.xylope.sogobot.infra.service.MailSenderService; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.JwtException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.thymeleaf.context.Context; import org.thymeleaf.spring5.SpringTemplateEngine; import javax.mail.MessagingException; import java.sql.SQLIntegrityConstraintViolationException; import java.util.Arrays; @ControllerAdvice ("com.xylope.sogobot.domain.authorize")@Slf4j @RequiredArgsConstructor public class AuthorizeAdvice { private final MailSenderService mailSenderService; private final SpringTemplateEngine templateEngine; @Value("${bot.admin-email") private String adminEmail; @ExceptionHandler(ExpiredJwtException.class) public String handleTokenExpiredError() { return "error/authorize-token-expired"; } @ExceptionHandler(JwtException.class) public String handleJwtException() { return "error/wrong-token"; } @ExceptionHandler(AlreadyEnrolledException.class) public String alreadyEnrolledException() { return "/error/already-enrolled"; } @ExceptionHandler(Exception.class) public void handleUnexpectedException(Exception e) { log.warn("예상치못한 예외가 발생하였습니다!\n" + e.getLocalizedMessage()); Context context = new Context(); context.setVariable("exception-class", e.getClass().getSimpleName()); context.setVariable("exception-reason", e.getLocalizedMessage()); context.setVariable("exception-stack-trace", Arrays.toString(e.getStackTrace())); String content = templateEngine.process("fatal-error-mail-template", context); try { mailSenderService.sendHtmlEmail(adminEmail, "[소고봇] 오류가 발생하였습니다!", content); } catch (MessagingException ex) { throw new EmailSendingFailureException(ex); } } }
2,346
0.762445
0.760699
61
36.540985
26.213232
89
false
false
0
0
0
0
0
0
0.590164
false
false
2
3e7f71af7068541a508166e94ca8c6808d492149
36,361,193,171,708
67abd381890ac4f4a139a807abe5d81c9481d66e
/Clase11/AprendiendoJDBC2/src/main/java/prueba/Prueba09.java
04ea0d6039068f9eeb5521e197e31773f906f780
[]
no_license
gcoronelc/IGH_ENERO_2021
https://github.com/gcoronelc/IGH_ENERO_2021
a1db0f76671132391bc610785a51fe1ee7b05f4d
c92c252fabe9bb89a5926eee98506d327584a44f
refs/heads/main
2023-03-23T18:50:41.134000
2021-03-12T22:30:49
2021-03-12T22:30:49
334,929,614
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package prueba; import java.util.List; import java.util.Map; import pe.igh.app.service.impl.ConsultasImpl; import pe.igh.app.service.impl.CuentaImpl; import pe.igh.app.service.spec.ConsultasSpec; import pe.igh.app.service.spec.CuentaSpec; /** * @author Eric Gustavo Coronel Castillo * @blog www.desarrollasoftware.com * @email gcoronelc@gmail.com * @youtube www.youtube.com/c/DesarrollaSoftware * @facebook www.facebook.com/groups/desarrollasoftware/ */ public class Prueba09 { public static void main(String[] args) { try { CuentaSpec cuentaService = new CuentaImpl(); cuentaService.registrarMovimiento("00100001", 200.0, "0005"); System.out.println("PRoceso ok."); } catch (Exception e) { System.err.println(e.getMessage()); } } }
UTF-8
Java
764
java
Prueba09.java
Java
[ { "context": "e.igh.app.service.spec.CuentaSpec;\n\n/**\n * @author Eric Gustavo Coronel Castillo\n * @blog www.desarrollasoftware.com\n * @email gco", "end": 285, "score": 0.999882161617279, "start": 256, "tag": "NAME", "value": "Eric Gustavo Coronel Castillo" }, { "context": "illo\n * @blog www.desarrollasoftware.com\n * @email gcoronelc@gmail.com\n * @youtube www.youtube.com/c/DesarrollaSoftware\n", "end": 351, "score": 0.9999244213104248, "start": 332, "tag": "EMAIL", "value": "gcoronelc@gmail.com" } ]
null
[]
package prueba; import java.util.List; import java.util.Map; import pe.igh.app.service.impl.ConsultasImpl; import pe.igh.app.service.impl.CuentaImpl; import pe.igh.app.service.spec.ConsultasSpec; import pe.igh.app.service.spec.CuentaSpec; /** * @author <NAME> * @blog www.desarrollasoftware.com * @email <EMAIL> * @youtube www.youtube.com/c/DesarrollaSoftware * @facebook www.facebook.com/groups/desarrollasoftware/ */ public class Prueba09 { public static void main(String[] args) { try { CuentaSpec cuentaService = new CuentaImpl(); cuentaService.registrarMovimiento("00100001", 200.0, "0005"); System.out.println("PRoceso ok."); } catch (Exception e) { System.err.println(e.getMessage()); } } }
729
0.73822
0.71466
29
25.344828
19.687693
64
false
false
0
0
0
0
0
0
1.172414
false
false
2
b24b76dd937ed3c82a8ab48bd25ad9e58851daa2
33,492,154,991,897
5e3db36f20b7fdbdeaa955acfad29ef4a54c4024
/Algorithms/src/algorithm/leetcode/DynamicProgramming.java
e4c15742216b129d0044c52961c6a4faf703d95d
[]
no_license
chaoling/Algorithms
https://github.com/chaoling/Algorithms
130d226ab718c1538124a58412215327be6c6985
f50e4965d66fbf9bb7277ce2bef61e2b6c17252e
refs/heads/master
2020-12-24T10:11:17.739000
2016-11-09T01:59:24
2016-11-09T01:59:24
73,244,171
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package algorithm.leetcode; public class DynamicProgramming { }
UTF-8
Java
66
java
DynamicProgramming.java
Java
[]
null
[]
package algorithm.leetcode; public class DynamicProgramming { }
66
0.80303
0.80303
5
12.2
14.661514
33
false
false
0
0
0
0
0
0
0.2
false
false
2
41354985b263691a3f7acb7462e6ee2f3e9c20f1
33,423,435,512,650
ba2ad04a1780999ed6160e057697d2ebcce2b6fd
/android/User/app/src/main/java/com/example/user/Dasaochu.java
7df9392868c3374a090ff9a8f93d4bb24275b32f
[]
no_license
QiangBoCai/Housekeeping-service
https://github.com/QiangBoCai/Housekeeping-service
3972e422e83194b6eef1131b0eea27f9b9e304d5
a534601b9c22f48275c10a53f2400a360350e919
refs/heads/master
2023-03-17T10:57:10.245000
2017-10-25T19:26:23
2017-10-25T19:26:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.user; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import entity.Servicetype; import entity.Unorder; import entity.Worker; /** * Created by 张广洁 on 2017/2/18. */ public class Dasaochu extends AppCompatActivity { private Servicetype dasaochu; private TextView intro; private TextView price; private Button goaunt; private String session; private List<Worker> dasaochulist=new ArrayList<>(); private Set<Worker> dasaochuset=new HashSet<>(); @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.dasaochu); // requestWindowFeature(Window.FEATURE_NO_TITLE); Intent get=Dasaochu.this.getIntent(); session=get.getStringExtra("session"); dasaochu = (Servicetype)get.getSerializableExtra("dasaochu"); intro=(TextView)findViewById(R.id.dasaochuintro); price=(TextView)findViewById(R.id.dasaochuprice); intro.setText("服务简介:"+dasaochu.getDescription()); price.setText("服务价格:"+dasaochu.getUserPrice().toString()+"元/小时"); dasaochuset=dasaochu.getWorkers(); dasaochulist.addAll(dasaochuset); goaunt=(Button)findViewById(R.id.goaunt_dasaochu); goaunt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent it1 = new Intent(Dasaochu.this, AuntDasaochuActivity.class); it1.putExtra("session",session); Bundle bundle3=new Bundle(); bundle3.putSerializable("dasaochuaunts",(Serializable)dasaochulist); it1.putExtras(bundle3); Dasaochu.this.startActivity(it1); } }); } }
UTF-8
Java
2,283
java
Dasaochu.java
Java
[ { "context": "der;\r\nimport entity.Worker;\r\n\r\n/**\r\n * Created by 张广洁 on 2017/2/18.\r\n */\r\npublic class Dasaochu extends", "end": 593, "score": 0.9996268153190613, "start": 590, "tag": "NAME", "value": "张广洁" } ]
null
[]
package com.example.user; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import entity.Servicetype; import entity.Unorder; import entity.Worker; /** * Created by 张广洁 on 2017/2/18. */ public class Dasaochu extends AppCompatActivity { private Servicetype dasaochu; private TextView intro; private TextView price; private Button goaunt; private String session; private List<Worker> dasaochulist=new ArrayList<>(); private Set<Worker> dasaochuset=new HashSet<>(); @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.dasaochu); // requestWindowFeature(Window.FEATURE_NO_TITLE); Intent get=Dasaochu.this.getIntent(); session=get.getStringExtra("session"); dasaochu = (Servicetype)get.getSerializableExtra("dasaochu"); intro=(TextView)findViewById(R.id.dasaochuintro); price=(TextView)findViewById(R.id.dasaochuprice); intro.setText("服务简介:"+dasaochu.getDescription()); price.setText("服务价格:"+dasaochu.getUserPrice().toString()+"元/小时"); dasaochuset=dasaochu.getWorkers(); dasaochulist.addAll(dasaochuset); goaunt=(Button)findViewById(R.id.goaunt_dasaochu); goaunt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent it1 = new Intent(Dasaochu.this, AuntDasaochuActivity.class); it1.putExtra("session",session); Bundle bundle3=new Bundle(); bundle3.putSerializable("dasaochuaunts",(Serializable)dasaochulist); it1.putExtras(bundle3); Dasaochu.this.startActivity(it1); } }); } }
2,283
0.669924
0.663261
70
30.157143
21.870813
84
false
false
0
0
0
0
0
0
0.7
false
false
2
51cd536967b4d2befa6845db77495dd44e8dcd53
22,711,787,081,522
888d8edfb7e3640e0c334a9f1fa641f6072c984b
/src/main/java/com/utils/GetResponse.java
f700351af9c2afb31379368ed13e09310134cad7
[]
no_license
jravindra/hdjdemo
https://github.com/jravindra/hdjdemo
3b6c92a723d9aa2917c1f1026169bbaf38118ff9
f55a90cf1b699292a618a6561ddea33d32dbe206
refs/heads/master
2020-04-02T21:15:47.596000
2017-03-27T22:49:43
2017-03-27T22:49:43
63,714,810
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.utils; import org.json.JSONException; import org.json.JSONObject; import java.io.*; import java.net.URL; import java.nio.charset.Charset; /** * Created by rjaraja on 7/18/16. */ public class GetResponse { private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } public static void main(String[] args) throws IOException, JSONException { String[] boardUrls = new String[]{ "http://100.65.4.65:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.4.72:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.169:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.173:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.4.64:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.214:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.8.161:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.109:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.8.162:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.8.148:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.4.7:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.199:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.4.57:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.4.66:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.35:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.138.190:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.170:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.168:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.171:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.102:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.101:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.175:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.98:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.174:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.99:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.249.60:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.104:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.4.73:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.64.7.160:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.64.7.213:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.64.7.172:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.64.7.162:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.64.7.19:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.34:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.36:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.64.7.179:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.29:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.32:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.30:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.33:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.64.7.163:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.8.150:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.212:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.48:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.46:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.45:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.222.218:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.195:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.49:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.216.90:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.50:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.44:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.150:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.51:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.47:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.100:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.8.149:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.8.151:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.97:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.8.160:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.8.15:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.212.8:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.64.7.203:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.4.56:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA" }; for (String boardUrl : boardUrls) { try { JSONObject json = readJsonFromUrl(boardUrl); System.out.println("url - " + boardUrl + " - json " + json); } catch (Exception e) { System.out.println(boardUrl); } } } }
UTF-8
Java
10,090
java
GetResponse.java
Java
[ { "context": "mport java.nio.charset.Charset;\n\n/**\n * Created by rjaraja on 7/18/16.\n */\npublic class GetResponse {\n\n p", "end": 178, "score": 0.9996404051780701, "start": 171, "tag": "USERNAME", "value": "rjaraja" }, { "context": "boardUrls = new String[]{\n \"http://100.65.4.65:8080/rest/GetCityStateProvince/results.json?Data.", "end": 1081, "score": 0.9995413422584534, "start": 1070, "tag": "IP_ADDRESS", "value": "100.65.4.65" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.4.72:8080/rest/GetCityStateProvince/results.json?Data.", "end": 1216, "score": 0.9996038675308228, "start": 1205, "tag": "IP_ADDRESS", "value": "100.65.4.72" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.137.169:8080/rest/GetCityStateProvince/results.json?Data.", "end": 1354, "score": 0.9808393716812134, "start": 1340, "tag": "IP_ADDRESS", "value": "10.116.137.169" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.137.173:8080/rest/GetCityStateProvince/results.json?Data.", "end": 1492, "score": 0.9960187673568726, "start": 1478, "tag": "IP_ADDRESS", "value": "10.116.137.173" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.4.64:8080/rest/GetCityStateProvince/results.json?Data.", "end": 1627, "score": 0.999500036239624, "start": 1616, "tag": "IP_ADDRESS", "value": "100.65.4.64" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.9.218.214:8080/rest/GetCityStateProvince/results.json?Data.", "end": 1763, "score": 0.9996106624603271, "start": 1751, "tag": "IP_ADDRESS", "value": "10.9.218.214" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.8.161:8080/rest/GetCityStateProvince/results.json?Data.", "end": 1899, "score": 0.999454915523529, "start": 1887, "tag": "IP_ADDRESS", "value": "100.65.8.161" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.9.218.109:8080/rest/GetCityStateProvince/results.json?Data.", "end": 2035, "score": 0.9994940757751465, "start": 2023, "tag": "IP_ADDRESS", "value": "10.9.218.109" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.8.162:8080/rest/GetCityStateProvince/results.json?Data.", "end": 2171, "score": 0.9993599057197571, "start": 2159, "tag": "IP_ADDRESS", "value": "100.65.8.162" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.8.148:8080/rest/GetCityStateProvince/results.json?Data.", "end": 2307, "score": 0.9971378445625305, "start": 2295, "tag": "IP_ADDRESS", "value": "100.65.8.148" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.4.7:8080/rest/GetCityStateProvince/results.json?Data.", "end": 2441, "score": 0.9984879493713379, "start": 2431, "tag": "IP_ADDRESS", "value": "100.65.4.7" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.9.218.199:8080/rest/GetCityStateProvince/results.json?Data.", "end": 2577, "score": 0.9995678067207336, "start": 2565, "tag": "IP_ADDRESS", "value": "10.9.218.199" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.4.57:8080/rest/GetCityStateProvince/results.json?Data.", "end": 2712, "score": 0.9991527199745178, "start": 2701, "tag": "IP_ADDRESS", "value": "100.65.4.57" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.4.66:8080/rest/GetCityStateProvince/results.json?Dat", "end": 2844, "score": 0.9907985329627991, "start": 2836, "tag": "IP_ADDRESS", "value": "100.65.4" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.10.35:8080/rest/GetCityStateProvince/results.json?Data.", "end": 2983, "score": 0.9890318512916565, "start": 2971, "tag": "IP_ADDRESS", "value": "10.117.10.35" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.138.190:8080/rest/GetCityStateProvince/results.json?Data.", "end": 3121, "score": 0.9908372759819031, "start": 3107, "tag": "IP_ADDRESS", "value": "10.116.138.190" }, { "context": ".Database.US=UAM_USA\",\n \"http://10.116.137.170:8080/rest/GetCityStateProvince/results.", "end": 3249, "score": 0.5141530632972717, "start": 3248, "tag": "IP_ADDRESS", "value": "1" }, { "context": "tabase.US=UAM_USA\",\n \"http://10.116.137.170:8080/rest/GetCityStateProvince/results.json", "end": 3253, "score": 0.8663290739059448, "start": 3252, "tag": "IP_ADDRESS", "value": "1" }, { "context": "se.US=UAM_USA\",\n \"http://10.116.137.170:8080/rest/GetCityStateProvince/results.json?Da", "end": 3255, "score": 0.8590329885482788, "start": 3255, "tag": "IP_ADDRESS", "value": "" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.137.168:8080/rest/GetCityStateProvince/results.json?Data.", "end": 3397, "score": 0.9944419264793396, "start": 3383, "tag": "IP_ADDRESS", "value": "10.116.137.168" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.137.171:8080/rest/GetCityStateProvince/results.json?Data.", "end": 3535, "score": 0.9854725003242493, "start": 3521, "tag": "IP_ADDRESS", "value": "10.116.137.171" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.141.102:8080/rest/GetCityStateProvince/resul", "end": 3660, "score": 0.7348368167877197, "start": 3659, "tag": "IP_ADDRESS", "value": "1" }, { "context": "n.Database.US=UAM_USA\",\n \"http://10.116.141.102:8080/rest/GetCityStateProvince/results", "end": 3661, "score": 0.5921157002449036, "start": 3661, "tag": "IP_ADDRESS", "value": "" }, { "context": "tabase.US=UAM_USA\",\n \"http://10.116.141.102:8080/rest/GetCityStateProvince/results.json?Data", "end": 3672, "score": 0.8631035685539246, "start": 3666, "tag": "IP_ADDRESS", "value": "141.10" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.141.101:8080/rest/GetCityStateProvince/results.json?Data.", "end": 3811, "score": 0.9972508549690247, "start": 3797, "tag": "IP_ADDRESS", "value": "10.116.141.101" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.137.175:8080/rest/GetCityStateProvince/results.json?Data.", "end": 3949, "score": 0.9794411659240723, "start": 3935, "tag": "IP_ADDRESS", "value": "10.116.137.175" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.141.98:8080/rest/GetCityStateProvince/results.json?Data.", "end": 4086, "score": 0.9898790717124939, "start": 4073, "tag": "IP_ADDRESS", "value": "10.116.141.98" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.137.174:8080/rest/GetCityStateProvince/results", "end": 4212, "score": 0.8726687431335449, "start": 4210, "tag": "IP_ADDRESS", "value": "10" }, { "context": ".Database.US=UAM_USA\",\n \"http://10.116.137.174:8080/rest/GetCityStateProvince/results.json?Data.", "end": 4224, "score": 0.9094479084014893, "start": 4213, "tag": "IP_ADDRESS", "value": "116.137.174" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.141.99:8080/rest/GetCityStateProvince/results.json?Data.", "end": 4361, "score": 0.9801123142242432, "start": 4348, "tag": "IP_ADDRESS", "value": "10.116.141.99" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.9.249.60:8080/rest/GetCityStateProvince/results.json?Data.", "end": 4496, "score": 0.9939331412315369, "start": 4485, "tag": "IP_ADDRESS", "value": "10.9.249.60" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.141.104:8080/rest/GetCityStateProvince/results.json?Data.", "end": 4634, "score": 0.9194154143333435, "start": 4620, "tag": "IP_ADDRESS", "value": "10.116.141.104" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.4.73:8080/rest/GetCityStateProvince/results.json?Data.", "end": 4769, "score": 0.9995148181915283, "start": 4758, "tag": "IP_ADDRESS", "value": "100.65.4.73" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.64.7.160:8080/rest/GetCityStateProvince/results.json?Data.", "end": 4905, "score": 0.9995710253715515, "start": 4893, "tag": "IP_ADDRESS", "value": "100.64.7.160" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.64.7.213:8080/rest/GetCityStateProvince/results.json?Data.", "end": 5041, "score": 0.9994327425956726, "start": 5029, "tag": "IP_ADDRESS", "value": "100.64.7.213" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.64.7.172:8080/rest/GetCityStateProvince/results.json?Data.", "end": 5177, "score": 0.9992286562919617, "start": 5165, "tag": "IP_ADDRESS", "value": "100.64.7.172" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.64.7.162:8080/rest/GetCityStateProvince/results.json?Data.", "end": 5313, "score": 0.9994099736213684, "start": 5301, "tag": "IP_ADDRESS", "value": "100.64.7.162" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.64.7.19:8080/rest/GetCityStateProvince/results.json?Data.", "end": 5448, "score": 0.9990573525428772, "start": 5437, "tag": "IP_ADDRESS", "value": "100.64.7.19" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.10.34:8080/rest/GetCityStateProvince/results.json?Data.", "end": 5584, "score": 0.9053661823272705, "start": 5572, "tag": "IP_ADDRESS", "value": "10.117.10.34" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.10.36:8080/rest/GetCityStateProvince/results.json?Data.", "end": 5720, "score": 0.9727491736412048, "start": 5708, "tag": "IP_ADDRESS", "value": "10.117.10.36" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.64.7.179:8080/rest/GetCityStateProvince/results.json?Data.", "end": 5856, "score": 0.999457836151123, "start": 5844, "tag": "IP_ADDRESS", "value": "100.64.7.179" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.10.29:8080/rest/GetCityStateProvince/results", "end": 5981, "score": 0.9198970198631287, "start": 5980, "tag": "IP_ADDRESS", "value": "1" }, { "context": ".Database.US=UAM_USA\",\n \"http://10.117.10.29:8080/rest/GetCityStateProvince/results.js", "end": 5984, "score": 0.6142134070396423, "start": 5983, "tag": "IP_ADDRESS", "value": "1" }, { "context": "tabase.US=UAM_USA\",\n \"http://10.117.10.29:8080/rest/GetCityStateProvince/results.json?D", "end": 5988, "score": 0.8278794288635254, "start": 5987, "tag": "IP_ADDRESS", "value": "1" }, { "context": "ase.US=UAM_USA\",\n \"http://10.117.10.29:8080/rest/GetCityStateProvince/results.json?Data", "end": 5991, "score": 0.9160333871841431, "start": 5990, "tag": "IP_ADDRESS", "value": "2" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.10.32:8080/rest/GetCityStateProvince/results.json?Data.", "end": 6128, "score": 0.9815813899040222, "start": 6116, "tag": "IP_ADDRESS", "value": "10.117.10.32" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.10.30:8080/rest/GetCityStateProvince/results.json?Data.", "end": 6264, "score": 0.9831235408782959, "start": 6252, "tag": "IP_ADDRESS", "value": "10.117.10.30" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.10.33:8080/rest/GetCityStateProvince/results", "end": 6389, "score": 0.9587975740432739, "start": 6388, "tag": "IP_ADDRESS", "value": "1" }, { "context": "n.Database.US=UAM_USA\",\n \"http://10.117.10.33:8080/rest/GetCityStateProvince/results.json?Data.", "end": 6400, "score": 0.9271629452705383, "start": 6391, "tag": "IP_ADDRESS", "value": "117.10.33" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.64.7.163:8080/rest/GetCityStateProvince/results.json?Data.", "end": 6536, "score": 0.9994726181030273, "start": 6524, "tag": "IP_ADDRESS", "value": "100.64.7.163" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.8.150:8080/rest/GetCityStateProvince/results.json?Data.", "end": 6672, "score": 0.999586820602417, "start": 6660, "tag": "IP_ADDRESS", "value": "100.65.8.150" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.9.218.212:8080/rest/GetCityStateProvince/results.json?", "end": 6803, "score": 0.7671942710876465, "start": 6796, "tag": "IP_ADDRESS", "value": "10.9.21" }, { "context": "base.US=UAM_USA\",\n \"http://10.9.218.212:8080/rest/GetCityStateProvince/results.json?Dat", "end": 6806, "score": 0.9131215214729309, "start": 6805, "tag": "IP_ADDRESS", "value": "2" }, { "context": "ase.US=UAM_USA\",\n \"http://10.117.13.48:8080/rest/GetCityStateProvince/results.json?Data", "end": 6943, "score": 0.668746829032898, "start": 6942, "tag": "IP_ADDRESS", "value": "4" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.13.46:8080/rest/GetCityStateProvince/results", "end": 7069, "score": 0.6353566646575928, "start": 7068, "tag": "IP_ADDRESS", "value": "1" }, { "context": "n.Database.US=UAM_USA\",\n \"http://10.117.13.46:8080/rest/GetCityStateProvince/results.jso", "end": 7073, "score": 0.622119128704071, "start": 7071, "tag": "IP_ADDRESS", "value": "11" }, { "context": "tabase.US=UAM_USA\",\n \"http://10.117.13.46:8080/rest/GetCityStateProvince/results.json?Data.", "end": 7080, "score": 0.7762029767036438, "start": 7075, "tag": "IP_ADDRESS", "value": "13.46" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.9.222.218:8080/rest/GetCityStateProvince/results.json?Data.", "end": 7352, "score": 0.9991762042045593, "start": 7340, "tag": "IP_ADDRESS", "value": "10.9.222.218" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.9.218.195:8080/rest/GetCityStateProvince/results.json?Data.", "end": 7488, "score": 0.9971489906311035, "start": 7476, "tag": "IP_ADDRESS", "value": "10.9.218.195" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.13.49:8080/rest/GetCityStateProvince/results", "end": 7613, "score": 0.91527259349823, "start": 7612, "tag": "IP_ADDRESS", "value": "1" }, { "context": "n.Database.US=UAM_USA\",\n \"http://10.117.13.49:8080/rest/GetCityStateProvince/results.jso", "end": 7617, "score": 0.8951119780540466, "start": 7615, "tag": "IP_ADDRESS", "value": "11" }, { "context": "tabase.US=UAM_USA\",\n \"http://10.117.13.49:8080/rest/GetCityStateProvince/results.json?Data.", "end": 7624, "score": 0.8663762211799622, "start": 7619, "tag": "IP_ADDRESS", "value": "13.49" }, { "context": "n.Database.US=UAM_USA\",\n \"http://10.9.216.90:8080/rest/GetCityStateProvince/results.js", "end": 7750, "score": 0.5617095828056335, "start": 7750, "tag": "IP_ADDRESS", "value": "" }, { "context": "Database.US=UAM_USA\",\n \"http://10.9.216.90:8080/rest/GetCityStateProvince/results.json", "end": 7752, "score": 0.5922074317932129, "start": 7752, "tag": "IP_ADDRESS", "value": "" }, { "context": "base.US=UAM_USA\",\n \"http://10.9.216.90:8080/rest/GetCityStateProvince/results.json?Dat", "end": 7756, "score": 0.7426108717918396, "start": 7756, "tag": "IP_ADDRESS", "value": "" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.13.50:8080/rest/GetCityStateProvince/results.json?Data.", "end": 7895, "score": 0.9287722706794739, "start": 7883, "tag": "IP_ADDRESS", "value": "10.117.13.50" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.13.44:8080/rest/GetCityStateProvince/results.json?Data.", "end": 8031, "score": 0.8776943683624268, "start": 8019, "tag": "IP_ADDRESS", "value": "10.117.13.44" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.9.218.150:8080/rest/GetCityStateProvince/results", "end": 8156, "score": 0.5062882900238037, "start": 8155, "tag": "IP_ADDRESS", "value": "1" }, { "context": "n.Database.US=UAM_USA\",\n \"http://10.9.218.150:8080/rest/GetCityStateProvince/results.j", "end": 8157, "score": 0.7116660475730896, "start": 8157, "tag": "IP_ADDRESS", "value": "" }, { "context": "Database.US=UAM_USA\",\n \"http://10.9.218.150:8080/rest/GetCityStateProvince/results.json", "end": 8161, "score": 0.7483049035072327, "start": 8160, "tag": "IP_ADDRESS", "value": "2" }, { "context": "base.US=UAM_USA\",\n \"http://10.9.218.150:8080/rest/GetCityStateProvince/results.json?Dat", "end": 8165, "score": 0.8505728244781494, "start": 8164, "tag": "IP_ADDRESS", "value": "1" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.13.51:8080/rest/GetCityStateProvince/results.json?Data.", "end": 8303, "score": 0.936717689037323, "start": 8291, "tag": "IP_ADDRESS", "value": "10.117.13.51" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.117.13.47:8080/rest/GetCityStateProvince/results.json?Data.", "end": 8439, "score": 0.8286098837852478, "start": 8427, "tag": "IP_ADDRESS", "value": "10.117.13.47" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.141.100:8080/rest/GetCityStateProvince/results.json?Data.", "end": 8577, "score": 0.8504714369773865, "start": 8563, "tag": "IP_ADDRESS", "value": "10.116.141.100" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.8.149:8080/rest/GetCityStateProvince/results.json?Data.", "end": 8713, "score": 0.9987666010856628, "start": 8701, "tag": "IP_ADDRESS", "value": "100.65.8.149" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.8.151:8080/rest/GetCityStateProvince/results.json?Data.", "end": 8849, "score": 0.9990120530128479, "start": 8837, "tag": "IP_ADDRESS", "value": "100.65.8.151" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.116.141.97:8080/rest/GetCityStateProvince/results.json?Data.", "end": 8986, "score": 0.9794101715087891, "start": 8973, "tag": "IP_ADDRESS", "value": "10.116.141.97" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.8.160:8080/rest/GetCityStateProvince/results.json?Data.", "end": 9122, "score": 0.9982938766479492, "start": 9110, "tag": "IP_ADDRESS", "value": "100.65.8.160" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.8.15:8080/rest/GetCityStateProvince/results.json?Data.", "end": 9257, "score": 0.9996177554130554, "start": 9246, "tag": "IP_ADDRESS", "value": "100.65.8.15" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://10.9.212.8:8080/rest/GetCityStateProvince/results.json?Data.", "end": 9391, "score": 0.9991018176078796, "start": 9381, "tag": "IP_ADDRESS", "value": "10.9.212.8" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.64.7.203:8080/rest/GetCityStateProvince/results.json?Data.", "end": 9527, "score": 0.999518632888794, "start": 9515, "tag": "IP_ADDRESS", "value": "100.64.7.203" }, { "context": "ion.Database.US=UAM_USA\",\n \"http://100.65.4.56:8080/rest/GetCityStateProvince/results.json?Data.", "end": 9662, "score": 0.9995716214179993, "start": 9651, "tag": "IP_ADDRESS", "value": "100.65.4.56" } ]
null
[]
package com.utils; import org.json.JSONException; import org.json.JSONObject; import java.io.*; import java.net.URL; import java.nio.charset.Charset; /** * Created by rjaraja on 7/18/16. */ public class GetResponse { private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } public static void main(String[] args) throws IOException, JSONException { String[] boardUrls = new String[]{ "http://192.168.127.12:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://192.168.127.12:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.169:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.173:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://192.168.127.12:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.214:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.31.10:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.109:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.31.10:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://192.168.3.11:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://192.168.127.12:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.199:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.58.3:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://100.65.4.66:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.35:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.138.190:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.170:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.168:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.171:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.102:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.101:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.175:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.98:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.137.174:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.99:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.249.60:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.104:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.17.32:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.58.3:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.17.32:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://192.168.3.11:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.17.32:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.31.10:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.34:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.36:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.58.3:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.29:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.32:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.30:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.10.33:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.17.32:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.58.3:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.212:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.48:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.46:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.45:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.222.218:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.195:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.49:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.216.90:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.50:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.44:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.218.150:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.51:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.117.13.47:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.100:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://192.168.3.11:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://192.168.3.11:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.116.141.97:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.31.10:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://192.168.127.12:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://10.9.212.8:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://172.16.58.3:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA", "http://192.168.127.12:8080/rest/GetCityStateProvince/results.json?Data.PostalCode=794231100&Option.Database.US=UAM_USA" }; for (String boardUrl : boardUrls) { try { JSONObject json = readJsonFromUrl(boardUrl); System.out.println("url - " + boardUrl + " - json " + json); } catch (Exception e) { System.out.println(boardUrl); } } } }
10,107
0.694252
0.552825
116
85.982758
57.159332
137
false
false
0
0
0
0
0
0
0.741379
false
false
2
1d70b59ab9364e2e5e8cd0d4863ccb095af8be73
12,257,836,682,281
c60a2c84feeaec71b8c513fb873f6d84b23c6c83
/HW28.12.20.java
d38e27d6c52ca2d01a54565169fadd72d4faddbb
[]
no_license
orkol1988/HomeWork
https://github.com/orkol1988/HomeWork
5089456b14f6bc9d95e4e72a00d234c0e3e63c40
8c3ef0659489f924a51530a6ff56d4c30af781d1
refs/heads/main
2023-05-10T11:26:50.463000
2021-06-07T14:25:59
2021-06-07T14:25:59
316,295,106
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); Random r = new Random(); //Home work //1. input array size from user //create int array in the given size //populate the array with random numbers //sum the array //print the average number System.out.println("Please input array size: "); int[] arr_int3 = new int[s.nextInt()]; for (int i9 = 0; i9 < arr_int3.length; i9++) { arr_int3[i9] = r.nextInt(100); } int sum2 = 0; for (int i10 = 0; i10 < arr_int3.length; i10++) { sum2 += arr_int3[i10]; } float avg = sum2 / arr_int3.length; System.out.println(String.format("The average of the class is: %g", avg)); //2. create an array of 5 Strings (hint: String[] word = new String[5]) //create a for loop and input words from the user into the array //now print the array in a for loop //*** etgar: print the average length of the words, i.e. hello java book pro about. the words length is [5,4,4,3,5] => average=4.2 String[] arr_string = new String[5]; for (int i14 = 0; i14 < arr_string.length; i14++) { System.out.println("Please input a word: "); arr_string[i14] = s.next(); } for (int i15 = 0; i15 < arr_string.length; i15++) { System.out.println(arr_string[i15]); } int sum_of_letters = 0; float avg_of_letters = 0; for (int i16 = 0; i16 < arr_string.length; i16++) { sum_of_letters += arr_string[i16].length(); } avg_of_letters = sum_of_letters / arr_string.length; System.out.println(String.format("the average of string length is: %g", avg_of_letters)); //3. create int array A with random numbers (size of 5) //create int array B with random numbers (size of 5) //create int array C (size of 5) which each element will be the sum of A+B //for exmaple: //A [ 5, 8, 6, 2, 3] -- random //B [ 3, 7, 8, 3, 1] -- random //C [ 8,15,14, 5, 4] -- sum int[] arr_random_a = new int[5]; for (int i17 = 0; i17 < arr_random_a.length; i17++) { arr_random_a[i17] = r.nextInt(10) + 1; System.out.println(arr_random_a[i17]); } int[] arr_random_b = new int[5]; for (int i18 = 0; i18 < arr_random_b.length; i18++) { arr_random_b[i18] = r.nextInt(10) + 1; System.out.println(arr_random_b[i18]); } int[] arr_random_c = new int[5]; for (int i19 = 0; i19 < arr_random_c.length; i19++) { arr_random_c[i19] = arr_random_a[i19] + arr_random_b[i19]; } //*etgar: create int array D which will contain the larger name from A or B //*D[ 5, 8, 8, 3, 3] int[] arr_random_d = new int[5]; for (int i20 = 0; i20 < arr_random_d.length; i20++) { if (arr_random_a[i20] > arr_random_b[i20]) { arr_random_d[i20] = arr_random_a[i20]; } else { arr_random_d[i20] = arr_random_b[i20]; } } //*etgar: create in array E which will be concat of the array A and B //*E[ 5, 8, 6, 2, 3, 3, 7, 8, 3, 1] int[] arr_random_ab = new int[10]; for (int i21 = 0; i21 < arr_random_ab.length / 2; i21++) { arr_random_ab[i21] = arr_random_a[i21]; } int i23 = 0; for (int i22 = 5; i22 < arr_random_ab.length; i22++) { arr_random_ab[i22] = arr_random_b[i23]; i23++; } for (int i24 = 0; i24 < arr_random_ab.length; i24++) { System.out.println(arr_random_ab[i24]); } //4. ***etgar crazy: //input number of classes from user //for each size input number of students //input all numbers from user //calculate the average of each class in an array //calculate the average of averages float sum_of_avg = 0; float total_avg = 0; System.out.println("Please input # of classes: "); int[] classes = new int[s.nextInt()]; for (int i11 = 0; i11 < classes.length; i11++) { System.out.println(String.format("Please input number of student in class #%d: ", i11 + 1)); int[] arr_grades = new int[s.nextInt()]; for (int i12 = 0; i12 < arr_grades.length; i12++) { System.out.println(String.format("Please input grade of student #%d: ", i12 + 1)); arr_grades[i12] = s.nextInt(); } int sum_of_class = 0; for (int i13 = 0; i13 < arr_grades.length; i13++) { sum_of_class += arr_grades[i13]; } float avg_of_class = sum_of_class / arr_grades.length; System.out.println(String.format("The average of the class is: %g", avg_of_class)); sum_of_avg += avg_of_class; total_avg = sum_of_avg / classes.length; } System.out.println(String.format("The average of all classes is: %g", total_avg)); } }
UTF-8
Java
5,349
java
HW28.12.20.java
Java
[]
null
[]
package com.company; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); Random r = new Random(); //Home work //1. input array size from user //create int array in the given size //populate the array with random numbers //sum the array //print the average number System.out.println("Please input array size: "); int[] arr_int3 = new int[s.nextInt()]; for (int i9 = 0; i9 < arr_int3.length; i9++) { arr_int3[i9] = r.nextInt(100); } int sum2 = 0; for (int i10 = 0; i10 < arr_int3.length; i10++) { sum2 += arr_int3[i10]; } float avg = sum2 / arr_int3.length; System.out.println(String.format("The average of the class is: %g", avg)); //2. create an array of 5 Strings (hint: String[] word = new String[5]) //create a for loop and input words from the user into the array //now print the array in a for loop //*** etgar: print the average length of the words, i.e. hello java book pro about. the words length is [5,4,4,3,5] => average=4.2 String[] arr_string = new String[5]; for (int i14 = 0; i14 < arr_string.length; i14++) { System.out.println("Please input a word: "); arr_string[i14] = s.next(); } for (int i15 = 0; i15 < arr_string.length; i15++) { System.out.println(arr_string[i15]); } int sum_of_letters = 0; float avg_of_letters = 0; for (int i16 = 0; i16 < arr_string.length; i16++) { sum_of_letters += arr_string[i16].length(); } avg_of_letters = sum_of_letters / arr_string.length; System.out.println(String.format("the average of string length is: %g", avg_of_letters)); //3. create int array A with random numbers (size of 5) //create int array B with random numbers (size of 5) //create int array C (size of 5) which each element will be the sum of A+B //for exmaple: //A [ 5, 8, 6, 2, 3] -- random //B [ 3, 7, 8, 3, 1] -- random //C [ 8,15,14, 5, 4] -- sum int[] arr_random_a = new int[5]; for (int i17 = 0; i17 < arr_random_a.length; i17++) { arr_random_a[i17] = r.nextInt(10) + 1; System.out.println(arr_random_a[i17]); } int[] arr_random_b = new int[5]; for (int i18 = 0; i18 < arr_random_b.length; i18++) { arr_random_b[i18] = r.nextInt(10) + 1; System.out.println(arr_random_b[i18]); } int[] arr_random_c = new int[5]; for (int i19 = 0; i19 < arr_random_c.length; i19++) { arr_random_c[i19] = arr_random_a[i19] + arr_random_b[i19]; } //*etgar: create int array D which will contain the larger name from A or B //*D[ 5, 8, 8, 3, 3] int[] arr_random_d = new int[5]; for (int i20 = 0; i20 < arr_random_d.length; i20++) { if (arr_random_a[i20] > arr_random_b[i20]) { arr_random_d[i20] = arr_random_a[i20]; } else { arr_random_d[i20] = arr_random_b[i20]; } } //*etgar: create in array E which will be concat of the array A and B //*E[ 5, 8, 6, 2, 3, 3, 7, 8, 3, 1] int[] arr_random_ab = new int[10]; for (int i21 = 0; i21 < arr_random_ab.length / 2; i21++) { arr_random_ab[i21] = arr_random_a[i21]; } int i23 = 0; for (int i22 = 5; i22 < arr_random_ab.length; i22++) { arr_random_ab[i22] = arr_random_b[i23]; i23++; } for (int i24 = 0; i24 < arr_random_ab.length; i24++) { System.out.println(arr_random_ab[i24]); } //4. ***etgar crazy: //input number of classes from user //for each size input number of students //input all numbers from user //calculate the average of each class in an array //calculate the average of averages float sum_of_avg = 0; float total_avg = 0; System.out.println("Please input # of classes: "); int[] classes = new int[s.nextInt()]; for (int i11 = 0; i11 < classes.length; i11++) { System.out.println(String.format("Please input number of student in class #%d: ", i11 + 1)); int[] arr_grades = new int[s.nextInt()]; for (int i12 = 0; i12 < arr_grades.length; i12++) { System.out.println(String.format("Please input grade of student #%d: ", i12 + 1)); arr_grades[i12] = s.nextInt(); } int sum_of_class = 0; for (int i13 = 0; i13 < arr_grades.length; i13++) { sum_of_class += arr_grades[i13]; } float avg_of_class = sum_of_class / arr_grades.length; System.out.println(String.format("The average of the class is: %g", avg_of_class)); sum_of_avg += avg_of_class; total_avg = sum_of_avg / classes.length; } System.out.println(String.format("The average of all classes is: %g", total_avg)); } }
5,349
0.522528
0.477285
139
37.482014
26.986368
140
false
false
0
0
0
0
0
0
0.856115
false
false
2
81be452fb8ce5e31763c96bc744f6ba7aeb60a95
23,871,428,256,964
35e2c451f61f26bf74f88e9ff309f6895c3cbcac
/src/com/company/Broker.java
9e353dacbb5ec48e73ffe58b34979425a62d591e
[ "MIT" ]
permissive
779799/broker-rmi
https://github.com/779799/broker-rmi
dc9a5279841cc6dfa299afa2f0d703d885968f1f
96c87547914c85f6dfb57cd1fc955a379b2638a5
refs/heads/master
2021-08-27T17:22:57.810000
2017-06-02T19:34:02
2017-06-02T19:34:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; /* * AUTORES: Rubén Moreno Jimeno 680882 e Iñigo Gascón Royo 685215 * FICHERO: Broker.java * DESCRIPCIÓN: */ import java.rmi.AlreadyBoundException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.Iterator; public class Broker implements BrokerInterface { public static final int port = 1099; ArrayList<Servidor> servidores = new ArrayList<Servidor>(); private static String ip; /** * Metodo constructor de la clase que asigna la IP de registro */ public Broker(String ip) { this.ip=ip; } /** * Método que, dado el nombre de un servicio alojado en un servidor registrado * en el bróker, y los parámetros necesarios para dicho servicio, ejecuta el * servicio especificado y devuelve su resultado en un String. * @param nom_servicio - Nombre del servicio que se desea ejecutar. * @param parametros_servicio - Array con los parámetros del servicio a ejecutar. * @return Un String con la respuesta del servicio ejecutado. */ public String ejecutar_servicio(String nom_servicio, String[] parametros_servicio) { boolean encontrado = false; Iterator<Servidor> iterServidor = servidores.iterator(); Servidor servidor = null; String tipo_retorno = ""; String[] lista_param = null; // Se itera en la lista de servidores con sus servicios, hasta encontrar el servicio // [nom_servicio] y dejar en la variable [servidor] el servidor que contiene dicho servicio while (iterServidor.hasNext() && !encontrado) { servidor = iterServidor.next(); Iterator<Servicio> servicio = servidor.getServicios().iterator(); while (servicio.hasNext() && !encontrado) { Servicio iterServ = servicio.next(); tipo_retorno = iterServ.getTipoRetorno(); lista_param = iterServ.getListaParam(); if (iterServ.getNombre().equals(nom_servicio)) { encontrado = true; } } } if (encontrado) { try { // Se coge el objeto remoto del broker Registry registry = LocateRegistry.getRegistry(servidor.getIP()); ServerInterface server = (ServerInterface) registry.lookup(servidor.getNombre()); return server.ejecuta_metodo(nom_servicio,lista_param,tipo_retorno,parametros_servicio); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } } return ""; } /** * Método accesible para cualquier servidor externo que quiera registrarse en el * bŕoker. Dados una IP y un nombre, el bróker registra a ese servidor en su * lista de servidores registrados. * @param host_remoto_IP_port - IP ó IP y puerto del servidor a registrar * @param nombre_registrado - Nombre con el que el servidor se ha registrado * en el registro de RMI. */ public void registrar_servidor(String host_remoto_IP_port, String nombre_registrado) { Servidor servidor = new Servidor(host_remoto_IP_port, nombre_registrado); servidores.add(servidor); } /** * Método accesible para cualquier servidor externo que quiera registrar sus * servicios en el bróker. El servidor proporcionará el nombre del servicio, una * lista de los parémetros del servicio y el tipo de retorno de dicho servicio. * También especificará el nombre del servidor. * @param nombre_registrado - Nombre con el que el servidor se ha registrado * en el registro de RMI. * @param nom_servicio - Nombre del servicio a registrar en el bróker. * @param lista_param - Array con los parámetros necesarios para ejecutar * el servicio. * @param tipo_retorno - Tipo del objeto de retorno del servicio cuando se * ejecuta. */ public void registrar_servicio(String nombre_regitrado, String nom_servicio, String[] lista_param, String tipo_retorno) { for (Servidor servidor : servidores) { if (servidor.getNombre().equals(nombre_regitrado)) { servidor.addServicio(nom_servicio, lista_param, tipo_retorno); } } } /** * Método que devuelve un ArrayList de Strings con el nombre y los * parámetros de todos los servicios disponibles en el bróker. * @return ArrayList de Strings con el nombre y los parámetros de * los servicios que ofrece el bróker. */ public ArrayList<String> listar_servicios() { ArrayList<String> listado = new ArrayList<String>(); Iterator<Servidor> iterServer = servidores.iterator(); while (iterServer.hasNext()) { Iterator<Servicio> iterServicio = iterServer.next().getServicios().iterator(); while (iterServicio.hasNext()) { listado.add(iterServicio.next().toString()); } } return listado; } /** * Método Main del bróker. Crea un stub del Bróker, crea o localiza * el registro de RMI y enalaza el stub en el registro. */ public static void main (String [] args) { try { Broker bro = new Broker(args[0]); System.setProperty("java.rmi.server.hostname", ip); //Se crea un stub y posteriormente se introduce al registro BrokerInterface stub = (BrokerInterface) UnicastRemoteObject.exportObject(bro, 0); Registry registry = null; //Intenta crear un nuevo registro o lo localiza si ya existe uno. try{ registry = LocateRegistry.createRegistry(port); } catch(RemoteException e){ registry = LocateRegistry.getRegistry(port); } //Enlaza el stub en el registro. registry.bind("BrokerInterface", stub); System.err.println("Broker registrado"); } catch (RemoteException e) { e.printStackTrace(); } catch (AlreadyBoundException e) { e.printStackTrace(); } } }
UTF-8
Java
6,323
java
Broker.java
Java
[ { "context": "package com.company;\n\n/*\n * AUTORES: Rubén Moreno Jimeno 680882 e Iñigo Gascón Royo 685215\n * FICHERO: Bro", "end": 56, "score": 0.999901533126831, "start": 37, "tag": "NAME", "value": "Rubén Moreno Jimeno" }, { "context": "pany;\n\n/*\n * AUTORES: Rubén Moreno Jimeno 680882 e Iñigo Gascón Royo 685215\n * FICHERO: Broker.java\n * DESCRIPCIÓN:\n *", "end": 83, "score": 0.9998957514762878, "start": 66, "tag": "NAME", "value": "Iñigo Gascón Royo" } ]
null
[]
package com.company; /* * AUTORES: <NAME> 680882 e <NAME> 685215 * FICHERO: Broker.java * DESCRIPCIÓN: */ import java.rmi.AlreadyBoundException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.Iterator; public class Broker implements BrokerInterface { public static final int port = 1099; ArrayList<Servidor> servidores = new ArrayList<Servidor>(); private static String ip; /** * Metodo constructor de la clase que asigna la IP de registro */ public Broker(String ip) { this.ip=ip; } /** * Método que, dado el nombre de un servicio alojado en un servidor registrado * en el bróker, y los parámetros necesarios para dicho servicio, ejecuta el * servicio especificado y devuelve su resultado en un String. * @param nom_servicio - Nombre del servicio que se desea ejecutar. * @param parametros_servicio - Array con los parámetros del servicio a ejecutar. * @return Un String con la respuesta del servicio ejecutado. */ public String ejecutar_servicio(String nom_servicio, String[] parametros_servicio) { boolean encontrado = false; Iterator<Servidor> iterServidor = servidores.iterator(); Servidor servidor = null; String tipo_retorno = ""; String[] lista_param = null; // Se itera en la lista de servidores con sus servicios, hasta encontrar el servicio // [nom_servicio] y dejar en la variable [servidor] el servidor que contiene dicho servicio while (iterServidor.hasNext() && !encontrado) { servidor = iterServidor.next(); Iterator<Servicio> servicio = servidor.getServicios().iterator(); while (servicio.hasNext() && !encontrado) { Servicio iterServ = servicio.next(); tipo_retorno = iterServ.getTipoRetorno(); lista_param = iterServ.getListaParam(); if (iterServ.getNombre().equals(nom_servicio)) { encontrado = true; } } } if (encontrado) { try { // Se coge el objeto remoto del broker Registry registry = LocateRegistry.getRegistry(servidor.getIP()); ServerInterface server = (ServerInterface) registry.lookup(servidor.getNombre()); return server.ejecuta_metodo(nom_servicio,lista_param,tipo_retorno,parametros_servicio); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } } return ""; } /** * Método accesible para cualquier servidor externo que quiera registrarse en el * bŕoker. Dados una IP y un nombre, el bróker registra a ese servidor en su * lista de servidores registrados. * @param host_remoto_IP_port - IP ó IP y puerto del servidor a registrar * @param nombre_registrado - Nombre con el que el servidor se ha registrado * en el registro de RMI. */ public void registrar_servidor(String host_remoto_IP_port, String nombre_registrado) { Servidor servidor = new Servidor(host_remoto_IP_port, nombre_registrado); servidores.add(servidor); } /** * Método accesible para cualquier servidor externo que quiera registrar sus * servicios en el bróker. El servidor proporcionará el nombre del servicio, una * lista de los parémetros del servicio y el tipo de retorno de dicho servicio. * También especificará el nombre del servidor. * @param nombre_registrado - Nombre con el que el servidor se ha registrado * en el registro de RMI. * @param nom_servicio - Nombre del servicio a registrar en el bróker. * @param lista_param - Array con los parámetros necesarios para ejecutar * el servicio. * @param tipo_retorno - Tipo del objeto de retorno del servicio cuando se * ejecuta. */ public void registrar_servicio(String nombre_regitrado, String nom_servicio, String[] lista_param, String tipo_retorno) { for (Servidor servidor : servidores) { if (servidor.getNombre().equals(nombre_regitrado)) { servidor.addServicio(nom_servicio, lista_param, tipo_retorno); } } } /** * Método que devuelve un ArrayList de Strings con el nombre y los * parámetros de todos los servicios disponibles en el bróker. * @return ArrayList de Strings con el nombre y los parámetros de * los servicios que ofrece el bróker. */ public ArrayList<String> listar_servicios() { ArrayList<String> listado = new ArrayList<String>(); Iterator<Servidor> iterServer = servidores.iterator(); while (iterServer.hasNext()) { Iterator<Servicio> iterServicio = iterServer.next().getServicios().iterator(); while (iterServicio.hasNext()) { listado.add(iterServicio.next().toString()); } } return listado; } /** * Método Main del bróker. Crea un stub del Bróker, crea o localiza * el registro de RMI y enalaza el stub en el registro. */ public static void main (String [] args) { try { Broker bro = new Broker(args[0]); System.setProperty("java.rmi.server.hostname", ip); //Se crea un stub y posteriormente se introduce al registro BrokerInterface stub = (BrokerInterface) UnicastRemoteObject.exportObject(bro, 0); Registry registry = null; //Intenta crear un nuevo registro o lo localiza si ya existe uno. try{ registry = LocateRegistry.createRegistry(port); } catch(RemoteException e){ registry = LocateRegistry.getRegistry(port); } //Enlaza el stub en el registro. registry.bind("BrokerInterface", stub); System.err.println("Broker registrado"); } catch (RemoteException e) { e.printStackTrace(); } catch (AlreadyBoundException e) { e.printStackTrace(); } } }
6,296
0.645433
0.642573
156
39.352566
29.138441
104
false
false
0
0
0
0
0
0
0.705128
false
false
2
701e73e7b6e6052612ad58adb238b7f5a47e84b3
5,360,119,187,488
c2bf5b82f209f41746d3b56b593db4a457e8bbd3
/src/main/java/br/com/travelmate/model/Heorcamento_.java
f28376ba14f68ba55164cdeaed546e051f75f434
[]
no_license
julioizidoro/systm-com
https://github.com/julioizidoro/systm-com
93d008f4d291bc2e1eda33ec32abdbc537388795
ecf99caebbf59adc2bda33c7a3925794f796980d
refs/heads/master
2020-03-27T10:52:17.319000
2018-08-29T19:59:32
2018-08-29T19:59:32
146,450,606
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.travelmate.model; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="Dali", date="2018-07-24T12:11:14.768-0300") @StaticMetamodel(Heorcamento.class) public class Heorcamento_ { public static volatile SingularAttribute<Heorcamento, Integer> idheorcamento; public static volatile SingularAttribute<Heorcamento, Date> dataemissao; public static volatile SingularAttribute<Heorcamento, String> horaemissao; public static volatile SingularAttribute<Heorcamento, String> observacao; public static volatile SingularAttribute<Heorcamento, Float> valorassessoria; public static volatile SingularAttribute<Heorcamento, Boolean> historicomedio; public static volatile SingularAttribute<Heorcamento, Boolean> passaporte; public static volatile SingularAttribute<Heorcamento, Boolean> historicosuperior; public static volatile SingularAttribute<Heorcamento, Boolean> score; public static volatile SingularAttribute<Heorcamento, String> sigla; public static volatile SingularAttribute<Heorcamento, Cliente> cliente; public static volatile SingularAttribute<Heorcamento, Usuario> usuario; public static volatile ListAttribute<Heorcamento, Heorcamentopais> heorcamentopaisList; }
UTF-8
Java
1,375
java
Heorcamento_.java
Java
[]
null
[]
package br.com.travelmate.model; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="Dali", date="2018-07-24T12:11:14.768-0300") @StaticMetamodel(Heorcamento.class) public class Heorcamento_ { public static volatile SingularAttribute<Heorcamento, Integer> idheorcamento; public static volatile SingularAttribute<Heorcamento, Date> dataemissao; public static volatile SingularAttribute<Heorcamento, String> horaemissao; public static volatile SingularAttribute<Heorcamento, String> observacao; public static volatile SingularAttribute<Heorcamento, Float> valorassessoria; public static volatile SingularAttribute<Heorcamento, Boolean> historicomedio; public static volatile SingularAttribute<Heorcamento, Boolean> passaporte; public static volatile SingularAttribute<Heorcamento, Boolean> historicosuperior; public static volatile SingularAttribute<Heorcamento, Boolean> score; public static volatile SingularAttribute<Heorcamento, String> sigla; public static volatile SingularAttribute<Heorcamento, Cliente> cliente; public static volatile SingularAttribute<Heorcamento, Usuario> usuario; public static volatile ListAttribute<Heorcamento, Heorcamentopais> heorcamentopaisList; }
1,375
0.847273
0.832
25
54
26.990368
88
false
false
0
0
0
0
0
0
1.84
false
false
2
792fad884e3b50d3e8f8a6ccc601872b55cc4014
21,096,879,384,219
09e9b8a1130d2c701a6ea1239ff749313fe468ae
/src/code/functionalInterface/FunA.java
5c8a946c14943c91dc1ee102b7c7b47f555971a3
[]
no_license
xorasysgen/R_D
https://github.com/xorasysgen/R_D
86942495a26b7316d638a4b2c6f614c157d0c61b
4f892eb637796fb7e01a128e70ad8d5a96acf0f5
refs/heads/master
2022-09-26T05:02:34.356000
2020-05-16T04:26:15
2020-05-16T04:26:15
189,402,798
0
0
null
false
2022-08-18T19:06:03
2019-05-30T11:36:43
2020-05-16T04:26:55
2022-08-18T19:06:00
636
0
0
4
Java
false
false
package code.functionalInterface; @FunctionalInterface public interface FunA { public abstract void method(); }
UTF-8
Java
114
java
FunA.java
Java
[]
null
[]
package code.functionalInterface; @FunctionalInterface public interface FunA { public abstract void method(); }
114
0.807018
0.807018
6
18
13.140269
33
false
false
0
0
0
0
0
0
0.5
false
false
2
75056ea011d48cce6ced10b6e25b675259d021c4
8,546,984,944,866
19609a86e23d73b9e6ab16b915237339b46f0b41
/src/main/java/edu/luc/comp473/facilityMan/business/entities/facility/Building.java
eda9b033c9695f84b61b076c2adf34428f95670a
[]
no_license
uuganbold/facilityMan
https://github.com/uuganbold/facilityMan
110616f0455eb8b1af6e5c0c0b4ba173c4b09b50
cd0431fb1b47887927b908611a2faa796402b199
refs/heads/master
2021-01-04T22:50:37.658000
2020-04-26T05:23:39
2020-04-26T05:23:39
240,784,130
0
2
null
false
2020-03-22T19:59:29
2020-02-15T20:35:19
2020-03-17T00:38:04
2020-03-22T19:59:29
64,704
0
1
7
Java
false
false
package edu.luc.comp473.facilityMan.business.entities.facility; import java.util.ArrayList; import java.util.List; /** * Building is a construction constructed by Units. */ public class Building extends Facility { /** * A building is constructed by units. */ private List<Unit> units = new ArrayList<>(); /** * Building's capacity is defined by it's units' capacities. */ @Override public int getCapacity() { int totalCapacity = 0; for (Unit unit : units) { totalCapacity += unit.getCapacity(); } return totalCapacity; } public List<Unit> getUnits() { return this.units; } public void setUnits(List<Unit> units){ this.units = units; } public void addUnit(Unit unit) { units.add(unit); } /** * Remove unit from the building. If it is removed successfully it returns true, * otherwise it returns false. * * @param unit Unit should be removed from the building. * @return true if unit removed successfully, otherwise false. */ public boolean removeUnit(Unit unit) { if (units.contains(unit)) { units.remove(unit); return true; } return false; } @Override public String toString() { String s = getClass().getSimpleName() + " [id=" + getId() + ", capacity=" + getCapacity() + ", detail=" + getDetail() + "]" + ", units: "; for (Unit u : units){ s += u.toString() + ", "; } return s; } }
UTF-8
Java
1,567
java
Building.java
Java
[]
null
[]
package edu.luc.comp473.facilityMan.business.entities.facility; import java.util.ArrayList; import java.util.List; /** * Building is a construction constructed by Units. */ public class Building extends Facility { /** * A building is constructed by units. */ private List<Unit> units = new ArrayList<>(); /** * Building's capacity is defined by it's units' capacities. */ @Override public int getCapacity() { int totalCapacity = 0; for (Unit unit : units) { totalCapacity += unit.getCapacity(); } return totalCapacity; } public List<Unit> getUnits() { return this.units; } public void setUnits(List<Unit> units){ this.units = units; } public void addUnit(Unit unit) { units.add(unit); } /** * Remove unit from the building. If it is removed successfully it returns true, * otherwise it returns false. * * @param unit Unit should be removed from the building. * @return true if unit removed successfully, otherwise false. */ public boolean removeUnit(Unit unit) { if (units.contains(unit)) { units.remove(unit); return true; } return false; } @Override public String toString() { String s = getClass().getSimpleName() + " [id=" + getId() + ", capacity=" + getCapacity() + ", detail=" + getDetail() + "]" + ", units: "; for (Unit u : units){ s += u.toString() + ", "; } return s; } }
1,567
0.574984
0.572431
60
25.116667
25.342382
131
false
false
0
0
0
0
0
0
0.366667
false
false
2
cad659b9e0fe8aaf04ea30931d0d05f5e6a2a2a8
38,938,173,526,256
786fe67cd690acac4c5509402c103866690bce0b
/templateMethodPattern/src/main.java
ba85805baf349a9cd09469d3e16dc9541f494f91
[]
no_license
KimyoonJIn/designPattern
https://github.com/KimyoonJIn/designPattern
b277b5a4d905b5af46786da2ecdf9d3ad29d2452
742e421765f67e43142fd2315678a9a549d0a193
refs/heads/master
2020-04-16T22:21:54.257000
2019-01-16T09:05:05
2019-01-16T09:05:05
165,964,607
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import com.rosa.dp.AbstGameConnectionHelper; import com.rosa.dp.DefaultGameConnectionHelper; public class main { public static void main(String[] args){ AbstGameConnectionHelper helper = new DefaultGameConnectionHelper(); helper.requestConnection("아이디 비밀번호 등 개인정보 암호화 데이터"); } }
UTF-8
Java
339
java
main.java
Java
[]
null
[]
import com.rosa.dp.AbstGameConnectionHelper; import com.rosa.dp.DefaultGameConnectionHelper; public class main { public static void main(String[] args){ AbstGameConnectionHelper helper = new DefaultGameConnectionHelper(); helper.requestConnection("아이디 비밀번호 등 개인정보 암호화 데이터"); } }
339
0.749175
0.749175
11
26.454546
27.026464
76
false
false
0
0
0
0
0
0
0.363636
false
false
2
0a7fef7cfc116412a0f595c3f0e85397fef4cd99
22,771,916,631,806
6df5f599f3599591ec7f9fd1d76ddaef9decaabd
/kanoon-authentication/src/main/java/de/writtscher/kanoon/authentication/service/security/UserDetailsServiceImpl.java
02d3545ee76353df1ee06291a3154cb6835f4d80
[]
no_license
Writtscher/kanoon
https://github.com/Writtscher/kanoon
9d5faec35fb54f812f233685b5634a6d8f053ac7
cb7b367c8ba6f4756b3b3a5500e8b501897ea0c8
refs/heads/master
2018-01-02T23:08:06.283000
2017-01-18T14:22:37
2017-01-18T14:22:37
71,554,580
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.writtscher.kanoon.authentication.service.security; import de.writtscher.kanoon.authentication.data.account.Account; import de.writtscher.kanoon.authentication.data.account.AccountRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; /** * @author Waldemar Rittscher * @since 31.08.2016 */ @Service public class UserDetailsServiceImpl implements UserDetailsService { private final AccountRepository accountRepository; @Autowired public UserDetailsServiceImpl(AccountRepository accountRepository) { this.accountRepository = accountRepository; } @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { Account account = accountRepository.findAccountByEmail(email); if (account != null && account.isValid()) { // TODO Fine for now return new User(account.getEmail(), account.getPassword(), AuthorityUtils.createAuthorityList("ROLE_USER")); } throw new UsernameNotFoundException("Failed to find account with email [" + email + "]"); } }
UTF-8
Java
1,500
java
UserDetailsServiceImpl.java
Java
[ { "context": "pringframework.stereotype.Service;\n\n/**\n * @author Waldemar Rittscher\n * @since 31.08.2016\n */\n@Service\npublic class Us", "end": 693, "score": 0.999885082244873, "start": 675, "tag": "NAME", "value": "Waldemar Rittscher" } ]
null
[]
package de.writtscher.kanoon.authentication.service.security; import de.writtscher.kanoon.authentication.data.account.Account; import de.writtscher.kanoon.authentication.data.account.AccountRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; /** * @author <NAME> * @since 31.08.2016 */ @Service public class UserDetailsServiceImpl implements UserDetailsService { private final AccountRepository accountRepository; @Autowired public UserDetailsServiceImpl(AccountRepository accountRepository) { this.accountRepository = accountRepository; } @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { Account account = accountRepository.findAccountByEmail(email); if (account != null && account.isValid()) { // TODO Fine for now return new User(account.getEmail(), account.getPassword(), AuthorityUtils.createAuthorityList("ROLE_USER")); } throw new UsernameNotFoundException("Failed to find account with email [" + email + "]"); } }
1,488
0.779333
0.774
39
37.46154
34.094776
120
false
false
0
0
0
0
0
0
0.435897
false
false
2
fc676e67be0349d376e42184bf50b83a5cf3d6db
32,409,823,235,549
42000a8390b943b58b69196cece01b7ca42c5092
/SpringData/Workshop-MVC-Project/nlt/src/main/java/softuni/workshop/service/services/impl/EmployeeServiceImpl.java
3b74e9578783271693fa8b6bb3e4dc34993bb575
[]
no_license
KrasimirKolchev/SpringData
https://github.com/KrasimirKolchev/SpringData
4103605dad8455477c35c0040b565dfbf49df9df
eac4eeed54c2016b7fe03bb8d555b799c98b23b7
refs/heads/master
2021-05-24T11:14:56.391000
2020-04-19T16:28:13
2020-04-19T16:28:13
253,533,456
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package softuni.workshop.service.services.impl; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import softuni.workshop.data.dtos.EmployeeRootDTO; import softuni.workshop.data.dtos.EmployeeViewDTO; import softuni.workshop.data.dtos.ProjectNameViewDTO; import softuni.workshop.data.entities.Employee; import softuni.workshop.data.repositories.EmployeeRepository; import softuni.workshop.service.services.EmployeeService; import softuni.workshop.service.services.ProjectService; import softuni.workshop.util.FileUtil; import softuni.workshop.util.XmlParser; import javax.xml.bind.JAXBException; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; @Service public class EmployeeServiceImpl implements EmployeeService { private final EmployeeRepository employeeRepository; private final FileUtil fileUtil; private final XmlParser xmlParser; private final ModelMapper modelMapper; private final ProjectService projectService; @Autowired public EmployeeServiceImpl(EmployeeRepository employeeRepository, FileUtil fileUtil, XmlParser xmlParser, ModelMapper modelMapper, ProjectService projectService) { this.employeeRepository = employeeRepository; this.fileUtil = fileUtil; this.xmlParser = xmlParser; this.modelMapper = modelMapper; this.projectService = projectService; } @Override public void importEmployees() throws JAXBException, FileNotFoundException { EmployeeRootDTO employees = this.xmlParser .importFromXML(EmployeeRootDTO.class, "src/main/resources/files/xmls/employees.xml"); employees.getEmployees().forEach(e -> { Employee employee = this.modelMapper.map(e, Employee.class); employee.setProject(this.projectService.getProjectByName(e.getProject().getName())); this.employeeRepository.save(employee); }); } @Override public boolean areImported() { return this.employeeRepository.count() > 0; } @Override public String readEmployeesXmlFile() throws IOException { return this.fileUtil.readFile("src/main/resources/files/xmls/employees.xml"); } @Override public String exportEmployeesWithAgeAbove() { List<EmployeeViewDTO> employees = this.employeeRepository .findEmployeesByAgeAfter(25) .stream() .map(e -> this.modelMapper.map(e, EmployeeViewDTO.class)) .collect(Collectors.toList()); StringBuilder sb = new StringBuilder(); employees.forEach(e -> sb.append(String.format("Name: %s %s\n\tAge: %d\n\tProject Name: %s\n", e.getFirstName(), e.getLastName(), e.getAge(), e.getProject().getName()))); return sb.toString(); } }
UTF-8
Java
3,013
java
EmployeeServiceImpl.java
Java
[]
null
[]
package softuni.workshop.service.services.impl; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import softuni.workshop.data.dtos.EmployeeRootDTO; import softuni.workshop.data.dtos.EmployeeViewDTO; import softuni.workshop.data.dtos.ProjectNameViewDTO; import softuni.workshop.data.entities.Employee; import softuni.workshop.data.repositories.EmployeeRepository; import softuni.workshop.service.services.EmployeeService; import softuni.workshop.service.services.ProjectService; import softuni.workshop.util.FileUtil; import softuni.workshop.util.XmlParser; import javax.xml.bind.JAXBException; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; @Service public class EmployeeServiceImpl implements EmployeeService { private final EmployeeRepository employeeRepository; private final FileUtil fileUtil; private final XmlParser xmlParser; private final ModelMapper modelMapper; private final ProjectService projectService; @Autowired public EmployeeServiceImpl(EmployeeRepository employeeRepository, FileUtil fileUtil, XmlParser xmlParser, ModelMapper modelMapper, ProjectService projectService) { this.employeeRepository = employeeRepository; this.fileUtil = fileUtil; this.xmlParser = xmlParser; this.modelMapper = modelMapper; this.projectService = projectService; } @Override public void importEmployees() throws JAXBException, FileNotFoundException { EmployeeRootDTO employees = this.xmlParser .importFromXML(EmployeeRootDTO.class, "src/main/resources/files/xmls/employees.xml"); employees.getEmployees().forEach(e -> { Employee employee = this.modelMapper.map(e, Employee.class); employee.setProject(this.projectService.getProjectByName(e.getProject().getName())); this.employeeRepository.save(employee); }); } @Override public boolean areImported() { return this.employeeRepository.count() > 0; } @Override public String readEmployeesXmlFile() throws IOException { return this.fileUtil.readFile("src/main/resources/files/xmls/employees.xml"); } @Override public String exportEmployeesWithAgeAbove() { List<EmployeeViewDTO> employees = this.employeeRepository .findEmployeesByAgeAfter(25) .stream() .map(e -> this.modelMapper.map(e, EmployeeViewDTO.class)) .collect(Collectors.toList()); StringBuilder sb = new StringBuilder(); employees.forEach(e -> sb.append(String.format("Name: %s %s\n\tAge: %d\n\tProject Name: %s\n", e.getFirstName(), e.getLastName(), e.getAge(), e.getProject().getName()))); return sb.toString(); } }
3,013
0.710256
0.70926
77
37.129871
30.991976
167
false
false
0
0
0
0
0
0
0.662338
false
false
2
3343a2c19ba8be4af89824794ec42b7326f41569
39,273,180,998,517
8ae909f770bf46fa7404587f6a2588a637911376
/src/main/java/it/classcard/classcard_gest/resources/LogoutResource.java
c7da70a2696dc6b22f9fd34963d369fb63aa7c7d
[]
no_license
MassimoCappellano/classcardappbase
https://github.com/MassimoCappellano/classcardappbase
3086f57c2f34ac3edc1685ee74ae79ae68867989
9b826a4e719148d34dfffe6f833a5e1ae55bf3be
refs/heads/master
2018-01-08T03:15:22.876000
2016-01-06T16:22:51
2016-01-06T16:22:51
48,653,721
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.classcard.classcard_gest.resources; import it.classcard.classcard_gest.client.CassandraClient; import it.classcard.classcard_gest.service.LogoutView; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.annotation.Timed; @Path("/logout") public class LogoutResource { private static final Logger log = LoggerFactory.getLogger(LogoutResource.class); private CassandraClient cassandraClient; public LogoutResource(CassandraClient cassandraClient) { this.cassandraClient = cassandraClient; } @GET() @Timed @Consumes(MediaType.TEXT_HTML) @Produces(MediaType.TEXT_HTML) public LogoutView getLogoutResource(@QueryParam("id") String uuid){ log.info("DOING LOGOUT for id: '{}'", uuid); cassandraClient.deleteSessionUser(uuid); return new LogoutView(); } }
UTF-8
Java
999
java
LogoutResource.java
Java
[]
null
[]
package it.classcard.classcard_gest.resources; import it.classcard.classcard_gest.client.CassandraClient; import it.classcard.classcard_gest.service.LogoutView; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.annotation.Timed; @Path("/logout") public class LogoutResource { private static final Logger log = LoggerFactory.getLogger(LogoutResource.class); private CassandraClient cassandraClient; public LogoutResource(CassandraClient cassandraClient) { this.cassandraClient = cassandraClient; } @GET() @Timed @Consumes(MediaType.TEXT_HTML) @Produces(MediaType.TEXT_HTML) public LogoutView getLogoutResource(@QueryParam("id") String uuid){ log.info("DOING LOGOUT for id: '{}'", uuid); cassandraClient.deleteSessionUser(uuid); return new LogoutView(); } }
999
0.77978
0.777778
39
24.615385
21.806393
81
false
false
0
0
0
0
0
0
1.128205
false
false
2
b33c83d4f0a2aa6a638cf478a9ef8300d94c3978
26,233,660,280,490
a3c1d5c2fe0e91b26b9910ce4bffe5c1ce641746
/src/main/java/com/tokyoboyband/entity/StoryEntity.java
713487e5121fcf1e20b1964e6db072235919afec
[]
no_license
huutuanhcmus/SpringMVCStorySky
https://github.com/huutuanhcmus/SpringMVCStorySky
9b531f296019364588f6bcccf15f7e3fc1a79be5
9cdc7ffa2d32e2e3adb9e9d2d94bf784151e3b7e
refs/heads/master
2022-11-08T07:46:42.821000
2020-06-29T13:07:10
2020-06-29T13:07:10
275,339,130
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tokyoboyband.entity; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "story") public class StoryEntity extends BaseEntity { @Column(name = "name") private String name; @Column(name = "introduce") private String introduce; @Column(name = "image") private String image; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "category_id") private CategoryEntity category; @OneToMany(mappedBy = "story", fetch = FetchType.LAZY) private List<CollectionStoryEntity> collectionStory = new ArrayList<CollectionStoryEntity>(0); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIntroduce() { return introduce; } public void setIntroduce(String introduce) { this.introduce = introduce; } public CategoryEntity getCategory() { return category; } public void setCategory(CategoryEntity category) { this.category = category; } public List<CollectionStoryEntity> getCollectionStory() { return collectionStory; } public void setCollectionStory(List<CollectionStoryEntity> collectionStory) { this.collectionStory = collectionStory; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } }
UTF-8
Java
1,546
java
StoryEntity.java
Java
[]
null
[]
package com.tokyoboyband.entity; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "story") public class StoryEntity extends BaseEntity { @Column(name = "name") private String name; @Column(name = "introduce") private String introduce; @Column(name = "image") private String image; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "category_id") private CategoryEntity category; @OneToMany(mappedBy = "story", fetch = FetchType.LAZY) private List<CollectionStoryEntity> collectionStory = new ArrayList<CollectionStoryEntity>(0); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIntroduce() { return introduce; } public void setIntroduce(String introduce) { this.introduce = introduce; } public CategoryEntity getCategory() { return category; } public void setCategory(CategoryEntity category) { this.category = category; } public List<CollectionStoryEntity> getCollectionStory() { return collectionStory; } public void setCollectionStory(List<CollectionStoryEntity> collectionStory) { this.collectionStory = collectionStory; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } }
1,546
0.751617
0.75097
73
20.178082
19.859329
95
false
false
0
0
0
0
0
0
1.09589
false
false
2
0348b3abcf43d346dae9a48d6d6ccde3bd263369
21,766,894,284,323
a7314bbd5717e8011d1f15a89380789faca4da05
/src/main/java/trees/NumberOfUniqueBSTFromSortedArray.java
a38eda0fa991aea5a2a012256ecdf4b804efac37
[]
no_license
harshchiki/Algorithms-Practise
https://github.com/harshchiki/Algorithms-Practise
1f16949889bfe686ed559dc3665ddfabeb0637c8
024e506306d26d3f63a36638e5f51074a957a100
refs/heads/master
2020-12-23T16:20:28.991000
2018-03-21T06:04:35
2018-03-21T06:04:35
92,562,288
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package trees; /* * Amazon SDE 2 interview * * http://www.geeksforgeeks.org/amazon-interview-set-82-for-sde-2/ * http://www.geeksforgeeks.org/construct-all-possible-bsts-for-keys-1-to-n/ * Algo given on just above link is different from what is done below. * * Algo: 1.) length == 0 -> 0 2.) length == 1 -> 1 3.) length == 2 -> 2 4.) Iterate through all the elements of the array, making each the root. 5.) Use the left elements, and pass recursively to get count of left subtrees. 6.) Use the right elements, and pass recursively to get count of right subtree. 7.) Count of tree with this i as root is multiplication of no. of left and no.right */ public class NumberOfUniqueBSTFromSortedArray { public static void main(String[] args) { System.out.println(getNoOfUniqueBST(getSortedArray())); } public static int getNoOfUniqueBST(int[] a){ if(a.length == 0){ return 0; } if(a.length == 1){ return 1; } if(a.length ==2){ return 2; } int count = 0; for(int i=0;i<a.length;i++){ int noOfUniqueBSTLeft = 0; int[] leftSubArray = new int[0]; leftSubArray = getSubArray(a, 0, i-1); noOfUniqueBSTLeft = getNoOfUniqueBST(leftSubArray); int noOfUniqueBSTRight = 0; int[] rightSubArray = new int[0]; rightSubArray = getSubArray(a,i+1,a.length-1); noOfUniqueBSTRight = getNoOfUniqueBST(rightSubArray); count += noOfUniqueBSTLeft * noOfUniqueBSTRight; // count += noOfUniqueBSTLeft > noOfUniqueBSTRight? noOfUniqueBSTLeft : noOfUniqueBSTRight; } return count; } public static int[] getSubArray(int[] arr, int startIndex, int endIndex){ if(startIndex <0 || endIndex <0 || startIndex > endIndex || startIndex > arr.length || endIndex > arr.length) return new int[0]; int a[] = new int[endIndex-startIndex+1]; int j = 0; for(int i = startIndex;i<=endIndex;i++,j++){ a[j] = arr[i]; } return a; } public static void printArray(int a[]){ for(int i=0;i<a.length;i++){ System.out.print(a[i]+", "); } System.out.println(); } public static int[] getSortedArray(){ int[] a = new int[4]; a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; return a; } }
UTF-8
Java
2,162
java
NumberOfUniqueBSTFromSortedArray.java
Java
[]
null
[]
package trees; /* * Amazon SDE 2 interview * * http://www.geeksforgeeks.org/amazon-interview-set-82-for-sde-2/ * http://www.geeksforgeeks.org/construct-all-possible-bsts-for-keys-1-to-n/ * Algo given on just above link is different from what is done below. * * Algo: 1.) length == 0 -> 0 2.) length == 1 -> 1 3.) length == 2 -> 2 4.) Iterate through all the elements of the array, making each the root. 5.) Use the left elements, and pass recursively to get count of left subtrees. 6.) Use the right elements, and pass recursively to get count of right subtree. 7.) Count of tree with this i as root is multiplication of no. of left and no.right */ public class NumberOfUniqueBSTFromSortedArray { public static void main(String[] args) { System.out.println(getNoOfUniqueBST(getSortedArray())); } public static int getNoOfUniqueBST(int[] a){ if(a.length == 0){ return 0; } if(a.length == 1){ return 1; } if(a.length ==2){ return 2; } int count = 0; for(int i=0;i<a.length;i++){ int noOfUniqueBSTLeft = 0; int[] leftSubArray = new int[0]; leftSubArray = getSubArray(a, 0, i-1); noOfUniqueBSTLeft = getNoOfUniqueBST(leftSubArray); int noOfUniqueBSTRight = 0; int[] rightSubArray = new int[0]; rightSubArray = getSubArray(a,i+1,a.length-1); noOfUniqueBSTRight = getNoOfUniqueBST(rightSubArray); count += noOfUniqueBSTLeft * noOfUniqueBSTRight; // count += noOfUniqueBSTLeft > noOfUniqueBSTRight? noOfUniqueBSTLeft : noOfUniqueBSTRight; } return count; } public static int[] getSubArray(int[] arr, int startIndex, int endIndex){ if(startIndex <0 || endIndex <0 || startIndex > endIndex || startIndex > arr.length || endIndex > arr.length) return new int[0]; int a[] = new int[endIndex-startIndex+1]; int j = 0; for(int i = startIndex;i<=endIndex;i++,j++){ a[j] = arr[i]; } return a; } public static void printArray(int a[]){ for(int i=0;i<a.length;i++){ System.out.print(a[i]+", "); } System.out.println(); } public static int[] getSortedArray(){ int[] a = new int[4]; a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; return a; } }
2,162
0.658187
0.635523
84
24.738094
26.365164
112
false
false
0
0
0
0
0
0
1.97619
false
false
2
63eb67124f3c551c9e62b7ff8960e6d27c063390
20,598,663,177,076
de3b8cea9fdd9d4e43eae5d019c31b9191068591
/src/main/java/com/github/rintaun/magicwands/command/IMagicWandsCommandSender.java
0da18f617b4dc695abab67b157c948ecce1ec7f9
[ "MIT" ]
permissive
rintaun/MagicWands
https://github.com/rintaun/MagicWands
577f2b4d0c1c48ac916a1e8ec7997b8cd73ef248
043067c323765f3ed6f352ce86afc96d83e8da45
refs/heads/master
2021-01-10T05:09:41.786000
2015-11-30T12:03:21
2015-11-30T12:03:21
46,901,430
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.rintaun.magicwands.command; import net.minecraft.command.ICommandSender; import net.minecraft.nbt.NBTTagCompound; public interface IMagicWandsCommandSender extends ICommandSender { public NBTTagCompound getCommandData(); }
UTF-8
Java
248
java
IMagicWandsCommandSender.java
Java
[ { "context": "package com.github.rintaun.magicwands.command;\n\nimport net.minecraft.command", "end": 26, "score": 0.9978006482124329, "start": 19, "tag": "USERNAME", "value": "rintaun" } ]
null
[]
package com.github.rintaun.magicwands.command; import net.minecraft.command.ICommandSender; import net.minecraft.nbt.NBTTagCompound; public interface IMagicWandsCommandSender extends ICommandSender { public NBTTagCompound getCommandData(); }
248
0.83871
0.83871
9
26.555555
24.157406
64
false
false
0
0
0
0
0
0
0.444444
false
false
2
a85a5c466cff48d29c7f503e61e05db044de5960
8,615,704,427,246
2a830e53f67755d3b6be6a29444bb02656bef025
/src/DataStructures/Maps.java
2ffcbd9e37103b3ce6831d3ccbb65236b3fc2028
[]
no_license
JaretWright/F20COMP1011S4W6
https://github.com/JaretWright/F20COMP1011S4W6
48859808e1ab068f8ffd4cd779d9169326295224
e183e944b7f7054791500fd48a18c9ba94ee00c1
refs/heads/master
2023-01-02T07:11:20.261000
2020-10-29T17:39:05
2020-10-29T17:39:05
306,677,001
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DataStructures; import java.util.HashMap; import java.util.TreeSet; public class Maps { public static void main(String[] args) { //Maps - have a key and a value HashMap<String, String> contacts = new HashMap<>(); contacts.put("Jaret","705-555-1234"); contacts.put("Lindsay","613-555-6457"); for(String key : contacts.keySet()) { System.out.printf("%s's phone number is %s%n", key, contacts.get(key)); } Student student1 = new Student("Fred","Flintstone",1001); Student student2 = new Student("Barney","Rubble",1002); Student student3 = new Student("Mr.", "Slate", 723); student1.addCourse("COMP 1030", 100); student1.addCourse("COMP 1008", 98); student1.addCourse("COMP 1011", 100); student2.addCourse("COMP 1030", 43); student2.addCourse("COMP 1030", 63); TreeSet<Student> treeSet = new TreeSet<>(); treeSet.add(student1); treeSet.add(student2); treeSet.add(student3); for (Student student : treeSet) System.out.println("Student: "+student +"\n"+student.getTranscript()); } }
UTF-8
Java
1,205
java
Maps.java
Java
[ { "context": "contacts = new HashMap<>();\n contacts.put(\"Jaret\",\"705-555-1234\");\n contacts.put(\"Lindsay\",", "end": 270, "score": 0.9997897148132324, "start": 265, "tag": "NAME", "value": "Jaret" }, { "context": "ut(\"Jaret\",\"705-555-1234\");\n contacts.put(\"Lindsay\",\"613-555-6457\");\n\n for(String key : conta", "end": 318, "score": 0.9997912049293518, "start": 311, "tag": "NAME", "value": "Lindsay" }, { "context": " }\n\n Student student1 = new Student(\"Fred\",\"Flintstone\",1001);\n Student student2 = n", "end": 551, "score": 0.999869704246521, "start": 547, "tag": "NAME", "value": "Fred" }, { "context": "}\n\n Student student1 = new Student(\"Fred\",\"Flintstone\",1001);\n Student student2 = new Student(\"B", "end": 564, "score": 0.9998489022254944, "start": 554, "tag": "NAME", "value": "Flintstone" }, { "context": "e\",1001);\n Student student2 = new Student(\"Barney\",\"Rubble\",1002);\n Student student3 = new S", "end": 619, "score": 0.9998507499694824, "start": 613, "tag": "NAME", "value": "Barney" }, { "context": "\n Student student2 = new Student(\"Barney\",\"Rubble\",1002);\n Student student3 = new Student(\"M", "end": 628, "score": 0.9998562932014465, "start": 622, "tag": "NAME", "value": "Rubble" }, { "context": ");\n Student student3 = new Student(\"Mr.\", \"Slate\", 723);\n\n student1.addCourse(\"COMP 1030\", ", "end": 689, "score": 0.9998594522476196, "start": 684, "tag": "NAME", "value": "Slate" } ]
null
[]
package DataStructures; import java.util.HashMap; import java.util.TreeSet; public class Maps { public static void main(String[] args) { //Maps - have a key and a value HashMap<String, String> contacts = new HashMap<>(); contacts.put("Jaret","705-555-1234"); contacts.put("Lindsay","613-555-6457"); for(String key : contacts.keySet()) { System.out.printf("%s's phone number is %s%n", key, contacts.get(key)); } Student student1 = new Student("Fred","Flintstone",1001); Student student2 = new Student("Barney","Rubble",1002); Student student3 = new Student("Mr.", "Slate", 723); student1.addCourse("COMP 1030", 100); student1.addCourse("COMP 1008", 98); student1.addCourse("COMP 1011", 100); student2.addCourse("COMP 1030", 43); student2.addCourse("COMP 1030", 63); TreeSet<Student> treeSet = new TreeSet<>(); treeSet.add(student1); treeSet.add(student2); treeSet.add(student3); for (Student student : treeSet) System.out.println("Student: "+student +"\n"+student.getTranscript()); } }
1,205
0.590042
0.528631
38
30.710526
22.946056
82
false
false
0
0
0
0
0
0
0.947368
false
false
2
863d49f87ef7980c0b1e4869ce5c6b17d4eecbf5
7,103,875,942,955
3a1a84b6b7ba66aa1f497d07f2c3d5ce13d8fcf9
/RPG/src/main/java/br/com/rpg/domain/Role.java
88cb9fd0cab5c34b666f44e14070f3c58306851b
[]
no_license
cottapedro/projeto1
https://github.com/cottapedro/projeto1
e89423e061dd160b9823e2f3832507820dab9869
c060f7ee212bf8e49c5d7365842bdbaa6eb4d4fb
refs/heads/master
2021-11-05T18:20:39.126000
2021-10-25T17:20:39
2021-10-25T17:20:39
147,111,490
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.rpg.domain; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import org.springframework.security.core.GrantedAuthority; import lombok.Getter; import lombok.Setter; @Getter @Setter @Entity @Table(name="role") public class Role implements GrantedAuthority { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) private Integer id; @Column(name="nomeRole") private String nomeRole; @ManyToMany(mappedBy = "roles") private List<Usuario> jogadores; private Usuario mestre; @Override public String getAuthority(){ return this.nomeRole; } }
UTF-8
Java
881
java
Role.java
Java
[]
null
[]
package br.com.rpg.domain; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import org.springframework.security.core.GrantedAuthority; import lombok.Getter; import lombok.Setter; @Getter @Setter @Entity @Table(name="role") public class Role implements GrantedAuthority { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) private Integer id; @Column(name="nomeRole") private String nomeRole; @ManyToMany(mappedBy = "roles") private List<Usuario> jogadores; private Usuario mestre; @Override public String getAuthority(){ return this.nomeRole; } }
881
0.744608
0.744608
41
20.487804
16.768324
58
false
false
0
0
0
0
0
0
0.439024
false
false
2
ae45d47167c1ae96dcb061c663277acb66885c70
27,994,596,895,909
26418ee9573d5ea3d799498ecc9475d243e7eb69
/ProjectWorkREST1/blood-bank-management-system/src/test/java/com/bloodbank/test/DonorServiceTest.java
305d91a136974f3c16448745c76c815c94795786
[]
no_license
NishchithKulkarni/AXIS_SCHOOL_OF_FINTECH
https://github.com/NishchithKulkarni/AXIS_SCHOOL_OF_FINTECH
76bbd57339e0e5d98636d2f72f04c4a7fb1da81c
25891a20e855e127c46ff667d9d655a6f880e637
refs/heads/main
2023-01-27T14:10:48.882000
2020-12-08T11:43:25
2020-12-08T11:43:25
301,168,315
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bloodbank.test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import com.bloodbank.dao.DonorDao; import com.bloodbank.dao.RequestDao; import com.bloodbank.model.DonorBean; import com.bloodbank.model.RequestBean; import com.bloodbank.serviceimpl.DonorService; import com.bloodbank.serviceimpl.RequestService; @SpringBootTest public class DonorServiceTest { @InjectMocks DonorService donorService; @Mock private DonorDao donorDao; @BeforeEach public void init() { MockitoAnnotations.initMocks(this); } @Test public void getAllDonorsTest() { List<DonorBean> donors = new ArrayList<>(); donors.add(new DonorBean("Manish","Hundekar","manish@gmail.com","990088","A+","11/11/2020","2","LIG Colony","Bidar","22","MALE")); donors.add(new DonorBean("Manish","Hundekar","manish@gmail.com","990088","A+","11/11/2020","2","LIG Colony","Bidar","22","MALE")); donors.add(new DonorBean("Manish","Hundekar","manish@gmail.com","990088","A+","11/11/2020","2","LIG Colony","Bidar","22","MALE")); when(donorDao.findAll()).thenReturn(donors); //System.out.println(requestService.getAllRequests().size()); assertEquals(3, donorService.getAllDonors().size()); } @Test public void addDonorTest() { DonorBean donor = new DonorBean("Manish","Hundekar","manish@gmail.com","990088","A+","11/11/2020","2","LIG Colony","Bidar","22","MALE"); when(donorDao.save(donor)).thenReturn(donor); assertEquals(donor,donorService.addDonor(donor)); } }
UTF-8
Java
1,943
java
DonorServiceTest.java
Java
[ { "context": "new ArrayList<>();\r\n\t\t\t donors.add(new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/", "end": 1074, "score": 0.9998228549957275, "start": 1068, "tag": "NAME", "value": "Manish" }, { "context": "List<>();\r\n\t\t\t donors.add(new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/11/2020\",\"2", "end": 1085, "score": 0.9993429183959961, "start": 1077, "tag": "NAME", "value": "Hundekar" }, { "context": "\t\t\t donors.add(new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/11/2020\",\"2\",\"LIG Colony\",\"Bid", "end": 1104, "score": 0.9999263286590576, "start": 1088, "tag": "EMAIL", "value": "manish@gmail.com" }, { "context": "ar\",\"22\",\"MALE\"));\r\n\t\t\t donors.add(new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/", "end": 1210, "score": 0.9998295307159424, "start": 1204, "tag": "NAME", "value": "Manish" }, { "context": "\"MALE\"));\r\n\t\t\t donors.add(new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/11/2020\",\"2", "end": 1221, "score": 0.9992498755455017, "start": 1213, "tag": "NAME", "value": "Hundekar" }, { "context": "\t\t\t donors.add(new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/11/2020\",\"2\",\"LIG Colony\",\"Bid", "end": 1240, "score": 0.9999246001243591, "start": 1224, "tag": "EMAIL", "value": "manish@gmail.com" }, { "context": "ar\",\"22\",\"MALE\"));\r\n\t\t\t donors.add(new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/", "end": 1346, "score": 0.999847412109375, "start": 1340, "tag": "NAME", "value": "Manish" }, { "context": "\"MALE\"));\r\n\t\t\t donors.add(new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/11/2020\",\"2", "end": 1357, "score": 0.9996144771575928, "start": 1349, "tag": "NAME", "value": "Hundekar" }, { "context": "\t\t\t donors.add(new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/11/2020\",\"2\",\"LIG Colony\",\"Bid", "end": 1376, "score": 0.9999237060546875, "start": 1360, "tag": "EMAIL", "value": "manish@gmail.com" }, { "context": "onorTest() {\r\n\t\t\tDonorBean donor = new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/", "end": 1727, "score": 0.9998233318328857, "start": 1721, "tag": "NAME", "value": "Manish" }, { "context": ") {\r\n\t\t\tDonorBean donor = new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/11/2020\",\"2", "end": 1738, "score": 0.999835193157196, "start": 1730, "tag": "NAME", "value": "Hundekar" }, { "context": "orBean donor = new DonorBean(\"Manish\",\"Hundekar\",\"manish@gmail.com\",\"990088\",\"A+\",\"11/11/2020\",\"2\",\"LIG Colony\",\"Bid", "end": 1757, "score": 0.9999240040779114, "start": 1741, "tag": "EMAIL", "value": "manish@gmail.com" }, { "context": "gmail.com\",\"990088\",\"A+\",\"11/11/2020\",\"2\",\"LIG Colony\",\"Bidar\",\"22\",\"MALE\");\r\n\t\t\t\r\n\t\t\twhen(donorDao.sav", "end": 1801, "score": 0.5218594670295715, "start": 1798, "tag": "NAME", "value": "ony" }, { "context": "com\",\"990088\",\"A+\",\"11/11/2020\",\"2\",\"LIG Colony\",\"Bidar\",\"22\",\"MALE\");\r\n\t\t\t\r\n\t\t\twhen(donorDao.save(donor)", "end": 1809, "score": 0.9997519254684448, "start": 1804, "tag": "NAME", "value": "Bidar" } ]
null
[]
package com.bloodbank.test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import com.bloodbank.dao.DonorDao; import com.bloodbank.dao.RequestDao; import com.bloodbank.model.DonorBean; import com.bloodbank.model.RequestBean; import com.bloodbank.serviceimpl.DonorService; import com.bloodbank.serviceimpl.RequestService; @SpringBootTest public class DonorServiceTest { @InjectMocks DonorService donorService; @Mock private DonorDao donorDao; @BeforeEach public void init() { MockitoAnnotations.initMocks(this); } @Test public void getAllDonorsTest() { List<DonorBean> donors = new ArrayList<>(); donors.add(new DonorBean("Manish","Hundekar","<EMAIL>","990088","A+","11/11/2020","2","LIG Colony","Bidar","22","MALE")); donors.add(new DonorBean("Manish","Hundekar","<EMAIL>","990088","A+","11/11/2020","2","LIG Colony","Bidar","22","MALE")); donors.add(new DonorBean("Manish","Hundekar","<EMAIL>","990088","A+","11/11/2020","2","LIG Colony","Bidar","22","MALE")); when(donorDao.findAll()).thenReturn(donors); //System.out.println(requestService.getAllRequests().size()); assertEquals(3, donorService.getAllDonors().size()); } @Test public void addDonorTest() { DonorBean donor = new DonorBean("Manish","Hundekar","<EMAIL>","990088","A+","11/11/2020","2","LIG Colony","Bidar","22","MALE"); when(donorDao.save(donor)).thenReturn(donor); assertEquals(donor,donorService.addDonor(donor)); } }
1,907
0.693258
0.657746
54
33.98148
34.240158
139
false
false
0
0
0
0
0
0
2.37037
false
false
2
36f0e6cf9f0d2925ea8d94d2f6cfd3cb670b651b
27,994,596,893,713
a4099882914b145012d7d93d3c0194e665c31ff7
/src/com/banda/bringme/DrawView.java
d414a56fb54147226cd201941ebb0eed0853bdc3
[]
no_license
drinovc/BringMe
https://github.com/drinovc/BringMe
0138c34f735e8c5f525b3a28af6d9d1f43d815f8
e0d2dd33b536e4f996fa796afbaa36e1b08d9ce7
refs/heads/master
2021-01-01T17:57:23.767000
2019-03-11T14:46:33
2019-03-11T14:46:33
27,647,738
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.banda.bringme; import java.util.Hashtable; import DataSources.Table; import DataSources.Table.Shape; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Region; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; public class DrawView extends View{ Hashtable<Long,Table> objects; Hashtable<Long,Region> regions; Point size = new Point(); Paint paint = new Paint(); Context context; Tables tables; public DrawView(Context context, Tables tables) { super(context); WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = window.getDefaultDisplay(); display.getSize(size); this.context = context; this.tables = tables; this.setOnTouchListener(drawViewTouch); } public void setObjects(Hashtable<Long,Table> objects){ this.objects = objects; this.regions = new Hashtable<Long,Region>(); for(long objectId : objects.keySet()){ updateOrAddRegion(objects.get(objectId)); } invalidate(); } @Override public void onDraw(Canvas canvas) { for(long objectId : objects.keySet()){ Table object = objects.get(objectId); int x = object.getXposition() * size.x / 100; int y = object.getYposition() * size.y / 100; int a = object.getAsize() * size.x / 100; int b = object.getBsize() * size.y / 100; paint.setColor(object.getColor()); if(object.getShape() == Table.Shape.CIRCLE){ canvas.drawCircle(x,y,a,paint); } if(object.getShape() == Table.Shape.RECTANGLE){ canvas.drawRect(x, y, x+a, y+b, paint); } } } class CanvasTouch{ long objectId; long time; int deltaX,x; int deltaY,y; boolean dragged = false; public CanvasTouch(long objectId, long time, int x, int y, int deltaX, int deltaY){ this.objectId = objectId; this.time = time; this.deltaX = deltaX; this.deltaY = deltaY; this.x = x; this.y = y; } } CanvasTouch lastTouch; OnTouchListener drawViewTouch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { System.out.println(String.valueOf(event.getAction())); if(event.getAction() == MotionEvent.ACTION_DOWN){ boolean foundRegion = false; for(long objectId : regions.keySet()){ Region region = regions.get(objectId); if(region.contains((int)event.getX(), (int)event.getY())){ Table object = (Table)objects.get(objectId); CanvasTouch touch = new CanvasTouch(objectId,event.getEventTime(),(int)event.getX(),(int)event.getY(), (int)(event.getX() - object.getXposition() * size.x / 100), (int)(event.getY() - object.getYposition() * size.y / 100)); foundRegion = true; if(lastTouch != null && lastTouch.time + 500 > touch.time){ System.out.println("Touched object " + object.getTableName()); } lastTouch = touch; break; } } if(!foundRegion){ lastTouch = null; return false; } } if(event.getAction() == MotionEvent.ACTION_MOVE){ if(lastTouch == null) return false; Table object = (Table) objects.get(lastTouch.objectId); Region region = (Region) regions.get(lastTouch.objectId); if(lastTouch.dragged || Math.sqrt(Math.pow(event.getX()-lastTouch.x,2)+Math.pow(event.getY()-lastTouch.y,2)) > 20){ lastTouch.dragged = true; object.setXposition(((int)(event.getX() - lastTouch.deltaX))*100/size.x); object.setYposition(((int)(event.getY() - lastTouch.deltaY))*100/size.y); invalidate(); } } if(event.getAction() == MotionEvent.ACTION_UP){ if(lastTouch == null) return false; Table object = (Table) objects.get(lastTouch.objectId); updateOrAddRegion(object); tables.tableDataSource.open(); tables.tableDataSource.updateTable(object); tables.tableDataSource.close(); lastTouch = null; } return true; } }; private void updateOrAddRegion(Table object){ Region region = regions.get(object.getID()); if(region == null) region = new Region(); int x=object.getXposition()*size.x / 100, y=object.getYposition()*size.y / 100; int a=object.getAsize()*size.x / 100, b=object.getBsize()*size.y / 100; if(object.getShape() == Shape.CIRCLE){ Path path = new Path(); path.addCircle(x, y, a, Path.Direction.CW); region.setPath(path,new Region(new Rect(x-a,y-a,x+a,y+a))); }else{ region.set(new Rect(x,y,a,b)); } regions.put(object.getID(), region); } }
UTF-8
Java
4,787
java
DrawView.java
Java
[]
null
[]
package com.banda.bringme; import java.util.Hashtable; import DataSources.Table; import DataSources.Table.Shape; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Region; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; public class DrawView extends View{ Hashtable<Long,Table> objects; Hashtable<Long,Region> regions; Point size = new Point(); Paint paint = new Paint(); Context context; Tables tables; public DrawView(Context context, Tables tables) { super(context); WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = window.getDefaultDisplay(); display.getSize(size); this.context = context; this.tables = tables; this.setOnTouchListener(drawViewTouch); } public void setObjects(Hashtable<Long,Table> objects){ this.objects = objects; this.regions = new Hashtable<Long,Region>(); for(long objectId : objects.keySet()){ updateOrAddRegion(objects.get(objectId)); } invalidate(); } @Override public void onDraw(Canvas canvas) { for(long objectId : objects.keySet()){ Table object = objects.get(objectId); int x = object.getXposition() * size.x / 100; int y = object.getYposition() * size.y / 100; int a = object.getAsize() * size.x / 100; int b = object.getBsize() * size.y / 100; paint.setColor(object.getColor()); if(object.getShape() == Table.Shape.CIRCLE){ canvas.drawCircle(x,y,a,paint); } if(object.getShape() == Table.Shape.RECTANGLE){ canvas.drawRect(x, y, x+a, y+b, paint); } } } class CanvasTouch{ long objectId; long time; int deltaX,x; int deltaY,y; boolean dragged = false; public CanvasTouch(long objectId, long time, int x, int y, int deltaX, int deltaY){ this.objectId = objectId; this.time = time; this.deltaX = deltaX; this.deltaY = deltaY; this.x = x; this.y = y; } } CanvasTouch lastTouch; OnTouchListener drawViewTouch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { System.out.println(String.valueOf(event.getAction())); if(event.getAction() == MotionEvent.ACTION_DOWN){ boolean foundRegion = false; for(long objectId : regions.keySet()){ Region region = regions.get(objectId); if(region.contains((int)event.getX(), (int)event.getY())){ Table object = (Table)objects.get(objectId); CanvasTouch touch = new CanvasTouch(objectId,event.getEventTime(),(int)event.getX(),(int)event.getY(), (int)(event.getX() - object.getXposition() * size.x / 100), (int)(event.getY() - object.getYposition() * size.y / 100)); foundRegion = true; if(lastTouch != null && lastTouch.time + 500 > touch.time){ System.out.println("Touched object " + object.getTableName()); } lastTouch = touch; break; } } if(!foundRegion){ lastTouch = null; return false; } } if(event.getAction() == MotionEvent.ACTION_MOVE){ if(lastTouch == null) return false; Table object = (Table) objects.get(lastTouch.objectId); Region region = (Region) regions.get(lastTouch.objectId); if(lastTouch.dragged || Math.sqrt(Math.pow(event.getX()-lastTouch.x,2)+Math.pow(event.getY()-lastTouch.y,2)) > 20){ lastTouch.dragged = true; object.setXposition(((int)(event.getX() - lastTouch.deltaX))*100/size.x); object.setYposition(((int)(event.getY() - lastTouch.deltaY))*100/size.y); invalidate(); } } if(event.getAction() == MotionEvent.ACTION_UP){ if(lastTouch == null) return false; Table object = (Table) objects.get(lastTouch.objectId); updateOrAddRegion(object); tables.tableDataSource.open(); tables.tableDataSource.updateTable(object); tables.tableDataSource.close(); lastTouch = null; } return true; } }; private void updateOrAddRegion(Table object){ Region region = regions.get(object.getID()); if(region == null) region = new Region(); int x=object.getXposition()*size.x / 100, y=object.getYposition()*size.y / 100; int a=object.getAsize()*size.x / 100, b=object.getBsize()*size.y / 100; if(object.getShape() == Shape.CIRCLE){ Path path = new Path(); path.addCircle(x, y, a, Path.Direction.CW); region.setPath(path,new Region(new Rect(x-a,y-a,x+a,y+a))); }else{ region.set(new Rect(x,y,a,b)); } regions.put(object.getID(), region); } }
4,787
0.656988
0.648005
155
29.883871
23.423439
128
false
false
0
0
0
0
0
0
3
false
false
2
188353c5d45a7d1691ba4b5753b4e9c95d3deb61
27,994,596,893,127
653eeefff2aa054f16d8833ad9ede590f6b6b410
/src/main/java/pg/gipter/services/TaskService.java
1d9959c9ca05f5c71551333fbfed6b78920ccef6
[ "MIT" ]
permissive
PreCyz/GitDiffGenerator
https://github.com/PreCyz/GitDiffGenerator
b47061e8482f00d0361cdddd445201828193e2aa
faf21555c29ecf122e1703c95340a9ca82631944
refs/heads/master
2023-07-27T12:38:49.941000
2023-07-23T20:02:04
2023-07-23T20:02:04
149,181,149
23
3
MIT
false
2023-09-14T19:36:39
2018-09-17T20:03:34
2023-09-10T18:02:42
2023-09-14T19:36:39
21,742
2
0
1
Java
false
false
package pg.gipter.services; import javafx.concurrent.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; abstract class TaskService<T> extends Task<T> { protected Logger logger; private long maxWork; private long workDone; private static final int NUMBER_OF_STEPS = 3; private final long defaultValue = Double.valueOf(Math.pow(10, 6)).longValue(); protected TaskService() { logger = LoggerFactory.getLogger(getClass()); workDone = 0; maxWork = defaultValue; } void initProgress(long maxWork) { if (maxWork == 0) { maxWork = 20 * defaultValue; } this.maxWork = maxWork + (NUMBER_OF_STEPS - 1) * defaultValue; } void increaseProgress() { workDone++; updateProgress(workDone, maxWork); } void increaseProgress(long workDone) { this.workDone = workDone; updateProgress(this.workDone, maxWork); } void updateTaskProgress(long workDone) { this.workDone += workDone; updateProgress(this.workDone, maxWork); } void updateMsg(String message) { logger.info(message); updateMessage(message); } void workCompleted() { updateProgress(maxWork, maxWork); } }
UTF-8
Java
1,273
java
TaskService.java
Java
[]
null
[]
package pg.gipter.services; import javafx.concurrent.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; abstract class TaskService<T> extends Task<T> { protected Logger logger; private long maxWork; private long workDone; private static final int NUMBER_OF_STEPS = 3; private final long defaultValue = Double.valueOf(Math.pow(10, 6)).longValue(); protected TaskService() { logger = LoggerFactory.getLogger(getClass()); workDone = 0; maxWork = defaultValue; } void initProgress(long maxWork) { if (maxWork == 0) { maxWork = 20 * defaultValue; } this.maxWork = maxWork + (NUMBER_OF_STEPS - 1) * defaultValue; } void increaseProgress() { workDone++; updateProgress(workDone, maxWork); } void increaseProgress(long workDone) { this.workDone = workDone; updateProgress(this.workDone, maxWork); } void updateTaskProgress(long workDone) { this.workDone += workDone; updateProgress(this.workDone, maxWork); } void updateMsg(String message) { logger.info(message); updateMessage(message); } void workCompleted() { updateProgress(maxWork, maxWork); } }
1,273
0.635507
0.626866
51
23.960785
19.800932
82
false
false
0
0
0
0
0
0
0.54902
false
false
2
527fd8699ece997d616826c65d81cc2e7b600be8
33,105,607,952,222
8d0d43dc95b127f26e9e50c0e97a273d0c8fd322
/SpringFinalProgramming/src/main/java/com/mycompany/myweb/dto/DetailOrder.java
6a1198a21f54b848fe718c07a82dd734e5c3f427
[]
no_license
jeongho9496/MyRepository
https://github.com/jeongho9496/MyRepository
9ca145e0b23120b69edf1de98c280a88718c053d
65b1ad0dd9ed33f726e725fa3d4eb81f7b4bc842
refs/heads/master
2022-05-14T06:14:16.838000
2022-03-20T12:52:23
2022-03-20T12:52:23
65,808,574
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mycompany.myweb.dto; //명진 - 주문, 1품목 위해 만듬 public class DetailOrder {//1품목에 대한 private String mname;//메뉴명 private int sameItemCount;//수량 private String xname;//사이드 이름들 private int sameItemPrice;//가격 private String oghowpay;//결제방식 private String hot_ice;//핫_아이스 public String getMname() { return mname; } public void setMname(String mname) { this.mname = mname; } public int getSameItemCount() { return sameItemCount; } public void setSameItemCount(int sameItemCount) { this.sameItemCount = sameItemCount; } public String getXname() { return xname; } public void setXname(String xname) { this.xname = xname; } public int getSameItemPrice() { return sameItemPrice; } public void setSameItemPrice(int sameItemPrice) { this.sameItemPrice = sameItemPrice; } public String getOghowpay() { return oghowpay; } public void setOghowpay(String oghowpay) { this.oghowpay = oghowpay; } public String getHot_ice() { return hot_ice; } public void setHot_ice(String hot_ice) { this.hot_ice = hot_ice; } }
UTF-8
Java
1,135
java
DetailOrder.java
Java
[ { "context": "ss DetailOrder {//1품목에 대한\n\tprivate String mname;//메뉴명\n\tprivate int sameItemCount;//수량\n\tprivate String", "end": 116, "score": 0.6150223612785339, "start": 115, "tag": "NAME", "value": "메" }, { "context": "s DetailOrder {//1품목에 대한\n\tprivate String mname;//메뉴명\n\tprivate int sameItemCount;//수량\n\tprivate String x", "end": 118, "score": 0.5560164451599121, "start": 116, "tag": "NAME", "value": "뉴명" } ]
null
[]
package com.mycompany.myweb.dto; //명진 - 주문, 1품목 위해 만듬 public class DetailOrder {//1품목에 대한 private String mname;//메뉴명 private int sameItemCount;//수량 private String xname;//사이드 이름들 private int sameItemPrice;//가격 private String oghowpay;//결제방식 private String hot_ice;//핫_아이스 public String getMname() { return mname; } public void setMname(String mname) { this.mname = mname; } public int getSameItemCount() { return sameItemCount; } public void setSameItemCount(int sameItemCount) { this.sameItemCount = sameItemCount; } public String getXname() { return xname; } public void setXname(String xname) { this.xname = xname; } public int getSameItemPrice() { return sameItemPrice; } public void setSameItemPrice(int sameItemPrice) { this.sameItemPrice = sameItemPrice; } public String getOghowpay() { return oghowpay; } public void setOghowpay(String oghowpay) { this.oghowpay = oghowpay; } public String getHot_ice() { return hot_ice; } public void setHot_ice(String hot_ice) { this.hot_ice = hot_ice; } }
1,135
0.715898
0.714017
51
19.843138
15.188195
50
false
false
0
0
0
0
0
0
1.529412
false
false
2
926c9ef6e0117796bc818ad01cab0f1ee5b7b3cd
20,401,094,687,320
8d151fd873c3e91510717e70d414d606f17088a6
/app/src/main/java/johnsmithwithharuhi/co/sakagumi/Presentation/Adapter/BlogListAdapter.java
9cd8a9ba1b848dc154a77d5327416c6e7470e21d
[]
no_license
JohnSmithWithHaruhi/Sakagumi
https://github.com/JohnSmithWithHaruhi/Sakagumi
5d78399b24b4effd9466e64ff16d7fc6c703c142
10de8142b8729e0bebc526b7307cad5afb7e6563
refs/heads/develop
2021-01-20T05:22:52.767000
2017-04-30T06:41:46
2017-04-30T06:41:46
89,776,060
0
0
null
false
2017-04-30T06:43:00
2017-04-29T09:34:58
2017-04-29T12:12:17
2017-04-30T06:43:00
186
0
0
0
Java
null
null
package johnsmithwithharuhi.co.sakagumi.Presentation.Adapter; import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v4.content.ContextCompat; 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 johnsmithwithharuhi.co.sakagumi.Presentation.ViewModel.Item.ItemBlogListViewModel; import johnsmithwithharuhi.co.sakagumi.R; import johnsmithwithharuhi.co.sakagumi.databinding.ItemBlogListBinding; public class BlogListAdapter extends RecyclerView.Adapter<BlogListAdapter.ViewHolder> { private Context mContext; private List<ItemBlogListViewModel> mViewModelList = new ArrayList<>(); private ItemBlogListViewModel.OnItemClickListener mListener; public BlogListAdapter(Context context, ItemBlogListViewModel.OnItemClickListener listener) { mContext = context; mListener = listener; } public void initViewModelList(List<ItemBlogListViewModel> viewModelList) { mViewModelList = viewModelList; notifyDataSetChanged(); } public void putViewModelList(List<ItemBlogListViewModel> viewModelList) { mViewModelList.addAll(0, viewModelList); notifyItemRangeInserted(0, viewModelList.size()); } public String getNewestUrl() { return mViewModelList.get(0).url.get(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_blog_list, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { ItemBlogListBinding binding = holder.getBinding(); ItemBlogListViewModel viewModel = mViewModelList.get(position); viewModel.setOnItemClickListener(mListener); binding.setViewModel(viewModel); binding.name.setTextColor(ContextCompat.getColor(mContext, viewModel.textColor)); } @Override public int getItemCount() { return mViewModelList.size(); } class ViewHolder extends RecyclerView.ViewHolder { private ItemBlogListBinding mBinding; ViewHolder(View itemView) { super(itemView); mBinding = DataBindingUtil.bind(itemView); } ItemBlogListBinding getBinding() { return mBinding; } } }
UTF-8
Java
2,369
java
BlogListAdapter.java
Java
[]
null
[]
package johnsmithwithharuhi.co.sakagumi.Presentation.Adapter; import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v4.content.ContextCompat; 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 johnsmithwithharuhi.co.sakagumi.Presentation.ViewModel.Item.ItemBlogListViewModel; import johnsmithwithharuhi.co.sakagumi.R; import johnsmithwithharuhi.co.sakagumi.databinding.ItemBlogListBinding; public class BlogListAdapter extends RecyclerView.Adapter<BlogListAdapter.ViewHolder> { private Context mContext; private List<ItemBlogListViewModel> mViewModelList = new ArrayList<>(); private ItemBlogListViewModel.OnItemClickListener mListener; public BlogListAdapter(Context context, ItemBlogListViewModel.OnItemClickListener listener) { mContext = context; mListener = listener; } public void initViewModelList(List<ItemBlogListViewModel> viewModelList) { mViewModelList = viewModelList; notifyDataSetChanged(); } public void putViewModelList(List<ItemBlogListViewModel> viewModelList) { mViewModelList.addAll(0, viewModelList); notifyItemRangeInserted(0, viewModelList.size()); } public String getNewestUrl() { return mViewModelList.get(0).url.get(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_blog_list, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { ItemBlogListBinding binding = holder.getBinding(); ItemBlogListViewModel viewModel = mViewModelList.get(position); viewModel.setOnItemClickListener(mListener); binding.setViewModel(viewModel); binding.name.setTextColor(ContextCompat.getColor(mContext, viewModel.textColor)); } @Override public int getItemCount() { return mViewModelList.size(); } class ViewHolder extends RecyclerView.ViewHolder { private ItemBlogListBinding mBinding; ViewHolder(View itemView) { super(itemView); mBinding = DataBindingUtil.bind(itemView); } ItemBlogListBinding getBinding() { return mBinding; } } }
2,369
0.779654
0.777543
71
32.366196
28.540674
97
false
false
0
0
0
0
0
0
0.605634
false
false
2
17ebd0d0fd5398c5ba4982e5b686c28ebe2c85cf
22,033,182,261,722
5f66a7d729227aafe51742926a18d7994f32d6a1
/NgramModel/corpus/program_language_dataset10/java/batik/1513.code.java
a4f21f0886d305e7f7db76fc793dc02de0ac4519
[]
no_license
SunshineAllWay/CCExperiment
https://github.com/SunshineAllWay/CCExperiment
c0a77868297dcf35d41ee5d6d4b67aff3dcc3563
2bb1c06679f8769e5ce18b636cd30a7aede5240b
refs/heads/master
2021-06-05T20:06:34.426000
2019-05-30T00:07:16
2019-05-30T00:07:16
139,319,619
0
2
null
false
2020-10-12T22:20:30
2018-07-01T10:25:55
2019-06-06T00:47:56
2020-10-12T22:20:29
137,624
0
2
5
Java
false
false
package org.apache.batik.ext.awt.image.codec.png; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import org.apache.batik.util.Base64DecodeStream; import org.apache.batik.util.Base64EncoderStream; public class Base64PNGEncoderTest extends PNGEncoderTest { public OutputStream buildOutputStream(ByteArrayOutputStream bos){ return new Base64EncoderStream(bos); } public InputStream buildInputStream(ByteArrayOutputStream bos){ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); return new Base64DecodeStream(bis); } }
UTF-8
Java
674
java
1513.code.java
Java
[]
null
[]
package org.apache.batik.ext.awt.image.codec.png; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import org.apache.batik.util.Base64DecodeStream; import org.apache.batik.util.Base64EncoderStream; public class Base64PNGEncoderTest extends PNGEncoderTest { public OutputStream buildOutputStream(ByteArrayOutputStream bos){ return new Base64EncoderStream(bos); } public InputStream buildInputStream(ByteArrayOutputStream bos){ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); return new Base64DecodeStream(bis); } }
674
0.780415
0.765579
17
38.64706
19.993944
69
false
false
0
0
0
0
0
0
0.588235
false
false
2
93d8625bede864b99b4a913fbcfab5c4b1fbcc6c
3,195,455,690,739
6ef4869c6bc2ce2e77b422242e347819f6a5f665
/devices/google/Pixel 2/29/QPP6.190730.005/src/framework/android/bluetooth/BluetoothHidDeviceAppQosSettings.java
1f2c6016ffd2e084d787793be88dfd77dccf3015
[]
no_license
hacking-android/frameworks
https://github.com/hacking-android/frameworks
40e40396bb2edacccabf8a920fa5722b021fb060
943f0b4d46f72532a419fb6171e40d1c93984c8e
refs/heads/master
2020-07-03T19:32:28.876000
2019-08-13T03:31:06
2019-08-13T03:31:06
202,017,534
2
0
null
false
2019-08-13T03:33:19
2019-08-12T22:19:30
2019-08-13T03:31:53
2019-08-13T03:33:18
63,898
0
0
0
Java
false
false
/* * Decompiled with CFR 0.145. */ package android.bluetooth; import android.os.Parcel; import android.os.Parcelable; public final class BluetoothHidDeviceAppQosSettings implements Parcelable { public static final Parcelable.Creator<BluetoothHidDeviceAppQosSettings> CREATOR = new Parcelable.Creator<BluetoothHidDeviceAppQosSettings>(){ @Override public BluetoothHidDeviceAppQosSettings createFromParcel(Parcel parcel) { return new BluetoothHidDeviceAppQosSettings(parcel.readInt(), parcel.readInt(), parcel.readInt(), parcel.readInt(), parcel.readInt(), parcel.readInt()); } public BluetoothHidDeviceAppQosSettings[] newArray(int n) { return new BluetoothHidDeviceAppQosSettings[n]; } }; public static final int MAX = -1; public static final int SERVICE_BEST_EFFORT = 1; public static final int SERVICE_GUARANTEED = 2; public static final int SERVICE_NO_TRAFFIC = 0; private final int mDelayVariation; private final int mLatency; private final int mPeakBandwidth; private final int mServiceType; private final int mTokenBucketSize; private final int mTokenRate; public BluetoothHidDeviceAppQosSettings(int n, int n2, int n3, int n4, int n5, int n6) { this.mServiceType = n; this.mTokenRate = n2; this.mTokenBucketSize = n3; this.mPeakBandwidth = n4; this.mLatency = n5; this.mDelayVariation = n6; } @Override public int describeContents() { return 0; } public int getDelayVariation() { return this.mDelayVariation; } public int getLatency() { return this.mLatency; } public int getPeakBandwidth() { return this.mPeakBandwidth; } public int getServiceType() { return this.mServiceType; } public int getTokenBucketSize() { return this.mTokenBucketSize; } public int getTokenRate() { return this.mTokenRate; } @Override public void writeToParcel(Parcel parcel, int n) { parcel.writeInt(this.mServiceType); parcel.writeInt(this.mTokenRate); parcel.writeInt(this.mTokenBucketSize); parcel.writeInt(this.mPeakBandwidth); parcel.writeInt(this.mLatency); parcel.writeInt(this.mDelayVariation); } }
UTF-8
Java
2,352
java
BluetoothHidDeviceAppQosSettings.java
Java
[]
null
[]
/* * Decompiled with CFR 0.145. */ package android.bluetooth; import android.os.Parcel; import android.os.Parcelable; public final class BluetoothHidDeviceAppQosSettings implements Parcelable { public static final Parcelable.Creator<BluetoothHidDeviceAppQosSettings> CREATOR = new Parcelable.Creator<BluetoothHidDeviceAppQosSettings>(){ @Override public BluetoothHidDeviceAppQosSettings createFromParcel(Parcel parcel) { return new BluetoothHidDeviceAppQosSettings(parcel.readInt(), parcel.readInt(), parcel.readInt(), parcel.readInt(), parcel.readInt(), parcel.readInt()); } public BluetoothHidDeviceAppQosSettings[] newArray(int n) { return new BluetoothHidDeviceAppQosSettings[n]; } }; public static final int MAX = -1; public static final int SERVICE_BEST_EFFORT = 1; public static final int SERVICE_GUARANTEED = 2; public static final int SERVICE_NO_TRAFFIC = 0; private final int mDelayVariation; private final int mLatency; private final int mPeakBandwidth; private final int mServiceType; private final int mTokenBucketSize; private final int mTokenRate; public BluetoothHidDeviceAppQosSettings(int n, int n2, int n3, int n4, int n5, int n6) { this.mServiceType = n; this.mTokenRate = n2; this.mTokenBucketSize = n3; this.mPeakBandwidth = n4; this.mLatency = n5; this.mDelayVariation = n6; } @Override public int describeContents() { return 0; } public int getDelayVariation() { return this.mDelayVariation; } public int getLatency() { return this.mLatency; } public int getPeakBandwidth() { return this.mPeakBandwidth; } public int getServiceType() { return this.mServiceType; } public int getTokenBucketSize() { return this.mTokenBucketSize; } public int getTokenRate() { return this.mTokenRate; } @Override public void writeToParcel(Parcel parcel, int n) { parcel.writeInt(this.mServiceType); parcel.writeInt(this.mTokenRate); parcel.writeInt(this.mTokenBucketSize); parcel.writeInt(this.mPeakBandwidth); parcel.writeInt(this.mLatency); parcel.writeInt(this.mDelayVariation); } }
2,352
0.677296
0.669218
81
28.024691
28.73419
164
false
false
0
0
0
0
0
0
0.567901
false
false
2
4e5a6b83fa44f4df0cc32fde28a57672aa7943e4
29,746,943,531,603
9df49e21af6c1d907e75ab3c7cafb7debf6bc998
/app/com/ga2sa/security/PasswordManager.java
09e587a56f5049076f983755dc8e7fdfcf314819
[ "Apache-2.0" ]
permissive
atnmorrison/google-analytics-to-salesforce-wave
https://github.com/atnmorrison/google-analytics-to-salesforce-wave
54fdcf8cea15dd53a4c14196b80cf98810e2b423
4427215205e13b569edb97728002c5dfe3e81205
refs/heads/master
2020-04-02T07:14:04.048000
2017-08-31T11:22:29
2017-08-31T11:22:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * This document is a part of the source code and related artifacts * for GA2SA, an open source code for Google Analytics to * Salesforce Analytics integration. * * Copyright © 2015 Cervello Inc., * * * 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. */ package com.ga2sa.security; import org.mindrot.jbcrypt.BCrypt; import play.Logger; /** * * Util class for work with password, the one uses for encrypt and check user password * * @author Igor Ivarov * @editor Sergey Legostaev * */ public class PasswordManager { public static final String PASSWORD_TMP = "password"; /** * Method for compare plain password and encrypted, this method uses for check password when user try to login. * * @param plainPassword * @param encryptedPassword * @return true or false */ public static boolean checkPassword(String plainPassword, String encryptedPassword) { try { return BCrypt.checkpw(plainPassword, encryptedPassword); } catch (IllegalArgumentException e) { Logger.error("Check password error: ", e) ; } return false; } /** * Encrypt password use default setting for BCrypt * * @param plain password * @return encrypted password */ public static String encryptPassword(String password) { return BCrypt.hashpw(password, BCrypt.gensalt()); } }
UTF-8
Java
1,485
java
PasswordManager.java
Java
[ { "context": "or encrypt and check user password \n * \n * @author Igor Ivarov\n * @editor Sergey Legostaev\n * \n */\npublic class ", "end": 640, "score": 0.9998717308044434, "start": 629, "tag": "NAME", "value": "Igor Ivarov" }, { "context": "er password \n * \n * @author Igor Ivarov\n * @editor Sergey Legostaev\n * \n */\npublic class PasswordManager {\n\t\n\tpublic ", "end": 668, "score": 0.9998783469200134, "start": 652, "tag": "NAME", "value": "Sergey Legostaev" }, { "context": "r {\n\t\n\tpublic static final String PASSWORD_TMP = \"password\";\n\t\n\t/**\n\t * Method for compare plain password an", "end": 762, "score": 0.641438364982605, "start": 754, "tag": "PASSWORD", "value": "password" } ]
null
[]
/** * This document is a part of the source code and related artifacts * for GA2SA, an open source code for Google Analytics to * Salesforce Analytics integration. * * Copyright © 2015 Cervello Inc., * * * 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. */ package com.ga2sa.security; import org.mindrot.jbcrypt.BCrypt; import play.Logger; /** * * Util class for work with password, the one uses for encrypt and check user password * * @author <NAME> * @editor <NAME> * */ public class PasswordManager { public static final String PASSWORD_TMP = "<PASSWORD>"; /** * Method for compare plain password and encrypted, this method uses for check password when user try to login. * * @param plainPassword * @param encryptedPassword * @return true or false */ public static boolean checkPassword(String plainPassword, String encryptedPassword) { try { return BCrypt.checkpw(plainPassword, encryptedPassword); } catch (IllegalArgumentException e) { Logger.error("Check password error: ", e) ; } return false; } /** * Encrypt password use default setting for BCrypt * * @param plain password * @return encrypted password */ public static String encryptPassword(String password) { return BCrypt.hashpw(password, BCrypt.gensalt()); } }
1,472
0.721698
0.717655
58
24.586206
27.758213
112
false
false
0
0
0
0
0
0
0.982759
false
false
2
b978887cef8c0f15e013ce78098b435a2dbb9158
566,935,724,234
c7193b292d559211868f8ed7dad1a1f18930c469
/given_parser/ast/WhileStatement.java
2c281486e82b8376ce2515b3b2f6cf365fa87a0c
[]
no_license
anitasouv/431-compiler
https://github.com/anitasouv/431-compiler
092aac92450b5027241283afc98d887e5f31c101
7548e32289f9ffe3f7a2e6759c91582e878cd12c
refs/heads/master
2020-03-17T16:06:28.980000
2018-06-13T20:24:08
2018-06-13T20:24:08
133,736,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ast; import java.util.List; import java.util.ArrayList; import cfg.*; import llvm.*; public class WhileStatement extends AbstractStatement { private final Expression guard; private final Statement body; public WhileStatement(int lineNum, Expression guard, Statement body) { super(lineNum); this.guard = guard; this.body = body; } public void typeOpCheck(List<TypeDeclaration> types, List<Declaration> decls, List<Function> func, Function curFunc) { guard.typeOpCheck(types, decls, func, curFunc); body.typeOpCheck(types, decls, func, curFunc); } public void typeCheck(List<TypeDeclaration> types, List<Declaration> decls, List<Function> func, Function curFunc) { //System.out.println("TYPECHECK: While"); } public boolean checkReturn() { return false; } public CFGNode cfg(List<TypeDeclaration> types, List<Declaration> decls, List<Function> func, Function curFunc, CFGNode startNode, CFGNode exitNode) { CFGNode guardNode = new CFGNode( startNode.name, exitNode.labelCountAndIncrement(), 0, 0, 0); guardNode.addGuard(guard); guardNode.addLLVMList(guard.toLLVM(types, decls, func, curFunc, startNode, exitNode)); String compareReg = guardNode.getLLVM().get(guardNode.getLLVM().size() - 1).getResultReg(); // adding break statement to the next block startNode.addLLVM(new BranchImmLLVM(guardNode.name + guardNode.blockNum) ); guardNode.addParent(startNode); startNode.addChild(guardNode); // two more nodes end node and the body CFGNode bodyNode = new CFGNode( startNode.name, exitNode.labelCountAndIncrement(), 0, 0, 0); guardNode.addChild(bodyNode); bodyNode.addParent(guardNode); CFGNode endNode = new CFGNode(startNode.name, exitNode.labelCountAndIncrement(), 0, 0, 0); endNode.addParent(guardNode); guardNode.addChild(endNode); // String op = ((BinaryExpression) guard).getOp(); guardNode.addLLVM(new BranchLLVM( compareReg , bodyNode.name + bodyNode.blockNum, endNode.name + endNode.blockNum)); bodyNode = body.cfg(types, decls, func, curFunc, bodyNode, exitNode); bodyNode.addChild(guardNode); guardNode.addParent(bodyNode); bodyNode.addLLVM(new BranchImmLLVM(guardNode.name + guardNode.blockNum)); return endNode; } public String typeToLLVM(List<TypeDeclaration> types, List<Declaration> decls, List<Function> func, Function curFunc) { return "whileType"; } public List<LLVM> toLLVM(List<TypeDeclaration> types, List<Declaration> decls, List<Function> func, Function curFunc) { return new ArrayList<LLVM>(); } }
UTF-8
Java
2,719
java
WhileStatement.java
Java
[]
null
[]
package ast; import java.util.List; import java.util.ArrayList; import cfg.*; import llvm.*; public class WhileStatement extends AbstractStatement { private final Expression guard; private final Statement body; public WhileStatement(int lineNum, Expression guard, Statement body) { super(lineNum); this.guard = guard; this.body = body; } public void typeOpCheck(List<TypeDeclaration> types, List<Declaration> decls, List<Function> func, Function curFunc) { guard.typeOpCheck(types, decls, func, curFunc); body.typeOpCheck(types, decls, func, curFunc); } public void typeCheck(List<TypeDeclaration> types, List<Declaration> decls, List<Function> func, Function curFunc) { //System.out.println("TYPECHECK: While"); } public boolean checkReturn() { return false; } public CFGNode cfg(List<TypeDeclaration> types, List<Declaration> decls, List<Function> func, Function curFunc, CFGNode startNode, CFGNode exitNode) { CFGNode guardNode = new CFGNode( startNode.name, exitNode.labelCountAndIncrement(), 0, 0, 0); guardNode.addGuard(guard); guardNode.addLLVMList(guard.toLLVM(types, decls, func, curFunc, startNode, exitNode)); String compareReg = guardNode.getLLVM().get(guardNode.getLLVM().size() - 1).getResultReg(); // adding break statement to the next block startNode.addLLVM(new BranchImmLLVM(guardNode.name + guardNode.blockNum) ); guardNode.addParent(startNode); startNode.addChild(guardNode); // two more nodes end node and the body CFGNode bodyNode = new CFGNode( startNode.name, exitNode.labelCountAndIncrement(), 0, 0, 0); guardNode.addChild(bodyNode); bodyNode.addParent(guardNode); CFGNode endNode = new CFGNode(startNode.name, exitNode.labelCountAndIncrement(), 0, 0, 0); endNode.addParent(guardNode); guardNode.addChild(endNode); // String op = ((BinaryExpression) guard).getOp(); guardNode.addLLVM(new BranchLLVM( compareReg , bodyNode.name + bodyNode.blockNum, endNode.name + endNode.blockNum)); bodyNode = body.cfg(types, decls, func, curFunc, bodyNode, exitNode); bodyNode.addChild(guardNode); guardNode.addParent(bodyNode); bodyNode.addLLVM(new BranchImmLLVM(guardNode.name + guardNode.blockNum)); return endNode; } public String typeToLLVM(List<TypeDeclaration> types, List<Declaration> decls, List<Function> func, Function curFunc) { return "whileType"; } public List<LLVM> toLLVM(List<TypeDeclaration> types, List<Declaration> decls, List<Function> func, Function curFunc) { return new ArrayList<LLVM>(); } }
2,719
0.698786
0.695108
84
31.369047
38.224831
153
false
false
0
0
0
0
0
0
1.011905
false
false
2
aeed7e9aa8e5a3595d78d8606a461837e9618747
19,129,784,377,475
788ea20672144e1f66f3123138676956955e0f8b
/src/HelloVar.java
1b4ed38060e7979fdc8fbd7b58a463bf9d23a4ec
[]
no_license
PatrickS2811/HelloVar
https://github.com/PatrickS2811/HelloVar
e58d1e5e44e40436f6ca98ce8a30065c98637c9d
e4080b0ee741dfcd7ccf8e074015be2835db3bff
refs/heads/master
2020-03-30T00:56:25.633000
2018-09-27T08:07:58
2018-09-27T08:07:58
150,551,297
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class HelloVar { public static void main (String[] args) { String name = "Patrick"; String achternaam = "Smalen"; int leerjaar = 1; double getal = 2.2; System.out.println(name + " " + achternaam); System.out.println("Hello Variables"); Scanner scan = new Scanner(System.in); name = scan.next(); System.out.println(name) ; } }
UTF-8
Java
449
java
HelloVar.java
Java
[ { "context": "id main (String[] args) {\n\n String name = \"Patrick\";\n String achternaam = \"Smalen\";\n i", "end": 129, "score": 0.9997234344482422, "start": 122, "tag": "NAME", "value": "Patrick" }, { "context": "ng name = \"Patrick\";\n String achternaam = \"Smalen\";\n int leerjaar = 1;\n double getal ", "end": 167, "score": 0.9998483657836914, "start": 161, "tag": "NAME", "value": "Smalen" } ]
null
[]
import java.util.Scanner; public class HelloVar { public static void main (String[] args) { String name = "Patrick"; String achternaam = "Smalen"; int leerjaar = 1; double getal = 2.2; System.out.println(name + " " + achternaam); System.out.println("Hello Variables"); Scanner scan = new Scanner(System.in); name = scan.next(); System.out.println(name) ; } }
449
0.567929
0.561247
25
17
18.491079
52
false
false
0
0
0
0
0
0
0.4
false
false
2
b80ecdbaab0ac49d2470ca782797583113af199a
27,736,898,829,378
89f5d66386ae95a23e81bebed061161618ff7c18
/test/integration/testcases/noncompile/2014G20/testdupclassdef.java
8564b7923259319d03d6a1c27960bcf59dfc759b
[]
no_license
hugoflug/compiler-haskell
https://github.com/hugoflug/compiler-haskell
1b3b59b69d30368030ddc35fb3e335b29c3125c6
2c0b2444ea6c7bb3f358f899fcf987917afaadd5
refs/heads/master
2022-01-18T16:32:26.090000
2019-08-03T16:09:32
2019-08-03T16:09:32
192,170,826
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class testdupclassdef { public static void main(String[] args) { } } class testdupclassdef { public int test(int a) { return a; } }
UTF-8
Java
138
java
testdupclassdef.java
Java
[]
null
[]
class testdupclassdef { public static void main(String[] args) { } } class testdupclassdef { public int test(int a) { return a; } }
138
0.681159
0.681159
9
14.333333
13.523642
41
false
false
0
0
0
0
0
0
0.777778
false
false
2
4b74eb7c72f46e13d600c77a017efb895e87d0cb
17,712,445,163,184
5c9a81ee6c3fd42c43f7f45bf7f050313c2566bc
/utilities/MYRPSmoketestUtil.java
1b542a7e655aafa17a6ade5dc3cb28e611a9d41d
[]
no_license
jayturla/propertyValue
https://github.com/jayturla/propertyValue
d1356ed2218baf6650b397c81b163dbd3cd18063
a7d30d6550be9754954bc49b3e0e3e81503225b0
refs/heads/master
2021-01-20T22:28:37.849000
2015-09-07T02:13:48
2015-09-07T02:13:48
38,467,673
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package myrp.utilities; import static org.openqa.selenium.By.xpath; import java.io.IOException; import java.util.List; import myrp.library.FunctionReference; import myrp.library.MYRPObjectReferenceRT_07810; import myrp.library.ObjectReference; import myrp.library.ObjectReferenceSmoketest; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.testng.Assert; import atu.testng.reports.ATUReports; public class MYRPSmoketestUtil extends FunctionReference { private String[] input = null; public MYRPSmoketestUtil(String[] i) { input = i; } public void clickSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.signUp )); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.signUp))); click(xpath(ObjectReferenceSmoketest.signUp)); waitForElementPresent(xpath(ObjectReferenceSmoketest.firstName)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.firstName))); System.out.println("Sign Up Pop up appeared"); } public void firstnameSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.firstName)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.firstName))); type(xpath(ObjectReferenceSmoketest.firstName), input[0]); System.out.println("First name entered"); } public void lastnameSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.lastName)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.lastName))); type(xpath(ObjectReferenceSmoketest.lastName), input[1]); System.out.println("Last name entered"); } public void emailSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.email)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.email))); type(xpath(ObjectReferenceSmoketest.email), input[2]); System.out.println("Email entered"); } public void confirmEmailSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.confirmMail)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.confirmMail))); type(xpath(ObjectReferenceSmoketest.confirmMail), input[3]); System.out.println("Email Confirmed"); } public void passwordSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.password)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.password))); type(xpath(ObjectReferenceSmoketest.password), input[4]); System.out.println("Password Entered"); } public void confirmPasswordSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.confirmPassword)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.confirmPassword))); type(xpath(ObjectReferenceSmoketest.confirmPassword), input[5]); System.out.println("Password Confirmed"); } public void securityQuestionSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.securityQuestion)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.securityQuestion))); type(xpath(ObjectReferenceSmoketest.securityQuestion), input[6]); System.out.println("Security Question"); } public void confirmsecurityQuestionSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.confirmSecuritQuestion)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.confirmSecuritQuestion))); type(xpath(ObjectReferenceSmoketest.confirmSecuritQuestion), input[7]); System.out.println("Security Question Confirm"); } public void acceptTermsSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.acceptTerms)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.acceptTerms))); click(xpath(ObjectReferenceSmoketest.acceptTerms)); System.out.println("Terms Accepted"); } public void userName() throws Exception{ log("ENtering Username"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin))); type(xpath(ObjectReferenceSmoketest.usernameLogin), input[2]); System.out.println("User name Entered"); } catch (AssertionError e) { fail("Unable to locate Element username"); } } public void passwordLogin() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin))); type(xpath(ObjectReferenceSmoketest.passwordLogin), input[4]); System.out.println("Password Entered"); } public boolean loginButton() throws Exception{ boolean success = false; log ("Preparing to Click Login Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.LoginRedbutton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.LoginRedbutton))); click(xpath(ObjectReferenceSmoketest.LoginRedbutton)); Thread.sleep(3000); System.out.println("Login Button Clicked"); } catch (Exception e) { fail("Was not Able to Click Login Button"); } return success; } public boolean estimatedValueSubricption() throws Exception{ boolean success = false; System.out.println("Search Address Via CFA"); try { if(login()){ userName(); passwordLogin(); loginButton(); clickCFAButton(); enterUnitnumber(); enterStreetname(); selectInAjax(); clickAddtoCartButton(3); gotoMyCart(); payViaMerchant(); if(successPayment()){ success = true; } } } catch (AssertionError e) { fail("Report was Not Purchased!!"); } return success; } public boolean successPayment() throws Exception{ boolean success = false; log("Click Login Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.purchaseSuccess)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.purchaseSuccess))); click(xpath(ObjectReferenceSmoketest.purchaseSuccess)); System.out.println("Page Directs to Seccessful Purchase page"); success = true; } catch (AssertionError e) { fail("Was not able to Direct to Purchase Page"); } return success; } public boolean login() throws Exception{ boolean success = false; log("Click Login Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.loginButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.loginButton))); click(xpath(ObjectReferenceSmoketest.loginButton)); System.out.println("Login pop up appears"); success = true; }catch (AssertionError e) { fail("Was not able to click Login Button"); } return success; } public void clickCFAButton()throws Exception{ log("Prepareing to click CFA Button"); try{ waitForElementPresent(xpath(ObjectReferenceSmoketest.cfaButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.cfaButton))); click(xpath(ObjectReferenceSmoketest.cfaButton)); log("Succesfully Click CFA BUtton"); Thread.sleep(2000); }catch(AssertionError e){ fail("Unable to locate element CFA Button"); } } public void enterUnitnumber()throws Exception{ log("Entering unit number"); try{ waitForElementPresent(xpath(ObjectReferenceSmoketest.unitNumber)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.unitNumber))); type(xpath(ObjectReferenceSmoketest.unitNumber), input[8]); }catch (AssertionError e){ fail("unable to Enter Unit Number"); } } public void enterStreetname()throws Exception{ log("Entering Street name"); try{ waitForElementPresent(xpath(ObjectReferenceSmoketest.streetName)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.streetName))); type(xpath(ObjectReferenceSmoketest.streetName), input[9]); Thread.sleep(2000); }catch (AssertionError e){ fail("unable to enter street name"); } } public void selectInAjax()throws Exception{ log("was able to Select in Ajax"); try{ waitForElementPresent(xpath(ObjectReferenceSmoketest.ajaxCFA)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.ajaxCFA))); click(xpath(ObjectReferenceSmoketest.ajaxCFA)); }catch (AssertionError e){ } } public void clickAddtoCartButton(int numberOfButton)throws Exception{ String purchaseButton = "(//*[@id='purchaseButton'])["+numberOfButton+"]"; log("Preparing to Add To Cart"); try{ waitForElementPresent(xpath(purchaseButton)); Assert.assertTrue(isElementPresent(xpath(purchaseButton))); click(xpath(purchaseButton)); log("Report was added to Cart"); }catch (AssertionError e){ fail("Report Was not Added to Cart!!!"); } } public void gotoMyCart()throws Exception{ log ("Go to my Cart"); try{ waitForElementPresent(xpath(ObjectReferenceSmoketest.gotoMyCart)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.gotoMyCart))); click(xpath(ObjectReferenceSmoketest.gotoMyCart)); log("My Cart Full page Fully Loads"); }catch (AssertionError e){ fail("My Card WAs not Able to Load"); } } public void payViaMerchant()throws Exception{ log("Preparing to Enter Payment Details"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.merchantName)); type(xpath(ObjectReferenceSmoketest.merchantName), input[10]); waitForElementPresent(xpath(ObjectReferenceSmoketest.merchantCard)); type(xpath(ObjectReferenceSmoketest.merchantCard), input[12]); waitForElementPresent(xpath(ObjectReferenceSmoketest.merchantCode)); type(xpath(ObjectReferenceSmoketest.merchantCode), input[13]); click(xpath(ObjectReferenceSmoketest.merchantPaynow)); Thread.sleep(2000); log("Was able to Pay with Entered Details"); } catch (AssertionError e) { fail("was not Able to Pay!"); } } public boolean loginDetailsExistingUser() throws Exception{ boolean success = false; System.out.println("Login Patrick"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.loginButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.loginButton))); click(xpath(ObjectReferenceSmoketest.loginButton)); System.out.println("Login pop up appears"); waitForElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin))); type(xpath(ObjectReferenceSmoketest.usernameLogin), input[14]); System.out.println("User name Entered"); waitForElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin))); type(xpath(ObjectReferenceSmoketest.passwordLogin), input[15]); System.out.println("Password Entered"); Thread.sleep(3000); success = true; }catch (AssertionError e) { fail("Details for Existing User is Entered"); } return success; } public boolean clickAdminTab() throws Exception{ boolean success = false; System.out.println("Preparing to Click Admin Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.adminButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.adminButton))); Thread.sleep(1000); click(xpath(ObjectReferenceSmoketest.adminButton)); Thread.sleep(2000); log("Was able to click login Button"); success = true; }catch (AssertionError e) { fail("was not able to click Admin Tab"); } return success; } public boolean clickHealthCheck() throws Exception{ boolean success = false; log("healthCheck Clicked"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.healthCheck)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.healthCheck))); click(xpath(ObjectReferenceSmoketest.healthCheck)); Thread.sleep(2000); }catch (AssertionError e) { fail("Was not Able to click Health check"); } return success; } public boolean clickAllConnections() throws Exception{ boolean success = false; log("prepariong to Click all connections"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.checkAllConnections)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.checkAllConnections))); click(xpath(ObjectReferenceSmoketest.checkAllConnections)); Thread.sleep(2000); } catch (AssertionError e) { fail("Was not able to click All Connections"); } return success; } public boolean clickLogout() throws Exception{ boolean success = false; log ("Preparing to Logout!"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.logOutButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.logOutButton))); click(xpath(ObjectReferenceSmoketest.logOutButton)); log("User has now Logged Out"); } catch (AssertionError e) { fail("Logout Button not clicked"); } return success; } public boolean successfulHeakthCheck() throws Exception{ boolean success = false; System.out.println("Waiting for Health Check Results"); waitForElementPresent(xpath(ObjectReferenceSmoketest.healthCheckResults)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.healthCheckResults))); List<WebElement> list = driver.findElements(By .xpath(ObjectReferenceSmoketest.healthCheckResults)); String listVal; for (WebElement element : list) { listVal = element.getText(); if (listVal.contains("Database connection is OK.") && listVal.contains("BSG connection is OK.") && listVal.contains("BSG 3.0 connection is OK.") && listVal.contains("S3 Bucket access is OK.") && listVal.contains("Manage Reports S3 Bucket access is OK.") && listVal.contains("Access to Payment Gateway is OK.") && listVal.contains("Vision6 connection is OK.") && listVal.contains("Access to RPConnect is OK.") && listVal.contains("Access to Cordell API is OK.") && listVal.contains("Access to Cordel API is OK.") && listVal.contains("Statistics API Connection is OK.") && listVal.contains("CPS is OK.")) { success = true; log("All Health Check Results are OK"); }else { success = false; fail("One Health check Result has Failed"); break; } } return success; } public boolean loginExistingUser() throws Exception{ boolean success = false; System.out.println("Existing User was Able to Login"); try { loginDetailsExistingUser(); loginButton(); clickAdminTab(); clickHealthCheck(); clickAllConnections(); if (successfulHeakthCheck()) { success = true; } }catch (AssertionError e) { fail("Health Check Has Failed"); } return success; } public boolean logoutUser() throws Exception{ boolean success = false; System.out.println("Preparing to login User"); try { loginDetailsExistingUser(); loginButton(); String text = getText(xpath(ObjectReferenceSmoketest.patName)); if (text.contains("Pat")) { success = true; log("Succesfully Patrick has Logged in"); Thread.sleep(2000); } else { fail("Unable to Login Patrick"); } clickLogout(); } catch (Exception e) { fail ("User was not Able to Logout!"); } return success; } public boolean preparetoLoginJohny() throws Exception { boolean success = false; System.out.println("Preparing to login Johnny"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.loginButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.loginButton))); click(xpath(ObjectReferenceSmoketest.loginButton)); System.out.println("Login pop up appears"); waitForElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin))); type(xpath(ObjectReferenceSmoketest.usernameLogin), input[2]); System.out.println("User name Entered"); waitForElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin))); type(xpath(ObjectReferenceSmoketest.passwordLogin), input[4]); System.out.println("Password Entered"); log("Details for Johnny is Entered"); } catch (AssertionError e) { fail("Details for Johnny was Not Entered"); } return success; } public boolean clickSuburbReportsButton() throws Exception { boolean success = false; System.out.println("Preparing to click suburb Reports Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.suburbReportsButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.suburbReportsButton))); click(xpath(ObjectReferenceSmoketest.suburbReportsButton)); Thread.sleep(2000); log("Was able to Click Suburb Reports Button"); waitForElementPresent(xpath(ObjectReferenceSmoketest.suburbReportsLabel)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.suburbReportsLabel))); String text = getText(xpath(ObjectReferenceSmoketest.suburbReportsLabel)); if (text.contains("Suburb Reports")) { success = true; log("Succesfully Visit the Suburb Reports Tab"); Thread.sleep(2000); } else { fail("Unable to locate Element Suburb Reports Tab"); } } catch (AssertionError e) { fail("Was Not Able to click Suburb Reports Button"); } return success; } public boolean searchSurryHills() throws Exception { boolean success = false; System.out.println("Preparing to Search in Slas"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.slasField)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.slasField))); type(xpath(ObjectReferenceSmoketest.slasField), input[16]); Thread.sleep(900); log("Surry Hills Entered in SLAS"); } catch (AssertionError e) { fail("Was not Able to Enter Surry Hills"); } return success; } public boolean selectinSLAS() throws Exception { boolean success = false; System.out.println("Preparing to Select address in Slas"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.selectajax)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.selectajax))); click(xpath(ObjectReferenceSmoketest.selectajax)); Thread.sleep(2000); log("Was Able to Select Address in Slas"); } catch (AssertionError e) { fail("Was Not Able to Select in SLAS"); } return success; } public boolean addSuburbSaleshistory() throws Exception { boolean success = false; System.out.println("Preparing to add Suburb Sales History Report"); try { preparetoLoginJohny(); loginButton(); clickSuburbReportsButton(); searchSurryHills(); selectinSLAS(); clickAddtoCartButton(1); gotoMyCart(); payViaMerchant(); if (successPayment()) { success = true; } } catch (AssertionError e) { fail("Report was Not Purchased!!"); } return success; } public boolean goTosuburbSalesMapSubscription() throws Exception { boolean success = false; System.out.println("Preparing to add Suburb Sales History Report"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.suburbSalesMapSubscription)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.suburbSalesMapSubscription))); click(xpath(ObjectReferenceSmoketest.suburbSalesMapSubscription)); Thread.sleep(2000); log("Was able to go to Suburb Sales Map Subscription (3months)"); } catch (AssertionError e) { fail("Was not able to go to Suburb Sales Map Subscription (3months)"); } return success; } public boolean searchOconnorAct() throws Exception { boolean success = false; System.out.println("Preparing to Address Search in Slas"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.slasField)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.slasField))); type(xpath(ObjectReferenceSmoketest.slasField), input[17]); log("Occonnor ACT Entered in SLAS"); } catch (AssertionError e) { fail("Was not Able to Enter Occonnor ACT"); } return success; } public boolean addSuburbMapSalesSuscription() throws Exception { boolean success = false; try { preparetoLoginJohny(); loginButton(); clickSuburbReportsButton(); goTosuburbSalesMapSubscription(); searchOconnorAct(); selectinSLAS(); clickAddtoCartButton(2); gotoMyCart(); payButtonCPS(); ////payViaMerchant(); enterCPSDetails(); clickSubmitCheckout(); if(successPayment()){ } } catch (AssertionError e) { fail("Suburb Map Sales Subscription Report was Not Purchased!!!"); } return success; } public boolean payButtonCPS() throws Exception { boolean success = false; log("Preparing to Clic Order Now Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.payNowCPS)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.payNowCPS))); click(xpath(ObjectReferenceSmoketest.payNowCPS)); Thread.sleep(2000); log("Pay now Button is Clicked"); } catch (AssertionError e) { fail("pay now button Was not Clicked"); } return success; } public boolean enterCPSDetails() throws Exception { boolean success = false; log("Preparing to enter Payment Details"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.cardNumber)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.cardNumber))); type(xpath(ObjectReferenceSmoketest.cardNumber), input[12]); type(xpath(ObjectReferenceSmoketest.cardHolder), input[6]); type(xpath(ObjectReferenceSmoketest.monthDate), input[18]); type(xpath(ObjectReferenceSmoketest.yearDate), input[19]); type(xpath(ObjectReferenceSmoketest.cardSecurutyCode), input[13]); log("Payment Details Entered"); } catch (AssertionError e) { fail("Details were Not Entered"); } return success; } public boolean clickSubmitCheckout() throws Exception { boolean success = false; log("Preparing to Submit Payment"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.submitButtonCheckout)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.submitButtonCheckout))); click(xpath(ObjectReferenceSmoketest.submitButtonCheckout)); Thread.sleep(2000); log("Submit Button Clicked"); } catch (AssertionError e) { fail("Submit Button Was Not Clicked"); } return success; } }
UTF-8
Java
22,851
java
MYRPSmoketestUtil.java
Java
[ { "context": "olean success = false;\n\t\tSystem.out.println(\"Login Patrick\");\n\t\n\t\ttry {\n\t\t\twaitForElementPresent(xpath(Objec", "end": 10211, "score": 0.9761040806770325, "start": 10204, "tag": "NAME", "value": "Patrick" }, { "context": "erenceSmoketest.patName));\n\t\t\t\tif (text.contains(\"Pat\")) {\n\t\t\t\t\tsuccess = true;\n\t\t\t\t\tlog(\"Succesfully P", "end": 15265, "score": 0.9996516704559326, "start": 15262, "tag": "NAME", "value": "Pat" }, { "context": "at\")) {\n\t\t\t\t\tsuccess = true;\n\t\t\t\t\tlog(\"Succesfully Patrick has Logged in\");\n\t\t\t\t\tThread.sleep(2000);\n\t\t\t\t} e", "end": 15321, "score": 0.9993124604225159, "start": 15314, "tag": "NAME", "value": "Patrick" }, { "context": "eep(2000);\n\t\t\t\t} else {\n\t\t\t\t\tfail(\"Unable to Login Patrick\");\n\t\t\t\t}\n\t\t\t\tclickLogout();\n\t\t\t} catch (Exception", "end": 15411, "score": 0.9987510442733765, "start": 15404, "tag": "NAME", "value": "Patrick" } ]
null
[]
package myrp.utilities; import static org.openqa.selenium.By.xpath; import java.io.IOException; import java.util.List; import myrp.library.FunctionReference; import myrp.library.MYRPObjectReferenceRT_07810; import myrp.library.ObjectReference; import myrp.library.ObjectReferenceSmoketest; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.testng.Assert; import atu.testng.reports.ATUReports; public class MYRPSmoketestUtil extends FunctionReference { private String[] input = null; public MYRPSmoketestUtil(String[] i) { input = i; } public void clickSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.signUp )); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.signUp))); click(xpath(ObjectReferenceSmoketest.signUp)); waitForElementPresent(xpath(ObjectReferenceSmoketest.firstName)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.firstName))); System.out.println("Sign Up Pop up appeared"); } public void firstnameSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.firstName)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.firstName))); type(xpath(ObjectReferenceSmoketest.firstName), input[0]); System.out.println("First name entered"); } public void lastnameSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.lastName)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.lastName))); type(xpath(ObjectReferenceSmoketest.lastName), input[1]); System.out.println("Last name entered"); } public void emailSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.email)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.email))); type(xpath(ObjectReferenceSmoketest.email), input[2]); System.out.println("Email entered"); } public void confirmEmailSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.confirmMail)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.confirmMail))); type(xpath(ObjectReferenceSmoketest.confirmMail), input[3]); System.out.println("Email Confirmed"); } public void passwordSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.password)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.password))); type(xpath(ObjectReferenceSmoketest.password), input[4]); System.out.println("Password Entered"); } public void confirmPasswordSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.confirmPassword)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.confirmPassword))); type(xpath(ObjectReferenceSmoketest.confirmPassword), input[5]); System.out.println("Password Confirmed"); } public void securityQuestionSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.securityQuestion)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.securityQuestion))); type(xpath(ObjectReferenceSmoketest.securityQuestion), input[6]); System.out.println("Security Question"); } public void confirmsecurityQuestionSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.confirmSecuritQuestion)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.confirmSecuritQuestion))); type(xpath(ObjectReferenceSmoketest.confirmSecuritQuestion), input[7]); System.out.println("Security Question Confirm"); } public void acceptTermsSignUp() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.acceptTerms)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.acceptTerms))); click(xpath(ObjectReferenceSmoketest.acceptTerms)); System.out.println("Terms Accepted"); } public void userName() throws Exception{ log("ENtering Username"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin))); type(xpath(ObjectReferenceSmoketest.usernameLogin), input[2]); System.out.println("User name Entered"); } catch (AssertionError e) { fail("Unable to locate Element username"); } } public void passwordLogin() throws Exception{ waitForElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin))); type(xpath(ObjectReferenceSmoketest.passwordLogin), input[4]); System.out.println("Password Entered"); } public boolean loginButton() throws Exception{ boolean success = false; log ("Preparing to Click Login Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.LoginRedbutton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.LoginRedbutton))); click(xpath(ObjectReferenceSmoketest.LoginRedbutton)); Thread.sleep(3000); System.out.println("Login Button Clicked"); } catch (Exception e) { fail("Was not Able to Click Login Button"); } return success; } public boolean estimatedValueSubricption() throws Exception{ boolean success = false; System.out.println("Search Address Via CFA"); try { if(login()){ userName(); passwordLogin(); loginButton(); clickCFAButton(); enterUnitnumber(); enterStreetname(); selectInAjax(); clickAddtoCartButton(3); gotoMyCart(); payViaMerchant(); if(successPayment()){ success = true; } } } catch (AssertionError e) { fail("Report was Not Purchased!!"); } return success; } public boolean successPayment() throws Exception{ boolean success = false; log("Click Login Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.purchaseSuccess)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.purchaseSuccess))); click(xpath(ObjectReferenceSmoketest.purchaseSuccess)); System.out.println("Page Directs to Seccessful Purchase page"); success = true; } catch (AssertionError e) { fail("Was not able to Direct to Purchase Page"); } return success; } public boolean login() throws Exception{ boolean success = false; log("Click Login Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.loginButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.loginButton))); click(xpath(ObjectReferenceSmoketest.loginButton)); System.out.println("Login pop up appears"); success = true; }catch (AssertionError e) { fail("Was not able to click Login Button"); } return success; } public void clickCFAButton()throws Exception{ log("Prepareing to click CFA Button"); try{ waitForElementPresent(xpath(ObjectReferenceSmoketest.cfaButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.cfaButton))); click(xpath(ObjectReferenceSmoketest.cfaButton)); log("Succesfully Click CFA BUtton"); Thread.sleep(2000); }catch(AssertionError e){ fail("Unable to locate element CFA Button"); } } public void enterUnitnumber()throws Exception{ log("Entering unit number"); try{ waitForElementPresent(xpath(ObjectReferenceSmoketest.unitNumber)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.unitNumber))); type(xpath(ObjectReferenceSmoketest.unitNumber), input[8]); }catch (AssertionError e){ fail("unable to Enter Unit Number"); } } public void enterStreetname()throws Exception{ log("Entering Street name"); try{ waitForElementPresent(xpath(ObjectReferenceSmoketest.streetName)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.streetName))); type(xpath(ObjectReferenceSmoketest.streetName), input[9]); Thread.sleep(2000); }catch (AssertionError e){ fail("unable to enter street name"); } } public void selectInAjax()throws Exception{ log("was able to Select in Ajax"); try{ waitForElementPresent(xpath(ObjectReferenceSmoketest.ajaxCFA)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.ajaxCFA))); click(xpath(ObjectReferenceSmoketest.ajaxCFA)); }catch (AssertionError e){ } } public void clickAddtoCartButton(int numberOfButton)throws Exception{ String purchaseButton = "(//*[@id='purchaseButton'])["+numberOfButton+"]"; log("Preparing to Add To Cart"); try{ waitForElementPresent(xpath(purchaseButton)); Assert.assertTrue(isElementPresent(xpath(purchaseButton))); click(xpath(purchaseButton)); log("Report was added to Cart"); }catch (AssertionError e){ fail("Report Was not Added to Cart!!!"); } } public void gotoMyCart()throws Exception{ log ("Go to my Cart"); try{ waitForElementPresent(xpath(ObjectReferenceSmoketest.gotoMyCart)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.gotoMyCart))); click(xpath(ObjectReferenceSmoketest.gotoMyCart)); log("My Cart Full page Fully Loads"); }catch (AssertionError e){ fail("My Card WAs not Able to Load"); } } public void payViaMerchant()throws Exception{ log("Preparing to Enter Payment Details"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.merchantName)); type(xpath(ObjectReferenceSmoketest.merchantName), input[10]); waitForElementPresent(xpath(ObjectReferenceSmoketest.merchantCard)); type(xpath(ObjectReferenceSmoketest.merchantCard), input[12]); waitForElementPresent(xpath(ObjectReferenceSmoketest.merchantCode)); type(xpath(ObjectReferenceSmoketest.merchantCode), input[13]); click(xpath(ObjectReferenceSmoketest.merchantPaynow)); Thread.sleep(2000); log("Was able to Pay with Entered Details"); } catch (AssertionError e) { fail("was not Able to Pay!"); } } public boolean loginDetailsExistingUser() throws Exception{ boolean success = false; System.out.println("Login Patrick"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.loginButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.loginButton))); click(xpath(ObjectReferenceSmoketest.loginButton)); System.out.println("Login pop up appears"); waitForElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin))); type(xpath(ObjectReferenceSmoketest.usernameLogin), input[14]); System.out.println("User name Entered"); waitForElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin))); type(xpath(ObjectReferenceSmoketest.passwordLogin), input[15]); System.out.println("Password Entered"); Thread.sleep(3000); success = true; }catch (AssertionError e) { fail("Details for Existing User is Entered"); } return success; } public boolean clickAdminTab() throws Exception{ boolean success = false; System.out.println("Preparing to Click Admin Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.adminButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.adminButton))); Thread.sleep(1000); click(xpath(ObjectReferenceSmoketest.adminButton)); Thread.sleep(2000); log("Was able to click login Button"); success = true; }catch (AssertionError e) { fail("was not able to click Admin Tab"); } return success; } public boolean clickHealthCheck() throws Exception{ boolean success = false; log("healthCheck Clicked"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.healthCheck)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.healthCheck))); click(xpath(ObjectReferenceSmoketest.healthCheck)); Thread.sleep(2000); }catch (AssertionError e) { fail("Was not Able to click Health check"); } return success; } public boolean clickAllConnections() throws Exception{ boolean success = false; log("prepariong to Click all connections"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.checkAllConnections)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.checkAllConnections))); click(xpath(ObjectReferenceSmoketest.checkAllConnections)); Thread.sleep(2000); } catch (AssertionError e) { fail("Was not able to click All Connections"); } return success; } public boolean clickLogout() throws Exception{ boolean success = false; log ("Preparing to Logout!"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.logOutButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.logOutButton))); click(xpath(ObjectReferenceSmoketest.logOutButton)); log("User has now Logged Out"); } catch (AssertionError e) { fail("Logout Button not clicked"); } return success; } public boolean successfulHeakthCheck() throws Exception{ boolean success = false; System.out.println("Waiting for Health Check Results"); waitForElementPresent(xpath(ObjectReferenceSmoketest.healthCheckResults)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.healthCheckResults))); List<WebElement> list = driver.findElements(By .xpath(ObjectReferenceSmoketest.healthCheckResults)); String listVal; for (WebElement element : list) { listVal = element.getText(); if (listVal.contains("Database connection is OK.") && listVal.contains("BSG connection is OK.") && listVal.contains("BSG 3.0 connection is OK.") && listVal.contains("S3 Bucket access is OK.") && listVal.contains("Manage Reports S3 Bucket access is OK.") && listVal.contains("Access to Payment Gateway is OK.") && listVal.contains("Vision6 connection is OK.") && listVal.contains("Access to RPConnect is OK.") && listVal.contains("Access to Cordell API is OK.") && listVal.contains("Access to Cordel API is OK.") && listVal.contains("Statistics API Connection is OK.") && listVal.contains("CPS is OK.")) { success = true; log("All Health Check Results are OK"); }else { success = false; fail("One Health check Result has Failed"); break; } } return success; } public boolean loginExistingUser() throws Exception{ boolean success = false; System.out.println("Existing User was Able to Login"); try { loginDetailsExistingUser(); loginButton(); clickAdminTab(); clickHealthCheck(); clickAllConnections(); if (successfulHeakthCheck()) { success = true; } }catch (AssertionError e) { fail("Health Check Has Failed"); } return success; } public boolean logoutUser() throws Exception{ boolean success = false; System.out.println("Preparing to login User"); try { loginDetailsExistingUser(); loginButton(); String text = getText(xpath(ObjectReferenceSmoketest.patName)); if (text.contains("Pat")) { success = true; log("Succesfully Patrick has Logged in"); Thread.sleep(2000); } else { fail("Unable to Login Patrick"); } clickLogout(); } catch (Exception e) { fail ("User was not Able to Logout!"); } return success; } public boolean preparetoLoginJohny() throws Exception { boolean success = false; System.out.println("Preparing to login Johnny"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.loginButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.loginButton))); click(xpath(ObjectReferenceSmoketest.loginButton)); System.out.println("Login pop up appears"); waitForElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.usernameLogin))); type(xpath(ObjectReferenceSmoketest.usernameLogin), input[2]); System.out.println("User name Entered"); waitForElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.passwordLogin))); type(xpath(ObjectReferenceSmoketest.passwordLogin), input[4]); System.out.println("Password Entered"); log("Details for Johnny is Entered"); } catch (AssertionError e) { fail("Details for Johnny was Not Entered"); } return success; } public boolean clickSuburbReportsButton() throws Exception { boolean success = false; System.out.println("Preparing to click suburb Reports Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.suburbReportsButton)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.suburbReportsButton))); click(xpath(ObjectReferenceSmoketest.suburbReportsButton)); Thread.sleep(2000); log("Was able to Click Suburb Reports Button"); waitForElementPresent(xpath(ObjectReferenceSmoketest.suburbReportsLabel)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.suburbReportsLabel))); String text = getText(xpath(ObjectReferenceSmoketest.suburbReportsLabel)); if (text.contains("Suburb Reports")) { success = true; log("Succesfully Visit the Suburb Reports Tab"); Thread.sleep(2000); } else { fail("Unable to locate Element Suburb Reports Tab"); } } catch (AssertionError e) { fail("Was Not Able to click Suburb Reports Button"); } return success; } public boolean searchSurryHills() throws Exception { boolean success = false; System.out.println("Preparing to Search in Slas"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.slasField)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.slasField))); type(xpath(ObjectReferenceSmoketest.slasField), input[16]); Thread.sleep(900); log("Surry Hills Entered in SLAS"); } catch (AssertionError e) { fail("Was not Able to Enter Surry Hills"); } return success; } public boolean selectinSLAS() throws Exception { boolean success = false; System.out.println("Preparing to Select address in Slas"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.selectajax)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.selectajax))); click(xpath(ObjectReferenceSmoketest.selectajax)); Thread.sleep(2000); log("Was Able to Select Address in Slas"); } catch (AssertionError e) { fail("Was Not Able to Select in SLAS"); } return success; } public boolean addSuburbSaleshistory() throws Exception { boolean success = false; System.out.println("Preparing to add Suburb Sales History Report"); try { preparetoLoginJohny(); loginButton(); clickSuburbReportsButton(); searchSurryHills(); selectinSLAS(); clickAddtoCartButton(1); gotoMyCart(); payViaMerchant(); if (successPayment()) { success = true; } } catch (AssertionError e) { fail("Report was Not Purchased!!"); } return success; } public boolean goTosuburbSalesMapSubscription() throws Exception { boolean success = false; System.out.println("Preparing to add Suburb Sales History Report"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.suburbSalesMapSubscription)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.suburbSalesMapSubscription))); click(xpath(ObjectReferenceSmoketest.suburbSalesMapSubscription)); Thread.sleep(2000); log("Was able to go to Suburb Sales Map Subscription (3months)"); } catch (AssertionError e) { fail("Was not able to go to Suburb Sales Map Subscription (3months)"); } return success; } public boolean searchOconnorAct() throws Exception { boolean success = false; System.out.println("Preparing to Address Search in Slas"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.slasField)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.slasField))); type(xpath(ObjectReferenceSmoketest.slasField), input[17]); log("Occonnor ACT Entered in SLAS"); } catch (AssertionError e) { fail("Was not Able to Enter Occonnor ACT"); } return success; } public boolean addSuburbMapSalesSuscription() throws Exception { boolean success = false; try { preparetoLoginJohny(); loginButton(); clickSuburbReportsButton(); goTosuburbSalesMapSubscription(); searchOconnorAct(); selectinSLAS(); clickAddtoCartButton(2); gotoMyCart(); payButtonCPS(); ////payViaMerchant(); enterCPSDetails(); clickSubmitCheckout(); if(successPayment()){ } } catch (AssertionError e) { fail("Suburb Map Sales Subscription Report was Not Purchased!!!"); } return success; } public boolean payButtonCPS() throws Exception { boolean success = false; log("Preparing to Clic Order Now Button"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.payNowCPS)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.payNowCPS))); click(xpath(ObjectReferenceSmoketest.payNowCPS)); Thread.sleep(2000); log("Pay now Button is Clicked"); } catch (AssertionError e) { fail("pay now button Was not Clicked"); } return success; } public boolean enterCPSDetails() throws Exception { boolean success = false; log("Preparing to enter Payment Details"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.cardNumber)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.cardNumber))); type(xpath(ObjectReferenceSmoketest.cardNumber), input[12]); type(xpath(ObjectReferenceSmoketest.cardHolder), input[6]); type(xpath(ObjectReferenceSmoketest.monthDate), input[18]); type(xpath(ObjectReferenceSmoketest.yearDate), input[19]); type(xpath(ObjectReferenceSmoketest.cardSecurutyCode), input[13]); log("Payment Details Entered"); } catch (AssertionError e) { fail("Details were Not Entered"); } return success; } public boolean clickSubmitCheckout() throws Exception { boolean success = false; log("Preparing to Submit Payment"); try { waitForElementPresent(xpath(ObjectReferenceSmoketest.submitButtonCheckout)); Assert.assertTrue(isElementPresent(xpath(ObjectReferenceSmoketest.submitButtonCheckout))); click(xpath(ObjectReferenceSmoketest.submitButtonCheckout)); Thread.sleep(2000); log("Submit Button Clicked"); } catch (AssertionError e) { fail("Submit Button Was Not Clicked"); } return success; } }
22,851
0.740405
0.735198
751
29.420773
34.220268
607
false
false
0
0
0
0
0
0
2.66711
false
false
2
faf97c7724a54210f9818e34517acf6dae959197
20,753,282,012,103
e3ee41e54eac512b8b6b90d1b9a4e4ac4ae5b8fd
/src/cn/moviebigdata/mdata/request/Takser.java
cdf45fd154cf83993b0ae54c1d39c76256bdb30c
[]
no_license
augustusliu/movie_hd_scrapy
https://github.com/augustusliu/movie_hd_scrapy
b7000ba70cafb2ab4a80be95093162ac99dbbc05
6a870c942a5dc03a85eb45e5ff1d02666a39d3dd
refs/heads/master
2020-05-19T10:33:22.435000
2019-05-05T03:28:41
2019-05-05T03:28:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.moviebigdata.mdata.request; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public abstract class Takser extends Thread { private static final Log LOG = LogFactory.getLog(Takser.class); public Takser() { this.setDaemon(true); LOG.info("initing thread -threadname : " + this.getName()); } @Override public void run() { begin(); } public abstract void begin(); }
UTF-8
Java
439
java
Takser.java
Java
[]
null
[]
package cn.moviebigdata.mdata.request; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public abstract class Takser extends Thread { private static final Log LOG = LogFactory.getLog(Takser.class); public Takser() { this.setDaemon(true); LOG.info("initing thread -threadname : " + this.getName()); } @Override public void run() { begin(); } public abstract void begin(); }
439
0.710706
0.710706
24
17.291666
20.612453
64
false
false
0
0
0
0
0
0
1.125
false
false
2
ee8b7c6448e99532c9c421cbaa93a1d63fe9307a
20,753,282,011,859
f2aa7fce63f3e8c45bacedd50763b881ae8ae804
/perfViewer/src/java/ch/heigvd/perfviewer/service/JpaQueryManager.java
9387a9d398f0204477d21a406fb153fc052dd12c
[]
no_license
ngoumnai/JPAPerf
https://github.com/ngoumnai/JPAPerf
d8917940e1e3e1b04acd09e4a1c924ddca94fe7f
eaa40b3c420b7afd39a16d1ef13953d192ccf84b
refs/heads/master
2021-01-23T20:18:35.704000
2013-08-30T13:54:51
2013-08-30T13:54:51
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. */ package ch.heigvd.perfviewer.service; import ch.heigvd.perfviewer.model.Bean.JPQLRequestBean; import ch.heigvd.perfviewer.model.query.JPAQuery; import java.util.HashMap; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author gauss */ @Stateless public class JpaQueryManager extends AbstractManager<JPAQuery> implements JpaQueryMangerLocal { @PersistenceContext(unitName = "perfViewerPU") private EntityManager em; HashMap<String, JPQLRequestBean> hashMapOfJPQLRequest; @Override protected EntityManager getEntityManager() { return em; } public JpaQueryManager() { super(JPAQuery.class); } @Override public List findByQueryname(String name){ return em.createNamedQuery("Jpaquery.findByQueryname") .setParameter("name", name) .getResultList(); } @Override public HashMap getHashMapOfJPQLRequest(){ setHashMapOfJPQLRequest(); return hashMapOfJPQLRequest; } @Override public void setHashMapOfJPQLRequest(){ List<JPAQuery> queryList = findAll(); hashMapOfJPQLRequest = new HashMap<String, JPQLRequestBean>(); for(JPAQuery jpaQuery: queryList){ //on ajoute la nouvelle requete a la liste des requetes identiques du JPQLRequestBean if(hashMapOfJPQLRequest.containsKey(jpaQuery.getQueryname())){ ((JPQLRequestBean) hashMapOfJPQLRequest.get(jpaQuery.getQueryname())).setJPQLRequestInfo(jpaQuery); } //On cree une liste de requete si ce type de requete n'a pas encore ete effectuee else{ JPQLRequestBean jpqlR = new JPQLRequestBean(jpaQuery); hashMapOfJPQLRequest.put(jpaQuery.getQueryname(), jpqlR); } } } }
UTF-8
Java
2,040
java
JpaQueryManager.java
Java
[ { "context": "persistence.PersistenceContext;\n\n/**\n *\n * @author gauss\n */\n@Stateless\npublic class JpaQueryManager exten", "end": 431, "score": 0.9993208050727844, "start": 426, "tag": "USERNAME", "value": "gauss" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ch.heigvd.perfviewer.service; import ch.heigvd.perfviewer.model.Bean.JPQLRequestBean; import ch.heigvd.perfviewer.model.query.JPAQuery; import java.util.HashMap; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author gauss */ @Stateless public class JpaQueryManager extends AbstractManager<JPAQuery> implements JpaQueryMangerLocal { @PersistenceContext(unitName = "perfViewerPU") private EntityManager em; HashMap<String, JPQLRequestBean> hashMapOfJPQLRequest; @Override protected EntityManager getEntityManager() { return em; } public JpaQueryManager() { super(JPAQuery.class); } @Override public List findByQueryname(String name){ return em.createNamedQuery("Jpaquery.findByQueryname") .setParameter("name", name) .getResultList(); } @Override public HashMap getHashMapOfJPQLRequest(){ setHashMapOfJPQLRequest(); return hashMapOfJPQLRequest; } @Override public void setHashMapOfJPQLRequest(){ List<JPAQuery> queryList = findAll(); hashMapOfJPQLRequest = new HashMap<String, JPQLRequestBean>(); for(JPAQuery jpaQuery: queryList){ //on ajoute la nouvelle requete a la liste des requetes identiques du JPQLRequestBean if(hashMapOfJPQLRequest.containsKey(jpaQuery.getQueryname())){ ((JPQLRequestBean) hashMapOfJPQLRequest.get(jpaQuery.getQueryname())).setJPQLRequestInfo(jpaQuery); } //On cree une liste de requete si ce type de requete n'a pas encore ete effectuee else{ JPQLRequestBean jpqlR = new JPQLRequestBean(jpaQuery); hashMapOfJPQLRequest.put(jpaQuery.getQueryname(), jpqlR); } } } }
2,040
0.670098
0.670098
65
30.384615
27.863785
115
false
false
0
0
0
0
0
0
0.4
false
false
2
b559b400d8e9871bfb451b638d6fbba9d98f28c5
20,907,900,833,292
df10a555fe1cd33dcb324e525689c6be857d03a4
/backend/src/main/java/com/example/fileSharing/dto/UserInfoDto.java
c2b734c188b93fbef3ae9da2475c368cd273097e
[]
no_license
nuxxxcake/fileSharing
https://github.com/nuxxxcake/fileSharing
3e5c7acca36ebbaa5743a5228e1a2278e1588b82
ac9745723eff0579d2ab58c80a67b30c9fc493fd
refs/heads/master
2023-06-03T14:01:24.412000
2021-06-25T10:36:03
2021-06-25T10:36:03
303,086,612
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.fileSharing.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.UUID; @Data @NoArgsConstructor public class UserInfoDto extends UserIdDto { private String userName; private String avatar; public UserInfoDto(String userName) { this.userName = userName; } public UserInfoDto(UUID id, String userName, String avatar) { super(id); this.userName = userName; this.avatar = avatar; } public UserInfoDto(UUID id, String userName) { this.id = id; this.userName = userName; } }
UTF-8
Java
591
java
UserInfoDto.java
Java
[ { "context": "UserInfoDto(String userName) {\n this.userName = userName;\n }\n\n public UserInfoDto(UUID id, String userNa", "end": 341, "score": 0.9912044405937195, "start": 333, "tag": "USERNAME", "value": "userName" }, { "context": "tring avatar) {\n super(id);\n this.userName = userName;\n this.avatar = avatar;\n }\n\n public UserInfo", "end": 455, "score": 0.9985401630401611, "start": 447, "tag": "USERNAME", "value": "userName" }, { "context": " userName) {\n this.id = id;\n this.userName = userName;\n }\n}\n", "end": 583, "score": 0.9980948567390442, "start": 575, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.example.fileSharing.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.UUID; @Data @NoArgsConstructor public class UserInfoDto extends UserIdDto { private String userName; private String avatar; public UserInfoDto(String userName) { this.userName = userName; } public UserInfoDto(UUID id, String userName, String avatar) { super(id); this.userName = userName; this.avatar = avatar; } public UserInfoDto(UUID id, String userName) { this.id = id; this.userName = userName; } }
591
0.729272
0.729272
29
19.379311
16.973434
63
false
false
0
0
0
0
0
0
0.551724
false
false
2
74fb5754604555ff08b3167a789727ed0bcd8344
39,599,598,490,909
d01df8e1f21f8e8065995a8b13bb5152318680ce
/Playground/src/de/gfn/oca8_test_all/StringBuilderInser.java
44fdee6273a5a444d57023e5e61a8ef8ab32a828
[]
no_license
wsen/Playground230418
https://github.com/wsen/Playground230418
caded0df52c943a70aba59af73a8bddc0e8c1f45
009f4f3e6281669843465d31f783f3e1dc7857be
refs/heads/master
2021-07-10T07:44:51.606000
2018-09-28T22:47:36
2018-09-28T22:47:36
131,116,488
0
0
null
true
2018-04-26T11:28:43
2018-04-26T07:23:59
2018-04-26T07:24:01
2018-04-26T11:28:42
14
0
0
0
Java
false
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 de.gfn.oca8_test_all; /** * * @author wsen */ public class StringBuilderInser { public static void main(String[] args) { StringBuilder s = new StringBuilder("Java"); s.append(" SE 6"); System.out.println(s); s.delete(8,9); System.out.println(s); s.insert(8, "7"); System.out.println(s); } }
UTF-8
Java
552
java
StringBuilderInser.java
Java
[ { "context": "/\npackage de.gfn.oca8_test_all;\n\n/**\n *\n * @author wsen\n */\npublic class StringBuilderInser {\n public ", "end": 238, "score": 0.9996302723884583, "start": 234, "tag": "USERNAME", "value": "wsen" } ]
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 de.gfn.oca8_test_all; /** * * @author wsen */ public class StringBuilderInser { public static void main(String[] args) { StringBuilder s = new StringBuilder("Java"); s.append(" SE 6"); System.out.println(s); s.delete(8,9); System.out.println(s); s.insert(8, "7"); System.out.println(s); } }
552
0.619565
0.608696
22
24.09091
20.871706
79
false
false
0
0
0
0
0
0
0.590909
false
false
2