blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
433a6459f6d2e24585bc55c23381e2d2245ca3ce
27,960,237,098,182
31925bc6c81369c5fdd82719e58d13b89e9cb0d8
/src/main/java/com/sensenets/sinopec/common/constant/factory/ConstantFactory.java
7add1b0ee0eea0d7df74abcc1cf6c0bc6daa399d
[]
no_license
xuzchu/sinopec
https://github.com/xuzchu/sinopec
93eac620da80f0934763bdb02ea6ced088ca1fa2
96d6e11494ac9a0537e8accb451cab8009545202
refs/heads/master
2018-11-08T01:27:26.017000
2018-10-17T02:54:26
2018-10-17T02:54:26
143,726,206
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sensenets.sinopec.common.constant.factory; import java.util.List; import org.springframework.context.annotation.DependsOn; import org.springframework.stereotype.Component; import com.sensenets.sinopec.common.utils.SpringContextHolder; /** * 常量的生产工厂 * * @author fengshuonan * @date 2017年2月13日 下午10:55:21 */ @Component @DependsOn("springContextHolder") public class ConstantFactory implements IConstantFactory { public static IConstantFactory me() { return SpringContextHolder.getBean("constantFactory"); } /** * 根据用户id获取用户账号 * * @author stylefeng * @date 2017年5月16日21:55:371 */ @Override public String getUserAccountById(Integer userId) { return null; } /** * 通过角色id获取角色名称 */ @Override public String getSingleRoleName(Integer roleId) { return ""; } /** * 通过角色id获取角色英文名称 */ @Override public String getSingleRoleTip(Integer roleId) { return ""; } /** * 获取部门名称 */ @Override public String getDeptName(Integer deptId) { return ""; } /** * 获取菜单的名称们(多个) */ @Override public String getMenuNames(String menuIds) { return null; } /** * 获取菜单名称 */ @Override public String getMenuName(Integer menuId) { return null; } /** * 获取菜单名称通过编号 */ @Override public String getMenuNameByCode(String code) { return null; } /** * 获取字典名称 */ @Override public String getDictName(Integer dictId) { return null; } /** * 获取通知标题 */ @Override public String getNoticeTitle(Integer dictId) { return null; } /** * 根据字典名称和字典中的值获取对应的名称 */ @Override public String getDictsByName(String name, Integer val) { return null; } /** * 获取性别名称 */ @Override public String getSexName(Integer sex) { return getDictsByName("性别", sex); } /** * 获取用户登录状态 */ @Override public String getStatusName(Integer status) { return null; } /** * 获取菜单状态 */ @Override public String getMenuStatusName(Integer status) { return null; } /** * 获取被缓存的对象(用户删除业务) */ @Override public String getCacheObject(String para) { return null; } /** * 获取子部门id */ @Override public List<Integer> getSubDeptId(Integer deptid) { return null; } /** * 获取所有父部门id */ @Override public List<Integer> getParentDeptIds(Integer deptid) { return null; } }
UTF-8
Java
2,998
java
ConstantFactory.java
Java
[ { "context": "SpringContextHolder;\n\n/**\n * 常量的生产工厂\n *\n * @author fengshuonan\n * @date 2017年2月13日 下午10:55:21\n */\n@Component\n@De", "end": 291, "score": 0.9994345903396606, "start": 280, "tag": "USERNAME", "value": "fengshuonan" }, { "context": "\n /**\n * 根据用户id获取用户账号\n *\n * @author stylefeng\n * @date 2017年5月16日21:55:371\n */\n @Ove", "end": 604, "score": 0.9996815323829651, "start": 595, "tag": "USERNAME", "value": "stylefeng" } ]
null
[]
package com.sensenets.sinopec.common.constant.factory; import java.util.List; import org.springframework.context.annotation.DependsOn; import org.springframework.stereotype.Component; import com.sensenets.sinopec.common.utils.SpringContextHolder; /** * 常量的生产工厂 * * @author fengshuonan * @date 2017年2月13日 下午10:55:21 */ @Component @DependsOn("springContextHolder") public class ConstantFactory implements IConstantFactory { public static IConstantFactory me() { return SpringContextHolder.getBean("constantFactory"); } /** * 根据用户id获取用户账号 * * @author stylefeng * @date 2017年5月16日21:55:371 */ @Override public String getUserAccountById(Integer userId) { return null; } /** * 通过角色id获取角色名称 */ @Override public String getSingleRoleName(Integer roleId) { return ""; } /** * 通过角色id获取角色英文名称 */ @Override public String getSingleRoleTip(Integer roleId) { return ""; } /** * 获取部门名称 */ @Override public String getDeptName(Integer deptId) { return ""; } /** * 获取菜单的名称们(多个) */ @Override public String getMenuNames(String menuIds) { return null; } /** * 获取菜单名称 */ @Override public String getMenuName(Integer menuId) { return null; } /** * 获取菜单名称通过编号 */ @Override public String getMenuNameByCode(String code) { return null; } /** * 获取字典名称 */ @Override public String getDictName(Integer dictId) { return null; } /** * 获取通知标题 */ @Override public String getNoticeTitle(Integer dictId) { return null; } /** * 根据字典名称和字典中的值获取对应的名称 */ @Override public String getDictsByName(String name, Integer val) { return null; } /** * 获取性别名称 */ @Override public String getSexName(Integer sex) { return getDictsByName("性别", sex); } /** * 获取用户登录状态 */ @Override public String getStatusName(Integer status) { return null; } /** * 获取菜单状态 */ @Override public String getMenuStatusName(Integer status) { return null; } /** * 获取被缓存的对象(用户删除业务) */ @Override public String getCacheObject(String para) { return null; } /** * 获取子部门id */ @Override public List<Integer> getSubDeptId(Integer deptid) { return null; } /** * 获取所有父部门id */ @Override public List<Integer> getParentDeptIds(Integer deptid) { return null; } }
2,998
0.571961
0.561894
158
15.974684
16.730156
62
false
false
0
0
0
0
0
0
0.151899
false
false
5
a7833d61e15a499c7c361d1fafdef7c0ddc33c9e
32,547,262,182,873
cb63f49a34bca7abd52adcc703083ed3f9cd88cf
/LearnDemo/14/14.4/src/main/java/com/mingrisoft/MainActivity.java
f8e5dd215c98fdcc7237196501641b994caf4a5a
[]
no_license
CarvenChen/CCAndroid
https://github.com/CarvenChen/CCAndroid
ebe699b4a619777dc03cd477ef665b763f3e0893
1c3b3e78029fb3e87bb51d81c12fac34ce206092
refs/heads/master
2023-01-31T05:59:41.571000
2020-11-23T07:51:05
2020-11-23T07:51:05
255,521,952
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mingrisoft; import android.app.Activity; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.Toast; public class MainActivity extends Activity { private ImageButton play, pause, stop; // 定义播放、暂停和停止按钮 private MediaPlayer mediaPlayer; // 定义MediaPlayer对象 private SurfaceHolder surfaceHolder; // 定义SurfaceHolder对象 private boolean noPlay = true; //定义播放状态 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //设置全屏显示 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); play = (ImageButton) findViewById(R.id.play); // 获取播放按钮对象 pause = (ImageButton) findViewById(R.id.pause); // 获取暂停按钮对象 stop = (ImageButton) findViewById(R.id.stop); // 获取停止按钮对象 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceView); //获取SurfaceView组件 surfaceHolder = surfaceView.getHolder(); //获取SurfaceHolder pause.setEnabled(false); //设置暂停按钮不可用 stop.setEnabled(false); //设置停止按钮不可用 mediaPlayer = new MediaPlayer(); //创建MediaPlayer对象 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); //设置多媒体的类型 play.setOnClickListener(new View.OnClickListener() { //实现播放与继续播放功能 @Override public void onClick(View v) { if (noPlay) { //如果没有播放视频 play(); //调用play()方法实现播放功能 noPlay = false; //设置播放状态为正在播放 } else { mediaPlayer.start(); //继续播放视频 } } }); pause.setOnClickListener(new View.OnClickListener() { //实现暂停功能 @Override public void onClick(View v) { if (mediaPlayer.isPlaying()) { //如果视频处于播放状态 mediaPlayer.pause(); //暂停视频的播放 } } }); stop.setOnClickListener(new View.OnClickListener() { //实现停止功能 @Override public void onClick(View v) { if (mediaPlayer.isPlaying()) { //如果视频处于播放状态 mediaPlayer.stop(); // 停止播放 noPlay = true; //设置播放状态为没有播放 pause.setEnabled(false); // 设置“暂停”按钮不可用 stop.setEnabled(false); //设置“停止”按钮不可用 } } }); // 为MediaPlayer对象添加完成事件监听器 mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Toast.makeText(MainActivity.this, "视频播放完毕!", Toast.LENGTH_SHORT).show(); } }); } public void play() { //创建play()方法,在该方法中实现视频的播放功能 mediaPlayer.reset(); //重置MediaPlayer mediaPlayer.setDisplay(surfaceHolder); //把视频画面输出到SurfaceView try { // 模拟器的SD卡上的视频文件 mediaPlayer.setDataSource(Environment.getExternalStorageDirectory() + "/video.mp4"); mediaPlayer.prepare(); // 预加载 } catch (Exception e) { //输出异常信息 e.printStackTrace(); } mediaPlayer.start(); // 开始播放 pause.setEnabled(true); // 设置“暂停”按钮可用 stop.setEnabled(true); //设置“停止”按钮可用 } @Override protected void onDestroy() { //当前Activity销毁时,停止正在播放的视频,并释放MediaPlayer所占用的资源 super.onDestroy(); if (mediaPlayer != null) { //如果MediaPlayer不为空 if (mediaPlayer.isPlaying()) { //如果处于播放状态 mediaPlayer.stop(); // 停止播放视频 } // Activity销毁时停止播放,释放资源。不做这个操作,即使退出还是能听到视频播放的声音 mediaPlayer.release(); } } }
UTF-8
Java
5,308
java
MainActivity.java
Java
[]
null
[]
package com.mingrisoft; import android.app.Activity; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.Toast; public class MainActivity extends Activity { private ImageButton play, pause, stop; // 定义播放、暂停和停止按钮 private MediaPlayer mediaPlayer; // 定义MediaPlayer对象 private SurfaceHolder surfaceHolder; // 定义SurfaceHolder对象 private boolean noPlay = true; //定义播放状态 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //设置全屏显示 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); play = (ImageButton) findViewById(R.id.play); // 获取播放按钮对象 pause = (ImageButton) findViewById(R.id.pause); // 获取暂停按钮对象 stop = (ImageButton) findViewById(R.id.stop); // 获取停止按钮对象 SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceView); //获取SurfaceView组件 surfaceHolder = surfaceView.getHolder(); //获取SurfaceHolder pause.setEnabled(false); //设置暂停按钮不可用 stop.setEnabled(false); //设置停止按钮不可用 mediaPlayer = new MediaPlayer(); //创建MediaPlayer对象 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); //设置多媒体的类型 play.setOnClickListener(new View.OnClickListener() { //实现播放与继续播放功能 @Override public void onClick(View v) { if (noPlay) { //如果没有播放视频 play(); //调用play()方法实现播放功能 noPlay = false; //设置播放状态为正在播放 } else { mediaPlayer.start(); //继续播放视频 } } }); pause.setOnClickListener(new View.OnClickListener() { //实现暂停功能 @Override public void onClick(View v) { if (mediaPlayer.isPlaying()) { //如果视频处于播放状态 mediaPlayer.pause(); //暂停视频的播放 } } }); stop.setOnClickListener(new View.OnClickListener() { //实现停止功能 @Override public void onClick(View v) { if (mediaPlayer.isPlaying()) { //如果视频处于播放状态 mediaPlayer.stop(); // 停止播放 noPlay = true; //设置播放状态为没有播放 pause.setEnabled(false); // 设置“暂停”按钮不可用 stop.setEnabled(false); //设置“停止”按钮不可用 } } }); // 为MediaPlayer对象添加完成事件监听器 mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Toast.makeText(MainActivity.this, "视频播放完毕!", Toast.LENGTH_SHORT).show(); } }); } public void play() { //创建play()方法,在该方法中实现视频的播放功能 mediaPlayer.reset(); //重置MediaPlayer mediaPlayer.setDisplay(surfaceHolder); //把视频画面输出到SurfaceView try { // 模拟器的SD卡上的视频文件 mediaPlayer.setDataSource(Environment.getExternalStorageDirectory() + "/video.mp4"); mediaPlayer.prepare(); // 预加载 } catch (Exception e) { //输出异常信息 e.printStackTrace(); } mediaPlayer.start(); // 开始播放 pause.setEnabled(true); // 设置“暂停”按钮可用 stop.setEnabled(true); //设置“停止”按钮可用 } @Override protected void onDestroy() { //当前Activity销毁时,停止正在播放的视频,并释放MediaPlayer所占用的资源 super.onDestroy(); if (mediaPlayer != null) { //如果MediaPlayer不为空 if (mediaPlayer.isPlaying()) { //如果处于播放状态 mediaPlayer.stop(); // 停止播放视频 } // Activity销毁时停止播放,释放资源。不做这个操作,即使退出还是能听到视频播放的声音 mediaPlayer.release(); } } }
5,308
0.544312
0.543871
112
38.5
27.541527
98
false
false
0
0
0
0
0
0
0.526786
false
false
5
7044831b1504139f1e394b953135b5ff1010eaf5
19,619,410,676,644
cd6222196007c5282a3cf8c43018774d1ab48b42
/demo/src/main/java/com/example/izhiliu/erp/web/rest/discount/qo/VocabularyQO.java
8f7dd4673a9683e7142ebc83e7c83df145110ddd
[]
no_license
bellmit/mall-2
https://github.com/bellmit/mall-2
455eadff04f35fb06ea879ca372319cb887d143f
107dd0736ad3810c9e30a9e4bb26e7c91152551d
refs/heads/master
2023-04-29T18:47:43.146000
2021-05-10T07:38:56
2021-05-10T07:38:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.izhiliu.erp.web.rest.discount.qo; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotNull; /** * @author King * @version 1.0 * @date 2021/2/2 15:19 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class VocabularyQO { private String login; /** * 词汇类型ID */ private Long vocabularyTypeId; /** * 词汇ID */ private Long vocabularyId; /** * 词汇类型名称 */ private String vocabularyTypeName; /** * 词汇名称 */ private String vocabularyName; @NotNull private Long page; @NotNull private Long size; }
UTF-8
Java
740
java
VocabularyQO.java
Java
[ { "context": "ax.validation.constraints.NotNull;\n\n/**\n * @author King\n * @version 1.0\n * @date 2021/2/2 15:19\n */\n@Data", "end": 223, "score": 0.920298159122467, "start": 219, "tag": "NAME", "value": "King" } ]
null
[]
package com.izhiliu.erp.web.rest.discount.qo; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotNull; /** * @author King * @version 1.0 * @date 2021/2/2 15:19 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class VocabularyQO { private String login; /** * 词汇类型ID */ private Long vocabularyTypeId; /** * 词汇ID */ private Long vocabularyId; /** * 词汇类型名称 */ private String vocabularyTypeName; /** * 词汇名称 */ private String vocabularyName; @NotNull private Long page; @NotNull private Long size; }
740
0.652542
0.635593
43
15.465117
12.430923
45
false
false
0
0
0
0
0
0
0.302326
false
false
5
d8ad82a1d87d1e4bf404e380acf12729975548b0
17,343,077,953,970
6be47e64b77d3297d4d41868d4e120bdac5c4eac
/observer/src/main/java/com/demo/observer/keyboard/EventListener.java
a29171cea9ecb6d09c42a13ca754f93c6db0b54e
[]
no_license
CaoWenCool/pattern
https://github.com/CaoWenCool/pattern
39babc561c3b55ee048f60f26270217365a30e8e
c37f7c22774ee755b4294e4285482f3c5e7054eb
refs/heads/master
2022-06-30T01:01:35.683000
2020-06-16T14:17:28
2020-06-16T14:17:28
250,419,557
1
0
null
false
2022-06-17T03:10:35
2020-03-27T02:14:36
2020-06-16T14:18:01
2022-06-17T03:10:34
786
1
0
5
Java
false
false
package com.demo.observer.keyboard; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * @author: Maniac Wen * @create: 2020/4/16 * @update: 7:23 * @version: V1.0 * @detail: 时间监听器 **/ public class EventListener { protected Map<String,Event> events = new HashMap<String,Event>(); //事件名称和一个目标对象来触发 public void addListener(String eventType,Object target) throws NoSuchMethodException { this.addListener(eventType,target,target.getClass().getMethod("on" + toUpperFirstCase(eventType),Event.class)); } public void addListener(String eventType, Object target, Method callBack){ events.put(eventType,new Event(target,callBack)); } //根据事件触发 private void trigger(Event event) throws InvocationTargetException, IllegalAccessException { event.setSource(this); event.setTime(System.currentTimeMillis()); if(event.getCallBack() != null){ //利用反射调用他的回调函数 event.getCallBack().invoke(event.getTarget(),event); } } //根据名称触发 protected void trigger(String trigger) throws InvocationTargetException, IllegalAccessException { if(!this.events.containsKey(trigger)){ return; } trigger(this.events.get(trigger).setTrigger(trigger)); } //将字符串首字母大写 private String toUpperFirstCase(String str){ char[] chars = str.toCharArray(); chars[0] -= 32; return String.valueOf(chars); } }
UTF-8
Java
1,653
java
EventListener.java
Java
[ { "context": "til.HashMap;\nimport java.util.Map;\n/**\n * @author: Maniac Wen\n * @create: 2020/4/16\n * @update: 7:23\n * @versio", "end": 196, "score": 0.9998408555984497, "start": 186, "tag": "NAME", "value": "Maniac Wen" } ]
null
[]
package com.demo.observer.keyboard; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * @author: <NAME> * @create: 2020/4/16 * @update: 7:23 * @version: V1.0 * @detail: 时间监听器 **/ public class EventListener { protected Map<String,Event> events = new HashMap<String,Event>(); //事件名称和一个目标对象来触发 public void addListener(String eventType,Object target) throws NoSuchMethodException { this.addListener(eventType,target,target.getClass().getMethod("on" + toUpperFirstCase(eventType),Event.class)); } public void addListener(String eventType, Object target, Method callBack){ events.put(eventType,new Event(target,callBack)); } //根据事件触发 private void trigger(Event event) throws InvocationTargetException, IllegalAccessException { event.setSource(this); event.setTime(System.currentTimeMillis()); if(event.getCallBack() != null){ //利用反射调用他的回调函数 event.getCallBack().invoke(event.getTarget(),event); } } //根据名称触发 protected void trigger(String trigger) throws InvocationTargetException, IllegalAccessException { if(!this.events.containsKey(trigger)){ return; } trigger(this.events.get(trigger).setTrigger(trigger)); } //将字符串首字母大写 private String toUpperFirstCase(String str){ char[] chars = str.toCharArray(); chars[0] -= 32; return String.valueOf(chars); } }
1,649
0.673338
0.663654
47
31.957447
26.881899
101
false
false
0
0
0
0
0
0
0.617021
false
false
5
7b4e7cfc07893cb83d17e7fe6489f09a676af826
28,527,172,786,859
8eae814bd704e0a33b1728082656e08ff3406700
/src/main/java/HelloWorld.java
c4719952cb5a7da8ff8d16e3a8848c6bb31cb13d
[]
no_license
Zshllj20160221/shiroDemo
https://github.com/Zshllj20160221/shiroDemo
a188f1ad29174e41afd5406193bb74a54fb6935c
b3edadd93ff4886096f51eaef81c33f19a6ba55c
refs/heads/master
2021-01-01T17:26:07.591000
2017-07-23T04:05:32
2017-07-23T04:05:32
98,013,981
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by zsh on 2017/7/22. * http://blog.csdn.net/edward0830ly/article/details/8250412 */ public class HelloWorld { private static final Logger logger = LoggerFactory.getLogger(HelloWorld.class); public static void main(String [] args){ logger.info("*******************************************************************"); logger.debug("*******************************************************************"); Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager= factory.getInstance(); //这一句不能少 SecurityUtils.setSecurityManager(securityManager); UsernamePasswordToken token = new UsernamePasswordToken("javass","cc"); token.setRememberMe(true); Subject subject = SecurityUtils.getSubject(); subject.login(token); boolean flag = subject.isPermitted("p1"); System.out.println("flag=="+flag); } }
UTF-8
Java
1,333
java
HelloWorld.java
Java
[ { "context": "import org.slf4j.LoggerFactory;\n\n/**\n * Created by zsh on 2017/7/22.\n * http://blog.csdn.net/edward0830l", "end": 353, "score": 0.9996612668037415, "start": 350, "tag": "USERNAME", "value": "zsh" }, { "context": "ated by zsh on 2017/7/22.\n * http://blog.csdn.net/edward0830ly/article/details/8250412\n */\npublic class HelloWor", "end": 404, "score": 0.9997267127037048, "start": 392, "tag": "USERNAME", "value": "edward0830ly" }, { "context": "ePasswordToken token = new UsernamePasswordToken(\"javass\",\"cc\");\n\n token.setRememberMe(true);\n\n ", "end": 1087, "score": 0.9012571573257446, "start": 1081, "tag": "PASSWORD", "value": "javass" } ]
null
[]
import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by zsh on 2017/7/22. * http://blog.csdn.net/edward0830ly/article/details/8250412 */ public class HelloWorld { private static final Logger logger = LoggerFactory.getLogger(HelloWorld.class); public static void main(String [] args){ logger.info("*******************************************************************"); logger.debug("*******************************************************************"); Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager= factory.getInstance(); //这一句不能少 SecurityUtils.setSecurityManager(securityManager); UsernamePasswordToken token = new UsernamePasswordToken("<PASSWORD>","cc"); token.setRememberMe(true); Subject subject = SecurityUtils.getSubject(); subject.login(token); boolean flag = subject.isPermitted("p1"); System.out.println("flag=="+flag); } }
1,337
0.644209
0.628312
41
31.219513
29.916561
96
false
false
0
0
0
0
0
0
0.512195
false
false
5
727af5973c47daf9cbf215e70dff77026bbc3b37
32,031,866,101,384
4697c59d7a53dc4b22e959bf2f4139922aefc786
/src/main/java/PaperSee/entity/SimplePaper.java
97f0ad9ab4b7755d6381751a489189a2a613b825
[]
no_license
diffractions/PapersViewer
https://github.com/diffractions/PapersViewer
2469d45dcfba24674fdcf9c1162e6f1ab8e71a04
b6e661aa39c9025f27300cc7bc542788f25248b5
refs/heads/master
2021-01-15T15:37:25.169000
2016-10-08T13:31:41
2016-10-08T13:31:41
51,227,211
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package entity; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.HashMap; import java.util.Map; import dao.exceptions.DaoSystemException; public class SimplePaper implements Paper { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id.hashCode(); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj.hashCode() != this.hashCode()) { return false; } if (!(obj instanceof SimplePaper)) { return false; } SimplePaper other = (SimplePaper) obj; if (this.id != other.id) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } // println("TRUE"); return true; } /** * */ private static transient final long serialVersionUID = 1L; @Override public String toString() { return "[id=" + id + ", name=" + name + ", hash=" + hashCode() + "]"; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } private String id; private String name; /** * @param id * @param name */ public SimplePaper(String id, String name) { // System.out.println(">>> FULL PAPER CONSTRUCTOR"); this.id = id; this.name = name; } /** * empty constructor only to correct work serializable */ @Deprecated public SimplePaper() { // println(">>> EMPTY PAPER CONSTRUCTOR"); } @Override public void writeExternal(ObjectOutput out) throws IOException { out.write(getId().getBytes()); out.writeObject(getName()); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { setId(in.readLine()); setName((String) in.readObject()); } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } private Map<String, String> proporties = null; @Override public Map<String, String> getProporties() throws DaoSystemException { return proporties; } @Override public void setProporties(Map<String, String> proporties) throws DaoSystemException { this.proporties = proporties; } }
UTF-8
Java
2,593
java
SimplePaper.java
Java
[ { "context": "PER CONSTRUCTOR\");\r\n\t\tthis.id = id;\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\t/**\r\n\t * empty constructor only to corre", "end": 1685, "score": 0.7619102597236633, "start": 1681, "tag": "NAME", "value": "name" } ]
null
[]
package entity; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.HashMap; import java.util.Map; import dao.exceptions.DaoSystemException; public class SimplePaper implements Paper { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id.hashCode(); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj.hashCode() != this.hashCode()) { return false; } if (!(obj instanceof SimplePaper)) { return false; } SimplePaper other = (SimplePaper) obj; if (this.id != other.id) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } // println("TRUE"); return true; } /** * */ private static transient final long serialVersionUID = 1L; @Override public String toString() { return "[id=" + id + ", name=" + name + ", hash=" + hashCode() + "]"; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } private String id; private String name; /** * @param id * @param name */ public SimplePaper(String id, String name) { // System.out.println(">>> FULL PAPER CONSTRUCTOR"); this.id = id; this.name = name; } /** * empty constructor only to correct work serializable */ @Deprecated public SimplePaper() { // println(">>> EMPTY PAPER CONSTRUCTOR"); } @Override public void writeExternal(ObjectOutput out) throws IOException { out.write(getId().getBytes()); out.writeObject(getName()); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { setId(in.readLine()); setName((String) in.readObject()); } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } private Map<String, String> proporties = null; @Override public Map<String, String> getProporties() throws DaoSystemException { return proporties; } @Override public void setProporties(Map<String, String> proporties) throws DaoSystemException { this.proporties = proporties; } }
2,593
0.622831
0.620902
136
17.066177
18.203588
71
false
false
0
0
0
0
0
0
1.529412
false
false
5
a2508c50391e8a3dc4aad4c9c5372e6162a62358
8,753,143,408,559
c5f62a4a8bd8c208fe8780033d4d2c94051417c2
/src/main/java/br/com/paripassu/senhas/GestaoDeSenhasApplication.java
adf39044beebe8245e997ecda534f93664aa11f6
[]
no_license
viniscr/gestao-senhas
https://github.com/viniscr/gestao-senhas
89e77a9fbe0cedcb1b5ccfca9b4a2dc48b67c209
1f68a1b50e1e5e82c8ee7a6a3f11dd929f642fa5
refs/heads/master
2020-07-18T09:34:17.530000
2019-09-04T17:43:14
2019-09-04T17:43:14
206,221,813
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.paripassu.senhas; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GestaoDeSenhasApplication { public static void main(String[] args) { SpringApplication.run(GestaoDeSenhasApplication.class, args); } }
UTF-8
Java
332
java
GestaoDeSenhasApplication.java
Java
[]
null
[]
package br.com.paripassu.senhas; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GestaoDeSenhasApplication { public static void main(String[] args) { SpringApplication.run(GestaoDeSenhasApplication.class, args); } }
332
0.828313
0.828313
13
24.538462
24.898611
68
false
false
0
0
0
0
0
0
0.692308
false
false
5
27c0f369fd8a8a49766bd2da6607edb548c8762c
15,470,472,220,315
98c56543c6d01f59ec6f7a8695a60a23ba083def
/app/src/main/java/nz/ac/auckland/lablet/script/components/ScriptTreeNodeSheet.java
7320bc4f0492bf5ddc0501b698f56a316976393a
[]
no_license
czeidler/Lablet
https://github.com/czeidler/Lablet
0eeb5435d9ef49e881ec95d23eb90716a8afc6d8
645530bab82f06387947c57b03b1bcf29bc96b22
refs/heads/master
2020-05-21T03:27:40.010000
2016-08-21T22:18:07
2016-08-21T22:18:07
15,094,459
3
3
null
false
2017-02-02T04:08:49
2013-12-11T01:06:02
2016-07-18T22:59:37
2017-02-02T04:06:18
3,925
1
3
1
Java
null
null
/* * Copyright 2013-2014. * Distributed under the terms of the GPLv3 License. * * Authors: * Clemens Zeidler <czei002@aucklanduni.ac.nz> */ package nz.ac.auckland.lablet.script.components; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.*; import android.widget.*; import nz.ac.auckland.lablet.camera.MotionAnalysis; import nz.ac.auckland.lablet.script.*; import nz.ac.auckland.lablet.views.graph.*; import nz.ac.auckland.lablet.R; import java.util.HashMap; import java.util.Map; /** * View holder for a view that only displays some text. */ class TextComponent extends ScriptComponentViewHolder { private String text = ""; private int typeface = Typeface.NORMAL; public TextComponent(Script script, String text) { super(script); this.text = text; setState(ScriptTreeNode.SCRIPT_STATE_DONE); } public void setTypeface(int typeface) { this.typeface = typeface; } @Override public View createView(Context context, android.support.v4.app.Fragment parent) { TextView textView = new TextView(context); textView.setTextAppearance(context, android.R.style.TextAppearance_Medium); textView.setTypeface(null, typeface); textView.setText(text); return textView; } @Override public boolean initCheck() { return true; } } /** * View holder for a view that has a checkbox and a text view. */ class CheckBoxQuestion extends ScriptComponentViewHolder { private String text = ""; public CheckBoxQuestion(Script script, String text) { super(script); this.text = text; setState(ScriptTreeNode.SCRIPT_STATE_ONGOING); } @Override public View createView(Context context, android.support.v4.app.Fragment parent) { CheckBox view = new CheckBox(context); view.setTextAppearance(context, android.R.style.TextAppearance_Medium); view.setBackgroundColor(context.getResources().getColor(R.color.sc_question_background_color)); view.setText(text); if (getState() == ScriptTreeNode.SCRIPT_STATE_DONE) view.setChecked(true); view.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean checked) { if (checked) setState(ScriptTreeNode.SCRIPT_STATE_DONE); else setState(ScriptTreeNode.SCRIPT_STATE_ONGOING); } }); return view; } @Override public boolean initCheck() { return true; } } /** * View holder for a view with just a question. */ class Question extends ScriptComponentViewHolder { private String text = ""; private ScriptTreeNodeSheetBase component; public Question(Script script, String text, ScriptTreeNodeSheetBase component) { super(script); this.text = text; this.component = component; setState(ScriptTreeNode.SCRIPT_STATE_DONE); } @Override public View createView(Context context, android.support.v4.app.Fragment parent) { // we have to get a fresh counter here, if we cache it we will miss that it has been deleted in the sheet // component ScriptTreeNodeSheetBase.Counter counter = this.component.getCounter("QuestionCounter"); TextView textView = new TextView(context); textView.setTextAppearance(context, android.R.style.TextAppearance_Medium); textView.setBackgroundColor(context.getResources().getColor(R.color.sc_question_background_color)); textView.setText("Q" + counter.increaseValue() + ": " + text); return textView; } @Override public boolean initCheck() { return true; } } /** * View holder for a view that has a question and a text input view. * <p> * The question is considered as answered as soon as the text input view contains some text. It is not checked if the * question is answered correctly. * </p> */ class TextQuestion extends ScriptComponentViewHolder { private String text = ""; private String answer = ""; private boolean optional = false; private ScriptTreeNodeSheetBase component; public TextQuestion(Script script, String text, ScriptTreeNodeSheetBase component) { super(script); this.text = text; this.component = component; setState(ScriptTreeNode.SCRIPT_STATE_ONGOING); } public void setOptional(boolean optional) { this.optional = optional; update(); } @Override public View createView(Context context, android.support.v4.app.Fragment parent) { ScriptTreeNodeSheetBase.Counter counter = this.component.getCounter("QuestionCounter"); // Note: we have to do this programmatically cause findViewById would find the wrong child items if there are // more than one text question. LinearLayout layout = new LinearLayout(context); layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); layout.setOrientation(LinearLayout.VERTICAL); layout.setBackgroundColor(context.getResources().getColor(R.color.sc_question_background_color)); TextView textView = new TextView(context); textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); textView.setTextAppearance(context, android.R.style.TextAppearance_Medium); textView.setText("Q" + counter.increaseValue() + ": " + text); EditText editText = new EditText(context); editText.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); assert editText != null; editText.setText(answer); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { answer = editable.toString(); update(); } }); layout.addView(textView); layout.addView(editText); return layout; } @Override public boolean initCheck() { return true; } public void toBundle(Bundle bundle) { bundle.putString("answer", answer); super.toBundle(bundle); } public boolean fromBundle(Bundle bundle) { answer = bundle.getString("answer", ""); return super.fromBundle(bundle); } private void update() { if (optional) setState(ScriptTreeNode.SCRIPT_STATE_DONE); else if (!answer.equals("")) setState(ScriptTreeNode.SCRIPT_STATE_DONE); else setState(ScriptTreeNode.SCRIPT_STATE_ONGOING); } } /** * View holder for a graph view that shows some experiment analysis results. */ class MotionAnalysisGraphView extends ScriptComponentViewHolder { private ScriptTreeNodeSheet experimentSheet; private ScriptExperimentRef experiment; private MarkerTimeGraphAdapter adapter; private String xAxisContentId = "x-position"; private String yAxisContentId = "y-position"; private String title = "Position Data"; private ScriptExperimentRef.IListener experimentListener; public MotionAnalysisGraphView(Script script, ScriptTreeNodeSheet experimentSheet, ScriptExperimentRef experiment) { super(script); this.experimentSheet = experimentSheet; this.experiment = experiment; setState(ScriptTreeNode.SCRIPT_STATE_DONE); } @Override public View createView(Context context, android.support.v4.app.Fragment parentFragment) { LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.script_component_graph_view, null); assert view != null; GraphView2D graphView2D = (GraphView2D)view.findViewById(R.id.graphView); assert graphView2D != null; graphView2D.setMaxWidth(500); MotionAnalysis sensorAnalysis = experiment.getMotionAnalysis(0); if (sensorAnalysis != null) { MarkerGraphAxis xAxis = createAxis(xAxisContentId); if (xAxis == null) xAxis = new XPositionMarkerGraphAxis(sensorAnalysis.getXUnit(), sensorAnalysis.getXMinRangeGetter()); MarkerGraphAxis yAxis = createAxis(yAxisContentId); if (yAxis == null) yAxis = new XPositionMarkerGraphAxis(sensorAnalysis.getXUnit(), sensorAnalysis.getYMinRangeGetter()); adapter = new MarkerTimeGraphAdapter(sensorAnalysis.getTagMarkers(), sensorAnalysis.getTimeData(), title, xAxis, yAxis); graphView2D.setAdapter(adapter); } // install listener experimentListener = new ScriptExperimentRef.IListener() { @Override public void onExperimentAnalysisUpdated() { MotionAnalysis motionAnalysis = experiment.getMotionAnalysis(0); adapter.setTo(motionAnalysis.getTagMarkers(), motionAnalysis.getTimeData()); } }; experiment.addListener(experimentListener); return view; } @Override protected void finalize() { experiment.removeListener(experimentListener); } public boolean setXAxisContent(String axis) { if (!isValidAxis(axis)) return false; xAxisContentId = axis; return true; } public boolean setYAxisContent(String axis) { if (!isValidAxis(axis)) return false; yAxisContentId = axis; return true; } public void showXVsYPosition() { setTitle("Position Data"); setXAxisContent("x-position"); setYAxisContent("y-position"); } public void showTimeVsXSpeed() { setTitle("X-Velocity vs. Time"); setXAxisContent("time_v"); setYAxisContent("x-velocity"); } public void showTimeVsYSpeed() { setTitle("Y-Velocity vs. Time"); setXAxisContent("time_v"); setYAxisContent("y-velocity"); } public void setTitle(String title) { this.title = title; } private MarkerGraphAxis createAxis(String id) { MotionAnalysis sensorAnalysis = experiment.getMotionAnalysis(0); if (id.equalsIgnoreCase("x-position")) return new XPositionMarkerGraphAxis(sensorAnalysis.getXUnit(), sensorAnalysis.getXMinRangeGetter()); if (id.equalsIgnoreCase("y-position")) return new YPositionMarkerGraphAxis(sensorAnalysis.getYUnit(), sensorAnalysis.getYMinRangeGetter()); if (id.equalsIgnoreCase("x-velocity")) return new XSpeedMarkerGraphAxis(sensorAnalysis.getXUnit(), sensorAnalysis.getTUnit()); if (id.equalsIgnoreCase("y-velocity")) return new YSpeedMarkerGraphAxis(sensorAnalysis.getYUnit(), sensorAnalysis.getTUnit()); if (id.equalsIgnoreCase("time")) return new TimeMarkerGraphAxis(sensorAnalysis.getTUnit()); if (id.equalsIgnoreCase("time_v")) return new SpeedTimeMarkerGraphAxis(sensorAnalysis.getTUnit()); return null; } private boolean isValidAxis(String id) { if (id.equalsIgnoreCase("x-position")) return true; if (id.equalsIgnoreCase("y-position")) return true; if (id.equalsIgnoreCase("x-velocity")) return true; if (id.equalsIgnoreCase("y-velocity")) return true; if (id.equalsIgnoreCase("time")) return true; if (id.equalsIgnoreCase("time_v")) return true; return false; } public MarkerTimeGraphAdapter getAdapter() { return adapter; } @Override public boolean initCheck() { if (experiment == null) { lastErrorMessage = "no experiment data"; return false; } return true; } } /** * Base class for the {@link ScriptTreeNodeSheet} class. * <p> * All important logic is done here. ScriptComponentTreeSheet only has an interface to add different child components. * </p> */ class ScriptTreeNodeSheetBase extends ScriptTreeNodeFragmentHolder { /** * Page wide counter. * <p> * This counter is, for example, used to number the questions on a sheet. * </p> */ public class Counter { private int counter = 0; public void setValue(int value) { counter = value; } public int increaseValue() { counter++; return counter; } } private SheetGroupLayout sheetGroupLayout = new SheetGroupLayout(LinearLayout.VERTICAL); private ScriptComponentContainer<ScriptComponentViewHolder> itemContainer = new ScriptComponentContainer<ScriptComponentViewHolder>(); private Map<String, Counter> mapOfCounter = new HashMap<String, Counter>(); public ScriptTreeNodeSheetBase(Script script) { super(script); itemContainer.setListener(new ScriptComponentContainer.IItemContainerListener() { @Override public void onAllItemStatusChanged(boolean allDone) { if (allDone) setState(ScriptTreeNode.SCRIPT_STATE_DONE); else setState(ScriptTreeNode.SCRIPT_STATE_ONGOING); } }); } public SheetLayout getSheetLayout() { return sheetGroupLayout; } @Override public boolean initCheck() { return itemContainer.initCheck(); } @Override public ScriptComponentGenericFragment createFragment() { ScriptComponentSheetFragment fragment = new ScriptComponentSheetFragment(); fragment.setScriptComponent(this); return fragment; } @Override public void toBundle(Bundle bundle) { super.toBundle(bundle); itemContainer.toBundle(bundle); } @Override public boolean fromBundle(Bundle bundle) { if (!super.fromBundle(bundle)) return false; return itemContainer.fromBundle(bundle); } public void setMainLayoutOrientation(String orientation) { if (orientation.equalsIgnoreCase("horizontal")) sheetGroupLayout.setOrientation(LinearLayout.HORIZONTAL); else sheetGroupLayout.setOrientation(LinearLayout.VERTICAL); } public SheetGroupLayout addHorizontalGroupLayout(SheetGroupLayout parent) { return addGroupLayout(LinearLayout.HORIZONTAL, parent); } public SheetGroupLayout addVerticalGroupLayout(SheetGroupLayout parent) { return addGroupLayout(LinearLayout.VERTICAL, parent); } protected SheetGroupLayout addGroupLayout(int orientation, SheetGroupLayout parent) { SheetGroupLayout layout = new SheetGroupLayout(orientation); if (parent == null) sheetGroupLayout.addLayout(layout); else parent.addLayout(layout); return layout; } protected SheetLayout addItemViewHolder(ScriptComponentViewHolder item, SheetGroupLayout parent) { itemContainer.addItem(item); SheetLayout layoutItem; if (parent == null) layoutItem = sheetGroupLayout.addView(item); else layoutItem = parent.addView(item); return layoutItem; } /** * The counter is valid for the lifetime of the fragment view. If not counter with the given name exist, a new * counter is created. * @param name counter name * @return a Counter */ public Counter getCounter(String name) { if (!mapOfCounter.containsKey(name)) { Counter counter = new Counter(); mapOfCounter.put(name, counter); return counter; } return mapOfCounter.get(name); } public void resetCounter() { mapOfCounter.clear(); } } /** * Powerful script component that can holds a various kind of child components, e.g., questions or text. */ public class ScriptTreeNodeSheet extends ScriptTreeNodeSheetBase { public ScriptTreeNodeSheet(Script script) { super(script); } public ScriptComponentViewHolder addText(String text, SheetGroupLayout parent) { TextComponent textOnlyQuestion = new TextComponent(script, text); addItemViewHolder(textOnlyQuestion, parent); return textOnlyQuestion; } public ScriptComponentViewHolder addHeader(String text, SheetGroupLayout parent) { TextComponent component = new TextComponent(script, text); component.setTypeface(Typeface.BOLD); addItemViewHolder(component, parent); return component; } public ScriptComponentViewHolder addQuestion(String text, SheetGroupLayout parent) { Question component = new Question(script, text, this); addItemViewHolder(component, parent); return component; } public ScriptComponentViewHolder addTextQuestion(String text, SheetGroupLayout parent) { TextQuestion component = new TextQuestion(script, text, this); addItemViewHolder(component, parent); return component; } public ScriptComponentViewHolder addCheckQuestion(String text, SheetGroupLayout parent) { CheckBoxQuestion question = new CheckBoxQuestion(script, text); addItemViewHolder(question, parent); return question; } public AccelerometerExperiment addAccelerometerExperiment(SheetGroupLayout parent) { AccelerometerExperiment experiment = new AccelerometerExperiment(script); addItemViewHolder(experiment, parent); return experiment; } public CameraExperiment addCameraExperiment(SheetGroupLayout parent) { CameraExperiment cameraExperiment = new CameraExperiment(script); addItemViewHolder(cameraExperiment, parent); return cameraExperiment; } public MicrophoneExperiment addMicrophoneExperiment(SheetGroupLayout parent) { MicrophoneExperiment experiment = new MicrophoneExperiment(script); addItemViewHolder(experiment, parent); return experiment; } public PotentialEnergy1 addPotentialEnergy1Question(SheetGroupLayout parent) { PotentialEnergy1 question = new PotentialEnergy1(script); addItemViewHolder(question, parent); return question; } public MotionAnalysisGraphView addMotionAnalysisGraph(ScriptExperimentRef experiment, SheetGroupLayout parent) { MotionAnalysisGraphView item = new MotionAnalysisGraphView(script, this, experiment); addItemViewHolder(item, parent); return item; } public Export addExportButton(SheetGroupLayout parent) { Export item = new Export(script); addItemViewHolder(item, parent); return item; } } interface IActivityStarterViewParent { public void startActivityForResultFromView(ActivityStarterView view, Intent intent, int requestCode); /** * The parent has to provide a unique id that stays the same also if the activity has been reloaded. For example, * if views get added in a fix order this should be a normal counter. * * @return a unique id */ public int getNewChildId(); } /** * Base class for a view that can start a child activity and is able to receive the activity response. */ abstract class ActivityStarterView extends FrameLayout { protected IActivityStarterViewParent parent; public ActivityStarterView(Context context, IActivityStarterViewParent parent) { super(context); setId(parent.getNewChildId()); this.parent = parent; } /** * Copies the behaviour of the Activity startActivityForResult method. * * @param intent the intent to start the activity * @param requestCode the request code for that activity */ public void startActivityForResult(Intent intent, int requestCode) { parent.startActivityForResultFromView(this, intent, requestCode); } /** * Called when the started activity returns. * * @param requestCode the code specified in {@link #startActivityForResult(Intent, int)}. * @param resultCode the result code * @param data the Intent returned by the activity */ abstract public void onActivityResult(int requestCode, int resultCode, Intent data); }
UTF-8
Java
21,132
java
ScriptTreeNodeSheet.java
Java
[ { "context": "terms of the GPLv3 License.\n *\n * Authors:\n * Clemens Zeidler <czei002@aucklanduni.ac.nz>\n */\npackage nz.ac.auc", "end": 118, "score": 0.9998471736907959, "start": 103, "tag": "NAME", "value": "Clemens Zeidler" }, { "context": " License.\n *\n * Authors:\n * Clemens Zeidler <czei002@aucklanduni.ac.nz>\n */\npackage nz.ac.auckland.lablet.script.compone", "end": 145, "score": 0.9999330639839172, "start": 120, "tag": "EMAIL", "value": "czei002@aucklanduni.ac.nz" } ]
null
[]
/* * Copyright 2013-2014. * Distributed under the terms of the GPLv3 License. * * Authors: * <NAME> <<EMAIL>> */ package nz.ac.auckland.lablet.script.components; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.*; import android.widget.*; import nz.ac.auckland.lablet.camera.MotionAnalysis; import nz.ac.auckland.lablet.script.*; import nz.ac.auckland.lablet.views.graph.*; import nz.ac.auckland.lablet.R; import java.util.HashMap; import java.util.Map; /** * View holder for a view that only displays some text. */ class TextComponent extends ScriptComponentViewHolder { private String text = ""; private int typeface = Typeface.NORMAL; public TextComponent(Script script, String text) { super(script); this.text = text; setState(ScriptTreeNode.SCRIPT_STATE_DONE); } public void setTypeface(int typeface) { this.typeface = typeface; } @Override public View createView(Context context, android.support.v4.app.Fragment parent) { TextView textView = new TextView(context); textView.setTextAppearance(context, android.R.style.TextAppearance_Medium); textView.setTypeface(null, typeface); textView.setText(text); return textView; } @Override public boolean initCheck() { return true; } } /** * View holder for a view that has a checkbox and a text view. */ class CheckBoxQuestion extends ScriptComponentViewHolder { private String text = ""; public CheckBoxQuestion(Script script, String text) { super(script); this.text = text; setState(ScriptTreeNode.SCRIPT_STATE_ONGOING); } @Override public View createView(Context context, android.support.v4.app.Fragment parent) { CheckBox view = new CheckBox(context); view.setTextAppearance(context, android.R.style.TextAppearance_Medium); view.setBackgroundColor(context.getResources().getColor(R.color.sc_question_background_color)); view.setText(text); if (getState() == ScriptTreeNode.SCRIPT_STATE_DONE) view.setChecked(true); view.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean checked) { if (checked) setState(ScriptTreeNode.SCRIPT_STATE_DONE); else setState(ScriptTreeNode.SCRIPT_STATE_ONGOING); } }); return view; } @Override public boolean initCheck() { return true; } } /** * View holder for a view with just a question. */ class Question extends ScriptComponentViewHolder { private String text = ""; private ScriptTreeNodeSheetBase component; public Question(Script script, String text, ScriptTreeNodeSheetBase component) { super(script); this.text = text; this.component = component; setState(ScriptTreeNode.SCRIPT_STATE_DONE); } @Override public View createView(Context context, android.support.v4.app.Fragment parent) { // we have to get a fresh counter here, if we cache it we will miss that it has been deleted in the sheet // component ScriptTreeNodeSheetBase.Counter counter = this.component.getCounter("QuestionCounter"); TextView textView = new TextView(context); textView.setTextAppearance(context, android.R.style.TextAppearance_Medium); textView.setBackgroundColor(context.getResources().getColor(R.color.sc_question_background_color)); textView.setText("Q" + counter.increaseValue() + ": " + text); return textView; } @Override public boolean initCheck() { return true; } } /** * View holder for a view that has a question and a text input view. * <p> * The question is considered as answered as soon as the text input view contains some text. It is not checked if the * question is answered correctly. * </p> */ class TextQuestion extends ScriptComponentViewHolder { private String text = ""; private String answer = ""; private boolean optional = false; private ScriptTreeNodeSheetBase component; public TextQuestion(Script script, String text, ScriptTreeNodeSheetBase component) { super(script); this.text = text; this.component = component; setState(ScriptTreeNode.SCRIPT_STATE_ONGOING); } public void setOptional(boolean optional) { this.optional = optional; update(); } @Override public View createView(Context context, android.support.v4.app.Fragment parent) { ScriptTreeNodeSheetBase.Counter counter = this.component.getCounter("QuestionCounter"); // Note: we have to do this programmatically cause findViewById would find the wrong child items if there are // more than one text question. LinearLayout layout = new LinearLayout(context); layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); layout.setOrientation(LinearLayout.VERTICAL); layout.setBackgroundColor(context.getResources().getColor(R.color.sc_question_background_color)); TextView textView = new TextView(context); textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); textView.setTextAppearance(context, android.R.style.TextAppearance_Medium); textView.setText("Q" + counter.increaseValue() + ": " + text); EditText editText = new EditText(context); editText.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); assert editText != null; editText.setText(answer); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { answer = editable.toString(); update(); } }); layout.addView(textView); layout.addView(editText); return layout; } @Override public boolean initCheck() { return true; } public void toBundle(Bundle bundle) { bundle.putString("answer", answer); super.toBundle(bundle); } public boolean fromBundle(Bundle bundle) { answer = bundle.getString("answer", ""); return super.fromBundle(bundle); } private void update() { if (optional) setState(ScriptTreeNode.SCRIPT_STATE_DONE); else if (!answer.equals("")) setState(ScriptTreeNode.SCRIPT_STATE_DONE); else setState(ScriptTreeNode.SCRIPT_STATE_ONGOING); } } /** * View holder for a graph view that shows some experiment analysis results. */ class MotionAnalysisGraphView extends ScriptComponentViewHolder { private ScriptTreeNodeSheet experimentSheet; private ScriptExperimentRef experiment; private MarkerTimeGraphAdapter adapter; private String xAxisContentId = "x-position"; private String yAxisContentId = "y-position"; private String title = "Position Data"; private ScriptExperimentRef.IListener experimentListener; public MotionAnalysisGraphView(Script script, ScriptTreeNodeSheet experimentSheet, ScriptExperimentRef experiment) { super(script); this.experimentSheet = experimentSheet; this.experiment = experiment; setState(ScriptTreeNode.SCRIPT_STATE_DONE); } @Override public View createView(Context context, android.support.v4.app.Fragment parentFragment) { LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.script_component_graph_view, null); assert view != null; GraphView2D graphView2D = (GraphView2D)view.findViewById(R.id.graphView); assert graphView2D != null; graphView2D.setMaxWidth(500); MotionAnalysis sensorAnalysis = experiment.getMotionAnalysis(0); if (sensorAnalysis != null) { MarkerGraphAxis xAxis = createAxis(xAxisContentId); if (xAxis == null) xAxis = new XPositionMarkerGraphAxis(sensorAnalysis.getXUnit(), sensorAnalysis.getXMinRangeGetter()); MarkerGraphAxis yAxis = createAxis(yAxisContentId); if (yAxis == null) yAxis = new XPositionMarkerGraphAxis(sensorAnalysis.getXUnit(), sensorAnalysis.getYMinRangeGetter()); adapter = new MarkerTimeGraphAdapter(sensorAnalysis.getTagMarkers(), sensorAnalysis.getTimeData(), title, xAxis, yAxis); graphView2D.setAdapter(adapter); } // install listener experimentListener = new ScriptExperimentRef.IListener() { @Override public void onExperimentAnalysisUpdated() { MotionAnalysis motionAnalysis = experiment.getMotionAnalysis(0); adapter.setTo(motionAnalysis.getTagMarkers(), motionAnalysis.getTimeData()); } }; experiment.addListener(experimentListener); return view; } @Override protected void finalize() { experiment.removeListener(experimentListener); } public boolean setXAxisContent(String axis) { if (!isValidAxis(axis)) return false; xAxisContentId = axis; return true; } public boolean setYAxisContent(String axis) { if (!isValidAxis(axis)) return false; yAxisContentId = axis; return true; } public void showXVsYPosition() { setTitle("Position Data"); setXAxisContent("x-position"); setYAxisContent("y-position"); } public void showTimeVsXSpeed() { setTitle("X-Velocity vs. Time"); setXAxisContent("time_v"); setYAxisContent("x-velocity"); } public void showTimeVsYSpeed() { setTitle("Y-Velocity vs. Time"); setXAxisContent("time_v"); setYAxisContent("y-velocity"); } public void setTitle(String title) { this.title = title; } private MarkerGraphAxis createAxis(String id) { MotionAnalysis sensorAnalysis = experiment.getMotionAnalysis(0); if (id.equalsIgnoreCase("x-position")) return new XPositionMarkerGraphAxis(sensorAnalysis.getXUnit(), sensorAnalysis.getXMinRangeGetter()); if (id.equalsIgnoreCase("y-position")) return new YPositionMarkerGraphAxis(sensorAnalysis.getYUnit(), sensorAnalysis.getYMinRangeGetter()); if (id.equalsIgnoreCase("x-velocity")) return new XSpeedMarkerGraphAxis(sensorAnalysis.getXUnit(), sensorAnalysis.getTUnit()); if (id.equalsIgnoreCase("y-velocity")) return new YSpeedMarkerGraphAxis(sensorAnalysis.getYUnit(), sensorAnalysis.getTUnit()); if (id.equalsIgnoreCase("time")) return new TimeMarkerGraphAxis(sensorAnalysis.getTUnit()); if (id.equalsIgnoreCase("time_v")) return new SpeedTimeMarkerGraphAxis(sensorAnalysis.getTUnit()); return null; } private boolean isValidAxis(String id) { if (id.equalsIgnoreCase("x-position")) return true; if (id.equalsIgnoreCase("y-position")) return true; if (id.equalsIgnoreCase("x-velocity")) return true; if (id.equalsIgnoreCase("y-velocity")) return true; if (id.equalsIgnoreCase("time")) return true; if (id.equalsIgnoreCase("time_v")) return true; return false; } public MarkerTimeGraphAdapter getAdapter() { return adapter; } @Override public boolean initCheck() { if (experiment == null) { lastErrorMessage = "no experiment data"; return false; } return true; } } /** * Base class for the {@link ScriptTreeNodeSheet} class. * <p> * All important logic is done here. ScriptComponentTreeSheet only has an interface to add different child components. * </p> */ class ScriptTreeNodeSheetBase extends ScriptTreeNodeFragmentHolder { /** * Page wide counter. * <p> * This counter is, for example, used to number the questions on a sheet. * </p> */ public class Counter { private int counter = 0; public void setValue(int value) { counter = value; } public int increaseValue() { counter++; return counter; } } private SheetGroupLayout sheetGroupLayout = new SheetGroupLayout(LinearLayout.VERTICAL); private ScriptComponentContainer<ScriptComponentViewHolder> itemContainer = new ScriptComponentContainer<ScriptComponentViewHolder>(); private Map<String, Counter> mapOfCounter = new HashMap<String, Counter>(); public ScriptTreeNodeSheetBase(Script script) { super(script); itemContainer.setListener(new ScriptComponentContainer.IItemContainerListener() { @Override public void onAllItemStatusChanged(boolean allDone) { if (allDone) setState(ScriptTreeNode.SCRIPT_STATE_DONE); else setState(ScriptTreeNode.SCRIPT_STATE_ONGOING); } }); } public SheetLayout getSheetLayout() { return sheetGroupLayout; } @Override public boolean initCheck() { return itemContainer.initCheck(); } @Override public ScriptComponentGenericFragment createFragment() { ScriptComponentSheetFragment fragment = new ScriptComponentSheetFragment(); fragment.setScriptComponent(this); return fragment; } @Override public void toBundle(Bundle bundle) { super.toBundle(bundle); itemContainer.toBundle(bundle); } @Override public boolean fromBundle(Bundle bundle) { if (!super.fromBundle(bundle)) return false; return itemContainer.fromBundle(bundle); } public void setMainLayoutOrientation(String orientation) { if (orientation.equalsIgnoreCase("horizontal")) sheetGroupLayout.setOrientation(LinearLayout.HORIZONTAL); else sheetGroupLayout.setOrientation(LinearLayout.VERTICAL); } public SheetGroupLayout addHorizontalGroupLayout(SheetGroupLayout parent) { return addGroupLayout(LinearLayout.HORIZONTAL, parent); } public SheetGroupLayout addVerticalGroupLayout(SheetGroupLayout parent) { return addGroupLayout(LinearLayout.VERTICAL, parent); } protected SheetGroupLayout addGroupLayout(int orientation, SheetGroupLayout parent) { SheetGroupLayout layout = new SheetGroupLayout(orientation); if (parent == null) sheetGroupLayout.addLayout(layout); else parent.addLayout(layout); return layout; } protected SheetLayout addItemViewHolder(ScriptComponentViewHolder item, SheetGroupLayout parent) { itemContainer.addItem(item); SheetLayout layoutItem; if (parent == null) layoutItem = sheetGroupLayout.addView(item); else layoutItem = parent.addView(item); return layoutItem; } /** * The counter is valid for the lifetime of the fragment view. If not counter with the given name exist, a new * counter is created. * @param name counter name * @return a Counter */ public Counter getCounter(String name) { if (!mapOfCounter.containsKey(name)) { Counter counter = new Counter(); mapOfCounter.put(name, counter); return counter; } return mapOfCounter.get(name); } public void resetCounter() { mapOfCounter.clear(); } } /** * Powerful script component that can holds a various kind of child components, e.g., questions or text. */ public class ScriptTreeNodeSheet extends ScriptTreeNodeSheetBase { public ScriptTreeNodeSheet(Script script) { super(script); } public ScriptComponentViewHolder addText(String text, SheetGroupLayout parent) { TextComponent textOnlyQuestion = new TextComponent(script, text); addItemViewHolder(textOnlyQuestion, parent); return textOnlyQuestion; } public ScriptComponentViewHolder addHeader(String text, SheetGroupLayout parent) { TextComponent component = new TextComponent(script, text); component.setTypeface(Typeface.BOLD); addItemViewHolder(component, parent); return component; } public ScriptComponentViewHolder addQuestion(String text, SheetGroupLayout parent) { Question component = new Question(script, text, this); addItemViewHolder(component, parent); return component; } public ScriptComponentViewHolder addTextQuestion(String text, SheetGroupLayout parent) { TextQuestion component = new TextQuestion(script, text, this); addItemViewHolder(component, parent); return component; } public ScriptComponentViewHolder addCheckQuestion(String text, SheetGroupLayout parent) { CheckBoxQuestion question = new CheckBoxQuestion(script, text); addItemViewHolder(question, parent); return question; } public AccelerometerExperiment addAccelerometerExperiment(SheetGroupLayout parent) { AccelerometerExperiment experiment = new AccelerometerExperiment(script); addItemViewHolder(experiment, parent); return experiment; } public CameraExperiment addCameraExperiment(SheetGroupLayout parent) { CameraExperiment cameraExperiment = new CameraExperiment(script); addItemViewHolder(cameraExperiment, parent); return cameraExperiment; } public MicrophoneExperiment addMicrophoneExperiment(SheetGroupLayout parent) { MicrophoneExperiment experiment = new MicrophoneExperiment(script); addItemViewHolder(experiment, parent); return experiment; } public PotentialEnergy1 addPotentialEnergy1Question(SheetGroupLayout parent) { PotentialEnergy1 question = new PotentialEnergy1(script); addItemViewHolder(question, parent); return question; } public MotionAnalysisGraphView addMotionAnalysisGraph(ScriptExperimentRef experiment, SheetGroupLayout parent) { MotionAnalysisGraphView item = new MotionAnalysisGraphView(script, this, experiment); addItemViewHolder(item, parent); return item; } public Export addExportButton(SheetGroupLayout parent) { Export item = new Export(script); addItemViewHolder(item, parent); return item; } } interface IActivityStarterViewParent { public void startActivityForResultFromView(ActivityStarterView view, Intent intent, int requestCode); /** * The parent has to provide a unique id that stays the same also if the activity has been reloaded. For example, * if views get added in a fix order this should be a normal counter. * * @return a unique id */ public int getNewChildId(); } /** * Base class for a view that can start a child activity and is able to receive the activity response. */ abstract class ActivityStarterView extends FrameLayout { protected IActivityStarterViewParent parent; public ActivityStarterView(Context context, IActivityStarterViewParent parent) { super(context); setId(parent.getNewChildId()); this.parent = parent; } /** * Copies the behaviour of the Activity startActivityForResult method. * * @param intent the intent to start the activity * @param requestCode the request code for that activity */ public void startActivityForResult(Intent intent, int requestCode) { parent.startActivityForResultFromView(this, intent, requestCode); } /** * Called when the started activity returns. * * @param requestCode the code specified in {@link #startActivityForResult(Intent, int)}. * @param resultCode the result code * @param data the Intent returned by the activity */ abstract public void onActivityResult(int requestCode, int resultCode, Intent data); }
21,105
0.669601
0.667802
636
32.226414
30.243284
120
false
false
0
0
0
0
0
0
0.515723
false
false
5
2da9e6131171491cbf3a74023771c94a87f87254
28,063,316,331,591
6e73af37c095284e707b8fa02c85dd5d6eb5f57c
/app/src/main/java/com/makguksu/mice/RecommendationPage.java
a69d59afd9dcc12ec730ebdbb5b5934baf97026a
[]
no_license
MinJeongHyeon/MiceProject
https://github.com/MinJeongHyeon/MiceProject
4f2d83908874974c0f5a3c8dc850600c06d9d292
c3c9be6456957abb9556a286b50f18972c6159bf
refs/heads/master
2023-04-02T07:46:06.132000
2021-12-10T16:57:19
2021-12-10T16:57:19
353,562,771
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.makguksu.mice; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class RecommendationPage extends Fragment { ViewGroup viewGroup; private com.google.firebase.auth.FirebaseAuth FirebaseAuth; private com.google.android.gms.auth.api.signin.GoogleSignInClient GoogleSignInClient; TextView Profile_name; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { viewGroup = (ViewGroup) inflater.inflate(R.layout.recommendationpage,container,false); Button recom_button = (Button) viewGroup.findViewById(R.id.recom_button); Profile_name = viewGroup.findViewById(R.id.recom_textView3); FirebaseAuth = FirebaseAuth.getInstance(); FirebaseUser FirebaseUser = FirebaseAuth.getCurrentUser(); if(FirebaseUser !=null) { Profile_name.setText(FirebaseUser.getDisplayName()); } GoogleSignInClient = GoogleSignIn.getClient(getContext(), GoogleSignInOptions.DEFAULT_SIGN_IN); recom_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity().getApplicationContext(), Survey_input.class); startActivity(intent); } }); return viewGroup; }; }
UTF-8
Java
1,979
java
RecommendationPage.java
Java
[]
null
[]
package com.makguksu.mice; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class RecommendationPage extends Fragment { ViewGroup viewGroup; private com.google.firebase.auth.FirebaseAuth FirebaseAuth; private com.google.android.gms.auth.api.signin.GoogleSignInClient GoogleSignInClient; TextView Profile_name; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { viewGroup = (ViewGroup) inflater.inflate(R.layout.recommendationpage,container,false); Button recom_button = (Button) viewGroup.findViewById(R.id.recom_button); Profile_name = viewGroup.findViewById(R.id.recom_textView3); FirebaseAuth = FirebaseAuth.getInstance(); FirebaseUser FirebaseUser = FirebaseAuth.getCurrentUser(); if(FirebaseUser !=null) { Profile_name.setText(FirebaseUser.getDisplayName()); } GoogleSignInClient = GoogleSignIn.getClient(getContext(), GoogleSignInOptions.DEFAULT_SIGN_IN); recom_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity().getApplicationContext(), Survey_input.class); startActivity(intent); } }); return viewGroup; }; }
1,979
0.739262
0.738757
52
37.057693
31.43272
132
false
false
0
0
0
0
0
0
0.730769
false
false
5
74822288b0b93b6fa185cc4c2df2b4adb50cbe1c
3,186,865,783,355
6a2d903d7eeb3500848d169392288d175ef648a6
/src/scenes/RegisterSceneCreator.java
2252e0df4f64cb9b06297285a3d07269a3e54c30
[]
no_license
matthewwier/StoreJavaFX
https://github.com/matthewwier/StoreJavaFX
c6feedaa84bf00583028a86b98899405accc7606
12446815c1d12595b4f96b80c403475c4a2eb767
refs/heads/master
2020-09-22T13:52:42.154000
2020-01-22T16:41:18
2020-01-22T16:41:18
225,227,474
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package scenes; import decorators.RegisterFormDecorator; import factory.UserFormFactory; import javafx.scene.Scene; import javafx.scene.layout.GridPane; public class RegisterSceneCreator implements SceneFactory { @Override public Scene createScene() { GridPane registerPane = new UserFormFactory().createForm(); RegisterFormDecorator registerFormDecorator = new RegisterFormDecorator(); registerFormDecorator.addControls(registerPane); return new Scene(registerPane, 800, 400); } }
UTF-8
Java
530
java
RegisterSceneCreator.java
Java
[]
null
[]
package scenes; import decorators.RegisterFormDecorator; import factory.UserFormFactory; import javafx.scene.Scene; import javafx.scene.layout.GridPane; public class RegisterSceneCreator implements SceneFactory { @Override public Scene createScene() { GridPane registerPane = new UserFormFactory().createForm(); RegisterFormDecorator registerFormDecorator = new RegisterFormDecorator(); registerFormDecorator.addControls(registerPane); return new Scene(registerPane, 800, 400); } }
530
0.762264
0.750943
18
28.444445
25.434496
82
false
false
0
0
0
0
0
0
0.611111
false
false
5
a1da92a58cbc363256feb55ff83f370e5e07633f
446,676,610,768
c4b5094086d7c91af28c26e63aeedf638a695677
/src/test/java/addtocartproductflow/MetalBedFrameProductDetailsChanges.java
d9b8510dcf377f1f197d27b68a272579f8287a22
[]
no_license
girjakahar/SleepycatAutomationV1
https://github.com/girjakahar/SleepycatAutomationV1
0cc4fe2c44bb18fffc4353476ae0c5443ebb04fe
e39aae5c23f7f56a2a72e171d2983eca2d79b586
refs/heads/main
2023-07-19T03:35:49.932000
2021-09-24T09:44:41
2021-09-24T09:44:41
403,358,462
0
0
null
false
2021-09-24T09:13:56
2021-09-05T16:29:15
2021-09-22T14:26:29
2021-09-24T09:13:55
369
0
0
0
Java
false
false
package addtocartproductflow; import java.io.IOException; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import pageobject.LandingPageObject; import pageobject.ProductDetailsPage; import resources.BaseSleepycat; public class MetalBedFrameProductDetailsChanges extends BaseSleepycat { static RemoteWebDriver driver; static WebDriverWait wait; public static Logger log =LogManager.getLogger(MetalBedFrameProductDetailsChanges.class); @BeforeTest public void startingDriver() throws IOException { driver=initializeChrome(); log.error("Starting driver"); } @Test public void metalBedFrameAddToCart() throws Exception { driver.get("https://sleepycat.in/"); log.error("Website opened Successfully"); driver.manage().window().maximize(); log.error("Website is maximized"); wait = new WebDriverWait(driver, 20); LandingPageObject landingpage = new LandingPageObject(driver); landingpage.offerModal(); landingpage.bedHeader(); log.error("Submenu link is opened"); wait.until(ExpectedConditions.visibilityOf(landingpage.metalBedFrameMenu())); landingpage.metalBedFrameMenu().click(); log.error("Clicked on metal Bed Frame Menu option"); landingpage.offerModal(); ProductDetailsPage productDetails = new ProductDetailsPage(driver); wait.until(ExpectedConditions.visibilityOf(productDetails.kingCategory())); productDetails.queenCategory().click(); log.error("Clicked on Queen category option"); landingpage.offerModal(); productDetails.pageScroll(); log.error("Scrolled down to size section"); landingpage.offerModal(); wait.until(ExpectedConditions.visibilityOf(productDetails.feetDimension())); productDetails.feetDimension().click(); log.error("Clicked on Feet dimension option"); landingpage.offerModal(); wait.until(ExpectedConditions.visibilityOf(productDetails.quantityField())); productDetails.quantityField().click(); log.error("Clicked on Quantity field dropdown"); landingpage.offerModal(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[@data-name='quantity']"))); List<WebElement> quantityvalue =driver.findElements(By.xpath("//li[@data-name='quantity']")); System.out.println(quantityvalue.size()); for(int i=0;i<quantityvalue.size();i++) { quantityvalue.get(i).getText(); if(quantityvalue.get(i).getText().contains("6")) { landingpage.offerModal(); quantityvalue.get(i).click(); log.error("Quantity is selected from drodown"); break; } } landingpage.offerModal(); productDetails.addToCart(); log.error("Clicked on add to cart button"); landingpage.offerModal(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='cart_item_mid']//div[@data-product_sku='SC-BED-Q-78x36x16']"))); boolean productname = driver.findElement(By.xpath("//div[@class='cart_item_mid']//div[@data-product_sku='SC-BED-Q-78x36x16']")).isDisplayed(); if(productname) { System.out.println("Queen category Metal Bed frame Product is added in cart"); log.error("Queen category Metal Bed frame Product is added in cart"); }else { System.out.println("Queen category Metal Bed frame Product is not added in cart"); log.error("Queen category Metal Bed frame Product is not added in cart"); } } @AfterTest public void closeDriver() throws IOException { driver.quit(); log.error("Driver is closed"); } }
UTF-8
Java
4,113
java
MetalBedFrameProductDetailsChanges.java
Java
[]
null
[]
package addtocartproductflow; import java.io.IOException; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import pageobject.LandingPageObject; import pageobject.ProductDetailsPage; import resources.BaseSleepycat; public class MetalBedFrameProductDetailsChanges extends BaseSleepycat { static RemoteWebDriver driver; static WebDriverWait wait; public static Logger log =LogManager.getLogger(MetalBedFrameProductDetailsChanges.class); @BeforeTest public void startingDriver() throws IOException { driver=initializeChrome(); log.error("Starting driver"); } @Test public void metalBedFrameAddToCart() throws Exception { driver.get("https://sleepycat.in/"); log.error("Website opened Successfully"); driver.manage().window().maximize(); log.error("Website is maximized"); wait = new WebDriverWait(driver, 20); LandingPageObject landingpage = new LandingPageObject(driver); landingpage.offerModal(); landingpage.bedHeader(); log.error("Submenu link is opened"); wait.until(ExpectedConditions.visibilityOf(landingpage.metalBedFrameMenu())); landingpage.metalBedFrameMenu().click(); log.error("Clicked on metal Bed Frame Menu option"); landingpage.offerModal(); ProductDetailsPage productDetails = new ProductDetailsPage(driver); wait.until(ExpectedConditions.visibilityOf(productDetails.kingCategory())); productDetails.queenCategory().click(); log.error("Clicked on Queen category option"); landingpage.offerModal(); productDetails.pageScroll(); log.error("Scrolled down to size section"); landingpage.offerModal(); wait.until(ExpectedConditions.visibilityOf(productDetails.feetDimension())); productDetails.feetDimension().click(); log.error("Clicked on Feet dimension option"); landingpage.offerModal(); wait.until(ExpectedConditions.visibilityOf(productDetails.quantityField())); productDetails.quantityField().click(); log.error("Clicked on Quantity field dropdown"); landingpage.offerModal(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[@data-name='quantity']"))); List<WebElement> quantityvalue =driver.findElements(By.xpath("//li[@data-name='quantity']")); System.out.println(quantityvalue.size()); for(int i=0;i<quantityvalue.size();i++) { quantityvalue.get(i).getText(); if(quantityvalue.get(i).getText().contains("6")) { landingpage.offerModal(); quantityvalue.get(i).click(); log.error("Quantity is selected from drodown"); break; } } landingpage.offerModal(); productDetails.addToCart(); log.error("Clicked on add to cart button"); landingpage.offerModal(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='cart_item_mid']//div[@data-product_sku='SC-BED-Q-78x36x16']"))); boolean productname = driver.findElement(By.xpath("//div[@class='cart_item_mid']//div[@data-product_sku='SC-BED-Q-78x36x16']")).isDisplayed(); if(productname) { System.out.println("Queen category Metal Bed frame Product is added in cart"); log.error("Queen category Metal Bed frame Product is added in cart"); }else { System.out.println("Queen category Metal Bed frame Product is not added in cart"); log.error("Queen category Metal Bed frame Product is not added in cart"); } } @AfterTest public void closeDriver() throws IOException { driver.quit(); log.error("Driver is closed"); } }
4,113
0.702893
0.698517
119
33.563026
29.526413
150
false
false
0
0
0
0
0
0
2.294118
false
false
5
4c88fac316d4301554946cffde116f92150945ce
31,602,369,398,624
55dad9bf8ee3c815f9e35f7b27fc91b7731334b7
/meituanSys/src/meituan/service/BusinessService.java
abd9507c19d72859a86a47bacc56422e991f2450
[]
no_license
13527614919/meituanSys
https://github.com/13527614919/meituanSys
8473dbb0eb9fb22a027ccea91dee11724e97fddc
35265333a94bddeac4a114ff81970bf1e580f173
refs/heads/master
2020-03-19T18:38:45.887000
2018-06-16T14:41:23
2018-06-16T14:41:23
136,818,335
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package meituan.service; import java.sql.SQLException; import meituan.dao.BusinessDao; import meituan.daoImpl.BusinessDaoImpl; import meituan.domain.Business; import meituan.exception.MyBusinessException; public class BusinessService { BusinessDao bsd = new BusinessDaoImpl(); //AjAx检查注册账号 public Business checkUsernameAjax(String bid) throws SQLException { return bsd.getIdByBIdAjax(bid); } //商家注册账号 public void regist(Business business) throws MyBusinessException { try { bsd.register(business); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new MyBusinessException("注册失败"); } } public Business loginByBIdAndPassword(String bid, String password) throws MyBusinessException { Business business = null; try { business = bsd.loginByBIdAndPassword(bid, password); if(business == null) { throw new MyBusinessException("用户账号或密码错误"); } } catch (SQLException e) { e.printStackTrace(); throw new MyBusinessException("用户名或密码错误"); } return business; } }
UTF-8
Java
1,166
java
BusinessService.java
Java
[]
null
[]
package meituan.service; import java.sql.SQLException; import meituan.dao.BusinessDao; import meituan.daoImpl.BusinessDaoImpl; import meituan.domain.Business; import meituan.exception.MyBusinessException; public class BusinessService { BusinessDao bsd = new BusinessDaoImpl(); //AjAx检查注册账号 public Business checkUsernameAjax(String bid) throws SQLException { return bsd.getIdByBIdAjax(bid); } //商家注册账号 public void regist(Business business) throws MyBusinessException { try { bsd.register(business); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new MyBusinessException("注册失败"); } } public Business loginByBIdAndPassword(String bid, String password) throws MyBusinessException { Business business = null; try { business = bsd.loginByBIdAndPassword(bid, password); if(business == null) { throw new MyBusinessException("用户账号或密码错误"); } } catch (SQLException e) { e.printStackTrace(); throw new MyBusinessException("用户名或密码错误"); } return business; } }
1,166
0.715455
0.715455
44
23
21.998966
96
false
false
0
0
0
0
0
0
1.795455
false
false
5
cbf467ea675b550e2eea0309916e3806a9f5b4a7
5,188,320,504,762
3f39df9e495dfd630d1eb543c246a7b54532e8cb
/spring/spring-boot-demo/spring-boot-demo-application/src/main/java/org/tuxdevelop/spring_boot_demo/security/constants/RoleConstants.java
6c1873dfa66d7f85a23c7449843f24d5a3d99faf
[ "Apache-2.0" ]
permissive
Ivanna07/demos
https://github.com/Ivanna07/demos
f3cf91bcbf50cd6a35564e570de232d777784654
b02d393019c0ec62126f4026dc662f5d2f0860c9
refs/heads/master
2021-07-08T08:41:12.046000
2015-02-19T20:57:18
2015-02-19T20:57:18
35,870,212
0
0
Apache-2.0
false
2021-05-12T00:17:08
2015-05-19T08:46:36
2016-06-12T18:36:52
2021-05-12T00:17:07
848
0
0
1
Java
false
false
package org.tuxdevelop.spring_boot_demo.security.constants; public abstract class RoleConstants { public static final String ROLE_USER = "ROLE_USER"; public static final String ROLE_ADMIN = "ROLE_ADMIN"; public static final String ROLE_WRITE = "ROLE_WRITE"; }
UTF-8
Java
266
java
RoleConstants.java
Java
[]
null
[]
package org.tuxdevelop.spring_boot_demo.security.constants; public abstract class RoleConstants { public static final String ROLE_USER = "ROLE_USER"; public static final String ROLE_ADMIN = "ROLE_ADMIN"; public static final String ROLE_WRITE = "ROLE_WRITE"; }
266
0.766917
0.766917
9
28.555555
25.923439
59
false
false
0
0
0
0
0
0
0.777778
false
false
5
57b784a3ba3bed3b6b9f309e9fa410b9ebc159b2
11,587,821,799,139
6d8bc1c7a2fd5193f21370d4c89ae81a13486d61
/src/conference-idea/src/main/java/cn/hurrican/dtl/QueryTopNumMeetingParam.java
ce50125184da717c2f203cf917be89770b26fdbe
[]
no_license
zengsn/conference
https://github.com/zengsn/conference
f431cc4aaedf15cfd9e677fff678cc56db6c62c7
42ef8ba621a452a0c42b606b92edbcad1f09d581
refs/heads/master
2018-02-07T16:04:56.421000
2017-12-18T07:24:47
2017-12-18T07:24:47
95,961,217
1
5
null
false
2018-05-10T04:00:09
2017-07-01T11:50:42
2018-05-05T16:03:57
2018-05-10T04:00:08
52,436
0
4
17
HTML
false
null
package cn.hurrican.dtl; /** * Created by NewObject on 2017/10/29. */ public class QueryTopNumMeetingParam { private String tag; private String startTime; private Integer offsetTime = 7; private Integer page; private Integer perPageNumber = 8; @Override public String toString() { return "QueryTopNumMeetingParam\n{" + "tag='" + tag + '\'' + ", \nstartTime='" + startTime + '\'' + ", \noffsetTime=" + offsetTime + ", \npage=" + page + ", \nperPageNumber=" + perPageNumber + "\n" + '}'; } public String getTag() { return tag; } public String getStartTime() { return startTime; } public Integer getOffsetTime() { return offsetTime; } public Integer getPage() { return page; } public Integer getPerPageNumber() { return perPageNumber; } public void setTag(String tag) { this.tag = tag; } public void setStartTime(String startTime) { this.startTime = startTime; } public void setOffsetTime(Integer offsetTime) { this.offsetTime = offsetTime; } public void setPage(Integer page) { this.page = page; } public void setPerPageNumber(Integer perPageNumber) { this.perPageNumber = perPageNumber; } }
UTF-8
Java
1,401
java
QueryTopNumMeetingParam.java
Java
[ { "context": "package cn.hurrican.dtl;\n\n/**\n * Created by NewObject on 2017/10/29.\n */\npublic class QueryTopNumMeetin", "end": 53, "score": 0.9993031620979309, "start": 44, "tag": "USERNAME", "value": "NewObject" } ]
null
[]
package cn.hurrican.dtl; /** * Created by NewObject on 2017/10/29. */ public class QueryTopNumMeetingParam { private String tag; private String startTime; private Integer offsetTime = 7; private Integer page; private Integer perPageNumber = 8; @Override public String toString() { return "QueryTopNumMeetingParam\n{" + "tag='" + tag + '\'' + ", \nstartTime='" + startTime + '\'' + ", \noffsetTime=" + offsetTime + ", \npage=" + page + ", \nperPageNumber=" + perPageNumber + "\n" + '}'; } public String getTag() { return tag; } public String getStartTime() { return startTime; } public Integer getOffsetTime() { return offsetTime; } public Integer getPage() { return page; } public Integer getPerPageNumber() { return perPageNumber; } public void setTag(String tag) { this.tag = tag; } public void setStartTime(String startTime) { this.startTime = startTime; } public void setOffsetTime(Integer offsetTime) { this.offsetTime = offsetTime; } public void setPage(Integer page) { this.page = page; } public void setPerPageNumber(Integer perPageNumber) { this.perPageNumber = perPageNumber; } }
1,401
0.56531
0.558173
64
20.890625
18.025257
61
false
false
0
0
0
0
0
0
0.328125
false
false
5
9d97eb1a0ed996d4adafd30f2e2380eef6900e39
29,523,605,223,589
dc15198bbeef72db481d1a389530355123054b42
/src/com/kgm/service/inf/PaymentServiceInf.java
b629fdfb9c29daaaa203f40c837b545c9a0fbb69
[]
no_license
primedari/Soocer-Lions-Application--Spring-MVC
https://github.com/primedari/Soocer-Lions-Application--Spring-MVC
a754c7c2f0de53b311595f2e7c3a6e1bbba0928a
a949a203e36a5389f042e8ee0f004bce52e0642c
refs/heads/master
2020-06-28T06:11:31.063000
2017-01-29T14:27:52
2017-01-29T14:27:52
74,504,194
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kgm.service.inf; import java.util.List; import com.kgm.bean.Payment; /* Payment Service Interface*/ public interface PaymentServiceInf { Payment getOrderById(int id); List<Payment> getAllOrder(); boolean addOrder(Payment pay); boolean deleteById(int id); boolean updateOrder(Payment pay); }
UTF-8
Java
325
java
PaymentServiceInf.java
Java
[]
null
[]
package com.kgm.service.inf; import java.util.List; import com.kgm.bean.Payment; /* Payment Service Interface*/ public interface PaymentServiceInf { Payment getOrderById(int id); List<Payment> getAllOrder(); boolean addOrder(Payment pay); boolean deleteById(int id); boolean updateOrder(Payment pay); }
325
0.738462
0.738462
14
21.214285
13.602408
36
false
false
0
0
0
0
0
0
0.928571
false
false
5
5d7c746294bea08827cff0c4529d7ea196294def
20,538,533,629,418
38be296d7c0b33686fb71b7bc90d5e75d90c8726
/app/src/main/java/com/ziqianfu/congresssearch/BillDetail.java
669e0940b62abb5fa34936b52ee2f1136da5e404
[]
no_license
fuziqianlu/CongressSearchAPP
https://github.com/fuziqianlu/CongressSearchAPP
ed777164cd9f1ab2337be616a248a2824b542b98
928276985b35ca9bde7fd9036798cbac42f4e27e
refs/heads/master
2021-01-11T09:40:22.286000
2016-12-30T09:29:00
2016-12-30T09:29:00
77,676,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ziqianfu.congresssearch; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.PersistableBundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.TextView; import android.widget.ViewSwitcher; import com.google.gson.Gson; import org.apache.commons.lang3.text.WordUtils; import org.apache.commons.lang3.time.FastDateFormat; import java.text.ParseException; import java.util.Date; /** * Created by lenovo on 2016/11/20. */ public class BillDetail extends AppCompatActivity { private TextView bill_id; private TextView bill_title; private TextView bill_type; private TextView bill_sponsor; private TextView bill_introduce; private TextView bill_status; private TextView bill_congress; private TextView bill_url; private TextView bill_version; private TextView bill_chamber; private ImageSwitcher favor_btn; private BillItem bill; private boolean saved; SharedPreferences preferences; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.bills_details); preferences=getSharedPreferences("favor_bills", MODE_APPEND); final SharedPreferences.Editor editor=preferences.edit(); Toolbar mtoolbar = (Toolbar) findViewById(R.id.tool_bar_bill); setSupportActionBar(mtoolbar); //getSupportActionBar().setTitle("Bills"); mtoolbar.setNavigationIcon(R.drawable.ic_arrow_back_white); mtoolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); getSupportActionBar().setTitle("Bill Info"); favor_btn=(ImageSwitcher)findViewById(R.id.favorite_button); bill_id=(TextView)findViewById(R.id.bill_id_data); bill_title=(TextView)findViewById(R.id.bill_title_data); bill_type=(TextView)findViewById(R.id.bill_type_data); bill_sponsor=(TextView)findViewById(R.id.bill_sponsor_data); bill_introduce=(TextView)findViewById(R.id.biil_introduce_data); bill_status=(TextView)findViewById(R.id.biil_status_data); bill_congress=(TextView)findViewById(R.id.bill_congress_data); bill_url=(TextView)findViewById(R.id.biil_url_data); bill_version=(TextView)findViewById(R.id.biil_version_data); bill_chamber=(TextView)findViewById(R.id.bill_chamber_data); Intent intent=getIntent(); final Gson gson=new Gson(); bill=gson.fromJson(intent.getStringExtra("bill_detail"), BillItem.class); favor_btn.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { return new ImageView(BillDetail.this); } }); favor_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(saved==false){ favor_btn.setImageResource(R.drawable.star_filled); saved=true; editor.putString(bill.bill_id, gson.toJson(bill, BillItem.class)); editor.commit(); } else { favor_btn.setImageResource(R.drawable.star_empty); saved=false; editor.remove(bill.bill_id); editor.commit(); } } }); if(preferences.getString(bill.bill_id, "0").equals("0")){ saved=false; favor_btn.setImageResource(R.drawable.star_empty); } else { saved=true; favor_btn.setImageResource(R.drawable.star_filled); } bill_sponsor.setText(bill.sponsor.title+". "+bill.sponsor.last_name+", "+bill.sponsor.first_name); bill_id.setText(bill.bill_id); bill_title.setText(bill.official_title); bill_type.setText(bill.bill_type); FastDateFormat parser=FastDateFormat.getInstance("yyyy-MM-dd"); FastDateFormat printer=FastDateFormat.getDateInstance(FastDateFormat.MEDIUM); try { Date introduce=parser.parse(bill.introduced_on); String str=printer.format(introduce); bill_introduce.setText(str); } catch (ParseException e) { e.printStackTrace(); } if(bill.last_version.urls.pdf==null){ bill_url.setText("N.A."); } else { bill_url.setText(bill.last_version.urls.pdf); } if(bill.urls.congress==null){ bill_congress.setText("N.A."); }else { bill_congress.setText(bill.urls.congress); } if(bill.history.active.equals("true")){ bill_status.setText("Active"); } else{ bill_status.setText("New"); } bill_chamber.setText(WordUtils.capitalize(bill.chamber)); if(bill.last_version.version_name==null){ bill_version.setText("N.A."); } else { bill_version.setText(bill.last_version.version_name); } } }
UTF-8
Java
5,400
java
BillDetail.java
Java
[ { "context": "ception;\nimport java.util.Date;\n\n/**\n * Created by lenovo on 2016/11/20.\n */\n\npublic class BillDetail exten", "end": 643, "score": 0.9995719194412231, "start": 637, "tag": "USERNAME", "value": "lenovo" } ]
null
[]
package com.ziqianfu.congresssearch; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.PersistableBundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.TextView; import android.widget.ViewSwitcher; import com.google.gson.Gson; import org.apache.commons.lang3.text.WordUtils; import org.apache.commons.lang3.time.FastDateFormat; import java.text.ParseException; import java.util.Date; /** * Created by lenovo on 2016/11/20. */ public class BillDetail extends AppCompatActivity { private TextView bill_id; private TextView bill_title; private TextView bill_type; private TextView bill_sponsor; private TextView bill_introduce; private TextView bill_status; private TextView bill_congress; private TextView bill_url; private TextView bill_version; private TextView bill_chamber; private ImageSwitcher favor_btn; private BillItem bill; private boolean saved; SharedPreferences preferences; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.bills_details); preferences=getSharedPreferences("favor_bills", MODE_APPEND); final SharedPreferences.Editor editor=preferences.edit(); Toolbar mtoolbar = (Toolbar) findViewById(R.id.tool_bar_bill); setSupportActionBar(mtoolbar); //getSupportActionBar().setTitle("Bills"); mtoolbar.setNavigationIcon(R.drawable.ic_arrow_back_white); mtoolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); getSupportActionBar().setTitle("Bill Info"); favor_btn=(ImageSwitcher)findViewById(R.id.favorite_button); bill_id=(TextView)findViewById(R.id.bill_id_data); bill_title=(TextView)findViewById(R.id.bill_title_data); bill_type=(TextView)findViewById(R.id.bill_type_data); bill_sponsor=(TextView)findViewById(R.id.bill_sponsor_data); bill_introduce=(TextView)findViewById(R.id.biil_introduce_data); bill_status=(TextView)findViewById(R.id.biil_status_data); bill_congress=(TextView)findViewById(R.id.bill_congress_data); bill_url=(TextView)findViewById(R.id.biil_url_data); bill_version=(TextView)findViewById(R.id.biil_version_data); bill_chamber=(TextView)findViewById(R.id.bill_chamber_data); Intent intent=getIntent(); final Gson gson=new Gson(); bill=gson.fromJson(intent.getStringExtra("bill_detail"), BillItem.class); favor_btn.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { return new ImageView(BillDetail.this); } }); favor_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(saved==false){ favor_btn.setImageResource(R.drawable.star_filled); saved=true; editor.putString(bill.bill_id, gson.toJson(bill, BillItem.class)); editor.commit(); } else { favor_btn.setImageResource(R.drawable.star_empty); saved=false; editor.remove(bill.bill_id); editor.commit(); } } }); if(preferences.getString(bill.bill_id, "0").equals("0")){ saved=false; favor_btn.setImageResource(R.drawable.star_empty); } else { saved=true; favor_btn.setImageResource(R.drawable.star_filled); } bill_sponsor.setText(bill.sponsor.title+". "+bill.sponsor.last_name+", "+bill.sponsor.first_name); bill_id.setText(bill.bill_id); bill_title.setText(bill.official_title); bill_type.setText(bill.bill_type); FastDateFormat parser=FastDateFormat.getInstance("yyyy-MM-dd"); FastDateFormat printer=FastDateFormat.getDateInstance(FastDateFormat.MEDIUM); try { Date introduce=parser.parse(bill.introduced_on); String str=printer.format(introduce); bill_introduce.setText(str); } catch (ParseException e) { e.printStackTrace(); } if(bill.last_version.urls.pdf==null){ bill_url.setText("N.A."); } else { bill_url.setText(bill.last_version.urls.pdf); } if(bill.urls.congress==null){ bill_congress.setText("N.A."); }else { bill_congress.setText(bill.urls.congress); } if(bill.history.active.equals("true")){ bill_status.setText("Active"); } else{ bill_status.setText("New"); } bill_chamber.setText(WordUtils.capitalize(bill.chamber)); if(bill.last_version.version_name==null){ bill_version.setText("N.A."); } else { bill_version.setText(bill.last_version.version_name); } } }
5,400
0.628519
0.625926
146
35.986301
22.719851
106
false
false
0
0
0
0
0
0
0.657534
false
false
5
8be19407e92e556793b77bcc14e527683d4cebc0
26,903,675,149,976
b4c19f9dd871766ceb42a3e7e0427bd3e047cc25
/Lab006.java
4d94b0e487ede166f114e205e741fa79fdd147ac
[]
no_license
Prayasjain78/javaprogram
https://github.com/Prayasjain78/javaprogram
80a091cff24c1d061b6740b955c942ac23d322ed
9572ce8402ce634417afafaad5b2cdd93ad67084
refs/heads/master
2020-04-11T04:32:27.611000
2018-12-24T17:35:13
2018-12-24T17:35:13
161,515,487
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package HelloWorld; public class Lab006 { public static void main(String[] args) { String str; int a; str="JLC"; a=99; System.out.println(str);//JLC System.out.println(a);//99 } }
UTF-8
Java
187
java
Lab006.java
Java
[]
null
[]
package HelloWorld; public class Lab006 { public static void main(String[] args) { String str; int a; str="JLC"; a=99; System.out.println(str);//JLC System.out.println(a);//99 } }
187
0.679144
0.641711
12
14.583333
12.352181
40
false
false
0
0
0
0
0
0
1.083333
false
false
5
420301f74b4012738b54badbe5234e01b2ec76d5
24,472,723,667,197
9509435e5ffd711fe511a9274d044d63e0cde2d8
/sodonto-system-web/src/gui/conversor/EstabelecimentoConverter.java
45b0a9ba0db455090887af1ba6cad1c70944b13b
[]
no_license
hmirandadeveloper/hsm-dental-system-java-ee
https://github.com/hmirandadeveloper/hsm-dental-system-java-ee
40b7b398ac7bb28048b8e76525a44d0c9cfa9fa6
d1838ad978835289d4f99aebd905a2fe2b918d9e
refs/heads/master
2020-04-09T11:46:48.455000
2018-12-04T08:28:03
2018-12-04T08:28:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gui.conversor; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import dto.EstabelecimentoDTO; public class EstabelecimentoConverter implements Converter{ @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { EstabelecimentoDTO estabelecimentoDTO = null; if(value != null && !value.equals("")) { estabelecimentoDTO = (EstabelecimentoDTO)component.getAttributes().get(value); } return estabelecimentoDTO; } @Override public String getAsString(FacesContext context, UIComponent component, Object object) { if(object != null && object instanceof EstabelecimentoDTO) { EstabelecimentoDTO estabelecimentoDTO = (EstabelecimentoDTO)object; component.getAttributes().put(estabelecimentoDTO.getCnpj(), estabelecimentoDTO); return estabelecimentoDTO.getCnpj(); } return ""; } }
UTF-8
Java
942
java
EstabelecimentoConverter.java
Java
[]
null
[]
package gui.conversor; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import dto.EstabelecimentoDTO; public class EstabelecimentoConverter implements Converter{ @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { EstabelecimentoDTO estabelecimentoDTO = null; if(value != null && !value.equals("")) { estabelecimentoDTO = (EstabelecimentoDTO)component.getAttributes().get(value); } return estabelecimentoDTO; } @Override public String getAsString(FacesContext context, UIComponent component, Object object) { if(object != null && object instanceof EstabelecimentoDTO) { EstabelecimentoDTO estabelecimentoDTO = (EstabelecimentoDTO)object; component.getAttributes().put(estabelecimentoDTO.getCnpj(), estabelecimentoDTO); return estabelecimentoDTO.getCnpj(); } return ""; } }
942
0.773885
0.773885
34
26.705883
27.044113
83
false
false
0
0
0
0
0
0
1.735294
false
false
5
ea6054ec4ce15803fb6b896b51191774050ed6e9
21,045,339,774,209
08ee4cd997a5e598c691213c20bc0252675dca67
/week-0/java/week-0/day5/Heat.java
8138c96d7586cc382018c99624effcfce3377407
[]
no_license
cvaishnav026/vaishnav
https://github.com/cvaishnav026/vaishnav
1c2c7256a88580373d44fa0be7ff11eb221a1b4c
90ee6762478c25576ab6c3b12a6d09e58ba4b768
refs/heads/master
2020-05-21T19:39:29.639000
2016-09-20T11:30:37
2016-09-20T11:30:37
60,060,998
0
0
null
false
2016-09-18T19:23:03
2016-05-31T05:37:53
2016-08-10T15:26:31
2016-09-18T19:23:03
37,446
0
0
3
Java
null
null
import java.lang.*; class Heat { public static void main(String ar[]) { int C=67; float F,n,d; n=9f; d=5f; F=(C*(n/d))+32; System.out.println("celseius C: "+C+"degrees \n"); System.out.println("Fahrenheit F: "+F+"degrees \n"); } }
UTF-8
Java
278
java
Heat.java
Java
[]
null
[]
import java.lang.*; class Heat { public static void main(String ar[]) { int C=67; float F,n,d; n=9f; d=5f; F=(C*(n/d))+32; System.out.println("celseius C: "+C+"degrees \n"); System.out.println("Fahrenheit F: "+F+"degrees \n"); } }
278
0.528777
0.507194
19
12.736842
16.379841
54
false
false
0
0
0
0
0
0
1.842105
false
false
5
27aed5f4b00a24cac3b526e0d96c4e6fb00ccb0a
16,363,825,437,342
76a815ff9a4e64ef06518dec2d94a1f8e1932bba
/shopping/src/com/qzp/controller/AdminLoginServlet.java
df272e9f1b99cc0b7d8c16d4faf5fcb3cff7d4a1
[]
no_license
Qzp990425/shopping
https://github.com/Qzp990425/shopping
0163b54d2ce4e78bed0e862668b44d03985b870e
942bf1a340416443a0a833bd7c82a5e096c2f6a7
refs/heads/master
2020-07-01T15:20:01.476000
2019-08-10T03:22:02
2019-08-10T03:22:02
201,209,011
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qzp.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.qzp.domain.Admin; import com.qzp.domain.User; import com.qzp.service.LoginService; public class AdminLoginServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String account = request.getParameter("account"); String password = request.getParameter("password"); String mess = ""; if("".equals(account)||"".equals(password)) { mess = "输入的信息不能为空"; request.setAttribute("mess", mess); request.getRequestDispatcher("/WEB-INF/jsp/adminLogin.jsp").forward(request, response); } else { Admin admin = new Admin(); admin.setAccount(account); admin.setPassword(password); LoginService loginService = new LoginService(); if(!loginService.haveAdmin(admin)) { mess = "输入的账号或密码错误"; request.setAttribute("mess", mess); request.getRequestDispatcher("/login.jsp").forward(request, response); } else { admin = loginService.getAdmin(admin); request.getSession().setAttribute("admin", admin); request.getRequestDispatcher("/WEB-INF/jsp/admin.jsp").forward(request, response); } } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub this.doPost(request, response); } }
UTF-8
Java
1,768
java
AdminLoginServlet.java
Java
[ { "context": "\tadmin.setAccount(account);\r\n\t\t\tadmin.setPassword(password);\r\n\t\t\tLoginService loginService = new LoginServi", "end": 1058, "score": 0.9971588850021362, "start": 1050, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.qzp.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.qzp.domain.Admin; import com.qzp.domain.User; import com.qzp.service.LoginService; public class AdminLoginServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String account = request.getParameter("account"); String password = request.getParameter("password"); String mess = ""; if("".equals(account)||"".equals(password)) { mess = "输入的信息不能为空"; request.setAttribute("mess", mess); request.getRequestDispatcher("/WEB-INF/jsp/adminLogin.jsp").forward(request, response); } else { Admin admin = new Admin(); admin.setAccount(account); admin.setPassword(<PASSWORD>); LoginService loginService = new LoginService(); if(!loginService.haveAdmin(admin)) { mess = "输入的账号或密码错误"; request.setAttribute("mess", mess); request.getRequestDispatcher("/login.jsp").forward(request, response); } else { admin = loginService.getAdmin(admin); request.getSession().setAttribute("admin", admin); request.getRequestDispatcher("/WEB-INF/jsp/admin.jsp").forward(request, response); } } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub this.doPost(request, response); } }
1,770
0.731214
0.730058
48
34.041668
28.118023
119
false
false
0
0
0
0
0
0
2.583333
false
false
5
c8cdc9435c54d5f893619944d5b2c9005eb2ee3a
29,918,742,225,732
0427b129d87adc67c78651e879da47b63974f94c
/src/main/java/com/primefaces/hibernate/dao/AddressDAO.java
bbe4b20d38b1a76fc056a290f4399385ac362f70
[]
no_license
flammiag/asta_fantacalcio
https://github.com/flammiag/asta_fantacalcio
013c5044d6af039502316b7763a6cdfdd8ebe2e6
2c20ca7c0c9134ae18f8edf46efac9c5200e5bd7
refs/heads/master
2021-01-19T19:01:45.833000
2017-10-07T15:05:43
2017-10-07T15:05:43
101,179,081
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.primefaces.hibernate.dao; import com.primefaces.hibernate.Idao.IAddressDAO; import com.primefaces.hibernate.generic.GenericDaoImpl; import com.primefaces.hibernate.model.Address; import com.primefaces.hibernate.model.City; import com.primefaces.hibernate.model.Country; import com.primefaces.hibernate.model.Employees; import com.primefaces.hibernate.util.HibernateUtil; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.apache.log4j.Logger; public class AddressDAO extends GenericDaoImpl<Address, Short> implements IAddressDAO { private static final Logger LOG = Logger.getLogger(AddressDAO.class); @Override public void create(Country country, City city, Address address) { Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); city.setCountry(country); address.setCity(city); session.save(address); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("AddressDAO - createAddress() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } } @Override public void addToEmmployees(Address address, List<Employees> empsList) { Session session = HibernateUtil.getSessionFactory().openSession(); // try { // session.beginTransaction(); // empsList.stream().forEach((emp) -> { // emp.setAddress(address); // session.saveOrUpdate(emp); // }); // session.getTransaction().commit(); // } catch (RuntimeException e) { // LOG.error("AddressDAO - addAddressToEmployees() failed, " + e.getMessage(), e); // } finally { // session.flush(); // session.close(); // } } @Override public Address findByName(String address, String address2) { List<Address> result = new ArrayList<>(); Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); String hql = "from Address a where a.address = :address and a.address2 = :address2"; result = session.createQuery(hql) .setString("address", address) .setString("address2", address2) .list(); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("AddressDAO - findAddressByName() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } if(result.size() > 0) return result.get(0); return null; } @Override public Address findOfEmployee(Employees employee) { Address address = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); List<Employees> emps = session.createQuery("from Employees e join fetch e.address where e.id = :id") .setInteger("id", employee.getId()) .list(); if(emps.size() > 0) { Employees emp = emps.get(0); address = emp.getAddress(); } session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("AddressDAO - findAddressOfEmployee() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } return address; } @Override public List<Address> findFromCity(City city) { List<Address> addressList = new ArrayList<>(); Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); addressList = session.createQuery("from Address a where a.city = :city") .setEntity("city", city) .list(); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("AddressDAO - findAddressFromCity() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } return addressList; } @Override public List<Address> list() { List<Address> addressList = new ArrayList<>(); Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); addressList = session.createQuery("from Address").list(); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("AddressDAO - listAddress() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } return addressList; } }
UTF-8
Java
5,221
java
AddressDAO.java
Java
[]
null
[]
package com.primefaces.hibernate.dao; import com.primefaces.hibernate.Idao.IAddressDAO; import com.primefaces.hibernate.generic.GenericDaoImpl; import com.primefaces.hibernate.model.Address; import com.primefaces.hibernate.model.City; import com.primefaces.hibernate.model.Country; import com.primefaces.hibernate.model.Employees; import com.primefaces.hibernate.util.HibernateUtil; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.apache.log4j.Logger; public class AddressDAO extends GenericDaoImpl<Address, Short> implements IAddressDAO { private static final Logger LOG = Logger.getLogger(AddressDAO.class); @Override public void create(Country country, City city, Address address) { Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); city.setCountry(country); address.setCity(city); session.save(address); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("AddressDAO - createAddress() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } } @Override public void addToEmmployees(Address address, List<Employees> empsList) { Session session = HibernateUtil.getSessionFactory().openSession(); // try { // session.beginTransaction(); // empsList.stream().forEach((emp) -> { // emp.setAddress(address); // session.saveOrUpdate(emp); // }); // session.getTransaction().commit(); // } catch (RuntimeException e) { // LOG.error("AddressDAO - addAddressToEmployees() failed, " + e.getMessage(), e); // } finally { // session.flush(); // session.close(); // } } @Override public Address findByName(String address, String address2) { List<Address> result = new ArrayList<>(); Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); String hql = "from Address a where a.address = :address and a.address2 = :address2"; result = session.createQuery(hql) .setString("address", address) .setString("address2", address2) .list(); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("AddressDAO - findAddressByName() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } if(result.size() > 0) return result.get(0); return null; } @Override public Address findOfEmployee(Employees employee) { Address address = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); List<Employees> emps = session.createQuery("from Employees e join fetch e.address where e.id = :id") .setInteger("id", employee.getId()) .list(); if(emps.size() > 0) { Employees emp = emps.get(0); address = emp.getAddress(); } session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("AddressDAO - findAddressOfEmployee() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } return address; } @Override public List<Address> findFromCity(City city) { List<Address> addressList = new ArrayList<>(); Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); addressList = session.createQuery("from Address a where a.city = :city") .setEntity("city", city) .list(); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("AddressDAO - findAddressFromCity() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } return addressList; } @Override public List<Address> list() { List<Address> addressList = new ArrayList<>(); Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); addressList = session.createQuery("from Address").list(); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("AddressDAO - listAddress() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } return addressList; } }
5,221
0.553151
0.551235
140
35.292858
24.749746
112
false
false
0
0
0
0
0
0
0.657143
false
false
5
c5ebe0460cfde5c638c32a5381884ba8dfa21955
26,525,718,037,903
56debfa7d5224130ec9dba98fc3f85773e486ab6
/Kotlin-Projects/Java8API/src/com/app/Main.java
dfdf6033b9bd6f5b28c8c93c4d7b4a5ceeaf9eb7
[]
no_license
pobsaeng/MyCode
https://github.com/pobsaeng/MyCode
53d8e864b975a3d8e4dde8193f5f6349440fd0b0
006c09af8ebefede40861132e9e3f4af60320293
refs/heads/master
2020-08-15T10:38:00.084000
2019-10-15T14:55:52
2019-10-15T14:55:52
215,325,435
0
0
null
false
2020-07-31T23:52:11
2019-10-15T14:53:50
2019-10-15T14:57:31
2020-07-31T23:52:10
76,291
0
0
59
TSQL
false
false
package com.app; import com.app.java8.bean.Person; import com.app.model.Averager; import com.app.model.DatabaseQuery; import com.app.model.Book; import com.app.model.Item; import java.util.*; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main { public void printBook(Book book) { System.out.println(book); } public void outside() { } public static void main(String[] args) { DatabaseQuery db = new DatabaseQuery(); List<Book> bookList = db.getBooks("select * from book"); //lambda expression // bookList.forEach(System.out::println); //method reference //bookList.forEach(new Main()::printBook); System.out.println("---------------------------------------------"); /* * The JDK contains many terminal operations (such as average, sum, min, max, and count) * that return one value by combining the contents of a stream. */ //average double bookAvg = bookList .stream() .filter(p -> p.getAuthors().startsWith("")) .mapToInt(Book::getPrice) .average() .getAsDouble(); //System.out.println(bookAvg); //sum Integer bookSum = bookList .stream() .mapToInt(Book::getPrice) .sum(); //System.out.println(bookSum); //reduce Integer booSumReduce = bookList .stream() .map(Book::getPrice) .reduce(0, (a, b) -> a + b); //System.out.println(booSumReduce); // Stream<Book> bookGroupby = bookList // .stream() // .map(Book:: new); Map<Integer, List<Book>> item = bookList .stream() .map(Book::new).collect(Collectors.groupingBy(Book::getPrice)); int maxPrice = bookList.stream() .map(Book::getPrice) .max(Comparator.comparing(b->b.doubleValue())).get(); System.out.println(maxPrice); //.map(Book::new Book(book.getId(), book.getTitle(), ..)) // List<Book> listBook = bookList.stream().map(Book::new).collect(Collectors.toList()); // List<Book> listBook = bookStream.collect(Collectors.toList()); //convert to List // listBook.forEach(System.out::println); } }
UTF-8
Java
2,494
java
Main.java
Java
[]
null
[]
package com.app; import com.app.java8.bean.Person; import com.app.model.Averager; import com.app.model.DatabaseQuery; import com.app.model.Book; import com.app.model.Item; import java.util.*; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main { public void printBook(Book book) { System.out.println(book); } public void outside() { } public static void main(String[] args) { DatabaseQuery db = new DatabaseQuery(); List<Book> bookList = db.getBooks("select * from book"); //lambda expression // bookList.forEach(System.out::println); //method reference //bookList.forEach(new Main()::printBook); System.out.println("---------------------------------------------"); /* * The JDK contains many terminal operations (such as average, sum, min, max, and count) * that return one value by combining the contents of a stream. */ //average double bookAvg = bookList .stream() .filter(p -> p.getAuthors().startsWith("")) .mapToInt(Book::getPrice) .average() .getAsDouble(); //System.out.println(bookAvg); //sum Integer bookSum = bookList .stream() .mapToInt(Book::getPrice) .sum(); //System.out.println(bookSum); //reduce Integer booSumReduce = bookList .stream() .map(Book::getPrice) .reduce(0, (a, b) -> a + b); //System.out.println(booSumReduce); // Stream<Book> bookGroupby = bookList // .stream() // .map(Book:: new); Map<Integer, List<Book>> item = bookList .stream() .map(Book::new).collect(Collectors.groupingBy(Book::getPrice)); int maxPrice = bookList.stream() .map(Book::getPrice) .max(Comparator.comparing(b->b.doubleValue())).get(); System.out.println(maxPrice); //.map(Book::new Book(book.getId(), book.getTitle(), ..)) // List<Book> listBook = bookList.stream().map(Book::new).collect(Collectors.toList()); // List<Book> listBook = bookStream.collect(Collectors.toList()); //convert to List // listBook.forEach(System.out::println); } }
2,494
0.555333
0.554531
86
27.988373
24.037033
96
false
false
0
0
0
0
0
0
0.453488
false
false
5
5cdd1da2e5f845021240c42213fa7266c1b909f4
3,702,261,828,856
902b0f6aa69e189910f39efc165c27e30490558d
/src/kumagai/smartviewer/Prediction.java
172a080d1d9a05b95c44c74f78c81dd0a58954a4
[]
no_license
iariro/JSPSmartViewer
https://github.com/iariro/JSPSmartViewer
c6570b28acd4f1ccc286b7be8abb916e3fa94aad
a5922a706012762a0851dfb968352950c29422a9
refs/heads/master
2021-01-19T00:28:21.468000
2019-12-30T06:31:42
2019-12-30T06:31:42
87,172,679
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kumagai.smartviewer; import ktool.datetime.DateTime; /** * 故障予測情報 */ public class Prediction { static private final long maxSecond = 1000000000; public int time1; public DateTime datetime1; public long value1; public int time2; public DateTime datetime2; public long value2; public long remainingHour1; public long remainingSecond2; /** * 予測故障日を算出 * @return 予測故障日 */ public DateTime getDeadDate1() { DateTime now = new DateTime(datetime2); for (long second = 3600 * remainingHour1;second>0;second-=maxSecond) { if (second > maxSecond) { now.add((int)maxSecond); } else { now.add((int)second); } } return now; } /** * 予測故障日を算出 * @return 予測故障日 */ public DateTime getDeadDate2() { DateTime now = new DateTime(datetime2); for (long second = remainingSecond2;second>0;second-=maxSecond) { if (second > maxSecond) { now.add((int)maxSecond); } else { now.add((int)second); } } return now; } /** * 予測寿命を返却 * @return 予測寿命 */ public int getRemainingHour2() { return (int)(remainingSecond2 / 3600); } /** * 指定の値をメンバーに割り当て * @param time1 基準稼働時間 * @param datetime1 基準日時 * @param value1 基準値 * @param time2 現在稼働時間 * @param datetime2 現在日時 * @param value2 現在値 * @param remainingHour1 残り時間 * @param remainingSecond2 残り時間 */ public Prediction(int time1, DateTime datetime1, long value1, int time2, DateTime datetime2, long value2, long remainingHour1, long remainingSecond2) { this.time1 = time1; this.datetime1 = datetime1; this.value1 = value1; this.time2 = time2; this.datetime2 = datetime2; this.value2 = value2; this.remainingHour1 = remainingHour1; this.remainingSecond2 = remainingSecond2; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return String.format( "%d:%d -> %d:%d = %d:0 %s", time1, value1, time2, value2, remainingHour1, getDeadDate1()); } }
UTF-8
Java
2,175
java
Prediction.java
Java
[]
null
[]
package kumagai.smartviewer; import ktool.datetime.DateTime; /** * 故障予測情報 */ public class Prediction { static private final long maxSecond = 1000000000; public int time1; public DateTime datetime1; public long value1; public int time2; public DateTime datetime2; public long value2; public long remainingHour1; public long remainingSecond2; /** * 予測故障日を算出 * @return 予測故障日 */ public DateTime getDeadDate1() { DateTime now = new DateTime(datetime2); for (long second = 3600 * remainingHour1;second>0;second-=maxSecond) { if (second > maxSecond) { now.add((int)maxSecond); } else { now.add((int)second); } } return now; } /** * 予測故障日を算出 * @return 予測故障日 */ public DateTime getDeadDate2() { DateTime now = new DateTime(datetime2); for (long second = remainingSecond2;second>0;second-=maxSecond) { if (second > maxSecond) { now.add((int)maxSecond); } else { now.add((int)second); } } return now; } /** * 予測寿命を返却 * @return 予測寿命 */ public int getRemainingHour2() { return (int)(remainingSecond2 / 3600); } /** * 指定の値をメンバーに割り当て * @param time1 基準稼働時間 * @param datetime1 基準日時 * @param value1 基準値 * @param time2 現在稼働時間 * @param datetime2 現在日時 * @param value2 現在値 * @param remainingHour1 残り時間 * @param remainingSecond2 残り時間 */ public Prediction(int time1, DateTime datetime1, long value1, int time2, DateTime datetime2, long value2, long remainingHour1, long remainingSecond2) { this.time1 = time1; this.datetime1 = datetime1; this.value1 = value1; this.time2 = time2; this.datetime2 = datetime2; this.value2 = value2; this.remainingHour1 = remainingHour1; this.remainingSecond2 = remainingSecond2; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return String.format( "%d:%d -> %d:%d = %d:0 %s", time1, value1, time2, value2, remainingHour1, getDeadDate1()); } }
2,175
0.657301
0.619669
111
16.954954
19.111521
150
false
false
0
0
0
0
0
0
2.018018
false
false
5
34aebcb2dcc1b54578d54f2bd0ad6f3450b0ef94
25,409,026,548,206
255afee7036a29c5ea68c86b1dea2cf0d6f24c15
/jacklyn-file/src/main/java/com/tcdng/jacklyn/file/entities/FileInbox.java
5d4e2ae5299ff3d1d6b663aad402193d25eee34a
[ "Apache-2.0" ]
permissive
tcdng/jacklyn-codebase
https://github.com/tcdng/jacklyn-codebase
2bb4a60ad7d12ead4d4b8d3c4c3963dcea69514d
4bc2253c18dbf45f56a73a930885f474e7b2682e
refs/heads/master
2022-06-29T01:18:34.508000
2022-06-19T07:30:24
2022-06-19T07:30:24
160,588,947
4
3
Apache-2.0
false
2022-06-19T07:30:24
2018-12-05T22:55:16
2021-01-15T22:22:55
2022-06-19T07:30:24
4,529
4
3
0
Java
false
false
/* * Copyright 2018-2020 The Code Department. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.tcdng.jacklyn.file.entities; import java.util.Date; import com.tcdng.jacklyn.common.annotation.Format; import com.tcdng.jacklyn.common.annotation.Managed; import com.tcdng.jacklyn.common.entities.ColumnPositionConstants; import com.tcdng.jacklyn.file.constants.FileModuleNameConstants; import com.tcdng.jacklyn.shared.file.FileInboxReadStatus; import com.tcdng.jacklyn.shared.file.FileInboxStatus; import com.tcdng.unify.core.annotation.Column; import com.tcdng.unify.core.annotation.ColumnType; import com.tcdng.unify.core.annotation.Table; import com.tcdng.unify.core.constant.HAlignType; /** * Entity for storing file inbox item information. * * @author Lateef Ojulari * @since 1.0 */ @Managed(module = FileModuleNameConstants.FILE_MODULE, title = "File Inbox", reportable = true, auditable = true) @Table("JKFILEINBOX") public class FileInbox extends AbstractFileTransferBox { @Format(halign = HAlignType.RIGHT) @Column private int downloadAttempts; @Column(type = ColumnType.TIMESTAMP_UTC, nullable = true) private Date downloadedOn; @Format(description = "$m{file.fileinbox.readstatus}", halign = HAlignType.CENTER) @Column private FileInboxReadStatus readStatus; @Column(name = "REC_ST", position = ColumnPositionConstants.BASE_COLUMN_POSITION) private FileInboxStatus status; public int getDownloadAttempts() { return downloadAttempts; } public void setDownloadAttempts(int downloadAttempts) { this.downloadAttempts = downloadAttempts; } public Date getDownloadedOn() { return downloadedOn; } public void setDownloadedOn(Date downloadedOn) { this.downloadedOn = downloadedOn; } public FileInboxStatus getStatus() { return status; } public void setStatus(FileInboxStatus status) { this.status = status; } public void setReadStatus(FileInboxReadStatus readStatus) { this.readStatus = readStatus; } public FileInboxReadStatus getReadStatus() { return readStatus; } }
UTF-8
Java
2,767
java
FileInbox.java
Java
[ { "context": "ring file inbox item information.\r\n * \r\n * @author Lateef Ojulari\r\n * @since 1.0\r\n */\r\n@Managed(module = FileModule", "end": 1331, "score": 0.9998804926872253, "start": 1317, "tag": "NAME", "value": "Lateef Ojulari" } ]
null
[]
/* * Copyright 2018-2020 The Code Department. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.tcdng.jacklyn.file.entities; import java.util.Date; import com.tcdng.jacklyn.common.annotation.Format; import com.tcdng.jacklyn.common.annotation.Managed; import com.tcdng.jacklyn.common.entities.ColumnPositionConstants; import com.tcdng.jacklyn.file.constants.FileModuleNameConstants; import com.tcdng.jacklyn.shared.file.FileInboxReadStatus; import com.tcdng.jacklyn.shared.file.FileInboxStatus; import com.tcdng.unify.core.annotation.Column; import com.tcdng.unify.core.annotation.ColumnType; import com.tcdng.unify.core.annotation.Table; import com.tcdng.unify.core.constant.HAlignType; /** * Entity for storing file inbox item information. * * @author <NAME> * @since 1.0 */ @Managed(module = FileModuleNameConstants.FILE_MODULE, title = "File Inbox", reportable = true, auditable = true) @Table("JKFILEINBOX") public class FileInbox extends AbstractFileTransferBox { @Format(halign = HAlignType.RIGHT) @Column private int downloadAttempts; @Column(type = ColumnType.TIMESTAMP_UTC, nullable = true) private Date downloadedOn; @Format(description = "$m{file.fileinbox.readstatus}", halign = HAlignType.CENTER) @Column private FileInboxReadStatus readStatus; @Column(name = "REC_ST", position = ColumnPositionConstants.BASE_COLUMN_POSITION) private FileInboxStatus status; public int getDownloadAttempts() { return downloadAttempts; } public void setDownloadAttempts(int downloadAttempts) { this.downloadAttempts = downloadAttempts; } public Date getDownloadedOn() { return downloadedOn; } public void setDownloadedOn(Date downloadedOn) { this.downloadedOn = downloadedOn; } public FileInboxStatus getStatus() { return status; } public void setStatus(FileInboxStatus status) { this.status = status; } public void setReadStatus(FileInboxReadStatus readStatus) { this.readStatus = readStatus; } public FileInboxReadStatus getReadStatus() { return readStatus; } }
2,759
0.714492
0.709433
86
30.174419
27.569445
113
false
false
0
0
0
0
0
0
0.406977
false
false
5
17def75689197e93226c0d56986e185307346d15
25,409,026,547,707
9653ee6bf6b7018126f3fffd07c7a62de028f841
/authority-mapper/src/main/java/org/authority/mapper/BaseDictionaryDetailMapper.java
c744e97b34c9016bf98fb7e8cd752231562052f0
[]
no_license
moutainhigh/cn.chenyongcan.cloud
https://github.com/moutainhigh/cn.chenyongcan.cloud
b6bbbf1eda12d91d6ccd9acb0e3af9f5d9e02ab8
baef970bf30c54631c9a8f535f90308ec7da448f
refs/heads/master
2020-09-10T06:27:33.794000
2019-11-14T09:30:08
2019-11-14T09:30:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.authority.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import org.authority.domain.BaseDictionaryDetailEntity; import com.github.pagehelper.Page; public interface BaseDictionaryDetailMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int deleteByPrimaryKey(String id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int insert(BaseDictionaryDetailEntity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int insertSelective(BaseDictionaryDetailEntity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ BaseDictionaryDetailEntity selectByPrimaryKey(String id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int updateByPrimaryKeySelective(BaseDictionaryDetailEntity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int updateByPrimaryKeyWithBLOBs(BaseDictionaryDetailEntity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int updateByPrimaryKey(BaseDictionaryDetailEntity record); Page<BaseDictionaryDetailEntity> ListByPage(BaseDictionaryDetailEntity record); void setDeleted(@Param("ids") List<String> ids); void deleteByCode(@Param("dictionaryCode") String dictionaryCode); List<BaseDictionaryDetailEntity> listByCode(@Param("dictionaryCode") String dictionaryCode); }
UTF-8
Java
2,370
java
BaseDictionaryDetailMapper.java
Java
[]
null
[]
package org.authority.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import org.authority.domain.BaseDictionaryDetailEntity; import com.github.pagehelper.Page; public interface BaseDictionaryDetailMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int deleteByPrimaryKey(String id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int insert(BaseDictionaryDetailEntity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int insertSelective(BaseDictionaryDetailEntity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ BaseDictionaryDetailEntity selectByPrimaryKey(String id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int updateByPrimaryKeySelective(BaseDictionaryDetailEntity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int updateByPrimaryKeyWithBLOBs(BaseDictionaryDetailEntity record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table dictionary_detail * * @mbg.generated Thu Nov 07 15:40:12 CST 2019 */ int updateByPrimaryKey(BaseDictionaryDetailEntity record); Page<BaseDictionaryDetailEntity> ListByPage(BaseDictionaryDetailEntity record); void setDeleted(@Param("ids") List<String> ids); void deleteByCode(@Param("dictionaryCode") String dictionaryCode); List<BaseDictionaryDetailEntity> listByCode(@Param("dictionaryCode") String dictionaryCode); }
2,370
0.711392
0.675949
74
31.040541
28.176298
93
false
false
0
0
0
0
0
0
0.283784
false
false
5
ad52b757824fe1bae3d97b5dbe8d5a4c754e4216
33,432,025,463,322
c367bf2f1190a34fb1c06b1a341ea484f8af9d1a
/src/main/java/com/shortthirdman/core/network/http/PasswordProtectedAccess.java
88ec2ed1e8e3c51cb9c6a6b1799903d0cfa1638a
[ "MIT" ]
permissive
shortthirdman/java-core
https://github.com/shortthirdman/java-core
e57d0c06ee2c47b9ba6c1d4b007422160935a124
af2b5f8949fbd867e418558660f54fcd0a01d2e6
refs/heads/master
2022-07-08T18:25:32.305000
2021-01-21T11:17:37
2021-01-21T11:17:37
91,598,597
0
0
MIT
false
2022-08-09T16:54:53
2017-05-17T16:38:29
2022-08-09T16:52:40
2022-08-09T16:54:52
230
0
0
0
Java
false
false
package com.shortthirdman.core.network.http; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.InetAddress; import java.net.PasswordAuthentication; import java.net.URL; public class PasswordProtectedAccess { public static void main(String[] argv) throws Exception { Authenticator.setDefault(new CustomAuthenticator()); URL url = new URL("http://hostname:80/index.html"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } } class CustomAuthenticator extends Authenticator { protected PasswordAuthentication getPasswordAuthentication() { String promptString = getRequestingPrompt(); System.out.println(promptString); String hostname = getRequestingHost(); System.out.println(hostname); InetAddress ipaddr = getRequestingSite(); System.out.println(ipaddr); int port = getRequestingPort(); String username = "name"; String password = "password"; return new PasswordAuthentication(username, password.toCharArray()); } }
UTF-8
Java
1,228
java
PasswordProtectedAccess.java
Java
[ { "context": " = getRequestingPort();\r\n\r\n String username = \"name\";\r\n String password = \"password\";\r\n return ", "end": 1109, "score": 0.9960782527923584, "start": 1105, "tag": "USERNAME", "value": "name" }, { "context": "String username = \"name\";\r\n String password = \"password\";\r\n return new PasswordAuthentication(username", "end": 1144, "score": 0.9994273781776428, "start": 1136, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.shortthirdman.core.network.http; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.InetAddress; import java.net.PasswordAuthentication; import java.net.URL; public class PasswordProtectedAccess { public static void main(String[] argv) throws Exception { Authenticator.setDefault(new CustomAuthenticator()); URL url = new URL("http://hostname:80/index.html"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } } class CustomAuthenticator extends Authenticator { protected PasswordAuthentication getPasswordAuthentication() { String promptString = getRequestingPrompt(); System.out.println(promptString); String hostname = getRequestingHost(); System.out.println(hostname); InetAddress ipaddr = getRequestingSite(); System.out.println(ipaddr); int port = getRequestingPort(); String username = "name"; String password = "<PASSWORD>"; return new PasswordAuthentication(username, password.toCharArray()); } }
1,230
0.711726
0.710098
39
29.538462
22.21093
84
false
false
0
0
0
0
0
0
0.615385
false
false
5
657a4ed306a4187f14910291bba040607d668741
13,572,096,704,626
bb15fb027cde570fcf5beea55fd267d2038d1dcf
/WebDS/src/main/java/lightning/webds/handler/AuthSuccessHandler.java
03e05b3cd7471082dd4c01649b62a0e117f10527
[]
no_license
frc-862/WebDS
https://github.com/frc-862/WebDS
8e746f9e3519853525e96c23a41fe8c8b8aee816
ef2dfda764b454ca7bc0bfc49282139efef986bf
refs/heads/master
2023-02-06T13:29:15.510000
2020-12-24T01:54:52
2020-12-24T01:54:52
273,778,345
3
2
null
false
2020-12-24T01:54:54
2020-06-20T20:18:12
2020-12-17T00:24:13
2020-12-24T01:54:53
31,183
2
1
0
C
false
false
package lightning.webds.handler; import java.util.Set; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.annotation.Configuration; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; @Configuration public class AuthSuccessHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { httpServletResponse.sendRedirect("/redirect"); } }
UTF-8
Java
846
java
AuthSuccessHandler.java
Java
[]
null
[]
package lightning.webds.handler; import java.util.Set; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.annotation.Configuration; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; @Configuration public class AuthSuccessHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { httpServletResponse.sendRedirect("/redirect"); } }
846
0.8487
0.8487
22
37.363636
42.297157
189
false
false
0
0
0
0
0
0
0.636364
false
false
5
c107a6759c9413fe545cf8518d22b9cd1a310aca
8,718,783,676,094
f244abe1736ea5317a4c8d532bc0f3888fc627cd
/src/main/java/org/fundacionjala/coding/melvi/EANValidator.java
05264870f14c2b8d1f2dc09194cdb5d34de98353
[]
no_license
AT-08/coding
https://github.com/AT-08/coding
f837fb59ce1a4d75c79ca61f0ab0989ffd70e41e
e4494c54ffc95fcc5a7e54707c35b67a2dc9b403
refs/heads/develop
2021-07-09T00:29:56.856000
2018-12-27T04:44:23
2018-12-27T04:44:23
148,206,889
0
0
null
false
2019-03-15T21:47:48
2018-09-10T19:19:26
2018-12-27T04:44:27
2019-03-15T21:41:57
397
0
0
17
Java
false
null
package org.fundacionjala.coding.melvi; /** <<<<<<< HEAD * A lot of goods have an International Article Number (formerly known as "European * Article Number") abbreviated "EAN". EAN is a 13-digits barcode consisting of * 12-digits data followed by a single-digit checksum (EAN-8 is not considered in this kata). * <p> * <p> * The single-digit checksum is calculated as followed (based upon the 12-digit data): * <p> * The digit at the first, third, fifth, etc. position (i.e. at the odd position) has to be multiplied with "1". * The digit at the second, fourth, sixth, etc. position (i.e. at the even position) has to be multiplied with "3". * Sum these results. * <p> * If this sum is dividable by 10, the checksum is 0. Otherwise the checksum has the following formula: * <p> * checksum = 10 - (sum mod 10) * <p> * For example, calculate the checksum for "400330101839" (= 12-digits data): * <p> * 4·1 + 0·3 + 0·1 + 3·3 + 3·1 + 0·3 + 1·1 + 0·3 + 1·1 + 8·3 + 3·1 + 9·3 * = 4 + 0 + 0 + 9 + 3 + 0 + 1 + 0 + 1 + 24 + 3 + 27 * = 72 * 10 - (72 mod 10) = 8 ⇒ Checksum: 8 * <p> * Thus, the EAN-Code is 4003301018398 (= 12-digits data followed by single-digit checksum). * <p> * Your Task. * Validate a given EAN-Code. Return true if the given EAN-Code is valid, otherwise false. * Assumption * You can assume the given code is syntactically valid, i.e. it only consists of numbers and it exactly * has a length of 13 characters. * Examples. * EANValidator.validate("4003301018398") // True. * EANValidator.validate("4003301018392") // False. */ public final class EANValidator { public static final int THREE = 3; public static final int TEN = 10; /** * */ private EANValidator() { } /** * @param eanCode code to validate * @return true if valid */ public static boolean validate(final String eanCode) { //Your code int suma = 0; for (int i = 0; i < eanCode.length() - 1; i++) { int digit = Integer.parseInt(eanCode.substring(i, i + 1)); suma += i % 2 == 0 ? digit : Math.multiplyExact(digit, THREE); } int last = Integer.parseInt(eanCode.substring(eanCode.length() - 1)); long checkSum = suma % TEN == 0 ? 0 : TEN - (suma % TEN); return last == checkSum; } }
UTF-8
Java
2,345
java
EANValidator.java
Java
[]
null
[]
package org.fundacionjala.coding.melvi; /** <<<<<<< HEAD * A lot of goods have an International Article Number (formerly known as "European * Article Number") abbreviated "EAN". EAN is a 13-digits barcode consisting of * 12-digits data followed by a single-digit checksum (EAN-8 is not considered in this kata). * <p> * <p> * The single-digit checksum is calculated as followed (based upon the 12-digit data): * <p> * The digit at the first, third, fifth, etc. position (i.e. at the odd position) has to be multiplied with "1". * The digit at the second, fourth, sixth, etc. position (i.e. at the even position) has to be multiplied with "3". * Sum these results. * <p> * If this sum is dividable by 10, the checksum is 0. Otherwise the checksum has the following formula: * <p> * checksum = 10 - (sum mod 10) * <p> * For example, calculate the checksum for "400330101839" (= 12-digits data): * <p> * 4·1 + 0·3 + 0·1 + 3·3 + 3·1 + 0·3 + 1·1 + 0·3 + 1·1 + 8·3 + 3·1 + 9·3 * = 4 + 0 + 0 + 9 + 3 + 0 + 1 + 0 + 1 + 24 + 3 + 27 * = 72 * 10 - (72 mod 10) = 8 ⇒ Checksum: 8 * <p> * Thus, the EAN-Code is 4003301018398 (= 12-digits data followed by single-digit checksum). * <p> * Your Task. * Validate a given EAN-Code. Return true if the given EAN-Code is valid, otherwise false. * Assumption * You can assume the given code is syntactically valid, i.e. it only consists of numbers and it exactly * has a length of 13 characters. * Examples. * EANValidator.validate("4003301018398") // True. * EANValidator.validate("4003301018392") // False. */ public final class EANValidator { public static final int THREE = 3; public static final int TEN = 10; /** * */ private EANValidator() { } /** * @param eanCode code to validate * @return true if valid */ public static boolean validate(final String eanCode) { //Your code int suma = 0; for (int i = 0; i < eanCode.length() - 1; i++) { int digit = Integer.parseInt(eanCode.substring(i, i + 1)); suma += i % 2 == 0 ? digit : Math.multiplyExact(digit, THREE); } int last = Integer.parseInt(eanCode.substring(eanCode.length() - 1)); long checkSum = suma % TEN == 0 ? 0 : TEN - (suma % TEN); return last == checkSum; } }
2,345
0.623767
0.56671
66
34.31818
34.0793
115
false
false
0
0
0
0
0
0
0.363636
false
false
5
b4c94dc115550340317498f410057fda0bd3c9f7
27,711,129,030,546
921845d07beb1a01b325da88c12e68320cda8b47
/src/main/java/com/feiyang/feeds/service/CategoryService.java
fa10461a3b643e009408446fc9590a36d3be3a65
[ "Apache-2.0" ]
permissive
feiyang21687/feeds
https://github.com/feiyang21687/feeds
1f21a2831ba513cc309ecae079559400894c9768
80a6eb713562d9cb70b34bc45e5e4c82743d7137
refs/heads/master
2020-06-06T20:05:33.655000
2013-05-16T16:49:09
2013-05-16T16:49:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.feiyang.feeds.service; import java.util.List; import com.feiyang.feeds.model.Category; import com.feiyang.feeds.model.User; public interface CategoryService { /** * user create a category in order to group some site together. * * @param category * @return */ Category createCategory(User user, String name); /** * query the category from the storage. * * @param user * @param categoryId * @return */ Category queryCategory(User user, long categoryId); /** * query the category from the storage. * * @param user * @param name * @return */ Category queryCategory(User user, String name); /** * query user's all category. * * @param user * @return */ List<Category> queryCategory(User user); /** * subscribe a site under a category. * * @param user * @param categoryId * @param site * @return the category with created Subscribe with the latest content. */ Category subscribeSite(User user, long categoryId, String site); }
UTF-8
Java
1,065
java
CategoryService.java
Java
[]
null
[]
package com.feiyang.feeds.service; import java.util.List; import com.feiyang.feeds.model.Category; import com.feiyang.feeds.model.User; public interface CategoryService { /** * user create a category in order to group some site together. * * @param category * @return */ Category createCategory(User user, String name); /** * query the category from the storage. * * @param user * @param categoryId * @return */ Category queryCategory(User user, long categoryId); /** * query the category from the storage. * * @param user * @param name * @return */ Category queryCategory(User user, String name); /** * query user's all category. * * @param user * @return */ List<Category> queryCategory(User user); /** * subscribe a site under a category. * * @param user * @param categoryId * @param site * @return the category with created Subscribe with the latest content. */ Category subscribeSite(User user, long categoryId, String site); }
1,065
0.643192
0.643192
52
18.48077
19.309713
72
false
false
0
0
0
0
0
0
1.019231
false
false
5
c3bb84416e6ea9446ed316c0a88a7e0303438607
19,731,079,758,363
ea9f1b34008b41f5fbe9476a26319fb3f6144a7e
/src/main/java/com/bingo/business/sys/service/SysRoleUserService.java
3f40ee3f13ab10fe5377a8ccdb3379465dde5d64
[]
no_license
bellmit/mmbigdata
https://github.com/bellmit/mmbigdata
caf7f935c437c4842e8f527dd033f071b5906df3
46191224e7c2f1a4556569f48eb9ae15af8b0ee8
refs/heads/master
2023-07-17T07:20:49.310000
2019-06-14T17:07:44
2019-06-14T17:07:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bingo.business.sys.service; import com.bingo.business.sys.model.SysRole; import com.bingo.business.sys.model.SysRoleRes; import com.bingo.business.sys.model.SysRoleUser; import com.bingo.business.sys.model.SysUser; import com.bingo.business.sys.repository.*; import com.bingo.common.exception.DaoException; import com.bingo.common.exception.ServiceException; import com.bingo.common.model.Page; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.transaction.Transactional; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author huangtw * 2018-06-25 00:30:49 * 对象功能: 角色用户关联 service管理 */ @Service @Transactional public class SysRoleUserService { @Resource private SysRoleUserRepository sysRoleUserRepository; @Resource private SysUserRepository sysuserRepository; @Resource private SysRoleRepository sysroleRepository; /** * @description: <保存对象> * @param: * @return: * @throws DaoException * @throws: */ public void saveOrUpdate(SysRoleUser vo) throws ServiceException, DaoException { sysRoleUserRepository.saveOrUpdate(vo); } /** * @description: <取对象> * @param id * @return * @throws DaoException */ public SysRoleUser get(Serializable id) throws DaoException{ return sysRoleUserRepository.getById(id); } /** * 根据角色ID,用户ID查询对象 * @description: <取对象> * @return * @throws DaoException */ public SysRoleUser query(Long roleid,Long userid) throws DaoException{ String hql = "from SysRoleUser where roleid=? and userid=?"; return sysRoleUserRepository.find(hql,new Long[]{roleid,userid}); } /** * @description: <删除对象> * @param id * @return * @throws DaoException */ public void delete(Serializable id) throws DaoException{ sysRoleUserRepository.deleteById(id); } /** * 根据角色ID和用户ID删除 * @param roleid * @param userid * @throws DaoException */ public void delete(Long roleid,Long userid) throws DaoException{ String hql = new String(" delete from SysRoleUser where roleid=? and userid=? "); sysRoleUserRepository.executeByHql(hql,new Long[]{roleid,userid}); } /** * @description: <取分页列表> * @param: * @return: * @throws: */ public Page<SysRoleUser> findPage(SysRoleRes vo){ StringBuffer hql = new StringBuffer(" from SysRoleUser where sid is not null "); List<Object> fldValues = new ArrayList<Object>(); /** if(StringUtils.isNotEmpty(vo.getUserAccount())){ hql.append(" and userAccount = ?"); fldValues.add(vo.getUserAccount()); } **/ return sysRoleUserRepository.findPage(hql.toString(), vo, fldValues); } /** * 查询某个角色下的用户,分页查询 * @description: <取分页列表> * @param: * @return: * @throws: */ public Page<SysUser> findPageByRole(Long roleid,SysUser vo){ StringBuffer hql = new StringBuffer(" from SysUser where userid in(select userid from SysRoleUser where roleid=?) "); List<Object> fldValues = new ArrayList<Object>(); fldValues.add(roleid); if(StringUtils.isNotEmpty(vo.getUseracc())){ hql.append(" and useracc like ?"); fldValues.add("%"+vo.getUseracc()+"%"); } if(StringUtils.isNotEmpty(vo.getNikename())){ hql.append(" and nikename like ?"); fldValues.add("%"+vo.getNikename()+"%"); } if(vo.getUsertype()!=null && vo.getUsertype()!=-1){ hql.append(" and usertype = ?"); fldValues.add(vo.getUsertype()); } if(vo.getState()!=null && vo.getState()!=-1){ hql.append(" and state = ?"); fldValues.add(vo.getState()); } //密码不返回 Page<SysUser> page = sysuserRepository.findPage(hql.toString(), vo, fldValues); if(page!=null && page.getTotalCount()>0){ for(SysUser user : page.getResult()){ //user.setPwd(null); } } return page; } /** * 查询某个用户下的角色,根据用户ID查询 * @description: <取分页列表> * @param: * @return: * @throws: */ public Page<SysRole> findPageByUser(Long userid,SysRole vo){ StringBuffer hql = new StringBuffer(" from SysRole where roleid in(select roleid from SysRoleUser where userid=?) "); List<Object> fldValues = new ArrayList<Object>(); fldValues.add(userid); if(StringUtils.isNotEmpty(vo.getRolename())){ hql.append(" and rolename like ?"); fldValues.add("%"+vo.getRolename()+"%"); } if(StringUtils.isNotEmpty(vo.getRolecode())){ hql.append(" and rolecode like ?"); fldValues.add("%"+vo.getRolecode()+"%"); } return sysroleRepository.findPage(hql.toString(), vo, fldValues); } }
UTF-8
Java
4,684
java
SysRoleUserService.java
Java
[ { "context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author huangtw\n * 2018-06-25 00:30:49\n * 对象功能: 角色用户关联 service管理\n", "end": 678, "score": 0.9996253848075867, "start": 671, "tag": "USERNAME", "value": "huangtw" } ]
null
[]
package com.bingo.business.sys.service; import com.bingo.business.sys.model.SysRole; import com.bingo.business.sys.model.SysRoleRes; import com.bingo.business.sys.model.SysRoleUser; import com.bingo.business.sys.model.SysUser; import com.bingo.business.sys.repository.*; import com.bingo.common.exception.DaoException; import com.bingo.common.exception.ServiceException; import com.bingo.common.model.Page; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.transaction.Transactional; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author huangtw * 2018-06-25 00:30:49 * 对象功能: 角色用户关联 service管理 */ @Service @Transactional public class SysRoleUserService { @Resource private SysRoleUserRepository sysRoleUserRepository; @Resource private SysUserRepository sysuserRepository; @Resource private SysRoleRepository sysroleRepository; /** * @description: <保存对象> * @param: * @return: * @throws DaoException * @throws: */ public void saveOrUpdate(SysRoleUser vo) throws ServiceException, DaoException { sysRoleUserRepository.saveOrUpdate(vo); } /** * @description: <取对象> * @param id * @return * @throws DaoException */ public SysRoleUser get(Serializable id) throws DaoException{ return sysRoleUserRepository.getById(id); } /** * 根据角色ID,用户ID查询对象 * @description: <取对象> * @return * @throws DaoException */ public SysRoleUser query(Long roleid,Long userid) throws DaoException{ String hql = "from SysRoleUser where roleid=? and userid=?"; return sysRoleUserRepository.find(hql,new Long[]{roleid,userid}); } /** * @description: <删除对象> * @param id * @return * @throws DaoException */ public void delete(Serializable id) throws DaoException{ sysRoleUserRepository.deleteById(id); } /** * 根据角色ID和用户ID删除 * @param roleid * @param userid * @throws DaoException */ public void delete(Long roleid,Long userid) throws DaoException{ String hql = new String(" delete from SysRoleUser where roleid=? and userid=? "); sysRoleUserRepository.executeByHql(hql,new Long[]{roleid,userid}); } /** * @description: <取分页列表> * @param: * @return: * @throws: */ public Page<SysRoleUser> findPage(SysRoleRes vo){ StringBuffer hql = new StringBuffer(" from SysRoleUser where sid is not null "); List<Object> fldValues = new ArrayList<Object>(); /** if(StringUtils.isNotEmpty(vo.getUserAccount())){ hql.append(" and userAccount = ?"); fldValues.add(vo.getUserAccount()); } **/ return sysRoleUserRepository.findPage(hql.toString(), vo, fldValues); } /** * 查询某个角色下的用户,分页查询 * @description: <取分页列表> * @param: * @return: * @throws: */ public Page<SysUser> findPageByRole(Long roleid,SysUser vo){ StringBuffer hql = new StringBuffer(" from SysUser where userid in(select userid from SysRoleUser where roleid=?) "); List<Object> fldValues = new ArrayList<Object>(); fldValues.add(roleid); if(StringUtils.isNotEmpty(vo.getUseracc())){ hql.append(" and useracc like ?"); fldValues.add("%"+vo.getUseracc()+"%"); } if(StringUtils.isNotEmpty(vo.getNikename())){ hql.append(" and nikename like ?"); fldValues.add("%"+vo.getNikename()+"%"); } if(vo.getUsertype()!=null && vo.getUsertype()!=-1){ hql.append(" and usertype = ?"); fldValues.add(vo.getUsertype()); } if(vo.getState()!=null && vo.getState()!=-1){ hql.append(" and state = ?"); fldValues.add(vo.getState()); } //密码不返回 Page<SysUser> page = sysuserRepository.findPage(hql.toString(), vo, fldValues); if(page!=null && page.getTotalCount()>0){ for(SysUser user : page.getResult()){ //user.setPwd(null); } } return page; } /** * 查询某个用户下的角色,根据用户ID查询 * @description: <取分页列表> * @param: * @return: * @throws: */ public Page<SysRole> findPageByUser(Long userid,SysRole vo){ StringBuffer hql = new StringBuffer(" from SysRole where roleid in(select roleid from SysRoleUser where userid=?) "); List<Object> fldValues = new ArrayList<Object>(); fldValues.add(userid); if(StringUtils.isNotEmpty(vo.getRolename())){ hql.append(" and rolename like ?"); fldValues.add("%"+vo.getRolename()+"%"); } if(StringUtils.isNotEmpty(vo.getRolecode())){ hql.append(" and rolecode like ?"); fldValues.add("%"+vo.getRolecode()+"%"); } return sysroleRepository.findPage(hql.toString(), vo, fldValues); } }
4,684
0.697861
0.69385
176
24.5
24.009232
119
false
false
0
0
0
0
0
0
1.568182
false
false
5
056f0ce1cafbacaff1ebef685864ee33855bdcdb
3,075,196,603,165
697db4ffa21739ff32aa8ec6ca85d58eeb2ad8fb
/docking-frames-demo-layouts/src/bibliothek/layouts/Icons.java
16d394033ca1fc61d3bbca8c38dd535f7fe5525a
[]
no_license
subes/DockingFrames
https://github.com/subes/DockingFrames
87e0a485b5c5bab6dcdf194a9c582e8662694cf2
76ab477a0888030791bacbfd094ab3db0af8d6c5
refs/heads/master
2022-07-08T01:15:18.362000
2022-06-30T12:22:57
2022-06-30T12:22:57
243,284,554
0
0
null
true
2020-02-26T14:36:49
2020-02-26T14:36:48
2019-12-06T06:59:48
2019-12-06T06:59:38
31,368
0
0
0
null
false
false
package bibliothek.layouts; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import javax.swing.Icon; import javax.swing.ImageIcon; public class Icons { private static Map<String, Icon> icons = new HashMap<String, Icon>(); private static BufferedImage iconImage; static{ load( "xml", "xml.png" ); load( "binary", "binary.png" ); load( "load", "load.png" ); load( "add factory", "add_factory.png" ); load( "remove factory", "remove_factory.png" ); load( "add dockable", "add_dockable.png" ); load( "remove dockable", "remove_dockable.png" ); try{ iconImage = ImageIO.read( Icons.class.getResource( "/data/bibliothek/commonLayouts/icons/icon.png" )); icons.put( "icon", new ImageIcon( iconImage )); } catch( IOException ex ){ ex.printStackTrace(); } } private static void load( String id, String path ){ URL url = Icons.class.getResource( "/data/bibliothek/commonLayouts/icons/" + path ); ImageIcon icon = new ImageIcon( url ); icons.put( id, icon ); } public static Icon get( String id ){ return icons.get( id ); } public static BufferedImage getIconImage() { return iconImage; } }
UTF-8
Java
1,450
java
Icons.java
Java
[]
null
[]
package bibliothek.layouts; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import javax.swing.Icon; import javax.swing.ImageIcon; public class Icons { private static Map<String, Icon> icons = new HashMap<String, Icon>(); private static BufferedImage iconImage; static{ load( "xml", "xml.png" ); load( "binary", "binary.png" ); load( "load", "load.png" ); load( "add factory", "add_factory.png" ); load( "remove factory", "remove_factory.png" ); load( "add dockable", "add_dockable.png" ); load( "remove dockable", "remove_dockable.png" ); try{ iconImage = ImageIO.read( Icons.class.getResource( "/data/bibliothek/commonLayouts/icons/icon.png" )); icons.put( "icon", new ImageIcon( iconImage )); } catch( IOException ex ){ ex.printStackTrace(); } } private static void load( String id, String path ){ URL url = Icons.class.getResource( "/data/bibliothek/commonLayouts/icons/" + path ); ImageIcon icon = new ImageIcon( url ); icons.put( id, icon ); } public static Icon get( String id ){ return icons.get( id ); } public static BufferedImage getIconImage() { return iconImage; } }
1,450
0.60069
0.60069
50
28
24.222303
114
false
false
0
0
0
0
0
0
0.76
false
false
5
e703e136cf0aa6a1668cf84967ad5e5a371f1bbe
14,628,658,656,183
54cfaf8c83e35424ffef21c7617f6898e9cba15c
/aula02-revisao/src/br/com/mariojp/folha/Funcionario.java
de2115cb1b73d6deaa8979e88b26f31d08ed3a73
[]
no_license
mariojp/poo-2021-1
https://github.com/mariojp/poo-2021-1
5976de3c49d5d3f751171b258532f5c6ddab215a
e7828fb65c79b6903c2af397ab0078e15e78ec6d
refs/heads/main
2023-03-15T08:16:46.770000
2021-03-19T09:59:22
2021-03-19T09:59:22
341,318,644
6
4
null
false
2021-03-02T18:05:40
2021-02-22T19:49:34
2021-02-28T02:25:27
2021-03-02T18:05:24
298
5
2
0
HTML
false
false
package br.com.mariojp.folha; public class Funcionario { String nome; String cargo; double salario; }
UTF-8
Java
109
java
Funcionario.java
Java
[]
null
[]
package br.com.mariojp.folha; public class Funcionario { String nome; String cargo; double salario; }
109
0.733945
0.733945
9
11.111111
10.6921
29
false
false
0
0
0
0
0
0
0.888889
false
false
5
ef510a4cacea429c32ea78d9a917446e268b8840
13,975,823,614,426
48839309de241304a2e2e5502232a5f0dd98b38f
/src/main/java/demo/spring/websocket/controller/Login.java
00e29693c18eeadb54954126288f3560de4f6b7a
[]
no_license
liuguangjie/spring-websocket
https://github.com/liuguangjie/spring-websocket
035e6a9bf64fdd8531a846939879e102791bd38a
f38abeea59d6b7bb2c4dd5e8499ea7439b7f7d2a
refs/heads/master
2020-03-23T16:07:31.971000
2018-07-21T08:26:18
2018-07-21T08:26:18
141,795,118
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package demo.spring.websocket.controller; import demo.spring.websocket.entity.Result; import demo.spring.websocket.entity.User; import org.redisson.api.RMap; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by free on 18-7-21. */ @RestController @RequestMapping public class Login { @Autowired private RedissonClient redissonClient; @RequestMapping("/reg") public Result register(User user) { /** RMap */ RMap<String, String> rMap = redissonClient.getMap(user.getUserName()); rMap.put("userName", user.getUserName()); rMap.put("passwd", user.getPasswd()); return Result.ok(null); } @RequestMapping("/login") public Result login(User user) { RMap<String, String> rMap = redissonClient.getMap(user.getUserName()); String passwd = rMap.get("passwd"); String userName = rMap.get("userName"); if (!user.getPasswd().equals(passwd) && !user.getUserName().equals(userName)) { return Result.error(); } return Result.ok(user.getUserName()); } }
UTF-8
Java
1,288
java
Login.java
Java
[ { "context": "ind.annotation.RestController;\n\n\n/**\n * Created by free on 18-7-21.\n */\n@RestController\n@RequestMapping\np", "end": 412, "score": 0.9987146854400635, "start": 408, "tag": "USERNAME", "value": "free" }, { "context": "\", user.getUserName());\n rMap.put(\"passwd\", user.getPasswd());\n return Result.ok(null);\n ", "end": 792, "score": 0.8896833062171936, "start": 788, "tag": "PASSWORD", "value": "user" }, { "context": "erName());\n rMap.put(\"passwd\", user.getPasswd());\n return Result.ok(null);\n }\n\n\n @", "end": 802, "score": 0.5376539826393127, "start": 800, "tag": "PASSWORD", "value": "wd" }, { "context": "et(\"passwd\");\n String userName = rMap.get(\"userName\");\n if (!user.getPasswd().equals(passwd) &", "end": 1081, "score": 0.9963341951370239, "start": 1073, "tag": "USERNAME", "value": "userName" } ]
null
[]
package demo.spring.websocket.controller; import demo.spring.websocket.entity.Result; import demo.spring.websocket.entity.User; import org.redisson.api.RMap; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by free on 18-7-21. */ @RestController @RequestMapping public class Login { @Autowired private RedissonClient redissonClient; @RequestMapping("/reg") public Result register(User user) { /** RMap */ RMap<String, String> rMap = redissonClient.getMap(user.getUserName()); rMap.put("userName", user.getUserName()); rMap.put("passwd", <PASSWORD>.getPasswd()); return Result.ok(null); } @RequestMapping("/login") public Result login(User user) { RMap<String, String> rMap = redissonClient.getMap(user.getUserName()); String passwd = rMap.get("passwd"); String userName = rMap.get("userName"); if (!user.getPasswd().equals(passwd) && !user.getUserName().equals(userName)) { return Result.error(); } return Result.ok(user.getUserName()); } }
1,294
0.677019
0.673137
45
27.622223
22.806713
78
false
false
0
0
0
0
0
0
0.488889
false
false
5
1f57cb49b7ef8ddeb0426ff5dc8c2cec842e7baf
32,899,449,507,024
7f6bcf8ec635561b9f1473166e923f6934f7707c
/service/src/test/java/cz/muni/pa165/pneuservis/service/BeanMappingServiceTest.java
e8f090d2ce209dac5fd654d4bbfb552b6b1e58b7
[]
no_license
javorka/PA165
https://github.com/javorka/PA165
d466f7b04fdfe12a03deb27dba7c647f813d5c36
ab25e9aa1d812749e0fca409c4728e448537afc7
refs/heads/master
2021-01-11T05:00:27.231000
2017-01-10T11:07:40
2017-01-10T11:07:40
71,364,621
2
2
null
false
2017-01-10T11:07:41
2016-10-19T14:16:43
2016-10-26T15:04:29
2017-01-10T11:07:41
423
2
3
1
Java
null
null
package cz.muni.pa165.pneuservis.service; import cz.muni.pa165.pneuservis.api.dto.OrderDTO; import cz.muni.pa165.pneuservis.persistence.domain.AdditionalService; import cz.muni.pa165.pneuservis.persistence.domain.Order; import cz.muni.pa165.pneuservis.persistence.domain.Tire; import cz.muni.pa165.pneuservis.persistence.domain.User; import cz.muni.pa165.pneuservis.persistence.enums.OrderState; import cz.muni.pa165.pneuservis.persistence.enums.Role; import cz.muni.pa165.pneuservis.persistence.enums.TireType; import cz.muni.pa165.pneuservis.service.config.ServiceConfiguration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import org.testng.annotations.Test; import javax.inject.Inject; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; /** * Created by peter on 11/24/16. */ @ContextConfiguration(classes = ServiceConfiguration.class) public class BeanMappingServiceTest extends AbstractTestNGSpringContextTests { @Inject BeanMappingService mappingService; @Test public void shouldMapNestedStructures() { Order order = new Order(); order.setPrice(BigDecimal.TEN); order.setAddress("Address"); order.setUser(createUser()); order.setAdditionalServices(createAdditionalServices()); order.setTire(createTire()); order.setTireQuantity(10); order.setState(OrderState.CANCELED); OrderDTO dto = mappingService.mapTo(order, OrderDTO.class); Assert.assertNull(dto.getId()); Assert.assertEquals(order.getPrice(), dto.getPrice(), "Price should be the same"); Assert.assertEquals(order.getAddress(), dto.getAddress(), "Address should be the same"); Assert.assertEquals(order.getAdditionalServices().size(), dto.getAdditionalServices().size(), "Additional services should be mapped"); Assert.assertEquals(order.getTire().getName(), dto.getTire().getName(), "Tire should be mapped"); Assert.assertEquals(order.getState().name(), dto.getState().name(), "Order state should be mapped"); Assert.assertEquals(order.getUser().getName(), dto.getUser().getName(), "User should be mapped"); Assert.assertEquals(order.getUser().getRoles().size(), dto.getUser().getRoles().size(), "User roles should be mapped"); } private List<AdditionalService> createAdditionalServices() { AdditionalService serviceA = new AdditionalService(); serviceA.setName("A"); serviceA.setPrice(BigDecimal.ZERO); serviceA.setDescription("Description A"); AdditionalService serviceB = new AdditionalService(); serviceB.setName("B"); serviceB.setPrice(BigDecimal.ONE); serviceB.setDescription("Description B"); return Arrays.asList(serviceA, serviceB); } private User createUser() { User user = new User(); user.setName("Admin"); user.setEmail("admin@admin.com"); user.setRoles(Arrays.asList(Role.ADMIN, Role.CUSTOMER)); return user; } private Tire createTire() { Tire tire = new Tire(); tire.setPrice(BigDecimal.ONE); tire.setName("Tire"); tire.setManufacturer("Manufacturer"); tire.setVehicleType("Sedan"); tire.setTireType(TireType.AllSeason_LightTruck); tire.setSize("48"); return tire; } }
UTF-8
Java
3,468
java
BeanMappingServiceTest.java
Java
[ { "context": ".Arrays;\nimport java.util.List;\n\n/**\n * Created by peter on 11/24/16.\n */\n@ContextConfiguration(classes = ", "end": 917, "score": 0.7310436367988586, "start": 912, "tag": "NAME", "value": "peter" }, { "context": " User user = new User();\n user.setName(\"Admin\");\n user.setEmail(\"admin@admin.com\");\n ", "end": 2997, "score": 0.7294532060623169, "start": 2992, "tag": "USERNAME", "value": "Admin" }, { "context": " user.setName(\"Admin\");\n user.setEmail(\"admin@admin.com\");\n user.setRoles(Arrays.asList(Role.ADMIN", "end": 3039, "score": 0.9999264478683472, "start": 3024, "tag": "EMAIL", "value": "admin@admin.com" }, { "context": "e.setPrice(BigDecimal.ONE);\n tire.setName(\"Tire\");\n tire.setManufacturer(\"Manufacturer\");\n", "end": 3265, "score": 0.9523683786392212, "start": 3261, "tag": "NAME", "value": "Tire" } ]
null
[]
package cz.muni.pa165.pneuservis.service; import cz.muni.pa165.pneuservis.api.dto.OrderDTO; import cz.muni.pa165.pneuservis.persistence.domain.AdditionalService; import cz.muni.pa165.pneuservis.persistence.domain.Order; import cz.muni.pa165.pneuservis.persistence.domain.Tire; import cz.muni.pa165.pneuservis.persistence.domain.User; import cz.muni.pa165.pneuservis.persistence.enums.OrderState; import cz.muni.pa165.pneuservis.persistence.enums.Role; import cz.muni.pa165.pneuservis.persistence.enums.TireType; import cz.muni.pa165.pneuservis.service.config.ServiceConfiguration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import org.testng.annotations.Test; import javax.inject.Inject; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; /** * Created by peter on 11/24/16. */ @ContextConfiguration(classes = ServiceConfiguration.class) public class BeanMappingServiceTest extends AbstractTestNGSpringContextTests { @Inject BeanMappingService mappingService; @Test public void shouldMapNestedStructures() { Order order = new Order(); order.setPrice(BigDecimal.TEN); order.setAddress("Address"); order.setUser(createUser()); order.setAdditionalServices(createAdditionalServices()); order.setTire(createTire()); order.setTireQuantity(10); order.setState(OrderState.CANCELED); OrderDTO dto = mappingService.mapTo(order, OrderDTO.class); Assert.assertNull(dto.getId()); Assert.assertEquals(order.getPrice(), dto.getPrice(), "Price should be the same"); Assert.assertEquals(order.getAddress(), dto.getAddress(), "Address should be the same"); Assert.assertEquals(order.getAdditionalServices().size(), dto.getAdditionalServices().size(), "Additional services should be mapped"); Assert.assertEquals(order.getTire().getName(), dto.getTire().getName(), "Tire should be mapped"); Assert.assertEquals(order.getState().name(), dto.getState().name(), "Order state should be mapped"); Assert.assertEquals(order.getUser().getName(), dto.getUser().getName(), "User should be mapped"); Assert.assertEquals(order.getUser().getRoles().size(), dto.getUser().getRoles().size(), "User roles should be mapped"); } private List<AdditionalService> createAdditionalServices() { AdditionalService serviceA = new AdditionalService(); serviceA.setName("A"); serviceA.setPrice(BigDecimal.ZERO); serviceA.setDescription("Description A"); AdditionalService serviceB = new AdditionalService(); serviceB.setName("B"); serviceB.setPrice(BigDecimal.ONE); serviceB.setDescription("Description B"); return Arrays.asList(serviceA, serviceB); } private User createUser() { User user = new User(); user.setName("Admin"); user.setEmail("<EMAIL>"); user.setRoles(Arrays.asList(Role.ADMIN, Role.CUSTOMER)); return user; } private Tire createTire() { Tire tire = new Tire(); tire.setPrice(BigDecimal.ONE); tire.setName("Tire"); tire.setManufacturer("Manufacturer"); tire.setVehicleType("Sedan"); tire.setTireType(TireType.AllSeason_LightTruck); tire.setSize("48"); return tire; } }
3,460
0.712226
0.700692
85
39.799999
30.60173
142
false
false
0
0
0
0
0
0
0.882353
false
false
5
0f9dbef4325b2929644b4d622ca41b5597f8a8ff
5,720,896,444,154
e6ad94f41ef93452be7440db81ea7e8261c65be3
/gongserver/branches/master/gong-login/src/main/java/com/gamejelly/game/gong/login/dao/NoticeDao.java
f08d7948b752ac8844dbc3abc6972bb645aec55b
[]
no_license
fanxingzhiduoshao/lin3
https://github.com/fanxingzhiduoshao/lin3
0a8278c221fb79922f1fb603a15d83d854f61514
4e0fb55dc19a4f7dd323489bcf7b6a9bfaf4a8be
refs/heads/master
2020-03-23T09:05:02.372000
2018-07-22T05:10:13
2018-07-22T05:10:13
141,366,222
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gamejelly.game.gong.login.dao; import org.springframework.stereotype.Component; import com.gamejelly.game.gong.login.meta.Notice; @Component("noticeDao") public class NoticeDao extends BaseDomainDao<Notice> { @Override protected Class<Notice> getDomainClass() { return Notice.class; } public Notice getRecentlyNotice() { return getObject("select * from Notice order by createTime desc limit 1"); } }
UTF-8
Java
426
java
NoticeDao.java
Java
[]
null
[]
package com.gamejelly.game.gong.login.dao; import org.springframework.stereotype.Component; import com.gamejelly.game.gong.login.meta.Notice; @Component("noticeDao") public class NoticeDao extends BaseDomainDao<Notice> { @Override protected Class<Notice> getDomainClass() { return Notice.class; } public Notice getRecentlyNotice() { return getObject("select * from Notice order by createTime desc limit 1"); } }
426
0.7723
0.769953
19
21.473684
23.694033
76
false
false
0
0
0
0
0
0
0.736842
false
false
5
144560cc85395e75e41edabedd9d0ac6156a7c83
6,614,249,646,862
a467cefd1874f0ade8b9231e5c71fd4bc8b3fe53
/src/main/java/jp/personal/gi/examazon/customerservice/model/port/models/customer/CustomerDtoMapper.java
fbc89fd819b79dc2e4b100fdf101e11150cc43da
[]
no_license
azmint/Examazon-CustomerService
https://github.com/azmint/Examazon-CustomerService
e677db2e5c958a6f827c070fcf14fa3cccdfb098
fa8334eaa92d0adb0fe64920f3144282b07053f5
refs/heads/master
2020-03-31T21:37:25.809000
2018-11-23T03:35:01
2018-11-23T03:35:01
152,587,519
0
0
null
false
2018-11-23T03:35:02
2018-10-11T12:24:41
2018-10-11T14:20:21
2018-11-23T03:35:01
24
0
0
0
Java
false
null
package jp.personal.gi.examazon.customerservice.model.port.models.customer; import jp.personal.gi.examazon.customerservice.model.core.models.customer.Customer; import java.util.Arrays; import java.util.function.BiConsumer; public enum CustomerDtoMapper { Id((customer, customerDto) -> customerDto.setId(customer.id().source())), Name((customer, customerDto) -> customerDto.setName(customer.name().source())), NameReading((customer, customerDto) -> customerDto.setNameReading(customer.nameReading().source())), RegistrationState((customer, customerDto) -> customerDto.setRegistrationState(customer.registrationState().source())), ; final BiConsumer<Customer, CustomerDto> mapping; CustomerDtoMapper(BiConsumer<Customer, CustomerDto> mapping) { this.mapping = mapping; } public static CustomerDto apply(Customer customer) { CustomerDto customerDto = new CustomerDto(); Arrays.asList(values()).forEach(customerMapper -> customerMapper.mapping.accept(customer, customerDto)); return customerDto; } }
UTF-8
Java
1,020
java
CustomerDtoMapper.java
Java
[]
null
[]
package jp.personal.gi.examazon.customerservice.model.port.models.customer; import jp.personal.gi.examazon.customerservice.model.core.models.customer.Customer; import java.util.Arrays; import java.util.function.BiConsumer; public enum CustomerDtoMapper { Id((customer, customerDto) -> customerDto.setId(customer.id().source())), Name((customer, customerDto) -> customerDto.setName(customer.name().source())), NameReading((customer, customerDto) -> customerDto.setNameReading(customer.nameReading().source())), RegistrationState((customer, customerDto) -> customerDto.setRegistrationState(customer.registrationState().source())), ; final BiConsumer<Customer, CustomerDto> mapping; CustomerDtoMapper(BiConsumer<Customer, CustomerDto> mapping) { this.mapping = mapping; } public static CustomerDto apply(Customer customer) { CustomerDto customerDto = new CustomerDto(); Arrays.asList(values()).forEach(customerMapper -> customerMapper.mapping.accept(customer, customerDto)); return customerDto; } }
1,020
0.784314
0.784314
26
38.23077
37.859364
119
false
false
0
0
0
0
0
0
1.5
false
false
5
66d5727d2e4b543ce92f96a0dfa5afc0cdfc7d52
28,424,093,618,407
096a96b3346988bdad3c23156555d573ca8087d9
/src/main/java/Creature/CalabashBrothers.java
75d4ff54b141539c16440509ff2ee032ae002f42
[]
no_license
JianhaoChen-nju/myhomework
https://github.com/JianhaoChen-nju/myhomework
cd6180eb9ebe6dc51c8bf12f92fca0ce2c4c2b7b
8d18520e1bfa8d74f83a6a976a3ee9b2227b6e94
refs/heads/master
2022-12-16T08:24:30.998000
2019-01-05T02:54:05
2019-01-05T02:54:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Creature; import BattleField.Existance; import BattleField.Space; import Record.Record; import UI.SScreen; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import java.io.File; /** * @ Author :cjh * @ Description:葫芦娃 */ public class CalabashBrothers extends Creature implements Runnable{ private Thread t; String color;// 葫芦娃的颜色 int rank;// 葫芦娃中的排行 Image image; CalabashBrothers(int i,int m,int n) { init(m,n); this.color = CalabashEnum.values()[i].getColor(); this.name =CalabashEnum.values()[i].getName(); this.rank = CalabashEnum.values()[i].getRank(); ListCalabash.add(this); String url=null; java.io.File file = new java.io.File("classes"+File.separator+rank+".png"); url = file.toURI().toString(); image = new Image(url); standOnMap(m,n); this.start(); } @Override public void draw(GraphicsContext gc) { gc.drawImage(image,column*80,row*80,80,80); } @Override public void standOnMap(int i,int j) { row=i; column=j; switch(rank) { case 1: Space.space[(int)i][(int)j]= Existance.bigbrother; break; case 2: Space.space[(int)i][(int)j]=Existance.secondbrother; break; case 3: Space.space[(int)i][(int)j]=Existance.thirdbrother; break; case 4: Space.space[(int)i][(int)j]=Existance.fourthbrother; break; case 5: Space.space[(int)i][(int)j]=Existance.fifthbrother; break; case 6: Space.space[(int)i][(int)j]=Existance.sixthbrother; break; case 7: Space.space[(int)i][(int)j]=Existance.seventhbrother; break; } } public static void swapPosition(CalabashBrothers[] brothers,int i,int j)/**两个葫芦娃交换位置*/ { CalabashBrothers temp; temp=brothers[i]; brothers[i]=brothers[j]; brothers[j]=temp; } public void reportColor()/**报颜色*/ { System.out.print(color+" "); } public void reportSwap(int i,int j)/**报位置改变*/ { System.out.println(name + ":" + i + "->" + j); } public static CalabashBrothers[] birth()/**葫芦娃出生(随机顺序)*/ { CalabashBrothers[] brothers=new CalabashBrothers[7]; for(int i=0;i<7;i++) { brothers[i]=new CalabashBrothers(i,i,3); } /* for(int i=0;i<7;i++) { int num1 = (int) (Math.random() * 7); int num2 = (int) (Math.random() * 7); CalabashBrothers.swapPosition(brothers,num1,num2); }*/ return brothers; } /* public static void main(String[] args) { // 让葫芦娃随便站队 CalabashBrothers[] brothers=CalabashBrothers.birth(); // 冒泡法以姓名排序 System.out.println("排序中报告位置改变:"); CalabashBrothersSort.sortByName(brothers); System.out.println("排序后按姓名报数:"); for(CalabashBrothers s:brothers) s.reportName(); // 再次让葫芦娃打乱位置 brothers=CalabashBrothers.birth(); for(int i=0;i<7;i++) { int num1 = (int) (Math.random() * 7); int num2 = (int) (Math.random() * 7); CalabashBrothers.swapPosition(brothers,num1,num2); } System.out.println(); System.out.println("再次随机后位置:"); for(CalabashBrothers s:brothers) s.reportName(); System.out.println(); // 二分法以颜色排序 System.out.println("排序中报告位置改变:"); CalabashBrothersSort.sortByColor(brothers); System.out.println("排序后按颜色报数:"); for(CalabashBrothers s:brothers) s.reportColor(); } */ public void run() { try { while (SScreen.getmGameState()!= SScreen.GameState.GAME_END&&Creature.ListCalabash.contains(this)) { if(SScreen.getmGameState()!=SScreen.GameState.GAME_PAUSE) { int oldCol=column; int oldRow=row; int temp = (int) (Math.random() * 4); switch (temp) { case 0: //left if (column == 0 && row == 0) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column += 1; break; case 1: row += 1; break; } } else if (column == 0 && row == 7) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column += 1; break; case 1: row -= 1; break; } } else if (column == 0) { temp = (int) (Math.random() * 3); switch (temp) { case 0: column += 1; break; case 1: row += 1; break; case 2: row -= 1; break; } } else { column -= 1; } break; case 1: //down if (row == 7 && column == 0) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column += 1; break; case 1: row -= 1; break; } } else if (row == 7 && column == 11) { temp = (int) (Math.random() * 2); switch (temp) { case 0: row -= 1; break; case 1: column -= 1; break; } } else if (row == 7) { temp = (int) (Math.random() * 3); switch (temp) { case 0: row -= 1; break; case 1: column += 1; break; case 2: column -= 1; break; } }else{ row += 1;} break; case 2: //up if (row == 0 && column == 0) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column += 1; break; case 1: row += 1; break; } } else if (row == 0 && column == 11) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column -= 1; break; case 1: row += 1; break; } } else if (row == 0) { temp = (int) (Math.random() * 3); switch (temp) { case 0: row += 1; break; case 1: column += 1; break; case 2: column -= 1; break; } } else { row -= 1; } break; case 3: //right if (column == 11 && row == 0) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column -= 1; break; case 1: row += 1; break; } } else if (column == 11 && row == 7) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column -= 1; break; case 1: row -= 1; break; } } else if (column == 11) { temp = (int) (Math.random() * 3); switch (temp) { case 0: column -= 1; break; case 1: row += 1; break; case 2: row -= 1; break; } } else { column += 1; } break; } for(int i=0;i<ListCalabash.indexOf(this);i++) { if(ListCalabash.get(i).row==this.row&&ListCalabash.get(i).column==this.column) { row=oldRow; column=oldCol; } } //Record r=new Record(rank,row,column); //Record.records.add(r); } //System.out.println(column+" "+row); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } public void start() { if (t == null) { t = new Thread (this); t.start (); } } @Deprecated public void close() { if(t!=null) { t.stop(); } } }
UTF-8
Java
12,794
java
CalabashBrothers.java
Java
[ { "context": "Image;\nimport java.io.File;\n\n/**\n * @ Author :cjh\n * @ Description:葫芦娃\n */\n\npublic class CalabashBr", "end": 239, "score": 0.9996720552444458, "start": 236, "tag": "USERNAME", "value": "cjh" } ]
null
[]
package Creature; import BattleField.Existance; import BattleField.Space; import Record.Record; import UI.SScreen; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import java.io.File; /** * @ Author :cjh * @ Description:葫芦娃 */ public class CalabashBrothers extends Creature implements Runnable{ private Thread t; String color;// 葫芦娃的颜色 int rank;// 葫芦娃中的排行 Image image; CalabashBrothers(int i,int m,int n) { init(m,n); this.color = CalabashEnum.values()[i].getColor(); this.name =CalabashEnum.values()[i].getName(); this.rank = CalabashEnum.values()[i].getRank(); ListCalabash.add(this); String url=null; java.io.File file = new java.io.File("classes"+File.separator+rank+".png"); url = file.toURI().toString(); image = new Image(url); standOnMap(m,n); this.start(); } @Override public void draw(GraphicsContext gc) { gc.drawImage(image,column*80,row*80,80,80); } @Override public void standOnMap(int i,int j) { row=i; column=j; switch(rank) { case 1: Space.space[(int)i][(int)j]= Existance.bigbrother; break; case 2: Space.space[(int)i][(int)j]=Existance.secondbrother; break; case 3: Space.space[(int)i][(int)j]=Existance.thirdbrother; break; case 4: Space.space[(int)i][(int)j]=Existance.fourthbrother; break; case 5: Space.space[(int)i][(int)j]=Existance.fifthbrother; break; case 6: Space.space[(int)i][(int)j]=Existance.sixthbrother; break; case 7: Space.space[(int)i][(int)j]=Existance.seventhbrother; break; } } public static void swapPosition(CalabashBrothers[] brothers,int i,int j)/**两个葫芦娃交换位置*/ { CalabashBrothers temp; temp=brothers[i]; brothers[i]=brothers[j]; brothers[j]=temp; } public void reportColor()/**报颜色*/ { System.out.print(color+" "); } public void reportSwap(int i,int j)/**报位置改变*/ { System.out.println(name + ":" + i + "->" + j); } public static CalabashBrothers[] birth()/**葫芦娃出生(随机顺序)*/ { CalabashBrothers[] brothers=new CalabashBrothers[7]; for(int i=0;i<7;i++) { brothers[i]=new CalabashBrothers(i,i,3); } /* for(int i=0;i<7;i++) { int num1 = (int) (Math.random() * 7); int num2 = (int) (Math.random() * 7); CalabashBrothers.swapPosition(brothers,num1,num2); }*/ return brothers; } /* public static void main(String[] args) { // 让葫芦娃随便站队 CalabashBrothers[] brothers=CalabashBrothers.birth(); // 冒泡法以姓名排序 System.out.println("排序中报告位置改变:"); CalabashBrothersSort.sortByName(brothers); System.out.println("排序后按姓名报数:"); for(CalabashBrothers s:brothers) s.reportName(); // 再次让葫芦娃打乱位置 brothers=CalabashBrothers.birth(); for(int i=0;i<7;i++) { int num1 = (int) (Math.random() * 7); int num2 = (int) (Math.random() * 7); CalabashBrothers.swapPosition(brothers,num1,num2); } System.out.println(); System.out.println("再次随机后位置:"); for(CalabashBrothers s:brothers) s.reportName(); System.out.println(); // 二分法以颜色排序 System.out.println("排序中报告位置改变:"); CalabashBrothersSort.sortByColor(brothers); System.out.println("排序后按颜色报数:"); for(CalabashBrothers s:brothers) s.reportColor(); } */ public void run() { try { while (SScreen.getmGameState()!= SScreen.GameState.GAME_END&&Creature.ListCalabash.contains(this)) { if(SScreen.getmGameState()!=SScreen.GameState.GAME_PAUSE) { int oldCol=column; int oldRow=row; int temp = (int) (Math.random() * 4); switch (temp) { case 0: //left if (column == 0 && row == 0) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column += 1; break; case 1: row += 1; break; } } else if (column == 0 && row == 7) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column += 1; break; case 1: row -= 1; break; } } else if (column == 0) { temp = (int) (Math.random() * 3); switch (temp) { case 0: column += 1; break; case 1: row += 1; break; case 2: row -= 1; break; } } else { column -= 1; } break; case 1: //down if (row == 7 && column == 0) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column += 1; break; case 1: row -= 1; break; } } else if (row == 7 && column == 11) { temp = (int) (Math.random() * 2); switch (temp) { case 0: row -= 1; break; case 1: column -= 1; break; } } else if (row == 7) { temp = (int) (Math.random() * 3); switch (temp) { case 0: row -= 1; break; case 1: column += 1; break; case 2: column -= 1; break; } }else{ row += 1;} break; case 2: //up if (row == 0 && column == 0) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column += 1; break; case 1: row += 1; break; } } else if (row == 0 && column == 11) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column -= 1; break; case 1: row += 1; break; } } else if (row == 0) { temp = (int) (Math.random() * 3); switch (temp) { case 0: row += 1; break; case 1: column += 1; break; case 2: column -= 1; break; } } else { row -= 1; } break; case 3: //right if (column == 11 && row == 0) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column -= 1; break; case 1: row += 1; break; } } else if (column == 11 && row == 7) { temp = (int) (Math.random() * 2); switch (temp) { case 0: column -= 1; break; case 1: row -= 1; break; } } else if (column == 11) { temp = (int) (Math.random() * 3); switch (temp) { case 0: column -= 1; break; case 1: row += 1; break; case 2: row -= 1; break; } } else { column += 1; } break; } for(int i=0;i<ListCalabash.indexOf(this);i++) { if(ListCalabash.get(i).row==this.row&&ListCalabash.get(i).column==this.column) { row=oldRow; column=oldCol; } } //Record r=new Record(rank,row,column); //Record.records.add(r); } //System.out.println(column+" "+row); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } public void start() { if (t == null) { t = new Thread (this); t.start (); } } @Deprecated public void close() { if(t!=null) { t.stop(); } } }
12,794
0.293241
0.281923
345
35.36232
19.908175
112
false
false
0
0
0
0
0
0
0.53913
false
false
5
a5d0fd85b703ba6b9965d9fefe83cf32669fede9
7,241,314,920,791
6570435495127d07802d3990619be5705c1c99b7
/drag/app/src/main/java/edu/gcit/drag/QContract.java
c834c08360d1ad2611926f04f959687324a4fcb7
[]
no_license
Tsheringwangchuk/personalapp
https://github.com/Tsheringwangchuk/personalapp
970269c567b7da2806876da9449b1deb6bc838e9
4aa7b02d8220c8a0aee1a63e16f785fd8c40ce6f
refs/heads/main
2023-05-15T04:46:49.154000
2021-05-27T16:52:02
2021-05-27T16:52:02
371,443,661
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.gcit.drag; public class QContract { }
UTF-8
Java
51
java
QContract.java
Java
[]
null
[]
package edu.gcit.drag; public class QContract { }
51
0.745098
0.745098
4
11.75
11.277743
24
false
false
0
0
0
0
0
0
0.25
false
false
5
6b8b686e768154e5c3d26f7a5fb2203c4992a477
7,241,314,919,714
a874fa3aad7035f714c53d4c00621bdf8c404763
/src/college_erp/ser/Delrece.java
00cee521089856be510e215588ae22c16b9a373b
[]
no_license
Shamture/CollegeERP
https://github.com/Shamture/CollegeERP
b165cb1c82167aba775c5acfea8f0a0d51b0b0d1
d0a16feecc4f2098b00107b129f00496030c25b2
refs/heads/master
2020-04-05T20:46:57.987000
2018-05-01T18:00:16
2018-05-01T18:00:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package college_erp.ser; import java.io.IOException; import java.net.URLEncoder; import java.sql.ResultSet; import javax.servlet.RequestDispatcher; 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 college_erp.dbutil.CrudOperation; /** * Servlet implementation class Delrece */ @WebServlet("/Delrece") public class Delrece extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Delrece() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub ResultSet rs=null; String emp=request.getParameter("emp"); String str="select * from employee where emp_id=?"; try {rs=CrudOperation.getData(str, emp); if(rs.next()) { request.setAttribute("empv",emp); RequestDispatcher rd=request.getRequestDispatcher("/jsp/delrecorde.jsp"); rd.forward(request, response); } else { String message = "Employee Id not found"; response.sendRedirect("/college_erp/jsp/deleterece.jsp?message=" + URLEncoder.encode(message, "UTF-8")); } } catch(Exception e) { } } }
UTF-8
Java
1,788
java
Delrece.java
Java
[]
null
[]
package college_erp.ser; import java.io.IOException; import java.net.URLEncoder; import java.sql.ResultSet; import javax.servlet.RequestDispatcher; 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 college_erp.dbutil.CrudOperation; /** * Servlet implementation class Delrece */ @WebServlet("/Delrece") public class Delrece extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Delrece() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub ResultSet rs=null; String emp=request.getParameter("emp"); String str="select * from employee where emp_id=?"; try {rs=CrudOperation.getData(str, emp); if(rs.next()) { request.setAttribute("empv",emp); RequestDispatcher rd=request.getRequestDispatcher("/jsp/delrecorde.jsp"); rd.forward(request, response); } else { String message = "Employee Id not found"; response.sendRedirect("/college_erp/jsp/deleterece.jsp?message=" + URLEncoder.encode(message, "UTF-8")); } } catch(Exception e) { } } }
1,788
0.73434
0.733221
67
25.686567
28.646694
119
false
false
0
0
0
0
0
0
1.447761
false
false
5
dd305910abb0542192861c9770b63736ecd9057d
30,640,296,718,513
63ad68453a9328ca35d682b29bba0a8097941040
/hframe-target/src/main/java/com/ucfgroup/client/beetle/bean/GetRegDetailResponse.java
b7d6a203f5c2c6e9148f8e0f45a8f0e02c5a73f8
[]
no_license
duduniao666/hframe-trunk
https://github.com/duduniao666/hframe-trunk
0f8641fbeb583f7e83afacaf8158b2e1e847c9e9
bd54d88b18843b068d9ddba4e915909d3460c4aa
refs/heads/master
2020-07-25T18:26:39.867000
2017-07-12T06:59:45
2017-07-12T06:59:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ucfgroup.client.beetle.bean; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import com.hframework.common.util.message.XmlUtils; import com.thoughtworks.xstream.annotations.XStreamOmitField; import com.ucfgroup.client.beetle.bean.getregdetailresponse.*; /** * generated by hframework on 2016-04-22. */ public class GetRegDetailResponse { @JsonProperty("error_code") private String errorCode; @JsonProperty("error_msg") private String errorMsg; @JsonProperty("data") private List<Data> dataList; @XStreamOmitField private boolean converted; public GetRegDetailResponse() { } public GetRegDetailResponse convert() throws Exception{ if(!converted) { String beforeInfo = XmlUtils.writeValueAsString(this); System.out.println(beforeInfo); converted = true; String afterInfo = XmlUtils.writeValueAsString(this); System.out.println(afterInfo); } return this; } public String getErrorCode(){ return errorCode; } public void setErrorCode(String errorCode){ this.errorCode = errorCode; } public String getErrorMsg(){ return errorMsg; } public void setErrorMsg(String errorMsg){ this.errorMsg = errorMsg; } public List<Data> getDataList(){ return dataList; } public void setDataList(List<Data> dataList){ this.dataList = dataList; } }
UTF-8
Java
1,463
java
GetRegDetailResponse.java
Java
[ { "context": "ean.getregdetailresponse.*;\n\n/**\n * generated by hframework on 2016-04-22.\n */\npublic class GetRegDetailRespo", "end": 328, "score": 0.6133700609207153, "start": 319, "tag": "USERNAME", "value": "framework" } ]
null
[]
package com.ucfgroup.client.beetle.bean; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import com.hframework.common.util.message.XmlUtils; import com.thoughtworks.xstream.annotations.XStreamOmitField; import com.ucfgroup.client.beetle.bean.getregdetailresponse.*; /** * generated by hframework on 2016-04-22. */ public class GetRegDetailResponse { @JsonProperty("error_code") private String errorCode; @JsonProperty("error_msg") private String errorMsg; @JsonProperty("data") private List<Data> dataList; @XStreamOmitField private boolean converted; public GetRegDetailResponse() { } public GetRegDetailResponse convert() throws Exception{ if(!converted) { String beforeInfo = XmlUtils.writeValueAsString(this); System.out.println(beforeInfo); converted = true; String afterInfo = XmlUtils.writeValueAsString(this); System.out.println(afterInfo); } return this; } public String getErrorCode(){ return errorCode; } public void setErrorCode(String errorCode){ this.errorCode = errorCode; } public String getErrorMsg(){ return errorMsg; } public void setErrorMsg(String errorMsg){ this.errorMsg = errorMsg; } public List<Data> getDataList(){ return dataList; } public void setDataList(List<Data> dataList){ this.dataList = dataList; } }
1,463
0.691046
0.685578
64
21.859375
19.161213
62
false
false
0
0
0
0
0
0
1.140625
false
false
5
6b197db2d9dd29a857330b5f5a00394a42eb5c4e
26,456,998,557,095
fb7f111be4ae4ef68aed14a95aea76b18452ad35
/src/main/java/com/example/demo/test/dataStructureAndArithmetic/tree/binaryTree/nodeModel/Node.java
db6f5240bef838b98055d2996d4183291297c1d1
[]
no_license
LiuJie6/SpringBootTest
https://github.com/LiuJie6/SpringBootTest
79414fc58a8fe2bfe6fec8a33287f0d1da81fee2
900631571658b961142300b79abb3f02545dd8bc
refs/heads/master
2020-03-28T12:25:53.041000
2019-02-15T09:52:33
2019-02-15T09:52:33
148,296,977
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.test.dataStructureAndArithmetic.tree.binaryTree.nodeModel; /** * Project Name:SpringBootTest * File Name:Node * Package Name:com.example.demo.test.dataStructureAndArithmetic.binaryTree * Date:2018/11/20 * Author:liujie * Description: * Copyright (c) 2018, 重庆云凯科技有限公司 All Rights Reserved. */ public class Node { private int data; //节点数据 private Node leftChild; //左节点 private Node rightChild; //右节点 private boolean isDeleted; //标识是否已删除 public Node(int data){ this.data = data; } public int getData() { return data; } public void setData(int data) { this.data = data; } public Node getLeftChild() { return leftChild; } public void setLeftChild(Node leftChild) { this.leftChild = leftChild; } public Node getRightChild() { return rightChild; } public void setRightChild(Node rightChild) { this.rightChild = rightChild; } public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean deleted) { isDeleted = deleted; } /** * 打印节点内容 */ public void printNode(){ System.out.println(data); } }
UTF-8
Java
1,320
java
Node.java
Java
[ { "context": "rithmetic.binaryTree\n * Date:2018/11/20\n * Author:liujie\n * Description:\n * Copyright (c) 2018, 重庆云凯科技有限公司", "end": 249, "score": 0.9995226263999939, "start": 243, "tag": "USERNAME", "value": "liujie" } ]
null
[]
package com.example.demo.test.dataStructureAndArithmetic.tree.binaryTree.nodeModel; /** * Project Name:SpringBootTest * File Name:Node * Package Name:com.example.demo.test.dataStructureAndArithmetic.binaryTree * Date:2018/11/20 * Author:liujie * Description: * Copyright (c) 2018, 重庆云凯科技有限公司 All Rights Reserved. */ public class Node { private int data; //节点数据 private Node leftChild; //左节点 private Node rightChild; //右节点 private boolean isDeleted; //标识是否已删除 public Node(int data){ this.data = data; } public int getData() { return data; } public void setData(int data) { this.data = data; } public Node getLeftChild() { return leftChild; } public void setLeftChild(Node leftChild) { this.leftChild = leftChild; } public Node getRightChild() { return rightChild; } public void setRightChild(Node rightChild) { this.rightChild = rightChild; } public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean deleted) { isDeleted = deleted; } /** * 打印节点内容 */ public void printNode(){ System.out.println(data); } }
1,320
0.621212
0.611643
63
18.904762
18.934904
83
false
false
0
0
0
0
0
0
0.253968
false
false
5
14452c71f648e3933b41974f58d897578be28f9c
2,972,117,425,352
02edb46246fa55009629e95084b634399fbcf446
/src/cs3500/animator/view/panel/AnimationPanel.java
f501eb74b11e6dee14764347e178db3dcc94d79d
[]
no_license
yasz24/Animator
https://github.com/yasz24/Animator
6bed730d9655a06ea68c527cb59594b08f7dc6fa
90bc70f11577429d48c806dccb9a4fe7a5cb54ef
refs/heads/master
2020-04-01T05:56:14.313000
2018-10-23T06:10:36
2018-10-23T06:10:36
124,985,737
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cs3500.animator.view.panel; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; import cs3500.animator.model.actor.IActor; import cs3500.animator.model.actor.IVisitableActor; import cs3500.animator.view.visitors.ModelVisitor; import cs3500.animator.view.visitors.SwingViewVisitor; /** * This class represents the Panel on which the shapes being drawn are displayed. * It essentially loops through given actors and renders them. * This panel is to be placed on a class extending JFrame. */ public class AnimationPanel extends JPanel implements IAnimationPanel { /** * Actors to be rendered. */ private List<IVisitableActor> actors; /** * Create a new {@code AnimationPanel} with no {@code IVisitableActor}s. */ public AnimationPanel() { this.actors = new ArrayList<>(); } @Override public void setActors(List<IVisitableActor> list) { if (list == null) { throw new IllegalArgumentException("Given a null list"); } this.actors = list; } @Override protected void paintComponent(Graphics g) { //ensures all functionality of the paint component method in the super class is still //implemented. super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; ModelVisitor<Graphics2D> visitor = new SwingViewVisitor(g2d); // Loop through all the actors and render them if they're visible. for (IActor a : actors) { if (a.isVisible()) { visitor.visit(a.getShape()); } } } }
UTF-8
Java
1,572
java
AnimationPanel.java
Java
[]
null
[]
package cs3500.animator.view.panel; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; import cs3500.animator.model.actor.IActor; import cs3500.animator.model.actor.IVisitableActor; import cs3500.animator.view.visitors.ModelVisitor; import cs3500.animator.view.visitors.SwingViewVisitor; /** * This class represents the Panel on which the shapes being drawn are displayed. * It essentially loops through given actors and renders them. * This panel is to be placed on a class extending JFrame. */ public class AnimationPanel extends JPanel implements IAnimationPanel { /** * Actors to be rendered. */ private List<IVisitableActor> actors; /** * Create a new {@code AnimationPanel} with no {@code IVisitableActor}s. */ public AnimationPanel() { this.actors = new ArrayList<>(); } @Override public void setActors(List<IVisitableActor> list) { if (list == null) { throw new IllegalArgumentException("Given a null list"); } this.actors = list; } @Override protected void paintComponent(Graphics g) { //ensures all functionality of the paint component method in the super class is still //implemented. super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; ModelVisitor<Graphics2D> visitor = new SwingViewVisitor(g2d); // Loop through all the actors and render them if they're visible. for (IActor a : actors) { if (a.isVisible()) { visitor.visit(a.getShape()); } } } }
1,572
0.711196
0.694656
59
25.644068
24.896235
89
false
false
0
0
0
0
0
0
0.305085
false
false
5
cbc8a98588e995e5ba5ffd8a8274428b068a8d43
9,500,467,682,570
c0b0d01777dc94b0f64c02b7affd1039239786ad
/src/tutorial/java/regularexpression/runApp/RegrexDemo.java
aaf664ea1cf43ffb858461d1ee2105d4ea3ab60f
[]
no_license
praveen0216/JavaTutorial
https://github.com/praveen0216/JavaTutorial
cd14a5e35f25d9308795691da27dbaaaacd1f139
b27fe3381a9cabf235e6cf98cf8344eb7a70ba80
refs/heads/master
2023-08-17T10:41:47.381000
2023-08-12T10:32:58
2023-08-12T10:32:58
356,208,793
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tutorial.java.regularexpression.runApp; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegrexDemo { public static void main(String[] args) { Supplier<String> supplier=()-> { List<String> s = Arrays.asList("Praveen Kumar Sharma","Rahul Yadav","Puneet Sharma","Ruma Rath","KK Singh", "Arvind Gupta","Ronit Sandhu","Nishant Jaiswal","Divya","Ankit Sinha1","@nkur","Litty"); return s.get((int)(Math.random()*(s.size()))); }; String str=supplier.get(); System.err.println(str); Pattern pattern = Pattern.compile(str, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher("@nkur"); boolean matchFound = matcher.find(); if(matchFound) { System.err.println("Match found"); } else { System.err.println("Match not found"); } } }
UTF-8
Java
938
java
RegrexDemo.java
Java
[ { "context": "plier=()-> {\n\t\t\t List<String> s = Arrays.asList(\"Praveen Kumar Sharma\",\"Rahul Yadav\",\"Puneet Sharma\",\"Ruma Rath\",\"KK Si", "end": 365, "score": 0.9998301267623901, "start": 345, "tag": "NAME", "value": "Praveen Kumar Sharma" }, { "context": "String> s = Arrays.asList(\"Praveen Kumar Sharma\",\"Rahul Yadav\",\"Puneet Sharma\",\"Ruma Rath\",\"KK Singh\",\n\t\t\t\t\t \"", "end": 379, "score": 0.9998417496681213, "start": 368, "tag": "NAME", "value": "Rahul Yadav" }, { "context": "rays.asList(\"Praveen Kumar Sharma\",\"Rahul Yadav\",\"Puneet Sharma\",\"Ruma Rath\",\"KK Singh\",\n\t\t\t\t\t \"Arvind Gupta\",\"R", "end": 395, "score": 0.9998259544372559, "start": 382, "tag": "NAME", "value": "Puneet Sharma" }, { "context": "veen Kumar Sharma\",\"Rahul Yadav\",\"Puneet Sharma\",\"Ruma Rath\",\"KK Singh\",\n\t\t\t\t\t \"Arvind Gupta\",\"Ronit Sandhu\"", "end": 407, "score": 0.9998371601104736, "start": 398, "tag": "NAME", "value": "Ruma Rath" }, { "context": "harma\",\"Rahul Yadav\",\"Puneet Sharma\",\"Ruma Rath\",\"KK Singh\",\n\t\t\t\t\t \"Arvind Gupta\",\"Ronit Sandhu\",\"Nishant J", "end": 418, "score": 0.9997994899749756, "start": 410, "tag": "NAME", "value": "KK Singh" }, { "context": "\",\"Puneet Sharma\",\"Ruma Rath\",\"KK Singh\",\n\t\t\t\t\t \"Arvind Gupta\",\"Ronit Sandhu\",\"Nishant Jaiswal\",\"Divya\",\"Ankit ", "end": 441, "score": 0.9998446702957153, "start": 429, "tag": "NAME", "value": "Arvind Gupta" }, { "context": "a\",\"Ruma Rath\",\"KK Singh\",\n\t\t\t\t\t \"Arvind Gupta\",\"Ronit Sandhu\",\"Nishant Jaiswal\",\"Divya\",\"Ankit Sinha1\",\"@nkur\"", "end": 456, "score": 0.9998375177383423, "start": 444, "tag": "NAME", "value": "Ronit Sandhu" }, { "context": "\"KK Singh\",\n\t\t\t\t\t \"Arvind Gupta\",\"Ronit Sandhu\",\"Nishant Jaiswal\",\"Divya\",\"Ankit Sinha1\",\"@nkur\",\"Litty\");\n\t\t\t re", "end": 474, "score": 0.9998371601104736, "start": 459, "tag": "NAME", "value": "Nishant Jaiswal" }, { "context": " \"Arvind Gupta\",\"Ronit Sandhu\",\"Nishant Jaiswal\",\"Divya\",\"Ankit Sinha1\",\"@nkur\",\"Litty\");\n\t\t\t return s.g", "end": 482, "score": 0.999550461769104, "start": 477, "tag": "NAME", "value": "Divya" }, { "context": " Gupta\",\"Ronit Sandhu\",\"Nishant Jaiswal\",\"Divya\",\"Ankit Sinha1\",\"@nkur\",\"Litty\");\n\t\t\t return s.get((int)(Math.r", "end": 497, "score": 0.9982563853263855, "start": 485, "tag": "NAME", "value": "Ankit Sinha1" }, { "context": "Sandhu\",\"Nishant Jaiswal\",\"Divya\",\"Ankit Sinha1\",\"@nkur\",\"Litty\");\n\t\t\t return s.get((int)(Math.random()*", "end": 505, "score": 0.9566466808319092, "start": 500, "tag": "USERNAME", "value": "@nkur" }, { "context": "shant Jaiswal\",\"Divya\",\"Ankit Sinha1\",\"@nkur\",\"Litty\");\n\t\t\t return s.get((int)(Math.random()*(s.size(", "end": 513, "score": 0.859904944896698, "start": 511, "tag": "NAME", "value": "ty" }, { "context": "SENSITIVE);\n\t Matcher matcher = pattern.matcher(\"@nkur\");\n\t boolean matchFound = matcher.find();\n\t ", "end": 754, "score": 0.9790839552879333, "start": 749, "tag": "USERNAME", "value": "@nkur" } ]
null
[]
package tutorial.java.regularexpression.runApp; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegrexDemo { public static void main(String[] args) { Supplier<String> supplier=()-> { List<String> s = Arrays.asList("<NAME>","<NAME>","<NAME>","<NAME>","<NAME>", "<NAME>","<NAME>","<NAME>","Divya","<NAME>","@nkur","Litty"); return s.get((int)(Math.random()*(s.size()))); }; String str=supplier.get(); System.err.println(str); Pattern pattern = Pattern.compile(str, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher("@nkur"); boolean matchFound = matcher.find(); if(matchFound) { System.err.println("Match found"); } else { System.err.println("Match not found"); } } }
880
0.666311
0.665245
30
30.299999
26.950758
112
false
false
0
0
0
0
0
0
2.033333
false
false
5
8d1fb5352f10c8e1369dc9de35541c9b39be3aef
21,861,383,604,720
009c3f1b8305bad65292e002ee357d6ce2a97d2f
/bookstore/src/bookstore/entities/BookTest.java
c2f0393f56dd3d72ecf8e3bf739c717fbb8430bd
[]
no_license
h1madona/bookstore-arbetsprov
https://github.com/h1madona/bookstore-arbetsprov
a0c9f7177c20cbdd67b4eb7bd83ebd8ff3578acf
6d5561b4e5b90a7d5355e27e299e96b61e7b7017
refs/heads/master
2021-04-28T14:51:37.780000
2018-02-20T06:09:24
2018-02-20T06:09:24
121,965,986
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bookstore.entities; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.BigDecimal; import org.junit.Before; import org.junit.Test; import bookstore.services.StoreManager; public class BookTest { StoreManager storeManager; Book testBookA; Book testBookB; @Before public void initialize() { storeManager = new StoreManager(); testBookA = new Book(); testBookA.setTitle("testTitleA"); testBookA.setAuthor("testAuthorA"); testBookA.setPrice(BigDecimal.ONE); testBookB = new Book(); testBookB.setTitle("testTitleB"); testBookB.setAuthor("testAuthorB"); testBookB.setPrice(BigDecimal.ONE); } @Test public void testEqualsIfTwoBooksHaveSameTitleAuthorPrice() { Book anotherBook = new Book(); anotherBook.setTitle("testTitleA"); anotherBook.setAuthor("testAuthorA"); anotherBook.setPrice(BigDecimal.ONE); assertTrue(testBookA.equals(anotherBook)); } @Test public void testCompareTo() { int actualCompareResult = testBookA.compareTo(testBookB); int expectedCompareResult = -1;//this means that the comparing instance(testBookA) should come before the compared instance(testBookB). assertEquals(expectedCompareResult, actualCompareResult); } }
UTF-8
Java
1,359
java
BookTest.java
Java
[]
null
[]
package bookstore.entities; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.BigDecimal; import org.junit.Before; import org.junit.Test; import bookstore.services.StoreManager; public class BookTest { StoreManager storeManager; Book testBookA; Book testBookB; @Before public void initialize() { storeManager = new StoreManager(); testBookA = new Book(); testBookA.setTitle("testTitleA"); testBookA.setAuthor("testAuthorA"); testBookA.setPrice(BigDecimal.ONE); testBookB = new Book(); testBookB.setTitle("testTitleB"); testBookB.setAuthor("testAuthorB"); testBookB.setPrice(BigDecimal.ONE); } @Test public void testEqualsIfTwoBooksHaveSameTitleAuthorPrice() { Book anotherBook = new Book(); anotherBook.setTitle("testTitleA"); anotherBook.setAuthor("testAuthorA"); anotherBook.setPrice(BigDecimal.ONE); assertTrue(testBookA.equals(anotherBook)); } @Test public void testCompareTo() { int actualCompareResult = testBookA.compareTo(testBookB); int expectedCompareResult = -1;//this means that the comparing instance(testBookA) should come before the compared instance(testBookB). assertEquals(expectedCompareResult, actualCompareResult); } }
1,359
0.734363
0.733628
54
23.166666
23.9496
137
false
false
0
0
0
0
0
0
1.611111
false
false
5
6565e5564352b6438e171d3b2ad8352f54919d73
27,685,359,230,308
50228d083d966f9ce1a609f5cc9c5508a7bf7c1c
/src/unmsm/edu/pe/practica/dao/component/EmpresaDAO.java
6db125d6140d0aff58b037eff69f82cf184feff7
[]
no_license
szab0/PatronDAOExample
https://github.com/szab0/PatronDAOExample
aea0ff97f70d327754a68675a08aa5b6f966d9e0
f6d162c9da5e591631036adbe2ac89d6bb9ecb1c
refs/heads/master
2022-02-22T04:31:39.596000
2019-09-25T08:02:46
2019-09-25T08:02:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package unmsm.edu.pe.practica.dao.component; import unmsm.edu.pe.practica.dao.design.IEmpresaDAO; import unmsm.edu.pe.practica.dao.ds.DBAccess; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import unmsm.edu.pe.practica.dao.objects.Empresa; /** * * @author Usuario */ public class EmpresaDAO implements IEmpresaDAO { private DBAccess db; public EmpresaDAO(){ db = new DBAccess(); } @Override public ArrayList<Empresa> getListaEmpresas() { ArrayList<Empresa> listaEmpresas = new ArrayList<>(); Empresa ep = null; Connection cn = db.getConnection(); try { PreparedStatement ps = cn.prepareStatement("SELECT IDEMPRESA, NOMEMPRESA, PRESIDENTE, TIPOFILIAL, PAGOPORHORA " + "FROM EMPRESA"); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { ep = new Empresa(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3), resultSet.getString(4), resultSet.getInt(5)); listaEmpresas.add(ep); } } catch (SQLException e) { System.out.println("Error crear la sentencia " + e.getMessage()); } return listaEmpresas; } }
UTF-8
Java
1,742
java
EmpresaDAO.java
Java
[ { "context": "tica.dao.objects.Empresa;\r\n\r\n\r\n/**\r\n *\r\n * @author Usuario\r\n */\r\npublic class EmpresaDAO implements IEmpresa", "end": 574, "score": 0.8003220558166504, "start": 567, "tag": "NAME", "value": "Usuario" } ]
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 unmsm.edu.pe.practica.dao.component; import unmsm.edu.pe.practica.dao.design.IEmpresaDAO; import unmsm.edu.pe.practica.dao.ds.DBAccess; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import unmsm.edu.pe.practica.dao.objects.Empresa; /** * * @author Usuario */ public class EmpresaDAO implements IEmpresaDAO { private DBAccess db; public EmpresaDAO(){ db = new DBAccess(); } @Override public ArrayList<Empresa> getListaEmpresas() { ArrayList<Empresa> listaEmpresas = new ArrayList<>(); Empresa ep = null; Connection cn = db.getConnection(); try { PreparedStatement ps = cn.prepareStatement("SELECT IDEMPRESA, NOMEMPRESA, PRESIDENTE, TIPOFILIAL, PAGOPORHORA " + "FROM EMPRESA"); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { ep = new Empresa(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3), resultSet.getString(4), resultSet.getInt(5)); listaEmpresas.add(ep); } } catch (SQLException e) { System.out.println("Error crear la sentencia " + e.getMessage()); } return listaEmpresas; } }
1,742
0.578645
0.575775
64
25.21875
26.79871
125
false
false
0
0
0
0
0
0
0.484375
false
false
5
047e910655d0c4ee0e5e09f12b56f3948a237858
17,686,675,373,657
378fa5175f79d1666b4c71b64bf47def67d2b7ee
/app/src/main/java/yuki/kit/ep/syussekinowtest/MyAdapter.java
0bea3043a960ac176e3d72969c85a88769f499d0
[]
no_license
YukiShimba/SyussekiNowTest
https://github.com/YukiShimba/SyussekiNowTest
3e6ca0bf93639363e1ebec9ee9a18e6efb70dd09
5d967cac8810ea682b25262ab36a84b89e49043a
refs/heads/master
2015-09-24T18:18:56.603000
2015-07-04T09:27:16
2015-07-04T09:27:16
38,297,288
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package yuki.kit.ep.syussekinowtest; import android.content.Context; import android.view.LayoutInflater; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.zip.Inflater; /** * Created by yuki on 2015/06/29. */ public class MyAdapter extends ArrayAdapter<Data> { private Context mContext; private LayoutInflater inflater; public MyAdapter(Context context, ArrayList<Data> objects){ super(context, 0, objects); inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mContext = context; } @Override public View getView(int position, View convertView, ViewGroup parent){ Data mData = getItem(position); if(convertView == null) { convertView = inflater.inflate(R.layout.custom_view, parent, false); } TextView name = (TextView)convertView.findViewById(R.id.textView_name); name.setText(mData.getName()); TextView id = (TextView)convertView.findViewById(R.id.textView_id); id.setText(String.valueOf(mData.getId())); TextView state = (TextView)convertView.findViewById(R.id.textView_state); state.setText(String.valueOf(mData.getState())); return convertView; } }
UTF-8
Java
1,420
java
MyAdapter.java
Java
[ { "context": "\nimport java.util.zip.Inflater;\n\n/**\n * Created by yuki on 2015/06/29.\n */\npublic class MyAdapter extends", "end": 373, "score": 0.9996352195739746, "start": 369, "tag": "USERNAME", "value": "yuki" } ]
null
[]
package yuki.kit.ep.syussekinowtest; import android.content.Context; import android.view.LayoutInflater; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.zip.Inflater; /** * Created by yuki on 2015/06/29. */ public class MyAdapter extends ArrayAdapter<Data> { private Context mContext; private LayoutInflater inflater; public MyAdapter(Context context, ArrayList<Data> objects){ super(context, 0, objects); inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mContext = context; } @Override public View getView(int position, View convertView, ViewGroup parent){ Data mData = getItem(position); if(convertView == null) { convertView = inflater.inflate(R.layout.custom_view, parent, false); } TextView name = (TextView)convertView.findViewById(R.id.textView_name); name.setText(mData.getName()); TextView id = (TextView)convertView.findViewById(R.id.textView_id); id.setText(String.valueOf(mData.getId())); TextView state = (TextView)convertView.findViewById(R.id.textView_state); state.setText(String.valueOf(mData.getState())); return convertView; } }
1,420
0.708451
0.701408
46
29.869566
25.884869
93
false
false
0
0
0
0
0
0
0.695652
false
false
5
e37e5f7e06003a7bf695add35e461f7130d001e6
31,250,182,054,733
8c58072b50d9564e4521838e41d79aa4c29cf3b7
/src/test/java/org/qacamp/tests/advanced/GoogleTranslation.java
e68a6c230e26981616aa7c3c3aa6e9374e84860b
[]
no_license
rotyuskiy/SeleniumEasy
https://github.com/rotyuskiy/SeleniumEasy
0b448646f5f64e93547708b599f8a837c1381017
52ee1f7ed04e2b828e25afa5783012dba32b8ded
refs/heads/master
2016-09-07T22:41:47.343000
2016-07-08T17:54:05
2016-07-08T17:54:05
38,124,237
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.qacamp.tests.advanced; import junit.framework.Assert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.qacamp.pages.PGoogleTranslate; import org.qacamp.utils.Browser; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Created on 6/25/2015. */ public class GoogleTranslation { private WebDriver driver; @BeforeClass public void beforeClass() { driver = Browser.setup(new FirefoxDriver()); } @AfterClass public void afterClass() { driver.quit(); } @Test public void engToFrenchCheeseTranslate() { PGoogleTranslate pGoogleTranslate = new PGoogleTranslate(driver); String wordToTranslate = "Cheese", expectedResult = "fromage"; pGoogleTranslate.setLanguages("English", "French"); String actualResult = pGoogleTranslate.translateWord(wordToTranslate); Assert.assertEquals(expectedResult, actualResult); } @Test(priority = 1) public void engToSpanishCheeseTranslate() { PGoogleTranslate pGoogleTranslate = new PGoogleTranslate(driver); String wordToTranslate = "Cheese", expectedResult = "queso"; pGoogleTranslate.setLanguages("English", "Spanish"); String actualResult = pGoogleTranslate.translateWord(wordToTranslate); Assert.assertEquals(expectedResult, actualResult); } }
UTF-8
Java
1,504
java
GoogleTranslation.java
Java
[]
null
[]
package org.qacamp.tests.advanced; import junit.framework.Assert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.qacamp.pages.PGoogleTranslate; import org.qacamp.utils.Browser; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Created on 6/25/2015. */ public class GoogleTranslation { private WebDriver driver; @BeforeClass public void beforeClass() { driver = Browser.setup(new FirefoxDriver()); } @AfterClass public void afterClass() { driver.quit(); } @Test public void engToFrenchCheeseTranslate() { PGoogleTranslate pGoogleTranslate = new PGoogleTranslate(driver); String wordToTranslate = "Cheese", expectedResult = "fromage"; pGoogleTranslate.setLanguages("English", "French"); String actualResult = pGoogleTranslate.translateWord(wordToTranslate); Assert.assertEquals(expectedResult, actualResult); } @Test(priority = 1) public void engToSpanishCheeseTranslate() { PGoogleTranslate pGoogleTranslate = new PGoogleTranslate(driver); String wordToTranslate = "Cheese", expectedResult = "queso"; pGoogleTranslate.setLanguages("English", "Spanish"); String actualResult = pGoogleTranslate.translateWord(wordToTranslate); Assert.assertEquals(expectedResult, actualResult); } }
1,504
0.705452
0.700133
51
28.490196
23.655512
78
false
false
0
0
0
0
0
0
0.54902
false
false
5
f3148706e4319dd9134ad1eb247565848f655d4b
33,028,298,517,056
9c0b95cc09d63618306c732f651989ee6c7c3b71
/Main.java
d671161a31a617a9b431face06678135630a1812
[]
no_license
Kk948/5.2-Runestone-challenge
https://github.com/Kk948/5.2-Runestone-challenge
ed67fb1c950ef8092d30eec5e8b1f19de8b15f95
d323f8897267124f099dcdf1be0820e216c1395e
refs/heads/master
2023-01-31T22:08:41.898000
2020-12-16T13:58:54
2020-12-16T13:58:54
321,999,306
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Main { public static void main(String[] args) { student s1 = new student(); student s2 = new student("Herbology"); student s3 = new student("Divination","Callum","Taurus","wind"); student s4 = new student("Charms","Duncan","Piseces","Metal"); s1.print(); s2.print(); s3.print(); s4.print(); } }
UTF-8
Java
337
java
Main.java
Java
[ { "context": "udent(\"Herbology\");\n student s3 = new student(\"Divination\",\"Callum\",\"Taurus\",\"wind\");\n student s4 = new ", "end": 171, "score": 0.9998395442962646, "start": 161, "tag": "NAME", "value": "Divination" }, { "context": "ogy\");\n student s3 = new student(\"Divination\",\"Callum\",\"Taurus\",\"wind\");\n student s4 = new student(\"", "end": 180, "score": 0.9998297691345215, "start": 174, "tag": "NAME", "value": "Callum" }, { "context": " student s3 = new student(\"Divination\",\"Callum\",\"Taurus\",\"wind\");\n student s4 = new student(\"Charms\",\"", "end": 189, "score": 0.9997912049293518, "start": 183, "tag": "NAME", "value": "Taurus" }, { "context": " s3 = new student(\"Divination\",\"Callum\",\"Taurus\",\"wind\");\n student s4 = new student(\"Charms\",\"Duncan\"", "end": 196, "score": 0.586467981338501, "start": 192, "tag": "NAME", "value": "wind" }, { "context": "\",\"Taurus\",\"wind\");\n student s4 = new student(\"Charms\",\"Duncan\",\"Piseces\",\"Metal\");\n\n s1.print();\n ", "end": 236, "score": 0.9998290538787842, "start": 230, "tag": "NAME", "value": "Charms" }, { "context": "\",\"wind\");\n student s4 = new student(\"Charms\",\"Duncan\",\"Piseces\",\"Metal\");\n\n s1.print();\n s2.prin", "end": 245, "score": 0.9998231530189514, "start": 239, "tag": "NAME", "value": "Duncan" }, { "context": ";\n student s4 = new student(\"Charms\",\"Duncan\",\"Piseces\",\"Metal\");\n\n s1.print();\n s2.print();\n s", "end": 255, "score": 0.9998177886009216, "start": 248, "tag": "NAME", "value": "Piseces" }, { "context": "ent s4 = new student(\"Charms\",\"Duncan\",\"Piseces\",\"Metal\");\n\n s1.print();\n s2.print();\n s3.print(", "end": 263, "score": 0.9992254972457886, "start": 258, "tag": "NAME", "value": "Metal" } ]
null
[]
class Main { public static void main(String[] args) { student s1 = new student(); student s2 = new student("Herbology"); student s3 = new student("Divination","Callum","Taurus","wind"); student s4 = new student("Charms","Duncan","Piseces","Metal"); s1.print(); s2.print(); s3.print(); s4.print(); } }
337
0.599407
0.575668
13
25
22.18454
68
false
false
0
0
0
0
0
0
1.076923
false
false
5
d8e94860909c16e5cfd393565dbe3c3686d454b3
27,255,862,511,533
3d5b57564f71bc40f2c71abb89ae1a76b8ac6fb2
/microservice-consumer-movie-ribbon-with-hystrix/src/main/java/org/ribbon/hystrix/controller/RibbonHystrixController.java
7892a32424025296b58f01fcdda6acff3b1ab1a8
[]
no_license
zero1814/spring-cloud-study
https://github.com/zero1814/spring-cloud-study
a12c796ac37f35149fef61002b9968fca07bb890
3d0778e86350d7a0f0aef5aa67aed407e9d33ef4
refs/heads/master
2021-05-03T08:09:56.963000
2018-04-12T00:10:06
2018-04-12T00:10:06
120,560,466
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.ribbon.hystrix.controller; import org.ribbon.hystrix.entity.User; import org.ribbon.hystrix.service.RibbonHystrixService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class RibbonHystrixController { @Autowired private RibbonHystrixService ribbonHystrixService; @GetMapping("{id}") public User findById(@PathVariable Long id) { return this.ribbonHystrixService.findById(id); } }
UTF-8
Java
624
java
RibbonHystrixController.java
Java
[]
null
[]
package org.ribbon.hystrix.controller; import org.ribbon.hystrix.entity.User; import org.ribbon.hystrix.service.RibbonHystrixService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class RibbonHystrixController { @Autowired private RibbonHystrixService ribbonHystrixService; @GetMapping("{id}") public User findById(@PathVariable Long id) { return this.ribbonHystrixService.findById(id); } }
624
0.833333
0.833333
19
31.842106
23.526609
62
false
false
0
0
0
0
0
0
0.842105
false
false
5
f7cfd87edcdcb8d85bb2f485861a25484266cf78
15,436,112,514,613
a1d17193731c0b627763098d7428eb02fda221ae
/src/main/java/com/lind/basic/config/RedisCacheConfig.java
f1fbe8e34c6021aada9f20fef76a64dce6bb6905
[]
no_license
yupengj/basic
https://github.com/yupengj/basic
6fb5a19844133a0b979272e882e9e27ce6b2e8d2
37069bd851699e5d52c3171406de6fba28f153cc
refs/heads/master
2020-05-17T02:58:01.362000
2019-01-21T06:21:29
2019-01-21T06:21:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lind.basic.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import java.time.Duration; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; @EnableCaching @Configuration public class RedisCacheConfig { /** * config. * * @return */ @Bean public RedisCacheConfiguration redisCacheConfiguration() { Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 持久化到redis里为json,默认是二进制 RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(300)) .serializeValuesWith(pair); return redisCacheConfiguration; } /** * cacheManager. * * @param connectionFactory . * @return */ @Bean public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) { //初始化一个RedisCacheWriter RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory); //初始化RedisCacheManager RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration()); return cacheManager; } }
UTF-8
Java
2,286
java
RedisCacheConfig.java
Java
[]
null
[]
package com.lind.basic.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import java.time.Duration; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; @EnableCaching @Configuration public class RedisCacheConfig { /** * config. * * @return */ @Bean public RedisCacheConfiguration redisCacheConfiguration() { Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 持久化到redis里为json,默认是二进制 RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(300)) .serializeValuesWith(pair); return redisCacheConfiguration; } /** * cacheManager. * * @param connectionFactory . * @return */ @Bean public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) { //初始化一个RedisCacheWriter RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory); //初始化RedisCacheManager RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration()); return cacheManager; } }
2,286
0.801693
0.797683
63
34.619049
28.494738
98
false
false
0
0
0
0
0
0
0.428571
false
false
5
b3f4c6f2b928ed47d945f75f38fb70c24f61bd27
29,755,533,490,489
4a121576c33c398330786df78d16f6a993cd40d9
/src/main/java/Topcoder/CoinFlipsDiv2.java
bc286787a947938e6d4566b49ad60271768f8c4e
[]
no_license
mdasadul/Java
https://github.com/mdasadul/Java
e0b31a870ee438c3910e87e942e605986d0124bc
232e95e5e08b7ab4db37b2d800655e22f9703264
refs/heads/master
2021-01-18T23:25:56.062000
2016-05-28T16:33:27
2016-05-28T16:33:27
37,553,939
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Topcoder; public class CoinFlipsDiv2 { public int countCoins(String state) { int count =0; if(state.length() <=1) { return 0; } if(state.charAt(0) !=state.charAt(1)) { count++; } for(int i=1;i<state.length()-1;++i) { if(state.charAt(i-1) !=state.charAt(i)) { count++; }else if(state.charAt(i) !=state.charAt(i+1)) { count++; } } if(state.charAt(state.length()-2) !=state.charAt(state.length()-1)) { count++; } return count; } public static void main(String[] args) { // TODO Auto-generated method stub CoinFlipsDiv2 obj = new CoinFlipsDiv2(); System.out.println(obj.countCoins("HTHHT")); System.out.println(obj.countCoins("HHHTTTHHHTTTHTHTH")); System.out.println(obj.countCoins("HHHHH")); System.out.println(obj.countCoins("HHTHHH")); System.out.println(obj.countCoins("HT")); } }
UTF-8
Java
856
java
CoinFlipsDiv2.java
Java
[]
null
[]
package Topcoder; public class CoinFlipsDiv2 { public int countCoins(String state) { int count =0; if(state.length() <=1) { return 0; } if(state.charAt(0) !=state.charAt(1)) { count++; } for(int i=1;i<state.length()-1;++i) { if(state.charAt(i-1) !=state.charAt(i)) { count++; }else if(state.charAt(i) !=state.charAt(i+1)) { count++; } } if(state.charAt(state.length()-2) !=state.charAt(state.length()-1)) { count++; } return count; } public static void main(String[] args) { // TODO Auto-generated method stub CoinFlipsDiv2 obj = new CoinFlipsDiv2(); System.out.println(obj.countCoins("HTHHT")); System.out.println(obj.countCoins("HHHTTTHHHTTTHTHTH")); System.out.println(obj.countCoins("HHHHH")); System.out.println(obj.countCoins("HHTHHH")); System.out.println(obj.countCoins("HT")); } }
856
0.646028
0.629673
34
24.17647
19.98451
71
false
false
0
0
0
0
0
0
2.352941
false
false
5
5b64ffdcd6cc7c535400f8ea6278f01bdaa6f746
29,497,835,428,344
c7e75bfe932cd21d2e14ae7848865cdb523cd3fc
/tobot/src/main/java/com/tobot/tobot/control/demand/Constants.java
42fa493eb4f546ec6f865ad74f807ee2f98da46a
[]
no_license
Tubot2018/Tubot-5.1
https://github.com/Tubot2018/Tubot-5.1
2f12c8d998a5114affae960204c7964463a36136
548ead1d98229c76d032d321fdbd886b75f4ff6d
refs/heads/master
2021-09-06T17:41:38.221000
2018-02-09T06:29:17
2018-02-09T06:29:17
116,338,690
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tobot.tobot.control.demand; /** * Created by YF-04 on 2017/11/3. */ public class Constants { /** * playUrl 和 bodyActionCode(舞蹈编号) 的分隔符 */ public static final String SEPARATOR_BETWEEN_PLAYURL_ACTION="#,#"; /** * 逗号,comma */ public static final String SEPARATOR_COMMA =","; public static final int UNZIP_SUCCESS=894524; public static final int UNZIP_FAILED=146564; public static final int UPDATE_CONFIG_SUCCESS=54865; public static final int UPDATE_CONFIG_FAILED=89758; /** * 舞蹈配置文件 的文件名称 */ public static final String CONFIG_FILE_NAME="config"; /** * 标点符号:点 */ public static final String PUNCTUATION_POINT="."; }
UTF-8
Java
786
java
Constants.java
Java
[ { "context": "com.tobot.tobot.control.demand;\n\n/**\n * Created by YF-04 on 2017/11/3.\n */\n\npublic class Constants {\n\n\n ", "end": 64, "score": 0.9992345571517944, "start": 59, "tag": "USERNAME", "value": "YF-04" } ]
null
[]
package com.tobot.tobot.control.demand; /** * Created by YF-04 on 2017/11/3. */ public class Constants { /** * playUrl 和 bodyActionCode(舞蹈编号) 的分隔符 */ public static final String SEPARATOR_BETWEEN_PLAYURL_ACTION="#,#"; /** * 逗号,comma */ public static final String SEPARATOR_COMMA =","; public static final int UNZIP_SUCCESS=894524; public static final int UNZIP_FAILED=146564; public static final int UPDATE_CONFIG_SUCCESS=54865; public static final int UPDATE_CONFIG_FAILED=89758; /** * 舞蹈配置文件 的文件名称 */ public static final String CONFIG_FILE_NAME="config"; /** * 标点符号:点 */ public static final String PUNCTUATION_POINT="."; }
786
0.634986
0.592287
35
19.742857
22.272779
71
false
false
0
0
0
0
0
0
0.342857
false
false
5
cabc70f3b8a461e60feba4da4d15355bb1e31d09
5,703,716,629,414
49f4c38a8495a3de09eedd864b5765c356e86141
/Course.java
e36944b378072ad91c6e43ae9c5a21cce0053a0c
[]
no_license
DuncantheeDuncan/prep-with-study-guide
https://github.com/DuncantheeDuncan/prep-with-study-guide
c7b031e912273d8086ca287a88172154b26d8162
8c52633ef0ec089551339f3df3af549909ec6175
refs/heads/master
2020-07-04T18:50:32.209000
2020-03-12T00:31:26
2020-03-12T00:31:26
202,380,750
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Course{ // class CourseName{ String courseName; Course(){ Course courseName = new Course();// runtime exception //The constructor of the class Course creates // an object of the class Course, which will // call the constructor again. courseName.courseName= "Programing"; } // } public static void main(String[] args) { Course courseName = new Course(); courseName.courseName = "Language"; System.out.println(courseName.courseName); } }
UTF-8
Java
543
java
Course.java
Java
[]
null
[]
class Course{ // class CourseName{ String courseName; Course(){ Course courseName = new Course();// runtime exception //The constructor of the class Course creates // an object of the class Course, which will // call the constructor again. courseName.courseName= "Programing"; } // } public static void main(String[] args) { Course courseName = new Course(); courseName.courseName = "Language"; System.out.println(courseName.courseName); } }
543
0.609576
0.609576
25
20.76
21.221272
61
false
false
0
0
0
0
0
0
0.28
false
false
5
6d057bbf92cf1fb6b56351f98e6e1ce92ce4861b
16,011,638,135,963
c6b98b918121daf32d01ecd8e7c237a905873b7c
/sunjoy-framework-service/src/main/java/com/sunjoy/framework/service/utils/I18nUtils.java
b4fb8eb8d18d1601e61682a2b797010c57a7af08
[]
no_license
habibliu/sunjoy-framework
https://github.com/habibliu/sunjoy-framework
760f0164e6de6f948271f7648115c979307f2986
bc5dd184c430ddb98ff3b5c4e0f7966a4463daae
refs/heads/master
2020-03-19T16:25:52.317000
2018-08-30T12:38:12
2018-08-30T12:38:12
136,714,997
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sunjoy.framework.service.utils; import java.util.ArrayList; import java.util.Locale; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; @Component public class I18nUtils { @Resource private MessageSource messageSource; public String getMessage(String key) { return this.getMessage(key, (String[]) null); } public String getMessage(String key, String[] args) { return this.getMessage(key, args, (HttpServletRequest) null); } public String getMessage(String key, String[] args, HttpServletRequest request) { return this.getMessage(key, args, (String) null, request); } public String getMessage(String key, String[] args, String defaultMessage, HttpServletRequest request) { Locale locale = null; if (null == request) { locale = Locale.getDefault(); } else { locale = request.getLocale(); } return this.getMessageByLocale(key, args, defaultMessage, locale); } public String getMessageByLocale(String key, String[] args, Locale locale) { return this.getMessageByLocale(key, args, (String) null, locale); } public String getMessageByLocale(String key, String[] args, String defaultMessage, Locale locale) { if (null == locale) { locale = Locale.getDefault(); } return null == defaultMessage ? this.messageSource.getMessage(key, this.getArgsMessage(args, locale), locale) : this.messageSource.getMessage(key, this.getArgsMessage(args, locale), this.messageSource.getMessage(defaultMessage, (Object[]) null, locale), locale); } private Object[] getArgsMessage(String[] args, Locale locale) { if (null != args && args.length != 0) { ArrayList<String> msgs = new ArrayList<String>(); String[] arg3 = args; int arg4 = args.length; for (int arg5 = 0; arg5 < arg4; ++arg5) { String arg = arg3[arg5]; if (null != arg) { msgs.add(this.messageSource.getMessage(arg, (Object[]) null, locale)); } } return msgs.toArray(); } else { return args; } } }
UTF-8
Java
2,091
java
I18nUtils.java
Java
[]
null
[]
package com.sunjoy.framework.service.utils; import java.util.ArrayList; import java.util.Locale; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; @Component public class I18nUtils { @Resource private MessageSource messageSource; public String getMessage(String key) { return this.getMessage(key, (String[]) null); } public String getMessage(String key, String[] args) { return this.getMessage(key, args, (HttpServletRequest) null); } public String getMessage(String key, String[] args, HttpServletRequest request) { return this.getMessage(key, args, (String) null, request); } public String getMessage(String key, String[] args, String defaultMessage, HttpServletRequest request) { Locale locale = null; if (null == request) { locale = Locale.getDefault(); } else { locale = request.getLocale(); } return this.getMessageByLocale(key, args, defaultMessage, locale); } public String getMessageByLocale(String key, String[] args, Locale locale) { return this.getMessageByLocale(key, args, (String) null, locale); } public String getMessageByLocale(String key, String[] args, String defaultMessage, Locale locale) { if (null == locale) { locale = Locale.getDefault(); } return null == defaultMessage ? this.messageSource.getMessage(key, this.getArgsMessage(args, locale), locale) : this.messageSource.getMessage(key, this.getArgsMessage(args, locale), this.messageSource.getMessage(defaultMessage, (Object[]) null, locale), locale); } private Object[] getArgsMessage(String[] args, Locale locale) { if (null != args && args.length != 0) { ArrayList<String> msgs = new ArrayList<String>(); String[] arg3 = args; int arg4 = args.length; for (int arg5 = 0; arg5 < arg4; ++arg5) { String arg = arg3[arg5]; if (null != arg) { msgs.add(this.messageSource.getMessage(arg, (Object[]) null, locale)); } } return msgs.toArray(); } else { return args; } } }
2,091
0.714969
0.70923
72
28.041666
29.642517
111
false
false
0
0
0
0
0
0
2.291667
false
false
5
739072aafd0a7c2e041e74bee8964e9470cb164d
13,460,427,537,799
374625b97c1f520f7b7a71e57fed8307a0b782ab
/com/hbm/render/block/RenderFence.java
c3dfa1384184d4080598cc679fdff0e02550f46b
[ "WTFPL" ]
permissive
yeyuluo123/Hbm-s-Nuclear-Tech-GIT
https://github.com/yeyuluo123/Hbm-s-Nuclear-Tech-GIT
6a05f45e305b03c36d2b1095ad187e4bcced98c3
011b6cf147389f255dc669249d7997ebd97e6e24
refs/heads/master
2021-06-13T16:03:10.829000
2020-08-13T04:05:56
2020-08-13T04:05:56
254,438,707
0
0
null
true
2020-08-05T08:29:01
2020-04-09T17:38:26
2020-05-05T12:43:34
2020-08-05T08:29:00
97,642
0
0
0
Java
false
false
package com.hbm.render.block; import com.hbm.blocks.ModBlocks; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.world.IBlockAccess; public class RenderFence implements ISimpleBlockRenderingHandler { @Override public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { } @Override public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { BlockFence fence = (BlockFence) ModBlocks.fence_metal; boolean flag = false; float f = 0.375F; float f1 = 0.625F; renderer.setRenderBounds((double)f, 0.0D, (double)f, (double)f1, 1.0D, (double)f1); renderer.renderStandardBlock(fence, x, y, z); flag = true; boolean flag1 = false; boolean flag2 = false; if (fence.canConnectFenceTo(world, x - 1, y, z) || fence.canConnectFenceTo(world, x + 1, y, z)) { flag1 = true; } if (fence.canConnectFenceTo(world, x, y, z - 1) || fence.canConnectFenceTo(world, x, y, z + 1)) { flag2 = true; } boolean flag3 = fence.canConnectFenceTo(world, x - 1, y, z); boolean flag4 = fence.canConnectFenceTo(world, x + 1, y, z); boolean flag5 = fence.canConnectFenceTo(world, x, y, z - 1); boolean flag6 = fence.canConnectFenceTo(world, x, y, z + 1); if (!flag1 && !flag2) { flag1 = true; } f = 0.4375F; f1 = 0.5625F; float f4 = flag3 ? 0.0F : f; float f5 = flag4 ? 1.0F : f1; float f6 = flag5 ? 0.0F : f; float f7 = flag6 ? 1.0F : f1; renderer.field_152631_f = true; if (flag1) { renderer.setRenderBounds((double)f4, (double)0, (double)0.5, (double)f5, (double)1, (double)0.5); renderer.renderStandardBlock(fence, x, y, z); flag = true; } if (flag2) { renderer.setRenderBounds((double)0.5, (double)0, (double)f6, (double)0.5, (double)1, (double)f7); renderer.renderStandardBlock(fence, x, y, z); flag = true; } renderer.field_152631_f = false; fence.setBlockBoundsBasedOnState(world, x, y, z); return flag; } @Override public boolean shouldRender3DInInventory(int modelId) { return false; } @Override public int getRenderId() { return 334082; } }
UTF-8
Java
2,610
java
RenderFence.java
Java
[]
null
[]
package com.hbm.render.block; import com.hbm.blocks.ModBlocks; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.world.IBlockAccess; public class RenderFence implements ISimpleBlockRenderingHandler { @Override public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { } @Override public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { BlockFence fence = (BlockFence) ModBlocks.fence_metal; boolean flag = false; float f = 0.375F; float f1 = 0.625F; renderer.setRenderBounds((double)f, 0.0D, (double)f, (double)f1, 1.0D, (double)f1); renderer.renderStandardBlock(fence, x, y, z); flag = true; boolean flag1 = false; boolean flag2 = false; if (fence.canConnectFenceTo(world, x - 1, y, z) || fence.canConnectFenceTo(world, x + 1, y, z)) { flag1 = true; } if (fence.canConnectFenceTo(world, x, y, z - 1) || fence.canConnectFenceTo(world, x, y, z + 1)) { flag2 = true; } boolean flag3 = fence.canConnectFenceTo(world, x - 1, y, z); boolean flag4 = fence.canConnectFenceTo(world, x + 1, y, z); boolean flag5 = fence.canConnectFenceTo(world, x, y, z - 1); boolean flag6 = fence.canConnectFenceTo(world, x, y, z + 1); if (!flag1 && !flag2) { flag1 = true; } f = 0.4375F; f1 = 0.5625F; float f4 = flag3 ? 0.0F : f; float f5 = flag4 ? 1.0F : f1; float f6 = flag5 ? 0.0F : f; float f7 = flag6 ? 1.0F : f1; renderer.field_152631_f = true; if (flag1) { renderer.setRenderBounds((double)f4, (double)0, (double)0.5, (double)f5, (double)1, (double)0.5); renderer.renderStandardBlock(fence, x, y, z); flag = true; } if (flag2) { renderer.setRenderBounds((double)0.5, (double)0, (double)f6, (double)0.5, (double)1, (double)f7); renderer.renderStandardBlock(fence, x, y, z); flag = true; } renderer.field_152631_f = false; fence.setBlockBoundsBasedOnState(world, x, y, z); return flag; } @Override public boolean shouldRender3DInInventory(int modelId) { return false; } @Override public int getRenderId() { return 334082; } }
2,610
0.607663
0.569349
89
28.325842
30.032482
124
false
false
0
0
0
0
0
0
1.47191
false
false
5
125203c4d3010cdba615a81abc807985483ad252
27,333,171,914,417
499daf337a547c7fe15f823b00292a67232eff33
/src/main/java/com/yuqiaotech/zsnews/model/Comment.java
21f72cd31f306a4580f8eadb4542524d4f4bdf5e
[]
no_license
yinchaodear/nbcb
https://github.com/yinchaodear/nbcb
9483fc90a6e72e78fcd3b9444d3421658ee87848
37c958d271aec9e9a872f8635c25105ec2f9d3ca
refs/heads/main
2023-03-03T23:22:45.799000
2021-02-09T09:32:21
2021-02-09T09:32:21
336,676,868
0
0
null
false
2021-02-07T02:16:44
2021-02-07T01:46:44
2021-02-07T02:06:11
2021-02-07T02:14:23
0
0
0
1
null
false
false
package com.yuqiaotech.zsnews.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.yuqiaotech.common.web.base.BaseModel; import com.yuqiaotech.sysadmin.model.User; /** * 评论。 * 评论,回复等。 */ @Entity public class Comment extends BaseModel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_user_info_id") private UserInfo userInfo; @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_news_id") private News news; /** * type 类型: 点赞|收藏|评论|回复(针对评论,回复) * 回复 评论回复的情况下 记录评论以及回复的用户 用answerUserInfo记录 */ private String type; @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_answer_user_id") private UserInfo answerUser; /** * 对评论的回复 */ @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_comment_id") private Comment comment; private String content; private Integer status;//评论的状态 private Integer deltag;//删除标识 private String checkResult;//不通过意见 private Date checkDate;//审核日期 @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_check_user_id") private User checkUser;//审核人 public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** * 回复人 * @return */ public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } /** * 问题标题 * @return */ public News getNews() { return news; } public void setNews(News news) { this.news = news; } /** * 回复内容 * @return */ public String getContent() { return content; } public void setContent(String content) { this.content = content; } /** * 追评评论 * @return */ public Comment getComment() { return comment; } public void setComment(Comment comment) { this.comment = comment; } /** * 类型 * @return */ public String getType() { return type; } public void setType(String type) { this.type = type; } /** * 评论目标用户 * @return */ public UserInfo getAnswerUser() { return answerUser; } public void setAnswerUser(UserInfo answerUser) { this.answerUser = answerUser; } /** * 状态 * @return */ public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } /** * 是否删除 * @return */ public Integer getDeltag() { return deltag; } public void setDeltag(Integer deltag) { this.deltag = deltag; } public String getCheckResult() { return checkResult; } public void setCheckResult(String checkResult) { this.checkResult = checkResult; } public Date getCheckDate() { return checkDate; } public void setCheckDate(Date checkDate) { this.checkDate = checkDate; } public User getCheckUser() { return checkUser; } public void setCheckUser(User checkUser) { this.checkUser = checkUser; } }
UTF-8
Java
4,407
java
Comment.java
Java
[]
null
[]
package com.yuqiaotech.zsnews.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.yuqiaotech.common.web.base.BaseModel; import com.yuqiaotech.sysadmin.model.User; /** * 评论。 * 评论,回复等。 */ @Entity public class Comment extends BaseModel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_user_info_id") private UserInfo userInfo; @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_news_id") private News news; /** * type 类型: 点赞|收藏|评论|回复(针对评论,回复) * 回复 评论回复的情况下 记录评论以及回复的用户 用answerUserInfo记录 */ private String type; @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_answer_user_id") private UserInfo answerUser; /** * 对评论的回复 */ @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_comment_id") private Comment comment; private String content; private Integer status;//评论的状态 private Integer deltag;//删除标识 private String checkResult;//不通过意见 private Date checkDate;//审核日期 @JsonIgnoreProperties(value = {"hibernateLazyInitializer"}) @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_check_user_id") private User checkUser;//审核人 public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** * 回复人 * @return */ public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } /** * 问题标题 * @return */ public News getNews() { return news; } public void setNews(News news) { this.news = news; } /** * 回复内容 * @return */ public String getContent() { return content; } public void setContent(String content) { this.content = content; } /** * 追评评论 * @return */ public Comment getComment() { return comment; } public void setComment(Comment comment) { this.comment = comment; } /** * 类型 * @return */ public String getType() { return type; } public void setType(String type) { this.type = type; } /** * 评论目标用户 * @return */ public UserInfo getAnswerUser() { return answerUser; } public void setAnswerUser(UserInfo answerUser) { this.answerUser = answerUser; } /** * 状态 * @return */ public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } /** * 是否删除 * @return */ public Integer getDeltag() { return deltag; } public void setDeltag(Integer deltag) { this.deltag = deltag; } public String getCheckResult() { return checkResult; } public void setCheckResult(String checkResult) { this.checkResult = checkResult; } public Date getCheckDate() { return checkDate; } public void setCheckDate(Date checkDate) { this.checkDate = checkDate; } public User getCheckUser() { return checkUser; } public void setCheckUser(User checkUser) { this.checkUser = checkUser; } }
4,407
0.577741
0.577741
224
17.691965
16.056505
63
false
false
0
0
0
0
0
0
0.227679
false
false
5
def56bff13342be8b9b60abdc6233dbefc221543
16,166,256,938,648
ec24ed13821b20e15a639ca9b7db42dd9e46d804
/src/fr/quentinmachu/jdijkstra/entities/Graph.java
fdc5b81c8d3fa54ed3cebaa3d67872c606ca05b7
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Quentin-M/JDijkstra
https://github.com/Quentin-M/JDijkstra
3cbb426e811e8b2e70f65521c4fa249b5d1f1007
b5e13191276ec5c32c31ecc1f8b938d54b28a8c9
refs/heads/master
2016-09-05T15:22:23.454000
2014-11-11T10:01:20
2014-11-11T10:01:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.quentinmachu.jdijkstra.entities; import java.util.HashMap; import fr.quentinmachu.jdijkstra.entities.Node; /** * This class defines a graph * * @author quentinmachu http://quentin-machu.fr * */ public class Graph { private HashMap<Integer,Node> nodes; /** * Construct an empty graph */ public Graph() { nodes = new HashMap<Integer, Node>(); } /** * Return the nodes of the graph, mapped using their indices * @return */ public HashMap<Integer, Node> getNodes() { return nodes; } /** * Return the number of the nodes in the graph * @return */ public int getNodesNumber() { return nodes.size(); } /** * Add a new node in the graph. If a node with this indice was previously existing, it is replaced. * @param node */ public void addNodes(Node node) { nodes.put(node.getIndice(), node); } /** * Return a node specified by its indice. * @param indice * @return the node or null if it doesn't exist */ public Node getNode(int indice) { return nodes.get(indice); } }
UTF-8
Java
1,097
java
Graph.java
Java
[ { "context": "**\r\n * This class defines a graph\r\n * \r\n * @author quentinmachu http://quentin-machu.fr\r\n *\r\n */\r\npubli", "end": 179, "score": 0.9206700325012207, "start": 177, "tag": "USERNAME", "value": "qu" }, { "context": "\n * This class defines a graph\r\n * \r\n * @author quentinmachu http://quentin-machu.fr\r\n *\r\n */\r\npublic class Gr", "end": 189, "score": 0.6757198572158813, "start": 179, "tag": "NAME", "value": "entinmachu" } ]
null
[]
package fr.quentinmachu.jdijkstra.entities; import java.util.HashMap; import fr.quentinmachu.jdijkstra.entities.Node; /** * This class defines a graph * * @author quentinmachu http://quentin-machu.fr * */ public class Graph { private HashMap<Integer,Node> nodes; /** * Construct an empty graph */ public Graph() { nodes = new HashMap<Integer, Node>(); } /** * Return the nodes of the graph, mapped using their indices * @return */ public HashMap<Integer, Node> getNodes() { return nodes; } /** * Return the number of the nodes in the graph * @return */ public int getNodesNumber() { return nodes.size(); } /** * Add a new node in the graph. If a node with this indice was previously existing, it is replaced. * @param node */ public void addNodes(Node node) { nodes.put(node.getIndice(), node); } /** * Return a node specified by its indice. * @param indice * @return the node or null if it doesn't exist */ public Node getNode(int indice) { return nodes.get(indice); } }
1,097
0.632634
0.632634
54
18.314816
20.52354
100
false
false
0
0
0
0
0
0
1.074074
false
false
5
fdd2e4fde503bc8b9b688d5bbf1773c91c546783
8,289,286,947,841
0748988d27c2b36c7a49cf559dbc88dac21ade06
/app/src/main/java/com/sesi/chris/animangaquiz/view/activity/MenuActivity.java
978af7c44b958705bd74bb759a47c6a3a39c7b1f
[]
no_license
SESI-Phonegap/AnimangaQuiz
https://github.com/SESI-Phonegap/AnimangaQuiz
911b27fa7bef74e727d53b904f4d237801215fd4
691feb91e47dcc25bd21c8731a6ebe34ecb9f973
refs/heads/master
2023-05-25T01:57:36.398000
2023-05-19T15:27:08
2023-05-19T15:27:08
126,198,445
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sesi.chris.animangaquiz.view.activity; import android.Manifest; import android.annotation.SuppressLint; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.AnimationDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.provider.MediaStore; import com.google.android.gms.ads.RequestConfiguration; import com.google.android.material.navigation.NavigationView; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.content.res.AppCompatResources; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.util.Base64; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.billingclient.api.BillingClient; import com.android.billingclient.api.Purchase; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import com.sesi.chris.animangaquiz.R; import com.sesi.chris.animangaquiz.data.api.Constants; import com.sesi.chris.animangaquiz.data.api.billing.BillingManager; import com.sesi.chris.animangaquiz.data.api.billing.BillingProvider; import com.sesi.chris.animangaquiz.data.api.client.QuizClient; import com.sesi.chris.animangaquiz.data.model.LoginResponse; import com.sesi.chris.animangaquiz.data.model.UpdateResponse; import com.sesi.chris.animangaquiz.data.model.User; import com.sesi.chris.animangaquiz.interactor.LoginInteractor; import com.sesi.chris.animangaquiz.presenter.LoginPresenter; import com.sesi.chris.animangaquiz.view.adapter.LargeGemsDelegate; import com.sesi.chris.animangaquiz.view.adapter.MedGemsDelegate; import com.sesi.chris.animangaquiz.view.adapter.SmallGemsDelegate; import com.sesi.chris.animangaquiz.view.fragment.AnimeCatalogoFragment; import com.sesi.chris.animangaquiz.view.fragment.FriendsFragment; import com.sesi.chris.animangaquiz.view.fragment.PurchaseFragment; import com.sesi.chris.animangaquiz.view.fragment.WallpaperFragment; import com.sesi.chris.animangaquiz.view.utils.ImageFilePath; import com.sesi.chris.animangaquiz.view.utils.Utils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; import static com.sesi.chris.animangaquiz.data.api.billing.BillingManager.BILLING_MANAGER_NOT_INITIALIZED; import static com.sesi.chris.animangaquiz.view.utils.UtilInternetConnection.isOnline; public class MenuActivity extends AppCompatActivity implements BillingProvider, NavigationView.OnNavigationItemSelectedListener, LoginPresenter.ViewLogin { private TextView tvUserName; private TextView tvEmail; private TextView tvGems; private TextView tvTotalScore; private CircleImageView imgAvatar; private ProgressBar progressBar; private LoginPresenter loginPresenter; private User userActual; private Context context; private AdView mAdview; private PurchaseFragment fPurchaseFragment; private static final String DIALOG_TAG = "dialog"; private BillingManager mBillingManager; private static final int PICK_IMAGE = 100; private ImageView imgShenglong; private FrameLayout frameLayout; private ImageView imgDragonBalls; private static final String APP_NAME = "AppName"; public User getUserActual() { return userActual; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); init(); // Try to restore dialog fragment if we were showing it prior to screen rotation if (savedInstanceState != null) { fPurchaseFragment = (PurchaseFragment) getSupportFragmentManager() .findFragmentByTag(DIALOG_TAG); } } public void init() { UpdateListener mUpdateListener = new UpdateListener(); // Create and initialize BillingManager which talks to BillingLibrary mBillingManager = new BillingManager(this, mUpdateListener); context = this; initAds(); loginPresenter = new LoginPresenter(new LoginInteractor(new QuizClient())); loginPresenter.setView(this); cargarPublicidad(); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); View headerView = navigationView.getHeaderView(0); tvEmail = headerView.findViewById(R.id.tv_email); tvUserName = headerView.findViewById(R.id.tv_username); tvGems = headerView.findViewById(R.id.tv_gemas); tvTotalScore = headerView.findViewById(R.id.tv_score); imgAvatar = headerView.findViewById(R.id.imgAvatar); imgDragonBalls = headerView.findViewById(R.id.imgEsferas); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); progressBar = findViewById(R.id.pb_login); userActual = (User) getIntent().getSerializableExtra("user"); changeFragment(AnimeCatalogoFragment.newInstance("quiz"), R.id.mainFrame, false, false); imgShenglong = findViewById(R.id.shenglong); frameLayout = findViewById(R.id.mainFrame); imgDragonBalls.setOnClickListener(v -> { if (userActual.getEsferas() == 7) { invokeShenlong(); } else { Toast.makeText(context(), R.string.msgErrorShenlong, Toast.LENGTH_LONG).show(); } }); imgAvatar.setOnClickListener(v -> openGallery() ); if (Build.VERSION.SDK_INT >= 23 && checkExternalStoragePermission()) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 999); } } private void initAds(){ MobileAds.initialize(this, initializationStatus -> { }); RequestConfiguration configuration = new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("212A472E4A57221D579423A6E0AC58B2")).build(); MobileAds.setRequestConfiguration(configuration); } private boolean checkExternalStoragePermission() { return ActivityCompat.checkSelfPermission(context(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED; } private void invokeShenlong() { loginPresenter.onUpdateGems(userActual.getUserName(),userActual.getPassword(),userActual.getIdUser(),userActual.getCoins() + 10000); frameLayout.setVisibility(View.GONE); imgShenglong.setVisibility(View.VISIBLE); imgShenglong.setBackgroundResource(R.drawable.animation_shenlong); DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } AnimationDrawable animationDrawable = (AnimationDrawable) imgShenglong.getBackground(); animationDrawable.setOneShot(true); if (!animationDrawable.isRunning()) { int totalFrameDuration = 0; for (int i = 0; i < animationDrawable.getNumberOfFrames(); i++) { totalFrameDuration += animationDrawable.getDuration(i); } animationDrawable.start(); new Handler().postDelayed(animationDrawable::stop, totalFrameDuration); } loginPresenter.onUpdateEsferas(userActual.getUserName(),userActual.getPassword(),userActual.getIdUser(),0); imgShenglong.setOnClickListener(v -> { if (!animationDrawable.isRunning()) { imgShenglong.setVisibility(View.GONE); frameLayout.setVisibility(View.VISIBLE); } }); } private void cargarPublicidad() { if (isOnline(context())) { mAdview = findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdview.loadAd(adRequest); mAdview.setAdListener(new AdListener() { @Override public void onAdClosed() { // Load the next interstitial. mAdview.loadAd(new AdRequest.Builder().build()); } }); } else { ImageView imgPubli = findViewById(R.id.img_publi_no_internet); imgPubli.setVisibility(View.VISIBLE); } } public void refreshUserData() { if (isOnline(context())) { loginPresenter.onLogin(userActual.getUserName(), userActual.getPassword()); } else { Toast.makeText(context(), getString(R.string.noInternet), Toast.LENGTH_LONG).show(); } } @Override protected void onResume() { super.onResume(); refreshUserData(); } @Override protected void onDestroy() { loginPresenter.terminate(); super.onDestroy(); } public void changeFragment(Fragment fragment, int resource, boolean isRoot, boolean backStack) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); if (isRoot) { transaction.add(resource, fragment); } else { transaction.replace(resource, fragment); } if (backStack) { transaction.addToBackStack(null); } // transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.enter_from_left); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); transaction.commit(); } /** * Remove loading spinner and refresh the UI */ public void showRefreshedUi() { if (fPurchaseFragment != null) { fPurchaseFragment.refreshUI(); } } private void openGallery() { if (Build.VERSION.SDK_INT >= 23) { if (ActivityCompat.checkSelfPermission(context(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MenuActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 999); } else { galleryFilter(); } } else { galleryFilter(); } } public void galleryFilter() { List<Intent> targetGalleryIntents = new ArrayList<>(); Intent galleryIntent = new Intent(); galleryIntent.setAction(Intent.ACTION_PICK); galleryIntent.setType("image/*"); PackageManager pm = getApplicationContext().getPackageManager(); List<ResolveInfo> resInfos = pm.queryIntentActivities(galleryIntent, 0); if (!resInfos.isEmpty()) { for (ResolveInfo resInfo : resInfos) { String packageName = resInfo.activityInfo.packageName; if (!packageName.contains("com.google.android.apps.photos") && !packageName.equals("com.google.android.apps.plus")) { Intent intent = new Intent(); intent.setComponent(new ComponentName(packageName, resInfo.activityInfo.name)); intent.putExtra(APP_NAME, resInfo.loadLabel(pm).toString()); intent.setAction(Intent.ACTION_PICK); intent.setType("image/*"); intent.setPackage(packageName); targetGalleryIntents.add(intent); } } if (!targetGalleryIntents.isEmpty()) { Collections.sort(targetGalleryIntents, (o1, o2) -> o1.getStringExtra(APP_NAME).compareTo(o2.getStringExtra(APP_NAME))); Intent chooserIntent = Intent.createChooser(targetGalleryIntents.remove(0), "Abrir Galeria"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetGalleryIntents.toArray(new Parcelable[]{})); startActivityForResult(chooserIntent, PICK_IMAGE); } else { Toast.makeText(getApplicationContext(), "No se encontro la galeria", Toast.LENGTH_LONG).show(); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) { try { Uri imageUri = data.getData(); String selectedImagePath; if (Build.VERSION.SDK_INT >= 23) { selectedImagePath = ImageFilePath.getPath(getApplication(), imageUri); } else { selectedImagePath = imageUri.toString(); } File fileImage = new File(selectedImagePath); Long lSizeImage = getImageSizeInKb(fileImage.length()); if (lSizeImage < 2000) { if (isOnline(context())) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri); imgAvatar.setImageBitmap(bitmap); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); String sImgBase64 = Base64.encodeToString(imageBytes, Base64.DEFAULT); Log.i("BASE64", sImgBase64); //guardar en la BD loginPresenter.onUpdateAvatar(userActual.getUserName(), userActual.getPassword(), userActual.getIdUser(), sImgBase64); } else { Toast.makeText(context(), getString(R.string.noInternet), Toast.LENGTH_LONG).show(); } } else { Toast.makeText(context(), R.string.msgImagenError, Toast.LENGTH_LONG).show(); } } catch (IOException e) { Log.e("Error-", e.getMessage()); } } } public Long getImageSizeInKb(Long imageLength) { if (imageLength <= 0) { return 0L; } else { return imageLength / 1024; } } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } } @SuppressLint("NonConstantResourceId") @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); switch (id) { case R.id.nav_quiz: changeFragment(AnimeCatalogoFragment.newInstance("quiz"), R.id.mainFrame, false, false); break; case R.id.nav_quizImg: changeFragment(AnimeCatalogoFragment.newInstance("img"), R.id.mainFrame, false, false); break; case R.id.nav_wallpaper: changeFragment(WallpaperFragment.newInstance(), R.id.mainFrame, false, false); break; case R.id.nav_tienda: if (fPurchaseFragment == null) { fPurchaseFragment = new PurchaseFragment(); } if (mBillingManager != null && mBillingManager.getBillingClientResponseCode() > BILLING_MANAGER_NOT_INITIALIZED) { fPurchaseFragment.onManagerReady(this); changeFragment(fPurchaseFragment, R.id.mainFrame, false, false); } break; case R.id.nav_friend: changeFragment(FriendsFragment.newInstance(), R.id.mainFrame, false, false); break; default: Utils.sharedSocial(context(), userActual.getUserName()); break; } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void showLoading() { progressBar.setVisibility(View.VISIBLE); } @Override public void hideLoading() { progressBar.setVisibility(View.GONE); } @Override public void showLoginNotFoundMessage() { progressBar.setVisibility(View.GONE); } @Override public void showServerError(String error) { progressBar.setVisibility(View.GONE); Toast.makeText(context(), getString(R.string.serverError, error), Toast.LENGTH_LONG).show(); } @Override public void renderLogin(LoginResponse loginResponse) { User user = loginResponse.getUser(); if (null != user) { String sName = getIntent().getStringExtra("name"); String sEmail = getIntent().getStringExtra("email"); tvUserName.setText((sName != null) ? sName : user.getName()); tvEmail.setText((sEmail != null) ? sEmail : user.getEmail()); tvTotalScore.setText(getString(R.string.score, String.valueOf(user.getTotalScore()))); tvGems.setText(String.valueOf(user.getCoins())); switch (user.getEsferas()) { case 1: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas1)); break; case 2: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas2)); break; case 3: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas3)); break; case 4: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas4)); break; case 5: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas5)); break; case 6: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas6)); break; case 7: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas7)); break; default: imgDragonBalls.setVisibility(View.INVISIBLE); break; } userActual = user; if (!user.getUrlImageUser().equals("")) { byte[] decodedAvatar = Base64.decode(user.getUrlImageUser(), Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedAvatar, 0, decodedAvatar.length); imgAvatar.setImageBitmap(decodedByte); } else { imgAvatar.setImageResource(R.drawable.ic_account_circle_white_48dp); } } } @Override public void updateGemsResponse(UpdateResponse updateResponse) { Toast.makeText(context(), updateResponse.estatus + "-" + updateResponse.error, Toast.LENGTH_LONG).show(); refreshUserData(); } @Override public void showUpdateGemsError() { Toast.makeText(context(), R.string.updateGemsError, Toast.LENGTH_LONG).show(); } @Override public void updateAvatarResponse(UpdateResponse updateResponse) { Toast.makeText(context(), updateResponse.estatus + "-" + updateResponse.error, Toast.LENGTH_LONG).show(); refreshUserData(); } @Override public void showUpdateAvatarError() { Toast.makeText(context(), R.string.msgAvatrError, Toast.LENGTH_LONG).show(); } @Override public void renderResponse(UpdateResponse updateResponse) { //Empty Method } @Override public void renderResponseFacebook(UpdateResponse updateResponse) { //Empty Method } @Override public void renderLoginFacbook(LoginResponse loginResponse) { //Empty Method } @Override public Context context() { return context; } @Override public BillingManager getBillingManager() { return mBillingManager; } @Override public boolean isSixMonthlySubscribed() { return false; } @Override public boolean isYearlySubscribed() { return false; } /** * Handler to billing updates */ private class UpdateListener implements BillingManager.BillingUpdatesListener { @Override public void onBillingClientSetupFinished() { if (null != fPurchaseFragment) fPurchaseFragment.onManagerReady(MenuActivity.this); } @Override public void onConsumeFinished(String token, int result) { Log.d("TAG", "Consumption finished. Purchase token: " + token + ", result: " + result); // Note: We know this is the SKU_GAS, because it's the only one we consume, so we don't // check if token corresponding to the expected sku was consumed. // If you have more than one sku, you probably need to validate that the token matches // the SKU you expect. // It could be done by maintaining a map (updating it every time you call consumeAsync) // of all tokens into SKUs which were scheduled to be consumed and then looking through // it here to check which SKU corresponds to a consumed token. //--------------------------------------------------------- if (result == BillingClient.BillingResponseCode.OK) { Log.d("TAG", "Consumption successful. Provisioning."); } else { Toast.makeText(context(), R.string.errorCompra, Toast.LENGTH_LONG).show(); Log.d("TAG", "Error consumption"); } showRefreshedUi(); Log.d("TAG", "End consumption flow."); } @Override public void onPurchasesUpdated(List<Purchase> purchaseList) { int iGemas = 0; for (Purchase purchase : purchaseList) { Log.d("SUSCRIPCION", purchase.getSkus().toString()); for(String sku : purchase.getSkus()) { switch (sku) { case SmallGemsDelegate.SKU_ID: iGemas = userActual.getCoins() + Constants.Compras.SMALL_GEMS; loginPresenter.onUpdateGems(userActual.getEmail(), userActual.getPassword(), userActual.getIdUser(), iGemas); getBillingManager().consumeAsync(purchase.getPurchaseToken()); break; case MedGemsDelegate.SKU_ID: iGemas = userActual.getCoins() + Constants.Compras.MED_GEMS; loginPresenter.onUpdateGems(userActual.getEmail(), userActual.getPassword(), userActual.getIdUser(), iGemas); getBillingManager().consumeAsync(purchase.getPurchaseToken()); break; case LargeGemsDelegate.SKU_ID: iGemas = userActual.getCoins() + Constants.Compras.LARGE_GEMS; loginPresenter.onUpdateGems(userActual.getEmail(), userActual.getPassword(), userActual.getIdUser(), iGemas); getBillingManager().consumeAsync(purchase.getPurchaseToken()); break; default: Toast.makeText(context(), R.string.noValid, Toast.LENGTH_LONG).show(); break; } } } } } }
UTF-8
Java
25,714
java
MenuActivity.java
Java
[]
null
[]
package com.sesi.chris.animangaquiz.view.activity; import android.Manifest; import android.annotation.SuppressLint; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.AnimationDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.provider.MediaStore; import com.google.android.gms.ads.RequestConfiguration; import com.google.android.material.navigation.NavigationView; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.content.res.AppCompatResources; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.util.Base64; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.billingclient.api.BillingClient; import com.android.billingclient.api.Purchase; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import com.sesi.chris.animangaquiz.R; import com.sesi.chris.animangaquiz.data.api.Constants; import com.sesi.chris.animangaquiz.data.api.billing.BillingManager; import com.sesi.chris.animangaquiz.data.api.billing.BillingProvider; import com.sesi.chris.animangaquiz.data.api.client.QuizClient; import com.sesi.chris.animangaquiz.data.model.LoginResponse; import com.sesi.chris.animangaquiz.data.model.UpdateResponse; import com.sesi.chris.animangaquiz.data.model.User; import com.sesi.chris.animangaquiz.interactor.LoginInteractor; import com.sesi.chris.animangaquiz.presenter.LoginPresenter; import com.sesi.chris.animangaquiz.view.adapter.LargeGemsDelegate; import com.sesi.chris.animangaquiz.view.adapter.MedGemsDelegate; import com.sesi.chris.animangaquiz.view.adapter.SmallGemsDelegate; import com.sesi.chris.animangaquiz.view.fragment.AnimeCatalogoFragment; import com.sesi.chris.animangaquiz.view.fragment.FriendsFragment; import com.sesi.chris.animangaquiz.view.fragment.PurchaseFragment; import com.sesi.chris.animangaquiz.view.fragment.WallpaperFragment; import com.sesi.chris.animangaquiz.view.utils.ImageFilePath; import com.sesi.chris.animangaquiz.view.utils.Utils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; import static com.sesi.chris.animangaquiz.data.api.billing.BillingManager.BILLING_MANAGER_NOT_INITIALIZED; import static com.sesi.chris.animangaquiz.view.utils.UtilInternetConnection.isOnline; public class MenuActivity extends AppCompatActivity implements BillingProvider, NavigationView.OnNavigationItemSelectedListener, LoginPresenter.ViewLogin { private TextView tvUserName; private TextView tvEmail; private TextView tvGems; private TextView tvTotalScore; private CircleImageView imgAvatar; private ProgressBar progressBar; private LoginPresenter loginPresenter; private User userActual; private Context context; private AdView mAdview; private PurchaseFragment fPurchaseFragment; private static final String DIALOG_TAG = "dialog"; private BillingManager mBillingManager; private static final int PICK_IMAGE = 100; private ImageView imgShenglong; private FrameLayout frameLayout; private ImageView imgDragonBalls; private static final String APP_NAME = "AppName"; public User getUserActual() { return userActual; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); init(); // Try to restore dialog fragment if we were showing it prior to screen rotation if (savedInstanceState != null) { fPurchaseFragment = (PurchaseFragment) getSupportFragmentManager() .findFragmentByTag(DIALOG_TAG); } } public void init() { UpdateListener mUpdateListener = new UpdateListener(); // Create and initialize BillingManager which talks to BillingLibrary mBillingManager = new BillingManager(this, mUpdateListener); context = this; initAds(); loginPresenter = new LoginPresenter(new LoginInteractor(new QuizClient())); loginPresenter.setView(this); cargarPublicidad(); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); View headerView = navigationView.getHeaderView(0); tvEmail = headerView.findViewById(R.id.tv_email); tvUserName = headerView.findViewById(R.id.tv_username); tvGems = headerView.findViewById(R.id.tv_gemas); tvTotalScore = headerView.findViewById(R.id.tv_score); imgAvatar = headerView.findViewById(R.id.imgAvatar); imgDragonBalls = headerView.findViewById(R.id.imgEsferas); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); progressBar = findViewById(R.id.pb_login); userActual = (User) getIntent().getSerializableExtra("user"); changeFragment(AnimeCatalogoFragment.newInstance("quiz"), R.id.mainFrame, false, false); imgShenglong = findViewById(R.id.shenglong); frameLayout = findViewById(R.id.mainFrame); imgDragonBalls.setOnClickListener(v -> { if (userActual.getEsferas() == 7) { invokeShenlong(); } else { Toast.makeText(context(), R.string.msgErrorShenlong, Toast.LENGTH_LONG).show(); } }); imgAvatar.setOnClickListener(v -> openGallery() ); if (Build.VERSION.SDK_INT >= 23 && checkExternalStoragePermission()) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 999); } } private void initAds(){ MobileAds.initialize(this, initializationStatus -> { }); RequestConfiguration configuration = new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("212A472E4A57221D579423A6E0AC58B2")).build(); MobileAds.setRequestConfiguration(configuration); } private boolean checkExternalStoragePermission() { return ActivityCompat.checkSelfPermission(context(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED; } private void invokeShenlong() { loginPresenter.onUpdateGems(userActual.getUserName(),userActual.getPassword(),userActual.getIdUser(),userActual.getCoins() + 10000); frameLayout.setVisibility(View.GONE); imgShenglong.setVisibility(View.VISIBLE); imgShenglong.setBackgroundResource(R.drawable.animation_shenlong); DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } AnimationDrawable animationDrawable = (AnimationDrawable) imgShenglong.getBackground(); animationDrawable.setOneShot(true); if (!animationDrawable.isRunning()) { int totalFrameDuration = 0; for (int i = 0; i < animationDrawable.getNumberOfFrames(); i++) { totalFrameDuration += animationDrawable.getDuration(i); } animationDrawable.start(); new Handler().postDelayed(animationDrawable::stop, totalFrameDuration); } loginPresenter.onUpdateEsferas(userActual.getUserName(),userActual.getPassword(),userActual.getIdUser(),0); imgShenglong.setOnClickListener(v -> { if (!animationDrawable.isRunning()) { imgShenglong.setVisibility(View.GONE); frameLayout.setVisibility(View.VISIBLE); } }); } private void cargarPublicidad() { if (isOnline(context())) { mAdview = findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdview.loadAd(adRequest); mAdview.setAdListener(new AdListener() { @Override public void onAdClosed() { // Load the next interstitial. mAdview.loadAd(new AdRequest.Builder().build()); } }); } else { ImageView imgPubli = findViewById(R.id.img_publi_no_internet); imgPubli.setVisibility(View.VISIBLE); } } public void refreshUserData() { if (isOnline(context())) { loginPresenter.onLogin(userActual.getUserName(), userActual.getPassword()); } else { Toast.makeText(context(), getString(R.string.noInternet), Toast.LENGTH_LONG).show(); } } @Override protected void onResume() { super.onResume(); refreshUserData(); } @Override protected void onDestroy() { loginPresenter.terminate(); super.onDestroy(); } public void changeFragment(Fragment fragment, int resource, boolean isRoot, boolean backStack) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); if (isRoot) { transaction.add(resource, fragment); } else { transaction.replace(resource, fragment); } if (backStack) { transaction.addToBackStack(null); } // transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.enter_from_left); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); transaction.commit(); } /** * Remove loading spinner and refresh the UI */ public void showRefreshedUi() { if (fPurchaseFragment != null) { fPurchaseFragment.refreshUI(); } } private void openGallery() { if (Build.VERSION.SDK_INT >= 23) { if (ActivityCompat.checkSelfPermission(context(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MenuActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 999); } else { galleryFilter(); } } else { galleryFilter(); } } public void galleryFilter() { List<Intent> targetGalleryIntents = new ArrayList<>(); Intent galleryIntent = new Intent(); galleryIntent.setAction(Intent.ACTION_PICK); galleryIntent.setType("image/*"); PackageManager pm = getApplicationContext().getPackageManager(); List<ResolveInfo> resInfos = pm.queryIntentActivities(galleryIntent, 0); if (!resInfos.isEmpty()) { for (ResolveInfo resInfo : resInfos) { String packageName = resInfo.activityInfo.packageName; if (!packageName.contains("com.google.android.apps.photos") && !packageName.equals("com.google.android.apps.plus")) { Intent intent = new Intent(); intent.setComponent(new ComponentName(packageName, resInfo.activityInfo.name)); intent.putExtra(APP_NAME, resInfo.loadLabel(pm).toString()); intent.setAction(Intent.ACTION_PICK); intent.setType("image/*"); intent.setPackage(packageName); targetGalleryIntents.add(intent); } } if (!targetGalleryIntents.isEmpty()) { Collections.sort(targetGalleryIntents, (o1, o2) -> o1.getStringExtra(APP_NAME).compareTo(o2.getStringExtra(APP_NAME))); Intent chooserIntent = Intent.createChooser(targetGalleryIntents.remove(0), "Abrir Galeria"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetGalleryIntents.toArray(new Parcelable[]{})); startActivityForResult(chooserIntent, PICK_IMAGE); } else { Toast.makeText(getApplicationContext(), "No se encontro la galeria", Toast.LENGTH_LONG).show(); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) { try { Uri imageUri = data.getData(); String selectedImagePath; if (Build.VERSION.SDK_INT >= 23) { selectedImagePath = ImageFilePath.getPath(getApplication(), imageUri); } else { selectedImagePath = imageUri.toString(); } File fileImage = new File(selectedImagePath); Long lSizeImage = getImageSizeInKb(fileImage.length()); if (lSizeImage < 2000) { if (isOnline(context())) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri); imgAvatar.setImageBitmap(bitmap); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); String sImgBase64 = Base64.encodeToString(imageBytes, Base64.DEFAULT); Log.i("BASE64", sImgBase64); //guardar en la BD loginPresenter.onUpdateAvatar(userActual.getUserName(), userActual.getPassword(), userActual.getIdUser(), sImgBase64); } else { Toast.makeText(context(), getString(R.string.noInternet), Toast.LENGTH_LONG).show(); } } else { Toast.makeText(context(), R.string.msgImagenError, Toast.LENGTH_LONG).show(); } } catch (IOException e) { Log.e("Error-", e.getMessage()); } } } public Long getImageSizeInKb(Long imageLength) { if (imageLength <= 0) { return 0L; } else { return imageLength / 1024; } } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } } @SuppressLint("NonConstantResourceId") @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); switch (id) { case R.id.nav_quiz: changeFragment(AnimeCatalogoFragment.newInstance("quiz"), R.id.mainFrame, false, false); break; case R.id.nav_quizImg: changeFragment(AnimeCatalogoFragment.newInstance("img"), R.id.mainFrame, false, false); break; case R.id.nav_wallpaper: changeFragment(WallpaperFragment.newInstance(), R.id.mainFrame, false, false); break; case R.id.nav_tienda: if (fPurchaseFragment == null) { fPurchaseFragment = new PurchaseFragment(); } if (mBillingManager != null && mBillingManager.getBillingClientResponseCode() > BILLING_MANAGER_NOT_INITIALIZED) { fPurchaseFragment.onManagerReady(this); changeFragment(fPurchaseFragment, R.id.mainFrame, false, false); } break; case R.id.nav_friend: changeFragment(FriendsFragment.newInstance(), R.id.mainFrame, false, false); break; default: Utils.sharedSocial(context(), userActual.getUserName()); break; } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void showLoading() { progressBar.setVisibility(View.VISIBLE); } @Override public void hideLoading() { progressBar.setVisibility(View.GONE); } @Override public void showLoginNotFoundMessage() { progressBar.setVisibility(View.GONE); } @Override public void showServerError(String error) { progressBar.setVisibility(View.GONE); Toast.makeText(context(), getString(R.string.serverError, error), Toast.LENGTH_LONG).show(); } @Override public void renderLogin(LoginResponse loginResponse) { User user = loginResponse.getUser(); if (null != user) { String sName = getIntent().getStringExtra("name"); String sEmail = getIntent().getStringExtra("email"); tvUserName.setText((sName != null) ? sName : user.getName()); tvEmail.setText((sEmail != null) ? sEmail : user.getEmail()); tvTotalScore.setText(getString(R.string.score, String.valueOf(user.getTotalScore()))); tvGems.setText(String.valueOf(user.getCoins())); switch (user.getEsferas()) { case 1: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas1)); break; case 2: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas2)); break; case 3: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas3)); break; case 4: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas4)); break; case 5: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas5)); break; case 6: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas6)); break; case 7: imgDragonBalls.setVisibility(View.VISIBLE); imgDragonBalls.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.esferas7)); break; default: imgDragonBalls.setVisibility(View.INVISIBLE); break; } userActual = user; if (!user.getUrlImageUser().equals("")) { byte[] decodedAvatar = Base64.decode(user.getUrlImageUser(), Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedAvatar, 0, decodedAvatar.length); imgAvatar.setImageBitmap(decodedByte); } else { imgAvatar.setImageResource(R.drawable.ic_account_circle_white_48dp); } } } @Override public void updateGemsResponse(UpdateResponse updateResponse) { Toast.makeText(context(), updateResponse.estatus + "-" + updateResponse.error, Toast.LENGTH_LONG).show(); refreshUserData(); } @Override public void showUpdateGemsError() { Toast.makeText(context(), R.string.updateGemsError, Toast.LENGTH_LONG).show(); } @Override public void updateAvatarResponse(UpdateResponse updateResponse) { Toast.makeText(context(), updateResponse.estatus + "-" + updateResponse.error, Toast.LENGTH_LONG).show(); refreshUserData(); } @Override public void showUpdateAvatarError() { Toast.makeText(context(), R.string.msgAvatrError, Toast.LENGTH_LONG).show(); } @Override public void renderResponse(UpdateResponse updateResponse) { //Empty Method } @Override public void renderResponseFacebook(UpdateResponse updateResponse) { //Empty Method } @Override public void renderLoginFacbook(LoginResponse loginResponse) { //Empty Method } @Override public Context context() { return context; } @Override public BillingManager getBillingManager() { return mBillingManager; } @Override public boolean isSixMonthlySubscribed() { return false; } @Override public boolean isYearlySubscribed() { return false; } /** * Handler to billing updates */ private class UpdateListener implements BillingManager.BillingUpdatesListener { @Override public void onBillingClientSetupFinished() { if (null != fPurchaseFragment) fPurchaseFragment.onManagerReady(MenuActivity.this); } @Override public void onConsumeFinished(String token, int result) { Log.d("TAG", "Consumption finished. Purchase token: " + token + ", result: " + result); // Note: We know this is the SKU_GAS, because it's the only one we consume, so we don't // check if token corresponding to the expected sku was consumed. // If you have more than one sku, you probably need to validate that the token matches // the SKU you expect. // It could be done by maintaining a map (updating it every time you call consumeAsync) // of all tokens into SKUs which were scheduled to be consumed and then looking through // it here to check which SKU corresponds to a consumed token. //--------------------------------------------------------- if (result == BillingClient.BillingResponseCode.OK) { Log.d("TAG", "Consumption successful. Provisioning."); } else { Toast.makeText(context(), R.string.errorCompra, Toast.LENGTH_LONG).show(); Log.d("TAG", "Error consumption"); } showRefreshedUi(); Log.d("TAG", "End consumption flow."); } @Override public void onPurchasesUpdated(List<Purchase> purchaseList) { int iGemas = 0; for (Purchase purchase : purchaseList) { Log.d("SUSCRIPCION", purchase.getSkus().toString()); for(String sku : purchase.getSkus()) { switch (sku) { case SmallGemsDelegate.SKU_ID: iGemas = userActual.getCoins() + Constants.Compras.SMALL_GEMS; loginPresenter.onUpdateGems(userActual.getEmail(), userActual.getPassword(), userActual.getIdUser(), iGemas); getBillingManager().consumeAsync(purchase.getPurchaseToken()); break; case MedGemsDelegate.SKU_ID: iGemas = userActual.getCoins() + Constants.Compras.MED_GEMS; loginPresenter.onUpdateGems(userActual.getEmail(), userActual.getPassword(), userActual.getIdUser(), iGemas); getBillingManager().consumeAsync(purchase.getPurchaseToken()); break; case LargeGemsDelegate.SKU_ID: iGemas = userActual.getCoins() + Constants.Compras.LARGE_GEMS; loginPresenter.onUpdateGems(userActual.getEmail(), userActual.getPassword(), userActual.getIdUser(), iGemas); getBillingManager().consumeAsync(purchase.getPurchaseToken()); break; default: Toast.makeText(context(), R.string.noValid, Toast.LENGTH_LONG).show(); break; } } } } } }
25,714
0.63199
0.627985
620
40.474194
33.388973
271
false
false
0
0
0
0
0
0
0.696774
false
false
5
a91de0250e8f8963c13ff743385de625337a12ca
14,791,867,431,094
0a5daf7f96b6b4049903fbab3c122ca4e3a9e72d
/app/src/main/java/com/kelvin/jacksgogo/CustomView/JGGEventInfoWindow.java
ff869d2cae2c79c5e104406be22fc66e75823bd6
[]
no_license
lightning331/JacksGoGo_Android
https://github.com/lightning331/JacksGoGo_Android
d0e18b79c6b07aa13c42f08119d30850b8dd4ea3
d028d669576b8182c99acbe2fcf9bcc291d06e3e
refs/heads/master
2020-04-02T09:24:15.833000
2018-06-11T08:05:32
2018-06-11T08:05:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kelvin.jacksgogo.CustomView; import android.content.Context; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Marker; import com.kelvin.jacksgogo.R; import com.kelvin.jacksgogo.Utils.Models.GoClub_Event.JGGEventModel; import com.squareup.picasso.Picasso; import java.util.ArrayList; import static com.kelvin.jacksgogo.Utils.Global.setBoldText; import static com.kelvin.jacksgogo.Utils.JGGTimeManager.getEventTime; public class JGGEventInfoWindow implements GoogleMap.InfoWindowAdapter { private final View contentView; private final Context mContext; public ImageView imgCategory; public ImageView imgPhoto; public TextView txtEventTitle; public TextView txtTime; public TextView txtClubName; public TextView txtEventMembers; private ArrayList<JGGEventModel> mEvents = new ArrayList<>(); public JGGEventInfoWindow(Context context, ArrayList<JGGEventModel> events) { contentView = getContentView(LayoutInflater.from(context)); mContext = context; mEvents = events; imgCategory = contentView.findViewById(R.id.img_category); imgPhoto = contentView.findViewById(R.id.img_event_photo); txtEventTitle = contentView.findViewById(R.id.txt_event_title); txtTime = contentView.findViewById(R.id.txt_event_end_time); txtClubName = contentView.findViewById(R.id.txt_club_name); txtEventMembers = contentView.findViewById(R.id.txt_event_members); } public void setEvent(JGGEventModel event) { if (event.getAttachmentURLs().size() != 0) { Picasso.with(mContext) .load(event.getAttachmentURLs().get(0)) .placeholder(R.mipmap.placeholder) .into(imgPhoto); } // Category Picasso.with(mContext) .load(event.getCategory().getImage()) .placeholder(null) .into(imgCategory); // Event title txtEventTitle.setText(event.getTitle()); txtTime.setText(getEventTime(event)); // Club name txtClubName.setText(""); txtEventMembers.setText(""); String boldText = "32"; String normalText = " people have to bid on this job!"; txtEventMembers.append(setBoldText(boldText)); txtEventMembers.append(normalText); } @Override public View getInfoWindow(Marker marker) { return null; } @Override public View getInfoContents(Marker marker) { if (render(marker, contentView)) { contentView.setLayoutParams(getLayoutParams()); return contentView; } else return null; } private View getContentView(LayoutInflater inflater) { return inflater.inflate(R.layout.jgg_event_info_window, null); } private LinearLayout.LayoutParams getLayoutParams() { WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); int width = display.getWidth(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int)(width * 0.8), LinearLayout.LayoutParams.WRAP_CONTENT); return params; } private boolean render(Marker marker, View view) { if (marker.getSnippet() != null) { int index = Integer.parseInt(marker.getSnippet()); JGGEventModel service = mEvents.get(index); setEvent(service); return true; } else { return false; } } }
UTF-8
Java
3,840
java
JGGEventInfoWindow.java
Java
[]
null
[]
package com.kelvin.jacksgogo.CustomView; import android.content.Context; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Marker; import com.kelvin.jacksgogo.R; import com.kelvin.jacksgogo.Utils.Models.GoClub_Event.JGGEventModel; import com.squareup.picasso.Picasso; import java.util.ArrayList; import static com.kelvin.jacksgogo.Utils.Global.setBoldText; import static com.kelvin.jacksgogo.Utils.JGGTimeManager.getEventTime; public class JGGEventInfoWindow implements GoogleMap.InfoWindowAdapter { private final View contentView; private final Context mContext; public ImageView imgCategory; public ImageView imgPhoto; public TextView txtEventTitle; public TextView txtTime; public TextView txtClubName; public TextView txtEventMembers; private ArrayList<JGGEventModel> mEvents = new ArrayList<>(); public JGGEventInfoWindow(Context context, ArrayList<JGGEventModel> events) { contentView = getContentView(LayoutInflater.from(context)); mContext = context; mEvents = events; imgCategory = contentView.findViewById(R.id.img_category); imgPhoto = contentView.findViewById(R.id.img_event_photo); txtEventTitle = contentView.findViewById(R.id.txt_event_title); txtTime = contentView.findViewById(R.id.txt_event_end_time); txtClubName = contentView.findViewById(R.id.txt_club_name); txtEventMembers = contentView.findViewById(R.id.txt_event_members); } public void setEvent(JGGEventModel event) { if (event.getAttachmentURLs().size() != 0) { Picasso.with(mContext) .load(event.getAttachmentURLs().get(0)) .placeholder(R.mipmap.placeholder) .into(imgPhoto); } // Category Picasso.with(mContext) .load(event.getCategory().getImage()) .placeholder(null) .into(imgCategory); // Event title txtEventTitle.setText(event.getTitle()); txtTime.setText(getEventTime(event)); // Club name txtClubName.setText(""); txtEventMembers.setText(""); String boldText = "32"; String normalText = " people have to bid on this job!"; txtEventMembers.append(setBoldText(boldText)); txtEventMembers.append(normalText); } @Override public View getInfoWindow(Marker marker) { return null; } @Override public View getInfoContents(Marker marker) { if (render(marker, contentView)) { contentView.setLayoutParams(getLayoutParams()); return contentView; } else return null; } private View getContentView(LayoutInflater inflater) { return inflater.inflate(R.layout.jgg_event_info_window, null); } private LinearLayout.LayoutParams getLayoutParams() { WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); int width = display.getWidth(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int)(width * 0.8), LinearLayout.LayoutParams.WRAP_CONTENT); return params; } private boolean render(Marker marker, View view) { if (marker.getSnippet() != null) { int index = Integer.parseInt(marker.getSnippet()); JGGEventModel service = mEvents.get(index); setEvent(service); return true; } else { return false; } } }
3,840
0.674219
0.672656
113
32.9823
25.23447
133
false
false
0
0
0
0
0
0
0.575221
false
false
5
a2919792bed9847b49630b7d027061f887b5f876
29,789,893,229,286
f41f981b7383b7d3f5ed1c3cbdb612a2e5b127c1
/app/src/main/java/csilva2810/udacity/com/popularmovies/models/Video.java
cf4b50ea0cc76048c0330ab747f45c79cdbb040c
[ "MIT", "Apache-2.0" ]
permissive
csilva2810/popular-movies
https://github.com/csilva2810/popular-movies
d703fca528ae0afc8303fcb6d4569a8041720a56
7cc239113ac52bd1f96e45d6261fe71b1b870a60
refs/heads/master
2021-01-15T19:40:20.898000
2018-10-19T19:01:10
2018-10-19T19:01:10
78,860,552
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package csilva2810.udacity.com.popularmovies.models; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import csilva2810.udacity.com.popularmovies.constants.MoviesApi; import static csilva2810.udacity.com.popularmovies.MainActivity.LOG_TAG; /** * Created by carlinhos on 1/15/17. */ public class Video { private String id; private String key; private String name; private String site; private String type; public Video(String id, String key, String name, String site, String type) { this.id = id; this.key = key; this.name = name; this.site = site; this.type = type; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getThumbUrl() { // possible sizes (default, hqdefault, mqdefault, sddefault, maxresdefault) return "https://img.youtube.com/vi/" + getKey() + "/sddefault.jpg"; } public String getYoutubeUrl() { return "http://www.youtube.com/watch?v=" + getKey(); } public static List<Video> parseJson(String json) { List<Video> videos = new ArrayList<>(); try { JSONObject jsonObject = new JSONObject(json); JSONArray moviesArray = jsonObject.getJSONArray("results"); for (int i = 0; i < moviesArray.length(); i++) { JSONObject videoJson = moviesArray.getJSONObject(i); String id = videoJson.getString("id"); String key = videoJson.getString("key"); String name = videoJson.getString("name"); String site = videoJson.getString("site"); String type = videoJson.getString("type"); if (!site.toUpperCase().equals("YOUTUBE")) { continue; } Video video = new Video(id, key, name, site, type); videos.add(video); } } catch (final JSONException e) { Log.e(LOG_TAG, "Parsing error:" + e.getMessage()); } return videos; } }
UTF-8
Java
2,744
java
Video.java
Java
[ { "context": "larmovies.MainActivity.LOG_TAG;\n\n/**\n * Created by carlinhos on 1/15/17.\n */\n\npublic class Video {\n\n privat", "end": 386, "score": 0.9995508193969727, "start": 377, "tag": "USERNAME", "value": "carlinhos" } ]
null
[]
package csilva2810.udacity.com.popularmovies.models; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import csilva2810.udacity.com.popularmovies.constants.MoviesApi; import static csilva2810.udacity.com.popularmovies.MainActivity.LOG_TAG; /** * Created by carlinhos on 1/15/17. */ public class Video { private String id; private String key; private String name; private String site; private String type; public Video(String id, String key, String name, String site, String type) { this.id = id; this.key = key; this.name = name; this.site = site; this.type = type; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getThumbUrl() { // possible sizes (default, hqdefault, mqdefault, sddefault, maxresdefault) return "https://img.youtube.com/vi/" + getKey() + "/sddefault.jpg"; } public String getYoutubeUrl() { return "http://www.youtube.com/watch?v=" + getKey(); } public static List<Video> parseJson(String json) { List<Video> videos = new ArrayList<>(); try { JSONObject jsonObject = new JSONObject(json); JSONArray moviesArray = jsonObject.getJSONArray("results"); for (int i = 0; i < moviesArray.length(); i++) { JSONObject videoJson = moviesArray.getJSONObject(i); String id = videoJson.getString("id"); String key = videoJson.getString("key"); String name = videoJson.getString("name"); String site = videoJson.getString("site"); String type = videoJson.getString("type"); if (!site.toUpperCase().equals("YOUTUBE")) { continue; } Video video = new Video(id, key, name, site, type); videos.add(video); } } catch (final JSONException e) { Log.e(LOG_TAG, "Parsing error:" + e.getMessage()); } return videos; } }
2,744
0.575437
0.568878
116
22.655172
22.568708
83
false
false
0
0
0
0
0
0
0.517241
false
false
5
61bfc055caaf9ac806b9a958e3f49533ca2aa957
6,167,573,100,296
729c7b9e26d12406ff9b4bd4259228ed66d99e4c
/src/main/java/com/kloudtek/log4j/JsonLayout.java
9df65783b90a1e3cba5d64797fd80544eea339de
[]
no_license
Kloudtek/ktlog4j
https://github.com/Kloudtek/ktlog4j
365414d3a44bab7f91496a944adced856b2b9eb9
feb4578cc348f2032278cde30fbbdb6c5905c481
refs/heads/master
2020-07-10T09:16:42.999000
2015-10-17T09:55:54
2015-10-17T09:55:54
44,350,833
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kloudtek.log4j; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.log4j.Layout; import org.apache.log4j.MDC; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * Created by yannick on 10/16/15. */ public class JsonLayout extends Layout { private final Gson gson = new GsonBuilder().create(); private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); private boolean locationInfo; public JsonLayout() { dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } private static String toString(Object obj) { try { return obj.toString(); } catch (Throwable e) { return "Error getting message: " + e.getMessage(); } } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Override public synchronized String format(LoggingEvent le) { return gson.toJson(toHashMap(le)) + "\n"; } private Map<String, Object> toHashMap(LoggingEvent le) { Map<String, Object> r = new LinkedHashMap<>(); r.put("timestamp", dateFormat.format(new Date(le.timeStamp))); r.put("level", le.getLevel().toString()); r.put("thread", le.getThreadName()); r.put("ndc", le.getNDC()); if( locationInfo ) { final LocationInfo locationInformation = le.getLocationInformation(); r.put("classname", locationInformation.getClassName()); r.put("filename", locationInformation.getFileName()); r.put("linenumber", Integer.parseInt(locationInformation.getLineNumber())); r.put("methodname", locationInformation.getMethodName()); } if (le.getMessage() != null) { r.put("message", toString(le.getMessage())); } if (le.getThrowableInformation() != null && le.getThrowableInformation().getThrowable() != null) { r.put("throwable", getThrowable(le)); } r.put("mdc", MDC.getContext()); return r; } private String getThrowable(LoggingEvent le) { Object[] parts = le.getThrowableStrRep(); StringBuilder sb = new StringBuilder(); for (int i = 0; ; i++) { sb.append(parts[i]); if (i == parts.length - 1) return sb.toString(); sb.append("\n"); } } @Override public boolean ignoresThrowable() { return false; } @Override public void activateOptions() { } public boolean isLocationInfo() { return locationInfo; } public void setLocationInfo(boolean locationInfo) { this.locationInfo = locationInfo; } }
UTF-8
Java
2,818
java
JsonLayout.java
Java
[ { "context": "DateFormat;\nimport java.util.*;\n\n/**\n * Created by yannick on 10/16/15.\n */\npublic class JsonLayout extends ", "end": 350, "score": 0.9994562268257141, "start": 343, "tag": "USERNAME", "value": "yannick" } ]
null
[]
package com.kloudtek.log4j; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.log4j.Layout; import org.apache.log4j.MDC; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * Created by yannick on 10/16/15. */ public class JsonLayout extends Layout { private final Gson gson = new GsonBuilder().create(); private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); private boolean locationInfo; public JsonLayout() { dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } private static String toString(Object obj) { try { return obj.toString(); } catch (Throwable e) { return "Error getting message: " + e.getMessage(); } } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") @Override public synchronized String format(LoggingEvent le) { return gson.toJson(toHashMap(le)) + "\n"; } private Map<String, Object> toHashMap(LoggingEvent le) { Map<String, Object> r = new LinkedHashMap<>(); r.put("timestamp", dateFormat.format(new Date(le.timeStamp))); r.put("level", le.getLevel().toString()); r.put("thread", le.getThreadName()); r.put("ndc", le.getNDC()); if( locationInfo ) { final LocationInfo locationInformation = le.getLocationInformation(); r.put("classname", locationInformation.getClassName()); r.put("filename", locationInformation.getFileName()); r.put("linenumber", Integer.parseInt(locationInformation.getLineNumber())); r.put("methodname", locationInformation.getMethodName()); } if (le.getMessage() != null) { r.put("message", toString(le.getMessage())); } if (le.getThrowableInformation() != null && le.getThrowableInformation().getThrowable() != null) { r.put("throwable", getThrowable(le)); } r.put("mdc", MDC.getContext()); return r; } private String getThrowable(LoggingEvent le) { Object[] parts = le.getThrowableStrRep(); StringBuilder sb = new StringBuilder(); for (int i = 0; ; i++) { sb.append(parts[i]); if (i == parts.length - 1) return sb.toString(); sb.append("\n"); } } @Override public boolean ignoresThrowable() { return false; } @Override public void activateOptions() { } public boolean isLocationInfo() { return locationInfo; } public void setLocationInfo(boolean locationInfo) { this.locationInfo = locationInfo; } }
2,818
0.620298
0.615685
91
29.967033
24.739279
106
false
false
0
0
0
0
0
0
0.604396
false
false
5
d816e800253aab840f01c2c8d65bae04c06a7f29
19,215,683,743,179
0c222a55f238c14f5caa31ba947c245c6bc21629
/solutions/chapter6/Exercise_06_27.java
d1b35a88b496cb29043b63be1f67550883a489ef
[ "MIT" ]
permissive
Olutobz/Intro-to-Java-Programming
https://github.com/Olutobz/Intro-to-Java-Programming
bf1a341845547ae27aba6aae1f026ab3ef80e4c5
94131eb5cbb9976b9c0671b0c900eeb9d96415a8
refs/heads/master
2022-03-06T01:23:02.038000
2021-06-23T10:51:56
2021-06-23T10:51:56
203,048,876
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter6; /* (Emirp) An emirp (prime spelled backward) is a nonpalindromic prime number whose reversal is also a prime. For example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps. Write a program that displays the first 100 emirps. Display 10 numbers per line, separated by exactly one space, as follows: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389 ... */ public class Exercise_06_27 { public static void main(String[] args) { final int NUMBER_OF_EMIRPS = 100; // Displays the first 100 emirps final int EMIRPS_PER_LINE = 10; // Display 10 numbers per line int count = 0; // Counts the number of emirps int n = 2; // Possible emirps // Displays the first 100 emirps. Display 10 numbers per line, // separated by exactly one space while (count < NUMBER_OF_EMIRPS) { if (isEmirp(n)) { count++; // Increment count System.out.print(count % EMIRPS_PER_LINE == 0 ? n + "\n" : n + " "); } n++; // Increment n } } /** * Method isEmirp returns true is number is an emirp. False otherwise */ public static boolean isEmirp(int num) { return PrimeNumberMethod.isPrime(num) && !Exercise_06_03.isPalindrome(num) && PrimeNumberMethod.isPrime(Exercise_06_03.reverse(num)); } }
UTF-8
Java
1,415
java
Exercise_06_27.java
Java
[]
null
[]
package chapter6; /* (Emirp) An emirp (prime spelled backward) is a nonpalindromic prime number whose reversal is also a prime. For example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps. Write a program that displays the first 100 emirps. Display 10 numbers per line, separated by exactly one space, as follows: 13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389 ... */ public class Exercise_06_27 { public static void main(String[] args) { final int NUMBER_OF_EMIRPS = 100; // Displays the first 100 emirps final int EMIRPS_PER_LINE = 10; // Display 10 numbers per line int count = 0; // Counts the number of emirps int n = 2; // Possible emirps // Displays the first 100 emirps. Display 10 numbers per line, // separated by exactly one space while (count < NUMBER_OF_EMIRPS) { if (isEmirp(n)) { count++; // Increment count System.out.print(count % EMIRPS_PER_LINE == 0 ? n + "\n" : n + " "); } n++; // Increment n } } /** * Method isEmirp returns true is number is an emirp. False otherwise */ public static boolean isEmirp(int num) { return PrimeNumberMethod.isPrime(num) && !Exercise_06_03.isPalindrome(num) && PrimeNumberMethod.isPrime(Exercise_06_03.reverse(num)); } }
1,415
0.614841
0.546996
40
34.375
28.40131
84
false
false
24
0.016961
0
0
0
0
0.35
false
false
5
22b53051e29e23b689495b4324490e22f195392d
16,793,322,179,747
41e3607d2294768e86fb0d6250a2680439017960
/src/com/telefonica/jee/dao/UserDAOImpl.java
5e4ec5029883fb525b1a0e1ede89784ac3d4bd6d
[]
no_license
LorenaCuervo/Lorena
https://github.com/LorenaCuervo/Lorena
d8d165d2b7e347583eb21f6c19f0efe3e19985c1
cc1d16a5f2924e05e06e880b2b05976441b0a992
refs/heads/master
2022-02-24T09:42:48.873000
2019-12-04T13:24:36
2019-12-04T13:24:36
219,604,491
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.telefonica.jee.dao; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import com.telefonica.jee.model.User; import com.telefonica.jee.util.JPAUtil; public class UserDAOImpl implements UserDAO { private static final String FINDBYEMAIL = "SELECT u from User u WHERE u.email = :email"; public UserDAOImpl() { } EntityManager manager; @Override public List<User> get() { try { manager = JPAUtil.getEntityManager(); TypedQuery<User> namedQuery = manager.createNamedQuery("User.findAll", User.class); List<User> results = namedQuery.getResultList(); manager.close(); return results; }catch(Exception e) { e.printStackTrace(); } return new ArrayList<User>(); } @Override public User get(int id) { User user = null; try { manager = JPAUtil.getEntityManager(); user = manager.find(User.class, id); manager.close(); }catch(Exception e) { e.printStackTrace(); } return user; } @Override public boolean save(User user) { boolean flag = false; try { manager = JPAUtil.getEntityManager(); manager.getTransaction().begin(); manager.persist(user); manager.getTransaction().commit(); manager.close(); flag = true; }catch(Exception ex) { ex.printStackTrace(); } return flag; } @Override public boolean delete(int id) { boolean flag = false; try { manager = JPAUtil.getEntityManager(); manager.getTransaction().begin(); User user = manager.find(User.class, id); if (user != null) { manager.remove(user); manager.getTransaction().commit(); flag = true; } manager.close(); }catch(Exception e) { e.printStackTrace(); } return flag; } @Override public boolean update(User user) { boolean flag = false; try { manager = JPAUtil.getEntityManager(); manager.getTransaction().begin(); manager.merge(user); manager.getTransaction().commit(); manager.close(); flag = true; }catch(Exception e) { e.printStackTrace(); } return flag; } @Override public boolean login(String email, String password) { TypedQuery<Long> query = manager.createQuery(FINDBYEMAIL, Long.class); query.setParameter("email", email); query.setParameter("password", password); Long numUsuario = query.getSingleResult(); System.out.println("Numero de usuarios con email y password: " + numUsuario); if (numUsuario > 0) { return true; } return false; //return: numUsuario > 0; } @Override public boolean login(String email) { // TODO Auto-generated method stub return false; } @Override public org.apache.tomcat.jni.User findByEmail(String email) { // TODO Auto-generated method stub return null; } }
UTF-8
Java
2,783
java
UserDAOImpl.java
Java
[ { "context": "(\"email\", email);\n\t\tquery.setParameter(\"password\", password);\n\t\tLong numUsuario = query.getSingleResult();\n\t\t", "end": 2319, "score": 0.9413248896598816, "start": 2311, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.telefonica.jee.dao; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import com.telefonica.jee.model.User; import com.telefonica.jee.util.JPAUtil; public class UserDAOImpl implements UserDAO { private static final String FINDBYEMAIL = "SELECT u from User u WHERE u.email = :email"; public UserDAOImpl() { } EntityManager manager; @Override public List<User> get() { try { manager = JPAUtil.getEntityManager(); TypedQuery<User> namedQuery = manager.createNamedQuery("User.findAll", User.class); List<User> results = namedQuery.getResultList(); manager.close(); return results; }catch(Exception e) { e.printStackTrace(); } return new ArrayList<User>(); } @Override public User get(int id) { User user = null; try { manager = JPAUtil.getEntityManager(); user = manager.find(User.class, id); manager.close(); }catch(Exception e) { e.printStackTrace(); } return user; } @Override public boolean save(User user) { boolean flag = false; try { manager = JPAUtil.getEntityManager(); manager.getTransaction().begin(); manager.persist(user); manager.getTransaction().commit(); manager.close(); flag = true; }catch(Exception ex) { ex.printStackTrace(); } return flag; } @Override public boolean delete(int id) { boolean flag = false; try { manager = JPAUtil.getEntityManager(); manager.getTransaction().begin(); User user = manager.find(User.class, id); if (user != null) { manager.remove(user); manager.getTransaction().commit(); flag = true; } manager.close(); }catch(Exception e) { e.printStackTrace(); } return flag; } @Override public boolean update(User user) { boolean flag = false; try { manager = JPAUtil.getEntityManager(); manager.getTransaction().begin(); manager.merge(user); manager.getTransaction().commit(); manager.close(); flag = true; }catch(Exception e) { e.printStackTrace(); } return flag; } @Override public boolean login(String email, String password) { TypedQuery<Long> query = manager.createQuery(FINDBYEMAIL, Long.class); query.setParameter("email", email); query.setParameter("password", <PASSWORD>); Long numUsuario = query.getSingleResult(); System.out.println("Numero de usuarios con email y password: " + numUsuario); if (numUsuario > 0) { return true; } return false; //return: numUsuario > 0; } @Override public boolean login(String email) { // TODO Auto-generated method stub return false; } @Override public org.apache.tomcat.jni.User findByEmail(String email) { // TODO Auto-generated method stub return null; } }
2,785
0.681279
0.680561
129
20.573643
18.525396
89
false
false
0
0
0
0
0
0
2.232558
false
false
5
20bcb76edd4d9f3a970845883cc28169cf7e6e1a
31,756,988,188,696
9b76ecdddad2dee3620480adff2bdf58bb7f0e46
/src/main/java/kafkastormredis/TestRedis.java
f1cb3a52b7aa9e040b7a19bc6b25fd24af9ca5f9
[]
no_license
zhenshiyiyang/hadoop
https://github.com/zhenshiyiyang/hadoop
a9feba9954004929eef95d9ffe9470ebfb4a7fe7
69f9a37b236a7e01328f4df572a98f5663a8778c
refs/heads/master
2020-03-23T15:19:42.679000
2019-02-27T07:20:49
2019-02-27T07:20:49
141,738,934
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kafkastormredis; /** * Created by hadoop on 2018/3/29. */ import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Set; import java.util.Map; public class TestRedis { public static void main(String[] args) { JedisPoolConfig poolConfig = new JedisPoolConfig(); // 最大连接数 poolConfig.setMaxTotal(1); // 最大空闲数 poolConfig.setMaxIdle(1); // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常: // Could not get a resource from the pool poolConfig.setMaxWaitMillis(1000); Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>(); nodes.add(new HostAndPort("192.168.217.128", 7001)); nodes.add(new HostAndPort("192.168.217.128", 7002)); nodes.add(new HostAndPort("192.168.217.128", 7003)); nodes.add(new HostAndPort("192.168.217.128", 7004)); nodes.add(new HostAndPort("192.168.217.128", 7005)); nodes.add(new HostAndPort("192.168.217.128", 7006)); //JedisCluster jedis = new JedisCluster(nodes, poolConfig); Jedis jedis = new Jedis("192.168.217.128",7006); // Map<String,String> wordCountMap = new HashMap<String,String>(); // wordCountMap.put("liuxin","2"); // wordCountMap.put("book","5"); // jedis.hmset("word",wordCountMap); Map<String,String> wordcount = jedis.hgetAll("wordcount"); System.out.println(wordcount); } }
UTF-8
Java
1,669
java
TestRedis.java
Java
[ { "context": "package kafkastormredis;\n\n/**\n * Created by hadoop on 2018/3/29.\n */\nimport redis.clients.jedis.Host", "end": 50, "score": 0.9986832737922668, "start": 44, "tag": "USERNAME", "value": "hadoop" }, { "context": "ostAndPort>();\n nodes.add(new HostAndPort(\"192.168.217.128\", 7001));\n nodes.add(new HostAndPort(\"192.", "end": 831, "score": 0.9996472597122192, "start": 816, "tag": "IP_ADDRESS", "value": "192.168.217.128" }, { "context": ".128\", 7001));\n nodes.add(new HostAndPort(\"192.168.217.128\", 7002));\n nodes.add(new HostAndPort(\"192.", "end": 892, "score": 0.9996548891067505, "start": 877, "tag": "IP_ADDRESS", "value": "192.168.217.128" }, { "context": ".128\", 7002));\n nodes.add(new HostAndPort(\"192.168.217.128\", 7003));\n nodes.add(new HostAndPort(\"192.", "end": 953, "score": 0.9996544122695923, "start": 938, "tag": "IP_ADDRESS", "value": "192.168.217.128" }, { "context": ".128\", 7003));\n nodes.add(new HostAndPort(\"192.168.217.128\", 7004));\n nodes.add(new HostAndPort(\"192.", "end": 1014, "score": 0.9996375441551208, "start": 999, "tag": "IP_ADDRESS", "value": "192.168.217.128" }, { "context": ".128\", 7004));\n nodes.add(new HostAndPort(\"192.168.217.128\", 7005));\n nodes.add(new HostAndPort(\"192.", "end": 1075, "score": 0.99964439868927, "start": 1060, "tag": "IP_ADDRESS", "value": "192.168.217.128" }, { "context": ".128\", 7005));\n nodes.add(new HostAndPort(\"192.168.217.128\", 7006));\n //JedisCluster jedis = new Jedi", "end": 1136, "score": 0.9996432065963745, "start": 1121, "tag": "IP_ADDRESS", "value": "192.168.217.128" }, { "context": "es, poolConfig);\n Jedis jedis = new Jedis(\"192.168.217.128\",7006);\n// Map<String,String> wordCountMap", "end": 1263, "score": 0.9996842741966248, "start": 1248, "tag": "IP_ADDRESS", "value": "192.168.217.128" } ]
null
[]
package kafkastormredis; /** * Created by hadoop on 2018/3/29. */ import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Set; import java.util.Map; public class TestRedis { public static void main(String[] args) { JedisPoolConfig poolConfig = new JedisPoolConfig(); // 最大连接数 poolConfig.setMaxTotal(1); // 最大空闲数 poolConfig.setMaxIdle(1); // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常: // Could not get a resource from the pool poolConfig.setMaxWaitMillis(1000); Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>(); nodes.add(new HostAndPort("192.168.217.128", 7001)); nodes.add(new HostAndPort("192.168.217.128", 7002)); nodes.add(new HostAndPort("192.168.217.128", 7003)); nodes.add(new HostAndPort("192.168.217.128", 7004)); nodes.add(new HostAndPort("192.168.217.128", 7005)); nodes.add(new HostAndPort("192.168.217.128", 7006)); //JedisCluster jedis = new JedisCluster(nodes, poolConfig); Jedis jedis = new Jedis("192.168.217.128",7006); // Map<String,String> wordCountMap = new HashMap<String,String>(); // wordCountMap.put("liuxin","2"); // wordCountMap.put("book","5"); // jedis.hmset("word",wordCountMap); Map<String,String> wordcount = jedis.hgetAll("wordcount"); System.out.println(wordcount); } }
1,669
0.664146
0.584121
42
36.785713
21.425991
73
false
false
0
0
0
0
0
0
1
false
false
5
43b8f6e512533cd662f9eac07c5276cc27131421
27,839,978,065,808
e307b72b13e483b1a321c54f6ab806088eb40307
/app/src/main/java/com/imedf/recettes/daoSqlite/IngredientDbAdapter.java
b40d368e6bd8ba3a0a75063cbf6230cfc9842e0a
[]
no_license
imed-ferfar/recettes-cuisine-ver1
https://github.com/imed-ferfar/recettes-cuisine-ver1
1b2749778b85062ec5a1b4565cae53965e67dc83
c5e2b43b2bdad79f6d43caa998df173c8b9390c8
refs/heads/main
2023-08-16T11:44:03.905000
2021-09-29T20:00:39
2021-09-29T20:00:39
410,943,490
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.imedf.recettes.daoSqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.widget.Toast; import com.imedf.recettes.modele.Ingredient; import com.imedf.recettes.modele.Recette; public class IngredientDbAdapter { private SQLiteDatabase db; private DbHelper dbHelper; private Context context; public IngredientDbAdapter(Context context) { this.context =context; this.dbHelper = new DbHelper(context,DbHelper.BD_NOM, null, DbHelper.VERSION); } private void openMadb(){ db = dbHelper.getWritableDatabase(); } private void fermerBd(){ db.close(); } public void ajouterIngredients (Recette recette){ openMadb(); int id = recette.getIdRecette(); for (Ingredient ingred : recette.getIngredients()) { ContentValues cv = new ContentValues(); cv.put(DbHelper.COL_ID_RECETTE, id); cv.put(DbHelper.COL_DESC, ingred.getDescription()); cv.put(DbHelper.COL_UNITE, ingred.getUnite()); cv.put(DbHelper.COL_QUTE, ingred.getQuantite()); db.insert(DbHelper.TABLE_INGREDIENT, null, cv); } fermerBd(); } public void selectionnerIngredients() { openMadb(); //indiquer les colonne de select String[] cols ={DbHelper.COL_ID, DbHelper.COL_TITRE, DbHelper.COL_PREPARATION}; Cursor curseur = db.query(DbHelper.TABLE_RECETTE,cols,null,null,null, null,null,null ); int id; String titre, preparation; curseur.moveToFirst(); while(!curseur.isAfterLast()){ id = curseur.getInt(0); titre = curseur.getString(1); preparation = curseur.getString(2); Toast.makeText(context,"Id : "+id+" ,Titre : "+titre+" ,Preparation : "+preparation,Toast.LENGTH_LONG).show(); curseur.moveToNext(); } fermerBd(); } public Recette rechercherIngredient(Recette recette) { openMadb(); //indiquer les colonne de select String[] cols ={DbHelper.COL_ID_RECETTE, DbHelper.COL_TITRE, DbHelper.COL_PREPARATION}; // 1ere technique : SQL // Cursor curseur = db.rawQuery("select * from utilisateur where courriel = ?", new String[] { user.getCourriel() }); int id; // 2ieme technique : SQL Cursor curseur = db.query(DbHelper.TABLE_RECETTE,cols,"titre='"+recette.getTitre()+"'",null,null, null,null); curseur.moveToFirst(); if(curseur.getCount() == 1){ id = curseur.getInt(0); recette.setPreparation(curseur.getString(1)); //Toast.makeText(context,"Bienvenue "+user.getPrenom()+" :)",Toast.LENGTH_LONG).show(); fermerBd(); return recette; } else { fermerBd(); return null; } } public void ajouterngredients(Recette recette){ openMadb(); int idRecette = recette.getIdRecette(); for (Ingredient ingred : recette.getIngredients()) { ContentValues cv = new ContentValues(); cv.put(DbHelper.COL_ID_RECETTE, idRecette); cv.put(DbHelper.COL_DESC, ingred.getDescription()); cv.put(DbHelper.COL_UNITE, ingred.getUnite()); cv.put(DbHelper.COL_QUTE, ingred.getQuantite()); db.insert(DbHelper.TABLE_INGREDIENT, null, cv); // Toast.makeText(context,"image : "+image,Toast.LENGTH_LONG).show(); } fermerBd(); //Toast.makeText(context,"Ajout reussi",Toast.LENGTH_LONG).show(); } }
UTF-8
Java
3,730
java
IngredientDbAdapter.java
Java
[]
null
[]
package com.imedf.recettes.daoSqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.widget.Toast; import com.imedf.recettes.modele.Ingredient; import com.imedf.recettes.modele.Recette; public class IngredientDbAdapter { private SQLiteDatabase db; private DbHelper dbHelper; private Context context; public IngredientDbAdapter(Context context) { this.context =context; this.dbHelper = new DbHelper(context,DbHelper.BD_NOM, null, DbHelper.VERSION); } private void openMadb(){ db = dbHelper.getWritableDatabase(); } private void fermerBd(){ db.close(); } public void ajouterIngredients (Recette recette){ openMadb(); int id = recette.getIdRecette(); for (Ingredient ingred : recette.getIngredients()) { ContentValues cv = new ContentValues(); cv.put(DbHelper.COL_ID_RECETTE, id); cv.put(DbHelper.COL_DESC, ingred.getDescription()); cv.put(DbHelper.COL_UNITE, ingred.getUnite()); cv.put(DbHelper.COL_QUTE, ingred.getQuantite()); db.insert(DbHelper.TABLE_INGREDIENT, null, cv); } fermerBd(); } public void selectionnerIngredients() { openMadb(); //indiquer les colonne de select String[] cols ={DbHelper.COL_ID, DbHelper.COL_TITRE, DbHelper.COL_PREPARATION}; Cursor curseur = db.query(DbHelper.TABLE_RECETTE,cols,null,null,null, null,null,null ); int id; String titre, preparation; curseur.moveToFirst(); while(!curseur.isAfterLast()){ id = curseur.getInt(0); titre = curseur.getString(1); preparation = curseur.getString(2); Toast.makeText(context,"Id : "+id+" ,Titre : "+titre+" ,Preparation : "+preparation,Toast.LENGTH_LONG).show(); curseur.moveToNext(); } fermerBd(); } public Recette rechercherIngredient(Recette recette) { openMadb(); //indiquer les colonne de select String[] cols ={DbHelper.COL_ID_RECETTE, DbHelper.COL_TITRE, DbHelper.COL_PREPARATION}; // 1ere technique : SQL // Cursor curseur = db.rawQuery("select * from utilisateur where courriel = ?", new String[] { user.getCourriel() }); int id; // 2ieme technique : SQL Cursor curseur = db.query(DbHelper.TABLE_RECETTE,cols,"titre='"+recette.getTitre()+"'",null,null, null,null); curseur.moveToFirst(); if(curseur.getCount() == 1){ id = curseur.getInt(0); recette.setPreparation(curseur.getString(1)); //Toast.makeText(context,"Bienvenue "+user.getPrenom()+" :)",Toast.LENGTH_LONG).show(); fermerBd(); return recette; } else { fermerBd(); return null; } } public void ajouterngredients(Recette recette){ openMadb(); int idRecette = recette.getIdRecette(); for (Ingredient ingred : recette.getIngredients()) { ContentValues cv = new ContentValues(); cv.put(DbHelper.COL_ID_RECETTE, idRecette); cv.put(DbHelper.COL_DESC, ingred.getDescription()); cv.put(DbHelper.COL_UNITE, ingred.getUnite()); cv.put(DbHelper.COL_QUTE, ingred.getQuantite()); db.insert(DbHelper.TABLE_INGREDIENT, null, cv); // Toast.makeText(context,"image : "+image,Toast.LENGTH_LONG).show(); } fermerBd(); //Toast.makeText(context,"Ajout reussi",Toast.LENGTH_LONG).show(); } }
3,730
0.613673
0.611528
100
36.290001
27.199373
125
false
false
0
0
0
0
0
0
1.04
false
false
5
2df08cb9f9d1bc49cd788e7c48afea2e35516fb9
27,839,978,065,387
5c2394b5369f61e29b3b122d1f0500261d97a7fd
/src/main/java/com/cosean/trajectory/service/ReductionService.java
f3a34923e1017af047d1868a97b434ae4862475d
[]
no_license
anilcosar/Cosean-Trajectory
https://github.com/anilcosar/Cosean-Trajectory
ee6503c1ed8801779eb19409c1124f485794fdc8
bed5a50fa754b84b21c141eb90e0887de1cdf23a
refs/heads/master
2021-09-10T05:46:01.342000
2018-03-21T08:07:39
2018-03-21T08:07:39
122,827,379
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cosean.trajectory.service; import com.cosean.trajectory.model.Point; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class ReductionService { private static final double epsilon = 0.001; public ResponseEntity simplify(List<Point> coordList) { long startTime = System.nanoTime(); List<Point> pointListOut = new ArrayList<>(); ramerDouglasPeucker(coordList, epsilon, pointListOut); Map<String, Object> map = new HashMap<>(); map.put("reducedData", pointListOut); map.put("reductionRatio", (1 - ((double) pointListOut.size() / coordList.size())) * 100); map.put("reductionDuration", (System.nanoTime() - startTime) / 1000000.0 + " ms"); return new ResponseEntity<>(map, HttpStatus.OK); } private static double perpendicularDistance(Point pt, Point lineStart, Point lineEnd) { double dx = lineEnd.getLatitude() - lineStart.getLatitude(); double dy = lineEnd.getLongitude() - lineStart.getLongitude(); double mag = Math.hypot(dx, dy); if (mag > 0.0) { dx /= mag; dy /= mag; } double pvx = pt.getLatitude() - lineStart.getLatitude(); double pvy = pt.getLongitude() - lineStart.getLongitude(); double pvdot = dx * pvx + dy * pvy; double ax = pvx - pvdot * dx; double ay = pvy - pvdot * dy; return Math.hypot(ax, ay); } private static void ramerDouglasPeucker(List<Point> pointList, double epsilon, List<Point> out) { if (pointList.size() < 2) throw new IllegalArgumentException("Not enough points to simplify"); double dMax = 0.0; int index = 0; int end = pointList.size() - 1; for (int i = 1; i < end; ++i) { double d = perpendicularDistance(pointList.get(i), pointList.get(0), pointList.get(end)); if (d > dMax) { index = i; dMax = d; } } if (dMax > epsilon) { List<Point> recResults1 = new ArrayList<>(); List<Point> recResults2 = new ArrayList<>(); List<Point> firstLine = pointList.subList(0, index + 1); List<Point> lastLine = pointList.subList(index, pointList.size()); ramerDouglasPeucker(firstLine, epsilon, recResults1); ramerDouglasPeucker(lastLine, epsilon, recResults2); out.addAll(recResults1.subList(0, recResults1.size() - 1)); out.addAll(recResults2); if (out.size() < 2) throw new RuntimeException("Not enough points to simplify"); } else { out.clear(); out.add(pointList.get(0)); out.add(pointList.get(pointList.size() - 1)); } } }
UTF-8
Java
2,963
java
ReductionService.java
Java
[]
null
[]
package com.cosean.trajectory.service; import com.cosean.trajectory.model.Point; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class ReductionService { private static final double epsilon = 0.001; public ResponseEntity simplify(List<Point> coordList) { long startTime = System.nanoTime(); List<Point> pointListOut = new ArrayList<>(); ramerDouglasPeucker(coordList, epsilon, pointListOut); Map<String, Object> map = new HashMap<>(); map.put("reducedData", pointListOut); map.put("reductionRatio", (1 - ((double) pointListOut.size() / coordList.size())) * 100); map.put("reductionDuration", (System.nanoTime() - startTime) / 1000000.0 + " ms"); return new ResponseEntity<>(map, HttpStatus.OK); } private static double perpendicularDistance(Point pt, Point lineStart, Point lineEnd) { double dx = lineEnd.getLatitude() - lineStart.getLatitude(); double dy = lineEnd.getLongitude() - lineStart.getLongitude(); double mag = Math.hypot(dx, dy); if (mag > 0.0) { dx /= mag; dy /= mag; } double pvx = pt.getLatitude() - lineStart.getLatitude(); double pvy = pt.getLongitude() - lineStart.getLongitude(); double pvdot = dx * pvx + dy * pvy; double ax = pvx - pvdot * dx; double ay = pvy - pvdot * dy; return Math.hypot(ax, ay); } private static void ramerDouglasPeucker(List<Point> pointList, double epsilon, List<Point> out) { if (pointList.size() < 2) throw new IllegalArgumentException("Not enough points to simplify"); double dMax = 0.0; int index = 0; int end = pointList.size() - 1; for (int i = 1; i < end; ++i) { double d = perpendicularDistance(pointList.get(i), pointList.get(0), pointList.get(end)); if (d > dMax) { index = i; dMax = d; } } if (dMax > epsilon) { List<Point> recResults1 = new ArrayList<>(); List<Point> recResults2 = new ArrayList<>(); List<Point> firstLine = pointList.subList(0, index + 1); List<Point> lastLine = pointList.subList(index, pointList.size()); ramerDouglasPeucker(firstLine, epsilon, recResults1); ramerDouglasPeucker(lastLine, epsilon, recResults2); out.addAll(recResults1.subList(0, recResults1.size() - 1)); out.addAll(recResults2); if (out.size() < 2) throw new RuntimeException("Not enough points to simplify"); } else { out.clear(); out.add(pointList.get(0)); out.add(pointList.get(pointList.size() - 1)); } } }
2,963
0.609855
0.596693
79
36.506329
28.885138
102
false
false
0
0
0
0
0
0
0.911392
false
false
5
5ffea03087851aebae208535b3331c8bb07f6056
14,267,881,397,029
b6f4e8dd7a804f322ea33aff06517b5148797494
/src/test/java/seo/dale/http/server/wrapper/ContentKeepingResponseWrapperTest.java
eb3ec91badfe8b1e8ca455e53c8745e410c48094
[]
no_license
DaleSeo/rest-client-java
https://github.com/DaleSeo/rest-client-java
668b1875b4ad7da41ff53348f89beb27654f72c2
1f98d28281d15f7ea4527e34e41fe336bb35e2ae
refs/heads/master
2021-01-13T09:16:16.926000
2017-03-03T04:06:42
2017-03-03T04:06:42
72,599,324
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package seo.dale.http.server.wrapper; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import javax.servlet.ServletOutputStream; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; public class ContentKeepingResponseWrapperTest { @Test public void getContentAsString() throws IOException { String content = "{\n" + " \"errorCode\": 100001,\n" + " \"errorMessage\": \"알 수 없는 오류\"\n" + "}"; MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(200); response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); response.setContentLength(content.length()); ContentKeepingResponseWrapper wrapper = new ContentKeepingResponseWrapper(response); // write raw response ServletOutputStream outFromResponse = response.getOutputStream(); IOUtils.write(content, outFromResponse); String contentWrittenViaResponse = wrapper.getContentAsString(); assertThat(contentWrittenViaResponse.isEmpty()).isTrue(); // write response wrapper ServletOutputStream outFromWrapper = wrapper.getOutputStream(); IOUtils.write(content, outFromWrapper); String contentWrittenViaWrapper = wrapper.getContentAsString(); assertThat(contentWrittenViaWrapper).isEqualTo(content); } }
UTF-8
Java
1,402
java
ContentKeepingResponseWrapperTest.java
Java
[]
null
[]
package seo.dale.http.server.wrapper; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import javax.servlet.ServletOutputStream; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; public class ContentKeepingResponseWrapperTest { @Test public void getContentAsString() throws IOException { String content = "{\n" + " \"errorCode\": 100001,\n" + " \"errorMessage\": \"알 수 없는 오류\"\n" + "}"; MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(200); response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); response.setContentLength(content.length()); ContentKeepingResponseWrapper wrapper = new ContentKeepingResponseWrapper(response); // write raw response ServletOutputStream outFromResponse = response.getOutputStream(); IOUtils.write(content, outFromResponse); String contentWrittenViaResponse = wrapper.getContentAsString(); assertThat(contentWrittenViaResponse.isEmpty()).isTrue(); // write response wrapper ServletOutputStream outFromWrapper = wrapper.getOutputStream(); IOUtils.write(content, outFromWrapper); String contentWrittenViaWrapper = wrapper.getContentAsString(); assertThat(contentWrittenViaWrapper).isEqualTo(content); } }
1,402
0.784892
0.777698
43
31.348837
25.851889
86
false
false
0
0
0
0
0
0
1.674419
false
false
5
7f4f4723389a54bd8d63c980f7fc6e480a65f270
8,658,654,117,456
1cd2af2722672d317563839ea2d3d7d1a45e263d
/src/main/java/io/zipcoder/interfaces/Instructor.java
f2b10ba49cab115d80593a29e95bebfed0198cef
[]
no_license
ahsonali/CR-MacroLabs-OOP-InstructorStudentClassroom
https://github.com/ahsonali/CR-MacroLabs-OOP-InstructorStudentClassroom
cf8992738aa77e131d03af7c99abcb5721769f93
3db7d3ae94f6863ae1b245562db3b6da49f70b13
refs/heads/master
2021-01-25T00:10:17.234000
2018-03-02T03:43:31
2018-03-02T03:43:31
123,289,499
0
0
null
true
2018-02-28T13:35:01
2018-02-28T13:35:01
2018-01-09T15:24:11
2018-02-28T04:07:55
36
0
0
0
null
false
null
package io.zipcoder.interfaces; public class Instructor extends Person implements Teacher { public Instructor (String name, long id) { super(name, id); } public void teach(Learner learner, double numbOfHours) { //5.1 calls a parameter of type Learner Interface (its public) learner.learn(numbOfHours); } public void lecture(Learner [] learners, double numberOfHours) { double numberOfHoursPerLearner = numberOfHours / learners.length; for(Learner element : learners) { teach(element, numberOfHoursPerLearner); } } }
UTF-8
Java
627
java
Instructor.java
Java
[]
null
[]
package io.zipcoder.interfaces; public class Instructor extends Person implements Teacher { public Instructor (String name, long id) { super(name, id); } public void teach(Learner learner, double numbOfHours) { //5.1 calls a parameter of type Learner Interface (its public) learner.learn(numbOfHours); } public void lecture(Learner [] learners, double numberOfHours) { double numberOfHoursPerLearner = numberOfHours / learners.length; for(Learner element : learners) { teach(element, numberOfHoursPerLearner); } } }
627
0.645933
0.642743
28
21.392857
25.08605
73
false
false
0
0
0
0
0
0
0.357143
false
false
5
355c8e7705d5a108966d74c468e28a9d750c6b9f
8,658,654,116,057
92f254d8aa2c4f10e330c74f76ff8b9a0b53f60d
/Board.java
583bfc3b86c5ae105d1a183c12d02da20e1ea991
[]
no_license
mansigoel98/Brick-Breaker
https://github.com/mansigoel98/Brick-Breaker
53edc9c22077f73a2450a5bb3c572356e9597f06
668de36ede694e92e367d2944ce2a849262c0370
refs/heads/master
2020-12-03T16:02:11.265000
2020-06-10T13:26:44
2020-06-10T13:26:44
231,381,999
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package brick_breaker; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.Timer; public class Board extends JPanel implements ActionListener { private final int B_width = 800; private final int B_height = 600; private final int Ball_size = 50; private final int Break_size = 50; private final int All_Brick = 80; private final int DELAY = 140; private Image ball; private Image paddle; private Image brick; private Boolean leftDirection = false; private Boolean rightDirection = false; private Boolean spaceStart = false; private int paddle_x = 0; private int paddle_y = 580; private int ball_x = 65; private int ball_y = 560; private Boolean ingame = true; private Timer timer; private int score = 0; private Boolean left = true; private Boolean right = false; private Boolean up = true; private Boolean down = false; private int x[] = new int[All_Brick]; private int y[] = new int[All_Brick]; Board() { initboard(); } private void initboard() { addKeyListener(new TAdapter()); setBackground(Color.black); setFocusable(true); setPreferredSize(new Dimension(B_width, B_height)); loadImages(); initgame(); } private void loadImages() { ImageIcon i1 = new ImageIcon("C:\\Users\\Mansi\\eclipse-workspace\\games\\src\\brick_breaker\\ball.png"); ImageIcon i2 = new ImageIcon("C:\\Users\\Mansi\\eclipse-workspace\\games\\src\\brick_breaker\\paddle.png"); ImageIcon i3 = new ImageIcon("C:\\Users\\Mansi\\eclipse-workspace\\games\\src\\brick_breaker\\brick.png"); ball = i1.getImage(); paddle = i2.getImage(); brick = i3.getImage(); } private void initgame() { int j = 0; for (int i = 0; i < 800; i = i + 50) { x[j] = i; y[j] = 0; j++; } for (int i = 0; i < 800; i = i + 50) { x[j] = i; y[j] = 30; j++; } for (int i = 50; i < 750; i = i + 50) { x[j] = i; y[j] = 60; j++; } for (int i = 100; i < 700; i = i + 50) { x[j] = i; y[j] = 90; j++; } for (int i = 150; i < 650; i = i + 50) { x[j] = i; y[j] = 120; j++; } for (int i = 200; i < 600; i = i + 50) { x[j] = i; y[j] = 150; j++; } timer = new Timer(DELAY, this); timer.start(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } private void doDrawing(Graphics g) { if (ingame) { for (int i = 0; i < x.length; i++) { g.drawImage(brick, x[i], y[i], 50, 30, Color.MAGENTA, this); } g.drawImage(paddle, paddle_x, paddle_y, 150, 20, Color.lightGray, this); g.drawImage(ball, ball_x, ball_y, 20, 20, Color.YELLOW, this); Toolkit.getDefaultToolkit().sync(); } else { if (score == 76) { winwin(g); } else { gameOver(g); } } } private void gameOver(Graphics g) { String msg = "Game Over"; String sc = "Score is " + Integer.toString(score); Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (B_width - metr.stringWidth(msg)) / 2, B_height / 2); g.drawString(sc, (B_width - metr.stringWidth(sc)) / 2, B_height / 2 + 20); } private void winwin(Graphics g) { String msg = "You Won"; String sc = "Score is " + Integer.toString(score); Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (B_width - metr.stringWidth(msg)) / 2, B_height / 2); g.drawString(sc, (B_width - metr.stringWidth(sc)) / 2, B_height / 2 + 20); } private void destroyBrick() { for (int i = 0; i < x.length; i++) { if (ball_y == y[i] + 30 && ball_x >= x[i] && ball_x <= x[i] + 50) { x[i] = 1000; up = false; down = true; score++; if (score == 76) { ingame = false; } } } } private void checkfall() { if (ball_y >= 560 && (ball_x < paddle_x || ball_x > paddle_x + 150)) { ingame = false; } if (!ingame) { timer.stop(); } } private void moveball() { if (spaceStart) { if (left == true && up == true) { ball_x = ball_x - 10; ball_y = ball_y - 10; if (ball_x <= 0) { right = true; left = false; } if (ball_y <= 0) { down = true; up = false; } } else if (right == true && up == true) { ball_x = ball_x + 10; ball_y = ball_y - 10; if (ball_y <= 0) { down = true; up = false; } if (ball_x >= 780) { left = true; right = false; } } else if (right == true && down == true) { ball_x = ball_x + 10; ball_y = ball_y + 10; if (ball_x >= 780) { left = true; right = false; } if (ball_y >= 560) { up = true; down = false; } } else if (left == true && down == true) { ball_x = ball_x - 10; ball_y = ball_y + 10; if (ball_y >= 560) { up = true; down = false; } if (ball_x <= 0) { right = true; left = false; } } } } private void movepaddle() { if (leftDirection == true && paddle_x > 0) { paddle_x = paddle_x - 20; } else if (rightDirection == true && paddle_x < 650) { paddle_x = paddle_x + 20; } } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (ingame) { destroyBrick(); checkfall(); moveball(); movepaddle(); leftDirection = false; rightDirection = false; } repaint(); } private class TAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if ((key == KeyEvent.VK_LEFT)) { leftDirection = true; rightDirection = false; } if ((key == KeyEvent.VK_RIGHT)) { rightDirection = true; leftDirection = false; } if ((key == KeyEvent.VK_SPACE)) { spaceStart = !spaceStart; } } } }
UTF-8
Java
6,164
java
Board.java
Java
[ { "context": "png\");\n\t\tImageIcon i2 = new ImageIcon(\"C:\\\\Users\\\\Mansi\\\\eclipse-workspace\\\\games\\\\src\\\\brick_breaker\\\\pa", "end": 1692, "score": 0.9059872627258301, "start": 1687, "tag": "NAME", "value": "Mansi" }, { "context": "png\");\n\t\tImageIcon i3 = new ImageIcon(\"C:\\\\Users\\\\Mansi\\\\eclipse-workspace\\\\games\\\\src\\\\brick_breaker\\\\br", "end": 1802, "score": 0.9169570207595825, "start": 1797, "tag": "NAME", "value": "Mansi" } ]
null
[]
package brick_breaker; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.Timer; public class Board extends JPanel implements ActionListener { private final int B_width = 800; private final int B_height = 600; private final int Ball_size = 50; private final int Break_size = 50; private final int All_Brick = 80; private final int DELAY = 140; private Image ball; private Image paddle; private Image brick; private Boolean leftDirection = false; private Boolean rightDirection = false; private Boolean spaceStart = false; private int paddle_x = 0; private int paddle_y = 580; private int ball_x = 65; private int ball_y = 560; private Boolean ingame = true; private Timer timer; private int score = 0; private Boolean left = true; private Boolean right = false; private Boolean up = true; private Boolean down = false; private int x[] = new int[All_Brick]; private int y[] = new int[All_Brick]; Board() { initboard(); } private void initboard() { addKeyListener(new TAdapter()); setBackground(Color.black); setFocusable(true); setPreferredSize(new Dimension(B_width, B_height)); loadImages(); initgame(); } private void loadImages() { ImageIcon i1 = new ImageIcon("C:\\Users\\Mansi\\eclipse-workspace\\games\\src\\brick_breaker\\ball.png"); ImageIcon i2 = new ImageIcon("C:\\Users\\Mansi\\eclipse-workspace\\games\\src\\brick_breaker\\paddle.png"); ImageIcon i3 = new ImageIcon("C:\\Users\\Mansi\\eclipse-workspace\\games\\src\\brick_breaker\\brick.png"); ball = i1.getImage(); paddle = i2.getImage(); brick = i3.getImage(); } private void initgame() { int j = 0; for (int i = 0; i < 800; i = i + 50) { x[j] = i; y[j] = 0; j++; } for (int i = 0; i < 800; i = i + 50) { x[j] = i; y[j] = 30; j++; } for (int i = 50; i < 750; i = i + 50) { x[j] = i; y[j] = 60; j++; } for (int i = 100; i < 700; i = i + 50) { x[j] = i; y[j] = 90; j++; } for (int i = 150; i < 650; i = i + 50) { x[j] = i; y[j] = 120; j++; } for (int i = 200; i < 600; i = i + 50) { x[j] = i; y[j] = 150; j++; } timer = new Timer(DELAY, this); timer.start(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } private void doDrawing(Graphics g) { if (ingame) { for (int i = 0; i < x.length; i++) { g.drawImage(brick, x[i], y[i], 50, 30, Color.MAGENTA, this); } g.drawImage(paddle, paddle_x, paddle_y, 150, 20, Color.lightGray, this); g.drawImage(ball, ball_x, ball_y, 20, 20, Color.YELLOW, this); Toolkit.getDefaultToolkit().sync(); } else { if (score == 76) { winwin(g); } else { gameOver(g); } } } private void gameOver(Graphics g) { String msg = "Game Over"; String sc = "Score is " + Integer.toString(score); Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (B_width - metr.stringWidth(msg)) / 2, B_height / 2); g.drawString(sc, (B_width - metr.stringWidth(sc)) / 2, B_height / 2 + 20); } private void winwin(Graphics g) { String msg = "You Won"; String sc = "Score is " + Integer.toString(score); Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (B_width - metr.stringWidth(msg)) / 2, B_height / 2); g.drawString(sc, (B_width - metr.stringWidth(sc)) / 2, B_height / 2 + 20); } private void destroyBrick() { for (int i = 0; i < x.length; i++) { if (ball_y == y[i] + 30 && ball_x >= x[i] && ball_x <= x[i] + 50) { x[i] = 1000; up = false; down = true; score++; if (score == 76) { ingame = false; } } } } private void checkfall() { if (ball_y >= 560 && (ball_x < paddle_x || ball_x > paddle_x + 150)) { ingame = false; } if (!ingame) { timer.stop(); } } private void moveball() { if (spaceStart) { if (left == true && up == true) { ball_x = ball_x - 10; ball_y = ball_y - 10; if (ball_x <= 0) { right = true; left = false; } if (ball_y <= 0) { down = true; up = false; } } else if (right == true && up == true) { ball_x = ball_x + 10; ball_y = ball_y - 10; if (ball_y <= 0) { down = true; up = false; } if (ball_x >= 780) { left = true; right = false; } } else if (right == true && down == true) { ball_x = ball_x + 10; ball_y = ball_y + 10; if (ball_x >= 780) { left = true; right = false; } if (ball_y >= 560) { up = true; down = false; } } else if (left == true && down == true) { ball_x = ball_x - 10; ball_y = ball_y + 10; if (ball_y >= 560) { up = true; down = false; } if (ball_x <= 0) { right = true; left = false; } } } } private void movepaddle() { if (leftDirection == true && paddle_x > 0) { paddle_x = paddle_x - 20; } else if (rightDirection == true && paddle_x < 650) { paddle_x = paddle_x + 20; } } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (ingame) { destroyBrick(); checkfall(); moveball(); movepaddle(); leftDirection = false; rightDirection = false; } repaint(); } private class TAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if ((key == KeyEvent.VK_LEFT)) { leftDirection = true; rightDirection = false; } if ((key == KeyEvent.VK_RIGHT)) { rightDirection = true; leftDirection = false; } if ((key == KeyEvent.VK_SPACE)) { spaceStart = !spaceStart; } } } }
6,164
0.587119
0.558404
292
20.109589
19.232935
109
false
false
0
0
0
0
0
0
2.636986
false
false
5
43f0e48f3249091611183ba27f766aa5fa46aa70
31,997,506,421,824
cfcfbf1a014ba08658e5c94256a5acaaaea57cf8
/Semestr2/KP/projects/Wilk i zajęcy[lab6]/Animal.java
1d9e114f61f9cea296b05a67577857e86f125393
[]
no_license
Bohdan-Belik/wppt-archive
https://github.com/Bohdan-Belik/wppt-archive
508323fcfeb6138961b7559f27119e82a3547513
d9e9123a0da30b60b75189945b016ffc371a6c64
refs/heads/master
2023-03-15T10:47:26.403000
2021-03-11T15:31:29
2021-03-11T16:01:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; /**Klasa umożliwiająca tworzenie zwieżąt w postaci wątków * * @author Maksym Telepchuk * @version 1.0 */ public abstract class Animal implements Runnable { /**Plansza, na której odbywa się gra */ protected Panel panel; /**Współrzędna zwierzęcia po x */ protected int x; /**Współrzędna zwierzęcia po y */ protected int y; /**Wymiar jednego punktu na plansze */ protected int d = Panel.sizeOfPoint; /**Współrzędna wroga po x */ protected int x_enemy; /**Współrzędna wroga po y */ protected int y_enemy; /**Stwarza wątek z danymi zwierzęcia * @param panel Plansza, na której odbywa się gra */ public Animal(Panel panel){ this.panel=panel; this.x = (int) (Math.random() * panel.n) * d + 1; this.y = (int) (Math.random() * panel.m) * d + 1; int i =0; while(i!=panel.hares.size()) { if((x==panel.hares.get(i).x&&y==panel.hares.get(i).y)||(x==panel.wolf.x&&y==panel.wolf.y)) { this.x = (int) (Math.random() * panel.n) * d + 1; this.y = (int) (Math.random() * panel.m) * d + 1; i=-1; } i++; } } @Override public abstract void run(); }
UTF-8
Java
1,374
java
Animal.java
Java
[ { "context": "tworzenie zwieżąt w postaci wątków\r\n *\r\n * @author Maksym Telepchuk\r\n * @version 1.0\r\n */\r\npublic abstract class Anim", "end": 112, "score": 0.9997642040252686, "start": 96, "tag": "NAME", "value": "Maksym Telepchuk" } ]
null
[]
package com.company; /**Klasa umożliwiająca tworzenie zwieżąt w postaci wątków * * @author <NAME> * @version 1.0 */ public abstract class Animal implements Runnable { /**Plansza, na której odbywa się gra */ protected Panel panel; /**Współrzędna zwierzęcia po x */ protected int x; /**Współrzędna zwierzęcia po y */ protected int y; /**Wymiar jednego punktu na plansze */ protected int d = Panel.sizeOfPoint; /**Współrzędna wroga po x */ protected int x_enemy; /**Współrzędna wroga po y */ protected int y_enemy; /**Stwarza wątek z danymi zwierzęcia * @param panel Plansza, na której odbywa się gra */ public Animal(Panel panel){ this.panel=panel; this.x = (int) (Math.random() * panel.n) * d + 1; this.y = (int) (Math.random() * panel.m) * d + 1; int i =0; while(i!=panel.hares.size()) { if((x==panel.hares.get(i).x&&y==panel.hares.get(i).y)||(x==panel.wolf.x&&y==panel.wolf.y)) { this.x = (int) (Math.random() * panel.n) * d + 1; this.y = (int) (Math.random() * panel.m) * d + 1; i=-1; } i++; } } @Override public abstract void run(); }
1,364
0.525223
0.519288
51
24.431372
21.757357
104
false
false
0
0
0
0
0
0
0.392157
false
false
5
f7b8a2fb128890dbb507c0ca0b10acb16ae0ec64
4,252,017,688,534
85d5a3293bc62c4360481b865f85090d9daddf12
/src/main/java/SeleniumSessions/ExplicitWaitConcept.java
e4074853ed4eb489be9acf5313e3c6328b4603f1
[]
no_license
smitatech17/Feb2020Selenium
https://github.com/smitatech17/Feb2020Selenium
6158efa436aa1fafe97cff80edfe1345fea98777
ea39044ce0b3b3d7d6e1a8fd9f9cfb61d240afe3
refs/heads/master
2023-05-10T17:08:23.805000
2020-05-05T20:13:14
2020-05-05T20:13:14
261,572,592
0
0
null
false
2023-05-09T17:57:32
2020-05-05T20:09:44
2020-05-05T20:13:41
2023-05-09T17:57:29
144
0
0
1
HTML
false
false
package SeleniumSessions; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import io.github.bonigarcia.wdm.WebDriverManager; public class ExplicitWaitConcept { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://app.hubspot.com/login"); // //explicitly wait is always defined with webdriverwait; create the object of Webdriverwait class // WebDriverWait wait = new WebDriverWait(driver, 15); // //wait.until(ExpectedConditions.titleIs("HubSpot Login")); // wait.until(ExpectedConditions.titleContains("HubSpot")); // System.out.println(driver.getTitle()); getElementWithExplicitWait(driver, 10, By.id("username")).sendKeys("test@gmail.com"); // WebDriverWait wait = new WebDriverWait(driver, 15); // wait.until(ExpectedConditions.presenceOfElementLocated(By.id("username"))); // // // WebElement emailId = driver.findElement(By.id("username")); // emailId.sendKeys("test"); WebElement password = driver.findElement(By.id("password")); password.sendKeys("test@123"); WebElement loginButton = driver.findElement(By.id("loginBtn")); loginButton.click(); } public static WebElement getElementWithExplicitWait(WebDriver driver, int timeout, By locator) { WebDriverWait wait = new WebDriverWait(driver, timeout); // WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(locator)); // return element; return wait.until(ExpectedConditions.presenceOfElementLocated(locator)); } }
UTF-8
Java
1,811
java
ExplicitWaitConcept.java
Java
[ { "context": "enium.support.ui.WebDriverWait;\n\nimport io.github.bonigarcia.wdm.WebDriverManager;\n\npublic class ExplicitWaitC", "end": 361, "score": 0.9666447639465332, "start": 351, "tag": "USERNAME", "value": "bonigarcia" }, { "context": "icitWait(driver, 10, By.id(\"username\")).sendKeys(\"test@gmail.com\");\n\t\t\n//\t\tWebDriverWait wait = new WebDriverWait(", "end": 1014, "score": 0.9999027252197266, "start": 1000, "tag": "EMAIL", "value": "test@gmail.com" }, { "context": "dElement(By.id(\"password\"));\n\t\tpassword.sendKeys(\"test@123\");\n\t\t\n\t\tWebElement loginButton = driver.findEleme", "end": 1356, "score": 0.999485969543457, "start": 1348, "tag": "PASSWORD", "value": "test@123" } ]
null
[]
package SeleniumSessions; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import io.github.bonigarcia.wdm.WebDriverManager; public class ExplicitWaitConcept { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://app.hubspot.com/login"); // //explicitly wait is always defined with webdriverwait; create the object of Webdriverwait class // WebDriverWait wait = new WebDriverWait(driver, 15); // //wait.until(ExpectedConditions.titleIs("HubSpot Login")); // wait.until(ExpectedConditions.titleContains("HubSpot")); // System.out.println(driver.getTitle()); getElementWithExplicitWait(driver, 10, By.id("username")).sendKeys("<EMAIL>"); // WebDriverWait wait = new WebDriverWait(driver, 15); // wait.until(ExpectedConditions.presenceOfElementLocated(By.id("username"))); // // // WebElement emailId = driver.findElement(By.id("username")); // emailId.sendKeys("test"); WebElement password = driver.findElement(By.id("password")); password.sendKeys("<PASSWORD>"); WebElement loginButton = driver.findElement(By.id("loginBtn")); loginButton.click(); } public static WebElement getElementWithExplicitWait(WebDriver driver, int timeout, By locator) { WebDriverWait wait = new WebDriverWait(driver, timeout); // WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(locator)); // return element; return wait.until(ExpectedConditions.presenceOfElementLocated(locator)); } }
1,806
0.759249
0.754279
54
32.537037
29.708281
100
false
false
0
0
0
0
0
0
1.944444
false
false
5
d000a04ad6062c5daf452a1e4150f7afa690bf4b
22,522,808,549,086
cdc9a334996b0c933269b7aa8b39357c97176ca5
/java/service-buc/src/main/java/com/suneee/platform/model/system/MessageRead.java
435e30a4ffa5a4c588e4843b1923c9f69301bd0f
[]
no_license
lmr1109665009/oa
https://github.com/lmr1109665009/oa
857c2729398f08f2094f47824f383cfa4d808ae6
21cf4bac10ab72520a1f0dfdd965b9378081823c
refs/heads/master
2020-05-16T10:39:51.316000
2019-04-23T10:13:26
2019-04-23T10:13:26
182,986,352
2
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.suneee.platform.model.system; import com.suneee.core.model.BaseModel; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; /** * 对象功能:接收状态 Model对象 * 开发公司:广州宏天软件有限公司 * 开发人员:csx * 创建时间:2012-01-14 15:14:51 */ public class MessageRead extends BaseModel { // 主键 protected Long id; // 消息ID protected Long messageId; // 接收人Id protected Long receiverId; // 接收人 protected String receiver; // 接收时间 protected java.util.Date receiveTime; public void setId(Long id) { this.id = id; } /** * 返回 主键 * @return */ public Long getId() { return id; } public void setMessageId(Long messageId) { this.messageId = messageId; } /** * 返回 消息ID * @return */ public Long getMessageId() { return messageId; } public void setReceiverId(Long receiverId) { this.receiverId = receiverId; } /** * 返回 接收人Id * @return */ public Long getReceiverId() { return receiverId; } public void setReceiver(String receiver) { this.receiver = receiver; } /** * 返回 接收人 * @return */ public String getReceiver() { return receiver; } public void setReceiveTime(java.util.Date receiveTime) { this.receiveTime = receiveTime; } /** * 返回 接收时间 * @return */ public java.util.Date getReceiveTime() { return receiveTime; } /** * @see Object#equals(Object) */ public boolean equals(Object object) { if (!(object instanceof MessageRead)) { return false; } MessageRead rhs = (MessageRead) object; return new EqualsBuilder() .append(this.id, rhs.id) .append(this.messageId, rhs.messageId) .append(this.receiverId, rhs.receiverId) .append(this.receiver, rhs.receiver) .append(this.receiveTime, rhs.receiveTime) .isEquals(); } /** * @see Object#hashCode() */ public int hashCode() { return new HashCodeBuilder(-82280557, -700257973) .append(this.id) .append(this.messageId) .append(this.receiverId) .append(this.receiver) .append(this.receiveTime) .toHashCode(); } /** * @see Object#toString() */ public String toString() { return new ToStringBuilder(this) .append("id", this.id) .append("messageId", this.messageId) .append("receiverId", this.receiverId) .append("receiver", this.receiver) .append("receiveTime", this.receiveTime) .toString(); } }
UTF-8
Java
2,572
java
MessageRead.java
Java
[ { "context": "*\n * 对象功能:接收状态 Model对象\n * 开发公司:广州宏天软件有限公司\n * 开发人员:csx\n * 创建时间:2012-01-14 15:14:51\n */\npublic class Mess", "end": 304, "score": 0.9940176606178284, "start": 301, "tag": "USERNAME", "value": "csx" } ]
null
[]
package com.suneee.platform.model.system; import com.suneee.core.model.BaseModel; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; /** * 对象功能:接收状态 Model对象 * 开发公司:广州宏天软件有限公司 * 开发人员:csx * 创建时间:2012-01-14 15:14:51 */ public class MessageRead extends BaseModel { // 主键 protected Long id; // 消息ID protected Long messageId; // 接收人Id protected Long receiverId; // 接收人 protected String receiver; // 接收时间 protected java.util.Date receiveTime; public void setId(Long id) { this.id = id; } /** * 返回 主键 * @return */ public Long getId() { return id; } public void setMessageId(Long messageId) { this.messageId = messageId; } /** * 返回 消息ID * @return */ public Long getMessageId() { return messageId; } public void setReceiverId(Long receiverId) { this.receiverId = receiverId; } /** * 返回 接收人Id * @return */ public Long getReceiverId() { return receiverId; } public void setReceiver(String receiver) { this.receiver = receiver; } /** * 返回 接收人 * @return */ public String getReceiver() { return receiver; } public void setReceiveTime(java.util.Date receiveTime) { this.receiveTime = receiveTime; } /** * 返回 接收时间 * @return */ public java.util.Date getReceiveTime() { return receiveTime; } /** * @see Object#equals(Object) */ public boolean equals(Object object) { if (!(object instanceof MessageRead)) { return false; } MessageRead rhs = (MessageRead) object; return new EqualsBuilder() .append(this.id, rhs.id) .append(this.messageId, rhs.messageId) .append(this.receiverId, rhs.receiverId) .append(this.receiver, rhs.receiver) .append(this.receiveTime, rhs.receiveTime) .isEquals(); } /** * @see Object#hashCode() */ public int hashCode() { return new HashCodeBuilder(-82280557, -700257973) .append(this.id) .append(this.messageId) .append(this.receiverId) .append(this.receiver) .append(this.receiveTime) .toHashCode(); } /** * @see Object#toString() */ public String toString() { return new ToStringBuilder(this) .append("id", this.id) .append("messageId", this.messageId) .append("receiverId", this.receiverId) .append("receiver", this.receiver) .append("receiveTime", this.receiveTime) .toString(); } }
2,572
0.669819
0.657072
141
16.25532
15.681404
56
false
false
0
0
0
0
0
0
1.326241
false
false
5
ba15f7562525d09c295e2315326c4050779666b0
2,027,224,615,796
cef8d2a21ed1531c6052dd8fbdccda89562dde30
/ezqlite/src/main/java/alfianyusufabdullah/ezqlite/EZQLite.java
5a6eb929777d4c3673c1062b1a2c493e642dbd31
[ "Apache-2.0" ]
permissive
alfianyusufabdullah/ezqlite-db
https://github.com/alfianyusufabdullah/ezqlite-db
21d3261c105d51e179ac726c3a5087bd4ed0164e
e1c2927f3445ae4299c3c41bd3f92e4337f744fd
refs/heads/master
2021-09-03T02:55:10.995000
2018-01-05T03:00:42
2018-01-05T03:00:42
115,909,388
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package alfianyusufabdullah.ezqlite; import android.app.Activity; import android.app.Fragment; import android.content.Context; import alfianyusufabdullah.ezqlite.configuration.DatabaseConfiguration; import alfianyusufabdullah.ezqlite.configuration.DatabaseHelperConfiguration; import alfianyusufabdullah.ezqlite.perform.Insert; import alfianyusufabdullah.ezqlite.perform.Load; import alfianyusufabdullah.ezqlite.perform.LoadWithRawQuery; import alfianyusufabdullah.ezqlite.perform.Remove; import alfianyusufabdullah.ezqlite.perform.Update; /** * Created by jonesrandom on 12/27/17. * * @site www.androidexample.web.id * @github @alfianyusufabdullah */ public class EZQLite { private DatabaseHelperConfiguration databaseHelperConfiguration; private EZQLite(Context context) { databaseHelperConfiguration = new DatabaseHelperConfiguration(context); } public static EZQLite getInstance(Activity activity) { return new EZQLite(activity.getApplicationContext()); } public static EZQLite getInstance(Fragment fragment) { return new EZQLite(fragment.getActivity().getApplicationContext()); } public Insert doInsert(String TableName) { return Insert.get(TableName, databaseHelperConfiguration); } public Load doLoad(String TableName) { return Load.init(TableName, databaseHelperConfiguration); } public Remove doRemove(String TableName) { return Remove.init(TableName, databaseHelperConfiguration); } public Update doUpdate(String TableName) { return Update.init(TableName, databaseHelperConfiguration); } public LoadWithRawQuery loadWithRawQuery(String Query) { return LoadWithRawQuery.init(Query, databaseHelperConfiguration); } }
UTF-8
Java
1,776
java
EZQLite.java
Java
[ { "context": "bdullah.ezqlite.perform.Update;\n\n/**\n * Created by jonesrandom on 12/27/17.\n *\n * @site www.androidexample.web.i", "end": 572, "score": 0.9997091889381409, "start": 561, "tag": "USERNAME", "value": "jonesrandom" }, { "context": ".\n *\n * @site www.androidexample.web.id\n * @github @alfianyusufabdullah\n */\n\npublic class EZQLite {\n\n private Database", "end": 655, "score": 0.9995961785316467, "start": 635, "tag": "USERNAME", "value": "@alfianyusufabdullah" } ]
null
[]
package alfianyusufabdullah.ezqlite; import android.app.Activity; import android.app.Fragment; import android.content.Context; import alfianyusufabdullah.ezqlite.configuration.DatabaseConfiguration; import alfianyusufabdullah.ezqlite.configuration.DatabaseHelperConfiguration; import alfianyusufabdullah.ezqlite.perform.Insert; import alfianyusufabdullah.ezqlite.perform.Load; import alfianyusufabdullah.ezqlite.perform.LoadWithRawQuery; import alfianyusufabdullah.ezqlite.perform.Remove; import alfianyusufabdullah.ezqlite.perform.Update; /** * Created by jonesrandom on 12/27/17. * * @site www.androidexample.web.id * @github @alfianyusufabdullah */ public class EZQLite { private DatabaseHelperConfiguration databaseHelperConfiguration; private EZQLite(Context context) { databaseHelperConfiguration = new DatabaseHelperConfiguration(context); } public static EZQLite getInstance(Activity activity) { return new EZQLite(activity.getApplicationContext()); } public static EZQLite getInstance(Fragment fragment) { return new EZQLite(fragment.getActivity().getApplicationContext()); } public Insert doInsert(String TableName) { return Insert.get(TableName, databaseHelperConfiguration); } public Load doLoad(String TableName) { return Load.init(TableName, databaseHelperConfiguration); } public Remove doRemove(String TableName) { return Remove.init(TableName, databaseHelperConfiguration); } public Update doUpdate(String TableName) { return Update.init(TableName, databaseHelperConfiguration); } public LoadWithRawQuery loadWithRawQuery(String Query) { return LoadWithRawQuery.init(Query, databaseHelperConfiguration); } }
1,776
0.771396
0.768018
58
29.620689
27.718304
79
false
false
0
0
0
0
0
0
0.431034
false
false
5
4f7a603255a21073f449eb326632cf7c001b7233
20,581,483,287,903
4008c174282fc5c09ca0b13db7f9e3d295ad34b3
/db/src/main/java/com/zero/zookeeper/CuratorTest.java
832897fff19b741dae6da3767257394ba5cb82b0
[]
no_license
zero-jianjia/javatest
https://github.com/zero-jianjia/javatest
80672b503a1cc363d2d4759c74dd841e18e21635
e348e3d307de90eb0aa1c3406b7b6aeb89f2c5c2
refs/heads/master
2021-05-22T08:05:19.203000
2020-08-02T12:22:48
2020-08-02T12:22:48
51,893,049
0
0
null
false
2021-04-26T16:08:23
2016-02-17T03:54:52
2020-08-02T12:23:15
2021-04-26T16:08:22
49,754
0
0
17
Java
false
false
package com.zero.zookeeper; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.framework.recipes.cache.*; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.utils.EnsurePath; import org.apache.zookeeper.CreateMode; import static com.zero.zookeeper.CuratorListenerTest.getClient; import static org.apache.zookeeper.ZooDefs.OpCode.delete; /** * Created by jianjia1 on 16/04/08. */ public class CuratorTest { public static CuratorFramework getClient() { String zkHosts = "10.210.228.89:2282"; int sessionTimeout = 30000;// session超时 int connectionTimeout = 30000; //连接超时 String namespace = "curator"; // 全局path前缀,常用来区分不同的应用 CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(zkHosts)//127.0.0.1:2181 .sessionTimeoutMs(sessionTimeout) .connectionTimeoutMs(connectionTimeout) //.canBeReadOnly(false) .retryPolicy(new ExponentialBackoffRetry(3000, 5)) .namespace(namespace) .defaultData(null) .build(); client.start(); //client.close(); return client; } public static void main(String[] args) throws Exception { //创建client CuratorFramework zkClient = getClient(); //zkClient.start(); //启动 System.out.println("zkClient.getState() = " + zkClient.getState());//LATENT // 如果zk尚未启动,则启动 if (zkClient.getState() == CuratorFrameworkState.LATENT) { zkClient.start(); } // System.out.println("zkClient.getState() = " + zkClient.getState());//STARTED //注意此时zkClient中可能 根节点还没创建,这里即namespace节点 //子节点创建 String child001 = "/child009"; if (zkClient.checkExists().forPath(child001) == null) { //会创建/curator/child001节点 String a = zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(child001); System.out.println("@@@@@@@" + a); try { a = zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(child001); System.out.println("-----" + a); } catch (Exception e) { System.out.println("$$$$$$$$$$$$$$"); } } //获取子节点 System.out.println(zkClient.getChildren().forPath("/child001")); // //设置并获取数据 // client.setData().forPath("/curator", "zero".getBytes()); // System.out.println(client.getData().forPath("/curator")); // // //删除节点 // client.delete().forPath("/curator"); // // 可以监控某一路径的直接子结点(一级子结点)变化,add,update,delete。 // 利用此特性可以很方便的监控集群中的所有结点,当然也就很方便的可以实现简单的key.hashCode()%serverCount式的分布式计算,还可以实现简单的定制规则的负载均衡。 // PathChildrenCache watcher = new PathChildrenCache(client, "/curator", true); // watcher.getListenable().addListener(new PathChildrenCacheListener() { // @Override // public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { // ChildData data = event.getData(); // if (data == null) { // System.out.println("No data in event[" + event + "]"); // } else { // System.out.println("Receive event: " // + "type=[" + event.getType() + "]" // + ", path=[" + data.getPath() + "]" // + ", data=[" + new String(data.getData()) + "]" // + ", stat=[" + data.getStat() + "]"); // } // } // }); // watcher.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); // System.out.println("Register zk watcher successfully!"); //Node Cache Watcher只能监听某一路径本身的add,delete,update // final NodeCache nodeCache = new NodeCache(client, C_PATH); // nodeCache.getListenable().addListener(new NodeCacheListener() { // @Override // public void nodeChanged() throws Exception { // System.out.println("================== catch node data change =================="); // ChildData childData = nodeCache.getCurrentData(); // if(childData == null){ // System.out.println("===delete, path=" + C_PATH + ", childData=" + childData); // }else{ // System.out.println("===update or add, path=" + C_PATH + ", childData=" + new String(childData.getData(), CHARSET)); // } // } // }); // nodeCache.start(); // // Thread.sleep(Integer.MAX_VALUE); // client.close(); //可以监控某一路径下的子结点(所有子结节,不管有多少层子结点)变化。 // 比NodeCache方便的是,可以监听一群结点,而不用一个节点一个节点的去设置监听 // final TreeCache treeCache = new TreeCache(client, C_PATH); // treeCache.getListenable().addListener(new TreeCacheListener() { // @Override // public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { // System.out.println("================== catch tree change =================="); // if(event.getData() == null){ // System.out.println("===init," + event.getType()); // return; // } // // if(event.getData().getData() == null){ // System.out.println("===delete," + event.getType() + "," + event.getData().getPath()); // }else{ // System.out.println("===update or add," + event.getType() + "," + event.getData().getPath() + "," + new String(event.getData().getData(), TreeListener.CHARSET)); // } // } // }); // treeCache.start(); // // Thread.sleep(Integer.MAX_VALUE); // client.close(); } // private static final int CLIENT_QTY = 10; // private static final String PATH = "/examples/leader"; // public static void leaderLatchTest(){ // List<CuratorFramework> clients = Lists.newArrayList(); // List<LeaderLatch> examples = Lists.newArrayList(); // TestingServer server = new TestingServer(); // try { // for (int i = 0; i < CLIENT_QTY; ++i) { // CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); // clients.add(client); // LeaderLatch example = new LeaderLatch(client, PATH, "Client #" + i); // examples.add(example); // client.start(); // example.start(); // } // // Thread.sleep(20000); // // LeaderLatch currentLeader = null; // for (int i = 0; i < CLIENT_QTY; ++i) { // LeaderLatch example = examples.get(i); // if (example.hasLeadership()) // currentLeader = example; // } // System.out.println("current leader is " + currentLeader.getId()); // System.out.println("release the leader " + currentLeader.getId()); // currentLeader.close(); // examples.get(0).await(2, TimeUnit.SECONDS); // System.out.println("Client #0 maybe is elected as the leader or not although it want to be"); // System.out.println("the new leader is " + examples.get(0).getLeader().getId()); // // System.out.println("Press enter/return to quit\n"); // new BufferedReader(new InputStreamReader(System.in)).readLine(); // // } catch (Exception e) { // e.printStackTrace(); // } finally { // System.out.println("Shutting down..."); // for (LeaderLatch exampleClient : examples) { // CloseableUtils.closeQuietly(exampleClient); // } // for (CuratorFramework client : clients) { // CloseableUtils.closeQuietly(client); // } // CloseableUtils.closeQuietly(server); // } // // } }
UTF-8
Java
8,793
java
CuratorTest.java
Java
[ { "context": "ookeeper.ZooDefs.OpCode.delete;\n\n/**\n * Created by jianjia1 on 16/04/08.\n */\npublic class CuratorTest {\n\n ", "end": 552, "score": 0.9995957612991333, "start": 544, "tag": "USERNAME", "value": "jianjia1" }, { "context": "Framework getClient() {\n String zkHosts = \"10.210.228.89:2282\";\n int sessionTimeout = 30000;// sess", "end": 686, "score": 0.999727189540863, "start": 673, "tag": "IP_ADDRESS", "value": "10.210.228.89" }, { "context": "ramework client = builder.connectString(zkHosts)//127.0.0.1:2181\n .sessionTimeoutMs(sessionTim", "end": 1010, "score": 0.9997580051422119, "start": 1001, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
null
[]
package com.zero.zookeeper; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.CuratorFrameworkState; import org.apache.curator.framework.recipes.cache.*; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.utils.EnsurePath; import org.apache.zookeeper.CreateMode; import static com.zero.zookeeper.CuratorListenerTest.getClient; import static org.apache.zookeeper.ZooDefs.OpCode.delete; /** * Created by jianjia1 on 16/04/08. */ public class CuratorTest { public static CuratorFramework getClient() { String zkHosts = "10.210.228.89:2282"; int sessionTimeout = 30000;// session超时 int connectionTimeout = 30000; //连接超时 String namespace = "curator"; // 全局path前缀,常用来区分不同的应用 CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(zkHosts)//127.0.0.1:2181 .sessionTimeoutMs(sessionTimeout) .connectionTimeoutMs(connectionTimeout) //.canBeReadOnly(false) .retryPolicy(new ExponentialBackoffRetry(3000, 5)) .namespace(namespace) .defaultData(null) .build(); client.start(); //client.close(); return client; } public static void main(String[] args) throws Exception { //创建client CuratorFramework zkClient = getClient(); //zkClient.start(); //启动 System.out.println("zkClient.getState() = " + zkClient.getState());//LATENT // 如果zk尚未启动,则启动 if (zkClient.getState() == CuratorFrameworkState.LATENT) { zkClient.start(); } // System.out.println("zkClient.getState() = " + zkClient.getState());//STARTED //注意此时zkClient中可能 根节点还没创建,这里即namespace节点 //子节点创建 String child001 = "/child009"; if (zkClient.checkExists().forPath(child001) == null) { //会创建/curator/child001节点 String a = zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(child001); System.out.println("@@@@@@@" + a); try { a = zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(child001); System.out.println("-----" + a); } catch (Exception e) { System.out.println("$$$$$$$$$$$$$$"); } } //获取子节点 System.out.println(zkClient.getChildren().forPath("/child001")); // //设置并获取数据 // client.setData().forPath("/curator", "zero".getBytes()); // System.out.println(client.getData().forPath("/curator")); // // //删除节点 // client.delete().forPath("/curator"); // // 可以监控某一路径的直接子结点(一级子结点)变化,add,update,delete。 // 利用此特性可以很方便的监控集群中的所有结点,当然也就很方便的可以实现简单的key.hashCode()%serverCount式的分布式计算,还可以实现简单的定制规则的负载均衡。 // PathChildrenCache watcher = new PathChildrenCache(client, "/curator", true); // watcher.getListenable().addListener(new PathChildrenCacheListener() { // @Override // public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { // ChildData data = event.getData(); // if (data == null) { // System.out.println("No data in event[" + event + "]"); // } else { // System.out.println("Receive event: " // + "type=[" + event.getType() + "]" // + ", path=[" + data.getPath() + "]" // + ", data=[" + new String(data.getData()) + "]" // + ", stat=[" + data.getStat() + "]"); // } // } // }); // watcher.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); // System.out.println("Register zk watcher successfully!"); //Node Cache Watcher只能监听某一路径本身的add,delete,update // final NodeCache nodeCache = new NodeCache(client, C_PATH); // nodeCache.getListenable().addListener(new NodeCacheListener() { // @Override // public void nodeChanged() throws Exception { // System.out.println("================== catch node data change =================="); // ChildData childData = nodeCache.getCurrentData(); // if(childData == null){ // System.out.println("===delete, path=" + C_PATH + ", childData=" + childData); // }else{ // System.out.println("===update or add, path=" + C_PATH + ", childData=" + new String(childData.getData(), CHARSET)); // } // } // }); // nodeCache.start(); // // Thread.sleep(Integer.MAX_VALUE); // client.close(); //可以监控某一路径下的子结点(所有子结节,不管有多少层子结点)变化。 // 比NodeCache方便的是,可以监听一群结点,而不用一个节点一个节点的去设置监听 // final TreeCache treeCache = new TreeCache(client, C_PATH); // treeCache.getListenable().addListener(new TreeCacheListener() { // @Override // public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { // System.out.println("================== catch tree change =================="); // if(event.getData() == null){ // System.out.println("===init," + event.getType()); // return; // } // // if(event.getData().getData() == null){ // System.out.println("===delete," + event.getType() + "," + event.getData().getPath()); // }else{ // System.out.println("===update or add," + event.getType() + "," + event.getData().getPath() + "," + new String(event.getData().getData(), TreeListener.CHARSET)); // } // } // }); // treeCache.start(); // // Thread.sleep(Integer.MAX_VALUE); // client.close(); } // private static final int CLIENT_QTY = 10; // private static final String PATH = "/examples/leader"; // public static void leaderLatchTest(){ // List<CuratorFramework> clients = Lists.newArrayList(); // List<LeaderLatch> examples = Lists.newArrayList(); // TestingServer server = new TestingServer(); // try { // for (int i = 0; i < CLIENT_QTY; ++i) { // CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); // clients.add(client); // LeaderLatch example = new LeaderLatch(client, PATH, "Client #" + i); // examples.add(example); // client.start(); // example.start(); // } // // Thread.sleep(20000); // // LeaderLatch currentLeader = null; // for (int i = 0; i < CLIENT_QTY; ++i) { // LeaderLatch example = examples.get(i); // if (example.hasLeadership()) // currentLeader = example; // } // System.out.println("current leader is " + currentLeader.getId()); // System.out.println("release the leader " + currentLeader.getId()); // currentLeader.close(); // examples.get(0).await(2, TimeUnit.SECONDS); // System.out.println("Client #0 maybe is elected as the leader or not although it want to be"); // System.out.println("the new leader is " + examples.get(0).getLeader().getId()); // // System.out.println("Press enter/return to quit\n"); // new BufferedReader(new InputStreamReader(System.in)).readLine(); // // } catch (Exception e) { // e.printStackTrace(); // } finally { // System.out.println("Shutting down..."); // for (LeaderLatch exampleClient : examples) { // CloseableUtils.closeQuietly(exampleClient); // } // for (CuratorFramework client : clients) { // CloseableUtils.closeQuietly(client); // } // CloseableUtils.closeQuietly(server); // } // // } }
8,793
0.556464
0.546242
206
39.364079
32.737534
182
false
false
0
0
0
0
0
0
0.61165
false
false
5
b3383ef966f0b2d38b930eb13122bac5180a06eb
326,417,537,595
e22c08e104c77503488723ebbe62c29a08e56a34
/Leetcode/src/main/java/year/before2020/problem467/Solution.java
76b6b12206a8d8f821c25fad34d0d156a50b9ad4
[]
no_license
ruanhang1993/LeetcodeJava
https://github.com/ruanhang1993/LeetcodeJava
c88b99ca0d2d92bcc0e9f454c1e127cb7a9bdbdd
3991b5daae29ddf60db6f54f5f29714f85ded27c
refs/heads/master
2021-01-19T13:25:12.221000
2020-06-29T13:27:28
2020-06-29T13:27:28
100,841,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package year.before2020.problem467; public class Solution { public int findSubstringInWraproundString(String p) { int index = 0; int[] maxRec = new int[26]; while(index<p.length()){ int startC = p.charAt(index)-'a'; int start = index; while(index+1<p.length() && isNext(p.charAt(index),p.charAt(index+1))){ index++; } maxRec[startC]= Math.max(maxRec[startC], index-start+1); index++; } int res = 0; for(int i = 0; i < 26; i++){ for(int j = 0; j < 26; j++){ if(i<j){ maxRec[i]= Math.max(maxRec[i], maxRec[j]-(26+i-j)); }else if(i>j){ maxRec[i]= Math.max(maxRec[i], maxRec[j]-(i-j)); } } } for(int i = 0; i < 26; i++){ res+=maxRec[i]; } return res; } public boolean isNext(char pre, char next){ if(pre=='z'&&next=='a') return true; if(next-pre==1) return true; return false; } }
UTF-8
Java
962
java
Solution.java
Java
[]
null
[]
package year.before2020.problem467; public class Solution { public int findSubstringInWraproundString(String p) { int index = 0; int[] maxRec = new int[26]; while(index<p.length()){ int startC = p.charAt(index)-'a'; int start = index; while(index+1<p.length() && isNext(p.charAt(index),p.charAt(index+1))){ index++; } maxRec[startC]= Math.max(maxRec[startC], index-start+1); index++; } int res = 0; for(int i = 0; i < 26; i++){ for(int j = 0; j < 26; j++){ if(i<j){ maxRec[i]= Math.max(maxRec[i], maxRec[j]-(26+i-j)); }else if(i>j){ maxRec[i]= Math.max(maxRec[i], maxRec[j]-(i-j)); } } } for(int i = 0; i < 26; i++){ res+=maxRec[i]; } return res; } public boolean isNext(char pre, char next){ if(pre=='z'&&next=='a') return true; if(next-pre==1) return true; return false; } }
962
0.516632
0.489605
36
25.75
18.991774
77
false
false
0
0
0
0
0
0
2.111111
false
false
5
20e13a772ff2bc64b0b691a8f6841c070df62916
24,644,522,350,235
3fcddd1bb86a12c3b4881a4889000736c451ac9e
/android/PolicyApp/src/com/personal/policy/ui/views/FindProviderActivity.java
5ac11f41926e5260911b0cbe2017f9b1e888cb0f
[]
no_license
saneeshjose/personal
https://github.com/saneeshjose/personal
c45135068d4b3acad11c2c2e7b7b4ef74d3ec539
e42cafa4100d335dfbbf58d336c7205a203be878
refs/heads/master
2016-09-05T18:33:18.074000
2013-10-21T15:10:25
2013-10-21T15:10:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.personal.policy.ui.views; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.personal.policy.Provider; import com.personal.policy.R; import com.personal.policy.net.NetUtils; import com.personal.policy.ui.ProviderListAdapter; public class FindProviderActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.find_provider); final List<Provider> providers = new ArrayList<Provider>(); final ProviderListAdapter adapter = new ProviderListAdapter(this, R.layout.provider_list_item, providers ); final ListView list = (ListView) findViewById(R.id.provider_list); list.setAdapter(adapter); Button b = (Button) findViewById(R.id.btnSearch); b.setOnClickListener( new OnClickListener() { @Override public void onClick(View arg0) { EditText txtProviderName = (EditText) findViewById(R.id.provider_name); EditText txtProviderLocation = (EditText) findViewById(R.id.provider_location); String name = txtProviderName.getText().toString(); String location = txtProviderLocation.getText().toString(); try { providers.clear(); providers.addAll( new NetUtils().getProviders(name, location)); adapter.notifyDataSetChanged(); } catch(Exception e) { e.printStackTrace(); } } }); } }
UTF-8
Java
1,624
java
FindProviderActivity.java
Java
[]
null
[]
package com.personal.policy.ui.views; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.personal.policy.Provider; import com.personal.policy.R; import com.personal.policy.net.NetUtils; import com.personal.policy.ui.ProviderListAdapter; public class FindProviderActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.find_provider); final List<Provider> providers = new ArrayList<Provider>(); final ProviderListAdapter adapter = new ProviderListAdapter(this, R.layout.provider_list_item, providers ); final ListView list = (ListView) findViewById(R.id.provider_list); list.setAdapter(adapter); Button b = (Button) findViewById(R.id.btnSearch); b.setOnClickListener( new OnClickListener() { @Override public void onClick(View arg0) { EditText txtProviderName = (EditText) findViewById(R.id.provider_name); EditText txtProviderLocation = (EditText) findViewById(R.id.provider_location); String name = txtProviderName.getText().toString(); String location = txtProviderLocation.getText().toString(); try { providers.clear(); providers.addAll( new NetUtils().getProviders(name, location)); adapter.notifyDataSetChanged(); } catch(Exception e) { e.printStackTrace(); } } }); } }
1,624
0.739532
0.738916
59
26.525423
25.041901
109
false
false
0
0
0
0
0
0
2.423729
false
false
5
ba708f47cf99bbe74614b94bcccc412345cf6bc0
33,148,557,649,939
b3dba7da7ece7f6ba2ffa4ac128dd56895549bb7
/src/restart/source/Mergesort.java
1fb29f7c94beec97da1a166ea11556bc38636c05
[]
no_license
restart32/DivideANDConquer
https://github.com/restart32/DivideANDConquer
2651fd461a2fd23480e7c357f58e3380b87c0e8f
25da8f37167f17ef7c9586ed0ed3074d893f2b70
refs/heads/master
2020-05-03T16:37:03.630000
2015-09-08T07:33:31
2015-09-08T07:33:31
39,230,507
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package restart.source; import java.util.Arrays; public class Mergesort { public void divide(int[] a) { // Divides a given array recursively if (a.length > 1) { int[] u = Arrays.copyOfRange(a, 0, a.length / 2); // Copy from array a, start to halfway int[] v = Arrays.copyOfRange(a, a.length / 2, a.length); // Copy from array b, halfway to end divide(u); // Recursively divide each array divide(v); mergenoduplicate(a, u, v); // Start ordering them } } public void merge(int[] a, int[] u, int[] v) { // merge will ignore duplicates int i, j, k; i = j = k = 0; while (i < u.length + v.length) { // If a array has space if (j < u.length && k < v.length) { // And both array have elements left if (u[j] < v[k]) { // First array has the smaller element a[i++] = u[j++]; } else { // Second array has the smaller element a[i++] = v[k++]; } } else { // One of the arrays is exhausted if (j >= u.length) { // Array u is exhausted while (k < v.length) { // Copy remaining v elements a[i++] = v[k++]; } } if (k >= v.length) { // Array v is exhausted while (j < u.length) { // Copy remaining u elements a[i++] = u[j++]; } } } } } public void mergenoduplicate(int[] a, int[] u, int[] v) { // mergenoduplicate will not ignores duplicates int i, j, k; // It needs help from cleanup i = j = k = 0; while (j < u.length && k < v.length) { // If both arrays have elements left if (i > 0 && a[i - 1] == u[j]) { // Check for duplicates j++; } else if (i > 0 && a[i - 1] == v[k]) { k++; } else if (u[j] < v[k]) { // See which is smaller a[i++] = u[j++]; } else if (v[k] < u[j]) { a[i++] = v[k++]; } else if (v[k] == u[j]) { // If they both equal a[i++] = v[k++]; } } if (j < u.length) { // Array v is exhausted while (j < u.length) { // Copy the rest of array u if (a[i - 1] != u[j]) { a[i++] = u[j++]; } else { ++j; } } } else { // Array u is exhausted while (k < v.length) { // Copy the rest of array v if (a[i - 1] != v[k]) { a[i++] = v[k++]; } else { ++k; } } } if (i < u.length + v.length) { // If a has still placeholders, while (i < u.length + v.length) { // must have been for duplicates. a[i++] = 0; // Put 0 in those positions. } } } public int[] cleanup(int[] c) { // Removes 0s from passed in arrays if (c != null && c.length > 0) { int[] temp = new int[c.length]; // Temp array with same size int loop = 1; temp[0] = c[0]; // Copy the first element for (int i = 1; i < c.length; ++i) { // Copy the rest if (c[i] != 0) { // Check for 0s temp[loop++] = c[i]; } } int[] temp2 = new int[loop]; // Temp array with the appropriate size System.arraycopy(temp, 0, temp2, 0, loop); // Copy from first temp to the second one return temp2; } else { return null; } } }
UTF-8
Java
5,068
java
Mergesort.java
Java
[]
null
[]
package restart.source; import java.util.Arrays; public class Mergesort { public void divide(int[] a) { // Divides a given array recursively if (a.length > 1) { int[] u = Arrays.copyOfRange(a, 0, a.length / 2); // Copy from array a, start to halfway int[] v = Arrays.copyOfRange(a, a.length / 2, a.length); // Copy from array b, halfway to end divide(u); // Recursively divide each array divide(v); mergenoduplicate(a, u, v); // Start ordering them } } public void merge(int[] a, int[] u, int[] v) { // merge will ignore duplicates int i, j, k; i = j = k = 0; while (i < u.length + v.length) { // If a array has space if (j < u.length && k < v.length) { // And both array have elements left if (u[j] < v[k]) { // First array has the smaller element a[i++] = u[j++]; } else { // Second array has the smaller element a[i++] = v[k++]; } } else { // One of the arrays is exhausted if (j >= u.length) { // Array u is exhausted while (k < v.length) { // Copy remaining v elements a[i++] = v[k++]; } } if (k >= v.length) { // Array v is exhausted while (j < u.length) { // Copy remaining u elements a[i++] = u[j++]; } } } } } public void mergenoduplicate(int[] a, int[] u, int[] v) { // mergenoduplicate will not ignores duplicates int i, j, k; // It needs help from cleanup i = j = k = 0; while (j < u.length && k < v.length) { // If both arrays have elements left if (i > 0 && a[i - 1] == u[j]) { // Check for duplicates j++; } else if (i > 0 && a[i - 1] == v[k]) { k++; } else if (u[j] < v[k]) { // See which is smaller a[i++] = u[j++]; } else if (v[k] < u[j]) { a[i++] = v[k++]; } else if (v[k] == u[j]) { // If they both equal a[i++] = v[k++]; } } if (j < u.length) { // Array v is exhausted while (j < u.length) { // Copy the rest of array u if (a[i - 1] != u[j]) { a[i++] = u[j++]; } else { ++j; } } } else { // Array u is exhausted while (k < v.length) { // Copy the rest of array v if (a[i - 1] != v[k]) { a[i++] = v[k++]; } else { ++k; } } } if (i < u.length + v.length) { // If a has still placeholders, while (i < u.length + v.length) { // must have been for duplicates. a[i++] = 0; // Put 0 in those positions. } } } public int[] cleanup(int[] c) { // Removes 0s from passed in arrays if (c != null && c.length > 0) { int[] temp = new int[c.length]; // Temp array with same size int loop = 1; temp[0] = c[0]; // Copy the first element for (int i = 1; i < c.length; ++i) { // Copy the rest if (c[i] != 0) { // Check for 0s temp[loop++] = c[i]; } } int[] temp2 = new int[loop]; // Temp array with the appropriate size System.arraycopy(temp, 0, temp2, 0, loop); // Copy from first temp to the second one return temp2; } else { return null; } } }
5,068
0.306433
0.301105
98
50.714287
42.335876
123
false
false
0
0
0
0
0
0
0.571429
false
false
5
173ac774e876c4cbc1600e5d52c8cd1074c21f53
32,890,859,567,550
c0be290a270c5a8eb3210f847b3e1dbebc330ae4
/core/src/tbs/doblon/io/views/Drawable.java
32e07127b7415843247db58be0b9f4434a8d2b96
[]
no_license
GDxU/DoblonsGDX
https://github.com/GDxU/DoblonsGDX
0457d5c3d245d72a5da99b0b70a4763391d6a0c2
ffab722718e76fbc0ac5a3fbeea68f60a5e9f1e4
refs/heads/master
2020-06-25T08:05:55.758000
2016-11-25T17:01:58
2016-11-25T17:01:58
199,253,865
1
0
null
true
2019-07-28T06:59:14
2019-07-28T06:59:14
2016-11-07T06:01:29
2016-11-25T17:02:08
1,154
0
0
0
null
false
false
package tbs.doblon.io.views; import com.badlogic.gdx.graphics.g2d.TextureRegion; import tbs.doblon.io.GameObject; /** * Created by Michael on 1/28/2015. */ public class Drawable extends GameObject implements Viewable { public boolean hasMultipleSides = false; public int x, y, w, h; public String name; public TextureRegion sprite; public Drawable(TextureRegion sprite, String name, int x, int y, int w, int h) { this.name = name; this.sprite = sprite; this.x = x; this.y = y; this.w = w; this.h = h; } @Override public void draw() { } @Override public void update(float delta) { } @Override public void setState(State state) { } @Override public void setTouchDown(boolean touchDown) { } @Override public Object getTag() { return null; } @Override public int getID() { return 0; } @Override public void draw(float relX, float relY, float parentRight, float parentTop) { } @Override public void dispose() { } public void setW(int w) { this.w = w; } public void setY(int y) { this.y = y; } public void setX(int x) { this.x = x; } public void setH(int h) { this.h = h; } public void setHasMultipleSides(boolean hasMultipleSides) { this.hasMultipleSides = hasMultipleSides; } @Override public String toString() { return String.format("%d : %d, %d >> %d, %d", sprite, x, y, w, h); } }
UTF-8
Java
1,593
java
Drawable.java
Java
[ { "context": "mport tbs.doblon.io.GameObject;\n\n/**\n * Created by Michael on 1/28/2015.\n */\npublic class Drawable extends G", "end": 142, "score": 0.9680451154708862, "start": 135, "tag": "NAME", "value": "Michael" } ]
null
[]
package tbs.doblon.io.views; import com.badlogic.gdx.graphics.g2d.TextureRegion; import tbs.doblon.io.GameObject; /** * Created by Michael on 1/28/2015. */ public class Drawable extends GameObject implements Viewable { public boolean hasMultipleSides = false; public int x, y, w, h; public String name; public TextureRegion sprite; public Drawable(TextureRegion sprite, String name, int x, int y, int w, int h) { this.name = name; this.sprite = sprite; this.x = x; this.y = y; this.w = w; this.h = h; } @Override public void draw() { } @Override public void update(float delta) { } @Override public void setState(State state) { } @Override public void setTouchDown(boolean touchDown) { } @Override public Object getTag() { return null; } @Override public int getID() { return 0; } @Override public void draw(float relX, float relY, float parentRight, float parentTop) { } @Override public void dispose() { } public void setW(int w) { this.w = w; } public void setY(int y) { this.y = y; } public void setX(int x) { this.x = x; } public void setH(int h) { this.h = h; } public void setHasMultipleSides(boolean hasMultipleSides) { this.hasMultipleSides = hasMultipleSides; } @Override public String toString() { return String.format("%d : %d, %d >> %d, %d", sprite, x, y, w, h); } }
1,593
0.574388
0.568738
92
16.315218
19.212162
84
false
false
0
0
0
0
0
0
0.423913
false
false
5
b5d8d3af2ca04ff4939e68870e98c08ec499cd02
32,890,859,570,505
01d6a90c90a380003da9f705e208b277de90a40b
/simon-test/src/main/java/org/simon/aop/proxyfactory/EnglishService.java
ba8240e3c91734dbe34144ff5ea645a35d5cfe85
[ "Apache-2.0" ]
permissive
30743905/spring-framework
https://github.com/30743905/spring-framework
0a5ddbdd701e69c4222a773f0e9864c0984528c7
b7a032011b4964577786f2e8069a036045925773
refs/heads/master
2022-12-11T21:18:19.130000
2020-03-08T10:02:04
2020-03-08T10:02:04
169,692,399
0
0
null
true
2019-02-08T06:05:47
2019-02-08T06:05:46
2019-02-08T04:42:34
2019-02-07T23:26:33
119,907
0
0
0
null
false
null
package org.simon.aop.proxyfactory; /** * @author Administrator * @Copyright © 2019 tiger Inc. All rights reserved. * @create 2019-02-12 下午 22:34 * @Description:TODO */ public class EnglishService implements PeopleService { @Override public void sayHello() { System.err.println("Hi~"); } @Override public void printName(String name) { System.err.println("Your name:" + name); } }
UTF-8
Java
402
java
EnglishService.java
Java
[ { "context": "ackage org.simon.aop.proxyfactory;\n\n/**\n * @author Administrator\n * @Copyright © 2019 tiger Inc. All rights reserv", "end": 65, "score": 0.9933531284332275, "start": 52, "tag": "NAME", "value": "Administrator" } ]
null
[]
package org.simon.aop.proxyfactory; /** * @author Administrator * @Copyright © 2019 tiger Inc. All rights reserved. * @create 2019-02-12 下午 22:34 * @Description:TODO */ public class EnglishService implements PeopleService { @Override public void sayHello() { System.err.println("Hi~"); } @Override public void printName(String name) { System.err.println("Your name:" + name); } }
402
0.702771
0.662468
19
19.894737
17.725672
54
false
false
0
0
0
0
0
0
0.684211
false
false
5
78225ff1e826c5875463eb43a8b1310ae21e9f28
28,741,921,196,572
bcdf0a87f7e218d847b9bb46d3f9b840d1b3efc4
/AOSMapmaker/src/main/drawables/Tessellation.java
c07d6c294d8450b9cc0a21d7fa7cb937597a6aba
[]
no_license
BradHipsher/AOSMapMaker
https://github.com/BradHipsher/AOSMapMaker
dc0d07679da5ee0d8f6e4aa6092e26d2501ed08e
b91a29a857b82ade42ca8f0bb203bc7e1755001c
refs/heads/master
2022-01-28T00:39:12.520000
2019-07-20T14:08:43
2019-07-20T14:08:43
196,770,130
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.drawables; import java.awt.Graphics2D; import java.util.ArrayList; import main.editRes.EditorResources; import static main.drawables.MapArea.*; public class Tessellation { private MapArea mapArea; private ArrayList<Hex> hexes; private int selectedHexID; public Tessellation(MapArea mapArea) { setMapArea(mapArea); setHexes(new ArrayList<Hex>()); setSelectedHexID(-1); tesselate(-1); } public void tesselate(int pageNum) { // if pageNum = -1, then it's being drawn for the program // if pageNum > -1, then it's drawing a page for the print. // ASSUMES THAT YOU HAVE AT LEAST 2 ROWS!!! // ASSUMES that Row 1 and Row 2 are only 1 // Tranposition means that L->R becomes T->B and vice versa // All that's happening is that x and y pixel drawings become y, x // Variable names will remain the same, obviously. // Text on hexes should maintain orientation? // TODO // Mountain drawings may need to back out transpostion on Hex file // TODO ArrayList<String> hexTypes = new ArrayList<String>(); if (hexes.size() > 0) { // Saves the types hexTypes = new ArrayList<String>(); for(Hex hex : hexes) { hexTypes.add(hex.getTileType()); } } wipeHexes(); int localMode = mapArea.getPanel().getPanel().getFrame().getEditor().getMode(); int tempHexesWidth1 = EditorResources.W1W2H[localMode][0]; // w2 -- USE dimensions.xslx (swapped row 1 and row 2) int tempHexesWidth2 = EditorResources.W1W2H[localMode][1]; // w1 -- USE dimensions.xslx (swapped row 1 and row 2) int tempHexesHeight = EditorResources.W1W2H[localMode][2]; // h -- USE dimensions.xslx int maxHexesWidth = Math.max(tempHexesWidth1, tempHexesWidth2); int minHexesWidth = Math.min(tempHexesWidth1, tempHexesWidth2); int totalHexesWidth = tempHexesWidth1 * Hex.HEX_D_I + (minHexesWidth - maxHexesWidth + 1) * Hex.HEX_R_I; int totalHexesHeight = Hex.HEX_A*2 + (tempHexesHeight - 1) * Hex.HEX_H_I; int centerAlignOffsetX = (mapArea.getPaperWidth() - totalHexesWidth) / 2; int centerAlignOffsetY = (mapArea.getPaperHeight() - totalHexesHeight) / 2; double x = tempHexesWidth1 - tempHexesWidth2; int row2Sign = (int) (-Math.pow(x, 2) + x + 1); // Input {-1, 0, 1} --> {-1, 1, 1} || -(x^2) + x + 1 int mapAreaOffsetX = 0; int mapAreaOffsetY = 0; if(pageNum == -1) { mapAreaOffsetX = mapArea.getBoundaryX(); mapAreaOffsetY = mapArea.getBoundaryY(); } int pageNumberOffsetX = 0; int pageNumberOffsetY = 0; if (pageNum > -1) { pageNumberOffsetX = (pageNum % EditorResources.PAGE_SCALES_W_H[localMode][0]) * PAPER_WIDTH * (-1); pageNumberOffsetY = ((pageNum / EditorResources.PAGE_SCALES_W_H[localMode][0]) % EditorResources.PAGE_SCALES_W_H[localMode][1]) * PAPER_HEIGHT * (-1); } int loopID = 0; if(mapArea.getPanel().getPanel().getFrame().getEditor().isTransposed()) { for(int i = 0; i < tempHexesHeight; i ++) { int tempHexesWidth = tempHexesWidth1; if (i % 2 == 1) tempHexesWidth = tempHexesWidth2; for(int j = 0; j < tempHexesWidth; j ++) { if (hexes.size() == loopID) hexTypes.add(EMPTY); Hex hex = new Hex( this, pageNumberOffsetY + centerAlignOffsetY + mapAreaOffsetY + Hex.HEX_A + i*Hex.HEX_H_I, pageNumberOffsetX + centerAlignOffsetX + mapAreaOffsetX + Hex.HEX_D_I/2 + j*Hex.HEX_D_I + Hex.HEX_R_I*(i % 2)*row2Sign, hexTypes.get(loopID), 1); hexes.add(hex); loopID ++; } } } else { for(int i = 0; i < tempHexesHeight; i ++) { int tempHexesWidth = tempHexesWidth1; if (i % 2 == 1) tempHexesWidth = tempHexesWidth2; for(int j = 0; j < tempHexesWidth; j ++) { if (hexes.size() == loopID) hexTypes.add(EMPTY); Hex hex = new Hex( this, pageNumberOffsetX + centerAlignOffsetX + mapAreaOffsetX + Hex.HEX_D_I/2 + j*Hex.HEX_D_I + Hex.HEX_R_I*(i % 2)*row2Sign, pageNumberOffsetY + centerAlignOffsetY + mapAreaOffsetY + Hex.HEX_A + i*Hex.HEX_H_I, hexTypes.get(loopID), 0); hexes.add(hex); loopID ++; } } } } public void drawGrid(Graphics2D g2d) { for(Hex hex : hexes) { hex.drawGrid(g2d); } } public void drawType(Graphics2D g2d) { for(Hex hex : hexes) { hex.drawType(g2d); } } public void drawWaterBorder(Graphics2D g2d) { for(Hex hex : hexes) { if(hex.getTileType().equals(WATER)) hex.drawWaterBorder(g2d); } } public void drawTileBorder(Graphics2D g2d) { for(Hex hex : hexes) { if (hex.getTileType().equals(LAND)) hex.drawTileBorder(g2d); if (hex.getTileType().equals(RIVER)) hex.drawTileBorder(g2d); if (hex.getTileType().equals(MOUNTAIN)) hex.drawTileBorder(g2d); if (hex.getTileType().equals(TOWN)) hex.drawTileBorder(g2d); if (hex.getTileType().equals(CITY)) hex.drawTileBorder(g2d); } } public void drawSelected(Graphics2D g2d, int mouseX, int mouseY) { int hexID = getSelectedHexID(); if (hexID !=-1) hexes.get(hexID).drawSelected(g2d); } public void selectHex(int selectedX, int selectedY) { setSelectedHexID(findSelectedHex(selectedX,selectedY)); } public String getSelectedHexType() { Hex selectedHex; String s = EMPTY; if ((selectedHex = getSelectedHex()) != null) s = selectedHex.getTileType(); return s; } public Hex getSelectedHex() { try { return hexes.get(getSelectedHexID()); } catch (ArrayIndexOutOfBoundsException e) { return null; } } private int findSelectedHex(int selectedX, int selectedY) { int ans = -1; ArrayList<Integer> multiValidID = new ArrayList<Integer>(); ArrayList<Double> distances = new ArrayList<Double>(); for (int i = 0; i < hexes.size(); i ++) { double distance; if ((distance = hexes.get(i).checkBounds(selectedX, selectedY))>-1) { multiValidID.add(i); distances.add(distance); } } if (multiValidID.size() > 0) ans = multiValidID.get(getIDOfMin(distances)); return ans; } public void wipeHexes() { hexes = new ArrayList<Hex>(); } public void deselectHex() { setSelectedHexID(-1); } // Static Methods public static int getIDOfMin(ArrayList<Double> al) { int id = -1; for (int i = 0; i < al.size(); i ++) { if (i==0) id = 0; if (al.get(i) < al.get(id)) id = i; } return id; } // Getters & Setters public MapArea getMapArea() { return mapArea; } public void setMapArea(MapArea mapArea) { this.mapArea = mapArea; } public ArrayList<Hex> getHexes() { return hexes; } public void setHexes(ArrayList<Hex> hexes) { this.hexes = hexes; } public int getSelectedHexID() { return selectedHexID; } public void setSelectedHexID(int i) { this.selectedHexID = i; } }
UTF-8
Java
6,904
java
Tessellation.java
Java
[]
null
[]
package main.drawables; import java.awt.Graphics2D; import java.util.ArrayList; import main.editRes.EditorResources; import static main.drawables.MapArea.*; public class Tessellation { private MapArea mapArea; private ArrayList<Hex> hexes; private int selectedHexID; public Tessellation(MapArea mapArea) { setMapArea(mapArea); setHexes(new ArrayList<Hex>()); setSelectedHexID(-1); tesselate(-1); } public void tesselate(int pageNum) { // if pageNum = -1, then it's being drawn for the program // if pageNum > -1, then it's drawing a page for the print. // ASSUMES THAT YOU HAVE AT LEAST 2 ROWS!!! // ASSUMES that Row 1 and Row 2 are only 1 // Tranposition means that L->R becomes T->B and vice versa // All that's happening is that x and y pixel drawings become y, x // Variable names will remain the same, obviously. // Text on hexes should maintain orientation? // TODO // Mountain drawings may need to back out transpostion on Hex file // TODO ArrayList<String> hexTypes = new ArrayList<String>(); if (hexes.size() > 0) { // Saves the types hexTypes = new ArrayList<String>(); for(Hex hex : hexes) { hexTypes.add(hex.getTileType()); } } wipeHexes(); int localMode = mapArea.getPanel().getPanel().getFrame().getEditor().getMode(); int tempHexesWidth1 = EditorResources.W1W2H[localMode][0]; // w2 -- USE dimensions.xslx (swapped row 1 and row 2) int tempHexesWidth2 = EditorResources.W1W2H[localMode][1]; // w1 -- USE dimensions.xslx (swapped row 1 and row 2) int tempHexesHeight = EditorResources.W1W2H[localMode][2]; // h -- USE dimensions.xslx int maxHexesWidth = Math.max(tempHexesWidth1, tempHexesWidth2); int minHexesWidth = Math.min(tempHexesWidth1, tempHexesWidth2); int totalHexesWidth = tempHexesWidth1 * Hex.HEX_D_I + (minHexesWidth - maxHexesWidth + 1) * Hex.HEX_R_I; int totalHexesHeight = Hex.HEX_A*2 + (tempHexesHeight - 1) * Hex.HEX_H_I; int centerAlignOffsetX = (mapArea.getPaperWidth() - totalHexesWidth) / 2; int centerAlignOffsetY = (mapArea.getPaperHeight() - totalHexesHeight) / 2; double x = tempHexesWidth1 - tempHexesWidth2; int row2Sign = (int) (-Math.pow(x, 2) + x + 1); // Input {-1, 0, 1} --> {-1, 1, 1} || -(x^2) + x + 1 int mapAreaOffsetX = 0; int mapAreaOffsetY = 0; if(pageNum == -1) { mapAreaOffsetX = mapArea.getBoundaryX(); mapAreaOffsetY = mapArea.getBoundaryY(); } int pageNumberOffsetX = 0; int pageNumberOffsetY = 0; if (pageNum > -1) { pageNumberOffsetX = (pageNum % EditorResources.PAGE_SCALES_W_H[localMode][0]) * PAPER_WIDTH * (-1); pageNumberOffsetY = ((pageNum / EditorResources.PAGE_SCALES_W_H[localMode][0]) % EditorResources.PAGE_SCALES_W_H[localMode][1]) * PAPER_HEIGHT * (-1); } int loopID = 0; if(mapArea.getPanel().getPanel().getFrame().getEditor().isTransposed()) { for(int i = 0; i < tempHexesHeight; i ++) { int tempHexesWidth = tempHexesWidth1; if (i % 2 == 1) tempHexesWidth = tempHexesWidth2; for(int j = 0; j < tempHexesWidth; j ++) { if (hexes.size() == loopID) hexTypes.add(EMPTY); Hex hex = new Hex( this, pageNumberOffsetY + centerAlignOffsetY + mapAreaOffsetY + Hex.HEX_A + i*Hex.HEX_H_I, pageNumberOffsetX + centerAlignOffsetX + mapAreaOffsetX + Hex.HEX_D_I/2 + j*Hex.HEX_D_I + Hex.HEX_R_I*(i % 2)*row2Sign, hexTypes.get(loopID), 1); hexes.add(hex); loopID ++; } } } else { for(int i = 0; i < tempHexesHeight; i ++) { int tempHexesWidth = tempHexesWidth1; if (i % 2 == 1) tempHexesWidth = tempHexesWidth2; for(int j = 0; j < tempHexesWidth; j ++) { if (hexes.size() == loopID) hexTypes.add(EMPTY); Hex hex = new Hex( this, pageNumberOffsetX + centerAlignOffsetX + mapAreaOffsetX + Hex.HEX_D_I/2 + j*Hex.HEX_D_I + Hex.HEX_R_I*(i % 2)*row2Sign, pageNumberOffsetY + centerAlignOffsetY + mapAreaOffsetY + Hex.HEX_A + i*Hex.HEX_H_I, hexTypes.get(loopID), 0); hexes.add(hex); loopID ++; } } } } public void drawGrid(Graphics2D g2d) { for(Hex hex : hexes) { hex.drawGrid(g2d); } } public void drawType(Graphics2D g2d) { for(Hex hex : hexes) { hex.drawType(g2d); } } public void drawWaterBorder(Graphics2D g2d) { for(Hex hex : hexes) { if(hex.getTileType().equals(WATER)) hex.drawWaterBorder(g2d); } } public void drawTileBorder(Graphics2D g2d) { for(Hex hex : hexes) { if (hex.getTileType().equals(LAND)) hex.drawTileBorder(g2d); if (hex.getTileType().equals(RIVER)) hex.drawTileBorder(g2d); if (hex.getTileType().equals(MOUNTAIN)) hex.drawTileBorder(g2d); if (hex.getTileType().equals(TOWN)) hex.drawTileBorder(g2d); if (hex.getTileType().equals(CITY)) hex.drawTileBorder(g2d); } } public void drawSelected(Graphics2D g2d, int mouseX, int mouseY) { int hexID = getSelectedHexID(); if (hexID !=-1) hexes.get(hexID).drawSelected(g2d); } public void selectHex(int selectedX, int selectedY) { setSelectedHexID(findSelectedHex(selectedX,selectedY)); } public String getSelectedHexType() { Hex selectedHex; String s = EMPTY; if ((selectedHex = getSelectedHex()) != null) s = selectedHex.getTileType(); return s; } public Hex getSelectedHex() { try { return hexes.get(getSelectedHexID()); } catch (ArrayIndexOutOfBoundsException e) { return null; } } private int findSelectedHex(int selectedX, int selectedY) { int ans = -1; ArrayList<Integer> multiValidID = new ArrayList<Integer>(); ArrayList<Double> distances = new ArrayList<Double>(); for (int i = 0; i < hexes.size(); i ++) { double distance; if ((distance = hexes.get(i).checkBounds(selectedX, selectedY))>-1) { multiValidID.add(i); distances.add(distance); } } if (multiValidID.size() > 0) ans = multiValidID.get(getIDOfMin(distances)); return ans; } public void wipeHexes() { hexes = new ArrayList<Hex>(); } public void deselectHex() { setSelectedHexID(-1); } // Static Methods public static int getIDOfMin(ArrayList<Double> al) { int id = -1; for (int i = 0; i < al.size(); i ++) { if (i==0) id = 0; if (al.get(i) < al.get(id)) id = i; } return id; } // Getters & Setters public MapArea getMapArea() { return mapArea; } public void setMapArea(MapArea mapArea) { this.mapArea = mapArea; } public ArrayList<Hex> getHexes() { return hexes; } public void setHexes(ArrayList<Hex> hexes) { this.hexes = hexes; } public int getSelectedHexID() { return selectedHexID; } public void setSelectedHexID(int i) { this.selectedHexID = i; } }
6,904
0.63934
0.623262
243
26.411522
29.253458
154
false
false
0
0
0
0
0
0
2.366255
false
false
5
6606e8e4230a3a49e55b94def40ac39ee8c1381a
5,025,111,790,944
6af0631fcdbc6403eee2dbefaa905a827c0117f6
/src/main/java/com/jstarcraft/rns/recommend/AbstractRecommender.java
f795c241c8e4aa1794c6ce4426d3743929237d50
[ "Apache-2.0" ]
permissive
dewey00/jstarcraft-rns
https://github.com/dewey00/jstarcraft-rns
cdff9afb9d96cc7425050905b4f94526307d3c31
825f60c4bd46a2ed5c342f05ac874aaff57a7a63
refs/heads/master
2020-06-26T23:06:56.249000
2019-07-30T13:21:39
2019-07-30T13:21:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jstarcraft.rns.recommend; import java.util.LinkedHashMap; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jstarcraft.ai.data.DataInstance; import com.jstarcraft.ai.data.DataModule; import com.jstarcraft.ai.data.DataSpace; import com.jstarcraft.ai.environment.EnvironmentContext; import com.jstarcraft.ai.math.structure.matrix.HashMatrix; import com.jstarcraft.ai.math.structure.matrix.MatrixScalar; import com.jstarcraft.ai.math.structure.matrix.SparseMatrix; import com.jstarcraft.core.resource.annotation.ResourceConfiguration; import com.jstarcraft.core.resource.annotation.ResourceId; import com.jstarcraft.core.utility.KeyValue; import com.jstarcraft.rns.configure.Configurator; import com.jstarcraft.rns.data.processor.DataMatcher; import com.jstarcraft.rns.data.processor.DataSorter; import it.unimi.dsi.fastutil.ints.Int2FloatRBTreeMap; /** * 抽象推荐器 * * @author Birdy * */ @ResourceConfiguration public abstract class AbstractRecommender implements Recommender { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @ResourceId protected String id; // 参数部分 /** 用户字段, 物品字段, 分数字段 */ protected String userField, itemField; /** 用户维度, 物品维度 */ protected int userDimension, itemDimension; /** 用户数量, 物品数量 */ protected int userSize, itemSize; /** 最低分数, 最高分数, 平均分数 */ protected float minimumOfScore, maximumOfScore, meanOfScore; /** 分数索引 (TODO 考虑取消或迁移.本质为连续特征离散化) */ protected LinkedHashMap<Float, Integer> scoreIndexes; /** 行为数量(TODO 此字段可能迁移到其它类.为避免重复行为,一般使用matrix或者tensor的元素数量) */ protected int numberOfActions; /** 训练矩阵(TODO 准备改名为actionMatrix或者scoreMatrix) */ protected SparseMatrix scoreMatrix; /** 测试矩阵(TODO 准备取消) */ @Deprecated protected SparseMatrix testMatrix; protected int[] dataPaginations; protected int[] dataPositions; @Override public void prepare(Configurator configuration, DataModule model, DataSpace space) { userField = configuration.getString("data.model.fields.user", "user"); itemField = configuration.getString("data.model.fields.item", "item"); userDimension = model.getQualityInner(userField); itemDimension = model.getQualityInner(itemField); userSize = space.getQualityAttribute(userField).getSize(); itemSize = space.getQualityAttribute(itemField).getSize(); dataPaginations = new int[userSize + 1]; dataPositions = new int[model.getSize()]; for (int index = 0; index < model.getSize(); index++) { dataPositions[index] = index; } DataMatcher matcher = DataMatcher.discreteOf(model, userDimension); matcher.match(dataPaginations, dataPositions); DataSorter sorter = DataSorter.featureOf(model); sorter.sort(dataPaginations, dataPositions); HashMatrix dataTable = new HashMatrix(true, userSize, itemSize, new Int2FloatRBTreeMap()); DataInstance instance = model.getInstance(0); for (int position : dataPositions) { instance.setCursor(position); int rowIndex = instance.getQualityFeature(userDimension); int columnIndex = instance.getQualityFeature(itemDimension); dataTable.setValue(rowIndex, columnIndex, instance.getQuantityMark()); } scoreMatrix = SparseMatrix.valueOf(userSize, itemSize, dataTable); numberOfActions = scoreMatrix.getElementSize(); // TODO 此处会与scoreIndexes一起重构,本质为连续特征离散化. TreeSet<Float> values = new TreeSet<>(); for (MatrixScalar term : scoreMatrix) { values.add(term.getValue()); } values.remove(0F); scoreIndexes = new LinkedHashMap<>(); Integer index = 0; for (Float value : values) { scoreIndexes.put(value, index++); } KeyValue<Float, Float> attribute = scoreMatrix.getBoundary(false); minimumOfScore = attribute.getKey(); maximumOfScore = attribute.getValue(); meanOfScore = scoreMatrix.getSum(false); meanOfScore /= numberOfActions; } protected abstract void doPractice(); protected void constructEnvironment() { } protected void destructEnvironment() { } @Override public final void practice() { EnvironmentContext context = EnvironmentContext.getContext(); context.doAlgorithmByEvery(this::constructEnvironment); doPractice(); context.doAlgorithmByEvery(this::destructEnvironment); } }
UTF-8
Java
4,987
java
AbstractRecommender.java
Java
[ { "context": "2FloatRBTreeMap;\r\n\r\n/**\r\n * 抽象推荐器\r\n * \r\n * @author Birdy\r\n *\r\n */\r\n@ResourceConfiguration\r\npublic abstract", "end": 968, "score": 0.9705018401145935, "start": 963, "tag": "USERNAME", "value": "Birdy" } ]
null
[]
package com.jstarcraft.rns.recommend; import java.util.LinkedHashMap; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jstarcraft.ai.data.DataInstance; import com.jstarcraft.ai.data.DataModule; import com.jstarcraft.ai.data.DataSpace; import com.jstarcraft.ai.environment.EnvironmentContext; import com.jstarcraft.ai.math.structure.matrix.HashMatrix; import com.jstarcraft.ai.math.structure.matrix.MatrixScalar; import com.jstarcraft.ai.math.structure.matrix.SparseMatrix; import com.jstarcraft.core.resource.annotation.ResourceConfiguration; import com.jstarcraft.core.resource.annotation.ResourceId; import com.jstarcraft.core.utility.KeyValue; import com.jstarcraft.rns.configure.Configurator; import com.jstarcraft.rns.data.processor.DataMatcher; import com.jstarcraft.rns.data.processor.DataSorter; import it.unimi.dsi.fastutil.ints.Int2FloatRBTreeMap; /** * 抽象推荐器 * * @author Birdy * */ @ResourceConfiguration public abstract class AbstractRecommender implements Recommender { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @ResourceId protected String id; // 参数部分 /** 用户字段, 物品字段, 分数字段 */ protected String userField, itemField; /** 用户维度, 物品维度 */ protected int userDimension, itemDimension; /** 用户数量, 物品数量 */ protected int userSize, itemSize; /** 最低分数, 最高分数, 平均分数 */ protected float minimumOfScore, maximumOfScore, meanOfScore; /** 分数索引 (TODO 考虑取消或迁移.本质为连续特征离散化) */ protected LinkedHashMap<Float, Integer> scoreIndexes; /** 行为数量(TODO 此字段可能迁移到其它类.为避免重复行为,一般使用matrix或者tensor的元素数量) */ protected int numberOfActions; /** 训练矩阵(TODO 准备改名为actionMatrix或者scoreMatrix) */ protected SparseMatrix scoreMatrix; /** 测试矩阵(TODO 准备取消) */ @Deprecated protected SparseMatrix testMatrix; protected int[] dataPaginations; protected int[] dataPositions; @Override public void prepare(Configurator configuration, DataModule model, DataSpace space) { userField = configuration.getString("data.model.fields.user", "user"); itemField = configuration.getString("data.model.fields.item", "item"); userDimension = model.getQualityInner(userField); itemDimension = model.getQualityInner(itemField); userSize = space.getQualityAttribute(userField).getSize(); itemSize = space.getQualityAttribute(itemField).getSize(); dataPaginations = new int[userSize + 1]; dataPositions = new int[model.getSize()]; for (int index = 0; index < model.getSize(); index++) { dataPositions[index] = index; } DataMatcher matcher = DataMatcher.discreteOf(model, userDimension); matcher.match(dataPaginations, dataPositions); DataSorter sorter = DataSorter.featureOf(model); sorter.sort(dataPaginations, dataPositions); HashMatrix dataTable = new HashMatrix(true, userSize, itemSize, new Int2FloatRBTreeMap()); DataInstance instance = model.getInstance(0); for (int position : dataPositions) { instance.setCursor(position); int rowIndex = instance.getQualityFeature(userDimension); int columnIndex = instance.getQualityFeature(itemDimension); dataTable.setValue(rowIndex, columnIndex, instance.getQuantityMark()); } scoreMatrix = SparseMatrix.valueOf(userSize, itemSize, dataTable); numberOfActions = scoreMatrix.getElementSize(); // TODO 此处会与scoreIndexes一起重构,本质为连续特征离散化. TreeSet<Float> values = new TreeSet<>(); for (MatrixScalar term : scoreMatrix) { values.add(term.getValue()); } values.remove(0F); scoreIndexes = new LinkedHashMap<>(); Integer index = 0; for (Float value : values) { scoreIndexes.put(value, index++); } KeyValue<Float, Float> attribute = scoreMatrix.getBoundary(false); minimumOfScore = attribute.getKey(); maximumOfScore = attribute.getValue(); meanOfScore = scoreMatrix.getSum(false); meanOfScore /= numberOfActions; } protected abstract void doPractice(); protected void constructEnvironment() { } protected void destructEnvironment() { } @Override public final void practice() { EnvironmentContext context = EnvironmentContext.getContext(); context.doAlgorithmByEvery(this::constructEnvironment); doPractice(); context.doAlgorithmByEvery(this::destructEnvironment); } }
4,987
0.683663
0.681751
132
33.659092
25.741379
98
false
false
0
0
0
0
0
0
0.757576
false
false
5
e224e212cbe750c3c034fbb8c599b1b8df9cb5dd
23,476,291,309,884
4cb0b547d1d09cf549d06eb542ec3f272c0b6858
/src/main/java/com/qintess/veterinaria/repositorios/CadastraAnimalRepository.java
d4cae63576ec50e3e6fe5d165ad2ebadee346028
[]
no_license
Everton-Santos/VAN
https://github.com/Everton-Santos/VAN
d44fe87ad6a96557b329d6c86a4d0b1d7f8cf80a
50351c84f103bfef316a457a19f168611a9063db
refs/heads/master
2023-03-28T12:26:26.573000
2021-03-28T19:33:44
2021-03-28T19:33:44
342,103,154
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qintess.veterinaria.repositorios; import org.springframework.data.repository.CrudRepository; import com.qintess.veterinaria.cadastro.CadastraAnimal; public interface CadastraAnimalRepository extends CrudRepository<CadastraAnimal, Integer>{ }
UTF-8
Java
258
java
CadastraAnimalRepository.java
Java
[]
null
[]
package com.qintess.veterinaria.repositorios; import org.springframework.data.repository.CrudRepository; import com.qintess.veterinaria.cadastro.CadastraAnimal; public interface CadastraAnimalRepository extends CrudRepository<CadastraAnimal, Integer>{ }
258
0.860465
0.860465
9
27.666666
32.70406
90
false
false
0
0
0
0
0
0
0.444444
false
false
5
72bae23740dfec680b3ea2225acf3f387c93d865
11,836,929,911,967
d68f9dfff6472d95b9b940cfbd7ec8e0904640a8
/Polygon/src/Main.java
26b02161cab4914ff9eda33573bcb932a10dd65b
[]
no_license
hashnet/Codeforces
https://github.com/hashnet/Codeforces
e31f36943d05335b1f54b63a9ffb328749a26e8a
c2df58b7b595fe126e25b4790bb17652a89cb839
refs/heads/master
2022-09-20T07:39:00.608000
2020-06-02T07:57:04
2020-06-02T07:57:04
119,391,603
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new File("src/input.txt")); int N = sc.nextInt(); while(N-- > 0) { int size = sc.nextInt(); //sc.nextLine(); int[][] matrix = new int[size][size]; for(int i=0; i<size; i++) { String line = sc.next(); for(int j=0; j<size; j++) { matrix[i][j] = line.charAt(j) - '0'; } } System.out.println(checkValid(matrix, size) ? "YES" : "NO"); } sc.close(); } private static boolean checkValid(int[][] matrix, int size) { for(int i=size-2; i>=0; i--) { for(int j=size-2; j>=0; j--) { if(matrix[i][j] == 1) { if(matrix[i+1][j] == 0 && matrix[i][j+1] == 0) return false; } } } return true; } }
UTF-8
Java
919
java
Main.java
Java
[]
null
[]
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new File("src/input.txt")); int N = sc.nextInt(); while(N-- > 0) { int size = sc.nextInt(); //sc.nextLine(); int[][] matrix = new int[size][size]; for(int i=0; i<size; i++) { String line = sc.next(); for(int j=0; j<size; j++) { matrix[i][j] = line.charAt(j) - '0'; } } System.out.println(checkValid(matrix, size) ? "YES" : "NO"); } sc.close(); } private static boolean checkValid(int[][] matrix, int size) { for(int i=size-2; i>=0; i--) { for(int j=size-2; j>=0; j--) { if(matrix[i][j] == 1) { if(matrix[i+1][j] == 0 && matrix[i][j+1] == 0) return false; } } } return true; } }
919
0.562568
0.548422
38
23.18421
20.430698
70
false
false
0
0
0
0
0
0
3.184211
false
false
5
7afb4d77ccda13c32906a1cc97c40316ff14c3fc
19,267,223,346,818
59275784cffa297723cff755f1664a63974c43da
/app/src/main/java/kr/co/switchnow/switch_now_client/Adapter/ChatContentsAdapter.java
67807014e6a6d37ff92f30b0c72a22f05042a6af
[]
no_license
whdlscjf97/switch_now_client
https://github.com/whdlscjf97/switch_now_client
8d897528e87a0cf14c0563b3b5c59760f8ec88e5
392af7b83961aa0e1232492acd0231ec181015db
refs/heads/master
2021-09-09T16:55:13.402000
2018-03-18T11:22:48
2018-03-18T11:22:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kr.co.switchnow.switch_now_client.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import kr.co.switchnow.switch_now_client.ADT.ChatMessage; import kr.co.switchnow.switch_now_client.Activity.PrivateChatActivity; import kr.co.switchnow.switch_now_client.R; import static kr.co.switchnow.switch_now_client.Activity.InteractionActivity.chatMessageDBManager; import static kr.co.switchnow.switch_now_client.Activity.PrivateChatActivity.mChatContentsAdapater; /** * Created by ceo on 2017-06-19. */ public class ChatContentsAdapter extends BaseAdapter { private static final int MESSAGE_FROM_USER = 0; private static final int MESSAGE_FROM_OPPONENT = 1; private static final int TIME_STAMP = 2; static protected Context mContext = null; protected LayoutInflater mInflater; public static ArrayList<ChatMessage> messageListData = new ArrayList<>(); URL imageURL; public ChatContentsAdapter(Context context, ArrayList<ChatMessage> objects) { super(); this.mContext = context; this.messageListData = objects; mInflater = LayoutInflater.from(context); } @Override public int getCount() { return messageListData.size(); } @Override public Object getItem(int position) { return messageListData.get(position); } @Override public long getItemId(int position) { return position; } public static void dataChange() { mChatContentsAdapater.notifyDataSetChanged(); } public int getItemViewType(int position) { return messageListData.get(position).msgType; } public int getViewTypeCount() { return 3; } public void addMessage(String roomId, String sender_id, String sender_name, String msg, int readStatus, String sendTime, int msgType) { ChatMessage addInfo; addInfo = new ChatMessage(); addInfo.roomId = roomId; addInfo.sender_Id = sender_id; addInfo.sender_name = sender_name; addInfo.TextCotents = msg; addInfo.read_status = readStatus; addInfo.send_time = sendTime; addInfo.msgType = msgType; if (addInfo.msgType == MESSAGE_FROM_OPPONENT) { try { imageURL = new URL("http://115.71.232.209/client/profile/" + addInfo.sender_Id + ".png"); addInfo.opponent_img_url = String.valueOf(imageURL); } catch (MalformedURLException e) { e.printStackTrace(); } } messageListData.add(addInfo); chatMessageDBManager.addMessageData(addInfo); dataChange(); } public void remove(int position) { messageListData.remove(position); dataChange(); } @Override public View getView(int position, View convertView, ViewGroup parent) { PrivateChatActivity.userMessageViewHolder myMsgHolder = null; PrivateChatActivity.opponentMessageViewHolder opponentMsgHolder = null; PrivateChatActivity.timeStampViewHolder timeMsgHolder = null; int msgType = getItemViewType(position); final ChatMessage chatMessage_data = messageListData.get(position); switch (msgType) { case MESSAGE_FROM_USER: { if (convertView == null) { mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.message_item_from_user, null); myMsgHolder = new PrivateChatActivity.userMessageViewHolder(); myMsgHolder.userMessage = (TextView) convertView.findViewById(R.id.msg_contents_user); myMsgHolder.userTimestamp = (TextView) convertView.findViewById(R.id.user_msg_timestamp); convertView.setTag(myMsgHolder); } else { myMsgHolder = (PrivateChatActivity.userMessageViewHolder) convertView.getTag(); } myMsgHolder.userMessage.setText(chatMessage_data.TextCotents); myMsgHolder.userTimestamp.setText(chatMessage_data.send_time); break; } case MESSAGE_FROM_OPPONENT: { if (convertView == null) { mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.message_item_from_opponent, null); opponentMsgHolder = new PrivateChatActivity.opponentMessageViewHolder(); opponentMsgHolder.profile_img_opponent = (ImageView) convertView.findViewById(R.id.profile_image_chat_opponent); opponentMsgHolder.opponent_name = (TextView) convertView.findViewById(R.id.name_txt_chat_opponent); opponentMsgHolder.opponent_message = (TextView) convertView.findViewById(R.id.msg_contents_opponent); opponentMsgHolder.opponent_timestamp = (TextView) convertView.findViewById(R.id.opponent_msg_timestamp); convertView.setTag(opponentMsgHolder); } else { opponentMsgHolder = (PrivateChatActivity.opponentMessageViewHolder) convertView.getTag(); } opponentMsgHolder.opponent_name.setText(chatMessage_data.sender_name); opponentMsgHolder.opponent_message.setText(chatMessage_data.TextCotents); opponentMsgHolder.opponent_timestamp.setText(chatMessage_data.send_time); Glide.with(mContext.getApplicationContext()).load(chatMessage_data.opponent_img_url).diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true).into(opponentMsgHolder.profile_img_opponent); break; } case TIME_STAMP: { if (convertView == null) { mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.message_timestamp_for_chat_window, null); timeMsgHolder = new PrivateChatActivity.timeStampViewHolder(); timeMsgHolder.timestamp_line = (View) convertView.findViewById(R.id.msg_contents_timeline); timeMsgHolder.timestamp_txt = (TextView) convertView.findViewById(R.id.msg_contents_timestamp); convertView.setTag(timeMsgHolder); } else { timeMsgHolder = (PrivateChatActivity.timeStampViewHolder) convertView.getTag(); } timeMsgHolder.timestamp_txt.setText(chatMessage_data.send_time); break; } } return convertView; } }
UTF-8
Java
7,174
java
ChatContentsAdapter.java
Java
[ { "context": " try {\n imageURL = new URL(\"http://115.71.232.209/client/profile/\" + addInfo.sender_Id + \".png\");\n ", "end": 2661, "score": 0.9432500600814819, "start": 2647, "tag": "IP_ADDRESS", "value": "115.71.232.209" } ]
null
[]
package kr.co.switchnow.switch_now_client.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import kr.co.switchnow.switch_now_client.ADT.ChatMessage; import kr.co.switchnow.switch_now_client.Activity.PrivateChatActivity; import kr.co.switchnow.switch_now_client.R; import static kr.co.switchnow.switch_now_client.Activity.InteractionActivity.chatMessageDBManager; import static kr.co.switchnow.switch_now_client.Activity.PrivateChatActivity.mChatContentsAdapater; /** * Created by ceo on 2017-06-19. */ public class ChatContentsAdapter extends BaseAdapter { private static final int MESSAGE_FROM_USER = 0; private static final int MESSAGE_FROM_OPPONENT = 1; private static final int TIME_STAMP = 2; static protected Context mContext = null; protected LayoutInflater mInflater; public static ArrayList<ChatMessage> messageListData = new ArrayList<>(); URL imageURL; public ChatContentsAdapter(Context context, ArrayList<ChatMessage> objects) { super(); this.mContext = context; this.messageListData = objects; mInflater = LayoutInflater.from(context); } @Override public int getCount() { return messageListData.size(); } @Override public Object getItem(int position) { return messageListData.get(position); } @Override public long getItemId(int position) { return position; } public static void dataChange() { mChatContentsAdapater.notifyDataSetChanged(); } public int getItemViewType(int position) { return messageListData.get(position).msgType; } public int getViewTypeCount() { return 3; } public void addMessage(String roomId, String sender_id, String sender_name, String msg, int readStatus, String sendTime, int msgType) { ChatMessage addInfo; addInfo = new ChatMessage(); addInfo.roomId = roomId; addInfo.sender_Id = sender_id; addInfo.sender_name = sender_name; addInfo.TextCotents = msg; addInfo.read_status = readStatus; addInfo.send_time = sendTime; addInfo.msgType = msgType; if (addInfo.msgType == MESSAGE_FROM_OPPONENT) { try { imageURL = new URL("http://192.168.3.11/client/profile/" + addInfo.sender_Id + ".png"); addInfo.opponent_img_url = String.valueOf(imageURL); } catch (MalformedURLException e) { e.printStackTrace(); } } messageListData.add(addInfo); chatMessageDBManager.addMessageData(addInfo); dataChange(); } public void remove(int position) { messageListData.remove(position); dataChange(); } @Override public View getView(int position, View convertView, ViewGroup parent) { PrivateChatActivity.userMessageViewHolder myMsgHolder = null; PrivateChatActivity.opponentMessageViewHolder opponentMsgHolder = null; PrivateChatActivity.timeStampViewHolder timeMsgHolder = null; int msgType = getItemViewType(position); final ChatMessage chatMessage_data = messageListData.get(position); switch (msgType) { case MESSAGE_FROM_USER: { if (convertView == null) { mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.message_item_from_user, null); myMsgHolder = new PrivateChatActivity.userMessageViewHolder(); myMsgHolder.userMessage = (TextView) convertView.findViewById(R.id.msg_contents_user); myMsgHolder.userTimestamp = (TextView) convertView.findViewById(R.id.user_msg_timestamp); convertView.setTag(myMsgHolder); } else { myMsgHolder = (PrivateChatActivity.userMessageViewHolder) convertView.getTag(); } myMsgHolder.userMessage.setText(chatMessage_data.TextCotents); myMsgHolder.userTimestamp.setText(chatMessage_data.send_time); break; } case MESSAGE_FROM_OPPONENT: { if (convertView == null) { mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.message_item_from_opponent, null); opponentMsgHolder = new PrivateChatActivity.opponentMessageViewHolder(); opponentMsgHolder.profile_img_opponent = (ImageView) convertView.findViewById(R.id.profile_image_chat_opponent); opponentMsgHolder.opponent_name = (TextView) convertView.findViewById(R.id.name_txt_chat_opponent); opponentMsgHolder.opponent_message = (TextView) convertView.findViewById(R.id.msg_contents_opponent); opponentMsgHolder.opponent_timestamp = (TextView) convertView.findViewById(R.id.opponent_msg_timestamp); convertView.setTag(opponentMsgHolder); } else { opponentMsgHolder = (PrivateChatActivity.opponentMessageViewHolder) convertView.getTag(); } opponentMsgHolder.opponent_name.setText(chatMessage_data.sender_name); opponentMsgHolder.opponent_message.setText(chatMessage_data.TextCotents); opponentMsgHolder.opponent_timestamp.setText(chatMessage_data.send_time); Glide.with(mContext.getApplicationContext()).load(chatMessage_data.opponent_img_url).diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true).into(opponentMsgHolder.profile_img_opponent); break; } case TIME_STAMP: { if (convertView == null) { mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.message_timestamp_for_chat_window, null); timeMsgHolder = new PrivateChatActivity.timeStampViewHolder(); timeMsgHolder.timestamp_line = (View) convertView.findViewById(R.id.msg_contents_timeline); timeMsgHolder.timestamp_txt = (TextView) convertView.findViewById(R.id.msg_contents_timestamp); convertView.setTag(timeMsgHolder); } else { timeMsgHolder = (PrivateChatActivity.timeStampViewHolder) convertView.getTag(); } timeMsgHolder.timestamp_txt.setText(chatMessage_data.send_time); break; } } return convertView; } }
7,172
0.654307
0.651101
198
35.232323
36.563995
142
false
false
0
0
0
0
0
0
0.520202
false
false
5
f6dca5a08915d49eb46b5e1b217f86a975bf2b49
26,499,948,221,911
140799ed648a534d57fde36370a266094035a08d
/linkedlist/src/linkedlist/LinkedListDouble.java
0d93bb877df12064408c62333ab59f870ccfbe2b
[]
no_license
KristinaPupavac/homeworks
https://github.com/KristinaPupavac/homeworks
0980d516467d7429a3e114c23c7c8a687c2ffd52
e7f9e98b76763767325bf955e5eaa3a7f0a1c4fa
refs/heads/master
2021-01-02T09:15:43.626000
2015-08-19T20:40:19
2015-08-19T20:40:19
37,604,966
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package linkedlist; import java.util.NoSuchElementException; public class LinkedListDouble { private Node start; private int size; /** * Empty constructor, empty list */ public LinkedListDouble() { this.start = null; this.size = 0; } /** * Constructor accepts LinkedListDouble object and copies all the elements * in the list. * * @param l * - LinkedListDouble object */ public LinkedListDouble(LinkedListDouble l) { for (int i = 0; i < l.size; i++) { add(l.get(i)); } } /** * Method adds elments to list * * @param element * - adding element */ public void add(Double element) { if (start == null) { start = new Node(element); } else { Node last = getLastNode(); last.setNext(new Node(element)); } size++; } /** * Metod returns last node in list * * @return - last node */ private Node getLastNode() { if (start == null) { return null; } Node temp = start; while (temp.getNext() != null) { temp = temp.getNext(); } return temp; } /** * Removing node form list * * @param index * - index of node which we want to remove */ public void remove(int index) { Node previous = start; for (int i = 0; i < index; i++) { if (previous == null) { throw new NoSuchElementException(); } previous = previous.getNext(); } if (previous.getNext() == null) { throw new NoSuchElementException(); } Node temp = previous.getNext(); previous.setNext(temp.getNext()); size--; } /** * Returns the node located at the given index * * @param index * @return * @throws NoSuchElementException */ public double get(int index) throws NoSuchElementException { Node temp = start; for (int i = 0; i < index; i++) { if (temp == null) { throw new NoSuchElementException(); } temp = temp.getNext(); } return temp.getValue(); } /** * Returns previous node * * @param n * @return */ public Node getPreviousNode(Node n) { if (n == start) { return null; } Node temp = start; while (temp.getNext() != n) { temp = temp.getNext(); } return temp; } /** * Returns list size * * @return - size */ public int size() { return size; } @Override public String toString() { if (start == null) { return "The list is empty"; } return start.toString(); } /** * Returns middle list node value * * @return */ public double getMiddlle() { return get((size - 1) / 2); } /** * Returns first list node value * * @return */ public double getFirst() { return start.getValue(); } /** * Returns last node value * * @return */ public double getLast() { return get(size - 1); } /** * Delete first node in list */ public void deleteFirst() { start = start.getNext(); size--; } /** * Delete last node in list */ public void deleteLast() { // Node last = getLastNode(); remove(size - 2); size--; } /** * Adding node on index, and setting value * * @param d * @param index */ public void add(Double d, int index) { Node previous = start; for (int i = 0; i < index - 1; i++) { previous = previous.getNext(); } Node temp = new Node(d); temp.setNext(previous.getNext()); previous.setNext(temp); } /** * * @author KrisTina * */ public class Node { private double value; private Node next; /** * Default constructor * * @param value */ public Node(double value) { this.value = value; } /** * @return the value */ public double getValue() { return value; } /** * @param value * the value to set */ public void setValue(double value) { this.value = value; } /** * @return the next */ public Node getNext() { return next; } /** * @param next * the next to set */ public void setNext(Node next) { this.next = next; } @Override public String toString() { if (next == null) { return value + ""; } return value + " " + next.toString(); } } }
UTF-8
Java
4,105
java
LinkedListDouble.java
Java
[ { "context": "\tprevious.setNext(temp);\n\t}\n\n\t/**\n\t * \n\t * @author KrisTina\n\t *\n\t */\n\tpublic class Node {\n\t\tprivate double va", "end": 3347, "score": 0.9996665716171265, "start": 3339, "tag": "NAME", "value": "KrisTina" } ]
null
[]
package linkedlist; import java.util.NoSuchElementException; public class LinkedListDouble { private Node start; private int size; /** * Empty constructor, empty list */ public LinkedListDouble() { this.start = null; this.size = 0; } /** * Constructor accepts LinkedListDouble object and copies all the elements * in the list. * * @param l * - LinkedListDouble object */ public LinkedListDouble(LinkedListDouble l) { for (int i = 0; i < l.size; i++) { add(l.get(i)); } } /** * Method adds elments to list * * @param element * - adding element */ public void add(Double element) { if (start == null) { start = new Node(element); } else { Node last = getLastNode(); last.setNext(new Node(element)); } size++; } /** * Metod returns last node in list * * @return - last node */ private Node getLastNode() { if (start == null) { return null; } Node temp = start; while (temp.getNext() != null) { temp = temp.getNext(); } return temp; } /** * Removing node form list * * @param index * - index of node which we want to remove */ public void remove(int index) { Node previous = start; for (int i = 0; i < index; i++) { if (previous == null) { throw new NoSuchElementException(); } previous = previous.getNext(); } if (previous.getNext() == null) { throw new NoSuchElementException(); } Node temp = previous.getNext(); previous.setNext(temp.getNext()); size--; } /** * Returns the node located at the given index * * @param index * @return * @throws NoSuchElementException */ public double get(int index) throws NoSuchElementException { Node temp = start; for (int i = 0; i < index; i++) { if (temp == null) { throw new NoSuchElementException(); } temp = temp.getNext(); } return temp.getValue(); } /** * Returns previous node * * @param n * @return */ public Node getPreviousNode(Node n) { if (n == start) { return null; } Node temp = start; while (temp.getNext() != n) { temp = temp.getNext(); } return temp; } /** * Returns list size * * @return - size */ public int size() { return size; } @Override public String toString() { if (start == null) { return "The list is empty"; } return start.toString(); } /** * Returns middle list node value * * @return */ public double getMiddlle() { return get((size - 1) / 2); } /** * Returns first list node value * * @return */ public double getFirst() { return start.getValue(); } /** * Returns last node value * * @return */ public double getLast() { return get(size - 1); } /** * Delete first node in list */ public void deleteFirst() { start = start.getNext(); size--; } /** * Delete last node in list */ public void deleteLast() { // Node last = getLastNode(); remove(size - 2); size--; } /** * Adding node on index, and setting value * * @param d * @param index */ public void add(Double d, int index) { Node previous = start; for (int i = 0; i < index - 1; i++) { previous = previous.getNext(); } Node temp = new Node(d); temp.setNext(previous.getNext()); previous.setNext(temp); } /** * * @author KrisTina * */ public class Node { private double value; private Node next; /** * Default constructor * * @param value */ public Node(double value) { this.value = value; } /** * @return the value */ public double getValue() { return value; } /** * @param value * the value to set */ public void setValue(double value) { this.value = value; } /** * @return the next */ public Node getNext() { return next; } /** * @param next * the next to set */ public void setNext(Node next) { this.next = next; } @Override public String toString() { if (next == null) { return value + ""; } return value + " " + next.toString(); } } }
4,105
0.572716
0.57028
262
14.667939
13.871013
75
false
false
0
0
0
0
0
0
1.652672
false
false
5
4ecc04722a6c8d550c70950a1b9ebc7e962479ab
13,099,650,286,014
b2c7b891647bb6b2e5198ad1a44af185f02e3f70
/src/com/company/shapes/ShapeSquare.java
1e4923a5f3703c0b7d99b5923b040630d6f1aacb
[]
no_license
yogesh-rts/GeoShapes
https://github.com/yogesh-rts/GeoShapes
9e04542c694f8f0b4afe879d70d0d457c26cd2f4
3f72fee9a51ee9f5f8cd24eea40a1df477a9091d
refs/heads/master
2022-12-19T03:33:32.638000
2020-09-26T03:52:16
2020-09-26T03:52:16
298,731,061
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.shapes; /* ShapeSquare: sub-class inherits the common methods and fields from its base class 'Shape' using 'extends' keyword So, via 'Inheritance' concept code-reusability is achieved to maintain code-readability and clean. */ import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput; public class ShapeSquare extends Shape { /* Via inheritance, method-overriding is achieved by overriding the implementation details of each abstract methods in the sub-class */ @Override public double perimeter() { return 4 * getSide(); } @Override public double area() { return Math.pow(getSide(), 2); } @Override public String displayresult() { String displayResult = "\n****************************************************************** \n" + " The area of a Square: " + Main.getDeciformat().format(area()) + " sq.units \n" + "****************************************************************** \n" + " The perimeter of a Square: " + Main.getDeciformat().format(perimeter()) + " units \n" + "****************************************************************** \n"; return displayResult; } }
UTF-8
Java
1,288
java
ShapeSquare.java
Java
[]
null
[]
package com.company.shapes; /* ShapeSquare: sub-class inherits the common methods and fields from its base class 'Shape' using 'extends' keyword So, via 'Inheritance' concept code-reusability is achieved to maintain code-readability and clean. */ import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput; public class ShapeSquare extends Shape { /* Via inheritance, method-overriding is achieved by overriding the implementation details of each abstract methods in the sub-class */ @Override public double perimeter() { return 4 * getSide(); } @Override public double area() { return Math.pow(getSide(), 2); } @Override public String displayresult() { String displayResult = "\n****************************************************************** \n" + " The area of a Square: " + Main.getDeciformat().format(area()) + " sq.units \n" + "****************************************************************** \n" + " The perimeter of a Square: " + Main.getDeciformat().format(perimeter()) + " units \n" + "****************************************************************** \n"; return displayResult; } }
1,288
0.512422
0.51087
42
29.666666
39.406712
120
false
false
0
0
0
0
0
0
0.214286
false
false
5
3caf7707bf3962a85c362529c18faf8824852b94
9,156,870,278,308
0fe383db3f5a74d57bb70c62b8162ba803022348
/microee-traditex-inbox/microee-traditex-inbox-oem/src/main/java/com/microee/traditex/inbox/oem/jumptrading/apiresult/JumpTradingApiResultForBooksynch.java
64ee6d92a10994be96aeba56647881b76bf4f33c
[]
no_license
moutainhigh/microee-traditex
https://github.com/moutainhigh/microee-traditex
87ac163cb6ae4b513d43d705136f4bcfe7c12243
742dbbf0b6df1eec1f502daf2e33c6c462555cf6
refs/heads/main
2023-02-03T18:35:23.529000
2020-12-26T12:19:18
2020-12-26T12:19:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.microee.traditex.inbox.oem.jumptrading.apiresult; import java.io.Serializable; import java.text.DecimalFormat; import com.fasterxml.jackson.annotation.JsonProperty; public class JumpTradingApiResultForBooksynch extends JumpTradingApiResultBase implements Serializable { private static final long serialVersionUID = -5823472984673324318L; @JsonProperty("FIXSeq") private Integer fixSeq; @JsonProperty("Symbol") private String symbol; @JsonProperty("QuoteID") private String quoteId; @JsonProperty("timestamp") private Double timestamp; // new DecimalFormat("#0.000").format(boosSynch.getTimestamp()) @JsonProperty("clientTS") private String clientTs; @JsonProperty("seq") private Long seq; public Integer getFixSeq() { return fixSeq; } public void setFixSeq(Integer fixSeq) { this.fixSeq = fixSeq; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public String getQuoteId() { return quoteId; } public void setQuoteId(String quoteId) { this.quoteId = quoteId; } public Long getTimestamp() { // 科学计数 return Long.parseLong(new DecimalFormat("#0.000").format(this.timestamp).replace(".", "")); } public void setTimestamp(Double timestamp) { this.timestamp = timestamp; } public String getClientTs() { return clientTs; } public void setClientTs(String clientTs) { this.clientTs = clientTs; } public Long getSeq() { return seq; } public void setSeq(Long seq) { this.seq = seq; } }
UTF-8
Java
1,732
java
JumpTradingApiResultForBooksynch.java
Java
[]
null
[]
package com.microee.traditex.inbox.oem.jumptrading.apiresult; import java.io.Serializable; import java.text.DecimalFormat; import com.fasterxml.jackson.annotation.JsonProperty; public class JumpTradingApiResultForBooksynch extends JumpTradingApiResultBase implements Serializable { private static final long serialVersionUID = -5823472984673324318L; @JsonProperty("FIXSeq") private Integer fixSeq; @JsonProperty("Symbol") private String symbol; @JsonProperty("QuoteID") private String quoteId; @JsonProperty("timestamp") private Double timestamp; // new DecimalFormat("#0.000").format(boosSynch.getTimestamp()) @JsonProperty("clientTS") private String clientTs; @JsonProperty("seq") private Long seq; public Integer getFixSeq() { return fixSeq; } public void setFixSeq(Integer fixSeq) { this.fixSeq = fixSeq; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public String getQuoteId() { return quoteId; } public void setQuoteId(String quoteId) { this.quoteId = quoteId; } public Long getTimestamp() { // 科学计数 return Long.parseLong(new DecimalFormat("#0.000").format(this.timestamp).replace(".", "")); } public void setTimestamp(Double timestamp) { this.timestamp = timestamp; } public String getClientTs() { return clientTs; } public void setClientTs(String clientTs) { this.clientTs = clientTs; } public Long getSeq() { return seq; } public void setSeq(Long seq) { this.seq = seq; } }
1,732
0.653712
0.638051
74
22.297297
21.882814
99
false
false
0
0
0
0
0
0
0.324324
false
false
5
5004808a7e4d736352b109a23fe8648d24702784
18,098,992,186,584
70d7113ccc4c6ecfe14a6e665dd16f1961bf8e6a
/Largest number in an array/Main.java
166a382b641b5fbefd2359614cedf4d03ac1e8c7
[]
no_license
Arpitadidwaniya/Playground
https://github.com/Arpitadidwaniya/Playground
9d29db266fe1955dd6aab4bb819981e230def5e0
36a4f146c199b053cd71309519e208a3a7e43f9a
refs/heads/master
2020-04-15T01:26:53.982000
2019-07-27T19:30:03
2019-07-27T19:30:03
164,276,295
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; class Main{ public static void main(String args[]){ // Type your code here Scanner in =new Scanner(System.in); int n =in.nextInt(); int m[]=new int[n]; for(int i=0;i<n;i++) { m[i]=in.nextInt(); } int max=0; for(int i=0;i<n;i++) { max = loop(max,m[i],n); } System.out.print(max); } public static int loop(int o,int p,int u) { for(int i=0;i<u;i++) { if(p>o) { return p; } else {return o; } } return 0; } }
UTF-8
Java
636
java
Main.java
Java
[]
null
[]
import java.util.Scanner; class Main{ public static void main(String args[]){ // Type your code here Scanner in =new Scanner(System.in); int n =in.nextInt(); int m[]=new int[n]; for(int i=0;i<n;i++) { m[i]=in.nextInt(); } int max=0; for(int i=0;i<n;i++) { max = loop(max,m[i],n); } System.out.print(max); } public static int loop(int o,int p,int u) { for(int i=0;i<u;i++) { if(p>o) { return p; } else {return o; } } return 0; } }
636
0.421384
0.413522
36
16.694445
11.787045
47
false
false
0
0
0
0
0
0
0.583333
false
false
5
7c37ad4cb017a03deedc61631d63489f70f7436b
7,249,904,829,739
2fb1b3f9adfe14434885f6856b1ec84e19693500
/src/main/java/com/nmcp/tech/casesmanagement/csvbatch/processors/DataItemProcessor.java
48c54da2f4647a893df2782459bdd2b52ef1f4f7
[]
no_license
Hamza-ye/cases-management
https://github.com/Hamza-ye/cases-management
7f9e703e34b9f45fc74f92f9beecc5eff31a3a79
54db5c4e044755317a530c4ce102c97771e0a18a
refs/heads/master
2020-05-15T14:40:44.722000
2019-04-20T01:41:06
2019-04-20T01:41:06
182,345,549
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nmcp.tech.casesmanagement.csvbatch.processors; //import com.infotech.batch.model.Person; import com.nmcp.tech.casesmanagement.data.DataElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; public class DataItemProcessor implements ItemProcessor<DataElement, DataElement> { private static final Logger log = LoggerFactory.getLogger(DataItemProcessor.class); @Override public DataElement process(final DataElement dataElement) throws Exception { // final String firstName = DataElement.getFirstName().toUpperCase(); // final String lastName = person.getLastName().toUpperCase(); // // final Person transformedPerson = new Person(firstName, lastName,person.getEmail(),person.getAge()); // // log.info("Converting (" + person + ") into (" + transformedPerson + ")"); return dataElement; } }
UTF-8
Java
922
java
DataItemProcessor.java
Java
[]
null
[]
package com.nmcp.tech.casesmanagement.csvbatch.processors; //import com.infotech.batch.model.Person; import com.nmcp.tech.casesmanagement.data.DataElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; public class DataItemProcessor implements ItemProcessor<DataElement, DataElement> { private static final Logger log = LoggerFactory.getLogger(DataItemProcessor.class); @Override public DataElement process(final DataElement dataElement) throws Exception { // final String firstName = DataElement.getFirstName().toUpperCase(); // final String lastName = person.getLastName().toUpperCase(); // // final Person transformedPerson = new Person(firstName, lastName,person.getEmail(),person.getAge()); // // log.info("Converting (" + person + ") into (" + transformedPerson + ")"); return dataElement; } }
922
0.741866
0.739696
26
34.5
35.275017
109
false
false
0
0
0
0
0
0
0.615385
false
false
5
e6a84f537013fafa65aaee0b8d0d14ab9929c65d
35,940,286,344,599
fc0950a2403ba5cc4369360b91855afdf3bf1699
/src/test/java/lapr/project/utils/TimeZoneUtilTest.java
62de072ba61a8beb6624e046cdf86dac5d38fb08
[]
no_license
BeatrizZamith/LAPR2HELP
https://github.com/BeatrizZamith/LAPR2HELP
35b9e0a726cc53c622b862ea80f56749c8ea0eab
120f4346763b26f9c51d25dc771fc4812554549f
refs/heads/master
2020-03-19T14:09:25.776000
2018-06-10T16:02:12
2018-06-10T16:02:12
136,611,233
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lapr.project.utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.TimeZone; import java.util.concurrent.TimeUnit; /** * Tests for the TimeZoneUtil methods. * * @author Luis Pinho */ public class TimeZoneUtilTest { /** * Ensure that generating a description for the system time zone works correctly. */ @Test public void ensureGenSystemTimeZoneDescriptionWorks() { TimeZone tz = TimeZone.getDefault(); short hours = (short) TimeUnit.MILLISECONDS.toHours(tz.getRawOffset()); short minutes = (short) (TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset()) - TimeUnit.HOURS.toMinutes(hours)); // To avoid cases where the value would be negative minutes = (short) Math.abs(minutes); String expected; if (hours > 0) { expected = String.format("(GMT+%02d:%02d) %s", hours, minutes, tz.getID()); } else { expected = String.format("(GMT%d:%02d) %s", hours, minutes, tz.getID()); } String result = TimeZoneUtil.genSystemTimeZoneDescription(); Assertions.assertEquals(expected, result, "Descriptions differ."); } /** * Ensure that finding a time zone by its description works. */ @Test public void ensureGetTimeZoneByDescriptionWorks() { String description = TimeZoneUtil.genSystemTimeZoneDescription(); TimeZone expected = TimeZone.getDefault(); TimeZone result = TimeZoneUtil.getTimeZoneByDescription(description); Assertions.assertEquals(expected, result, "TimeZones differ."); } }
UTF-8
Java
1,634
java
TimeZoneUtilTest.java
Java
[ { "context": " Tests for the TimeZoneUtil methods.\n *\n * @author Luis Pinho\n */\npublic class TimeZoneUtilTest {\n\n /**\n ", "end": 239, "score": 0.9998487234115601, "start": 229, "tag": "NAME", "value": "Luis Pinho" } ]
null
[]
package lapr.project.utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.TimeZone; import java.util.concurrent.TimeUnit; /** * Tests for the TimeZoneUtil methods. * * @author <NAME> */ public class TimeZoneUtilTest { /** * Ensure that generating a description for the system time zone works correctly. */ @Test public void ensureGenSystemTimeZoneDescriptionWorks() { TimeZone tz = TimeZone.getDefault(); short hours = (short) TimeUnit.MILLISECONDS.toHours(tz.getRawOffset()); short minutes = (short) (TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset()) - TimeUnit.HOURS.toMinutes(hours)); // To avoid cases where the value would be negative minutes = (short) Math.abs(minutes); String expected; if (hours > 0) { expected = String.format("(GMT+%02d:%02d) %s", hours, minutes, tz.getID()); } else { expected = String.format("(GMT%d:%02d) %s", hours, minutes, tz.getID()); } String result = TimeZoneUtil.genSystemTimeZoneDescription(); Assertions.assertEquals(expected, result, "Descriptions differ."); } /** * Ensure that finding a time zone by its description works. */ @Test public void ensureGetTimeZoneByDescriptionWorks() { String description = TimeZoneUtil.genSystemTimeZoneDescription(); TimeZone expected = TimeZone.getDefault(); TimeZone result = TimeZoneUtil.getTimeZoneByDescription(description); Assertions.assertEquals(expected, result, "TimeZones differ."); } }
1,630
0.669523
0.665239
50
31.68
31.375429
119
false
false
0
0
0
0
0
0
0.56
false
false
5
00943d43da21946ef506638b8690e863ca5c3f38
27,943,057,296,939
d3466c7ee71c5168ba43f09e9fb733273b155de5
/lab2/FileReverse.java
27bfe73752856a56e6f751dfa53cb53c5e7b4fdf
[]
no_license
jacklau1803/CMPS12B
https://github.com/jacklau1803/CMPS12B
0ba826b8c825dd6bf1d6c10ba43422ef41ca8fb6
1e1036c07b060882a644cab572bffae6ea1d4eb2
refs/heads/master
2020-09-16T21:56:58.607000
2019-11-25T08:29:30
2019-11-25T08:29:30
223,897,963
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//FileReverse.java //Jack Liu //dliu34 //lab2 //This program reads every word in a file and prints out the reversed version of them to another file. import java.lang.*; import java.io.*; import java.util.*; class FileReverse{ public static void main(String[] args) throws IOException{ Scanner in = null; PrintWriter out = null; String line = null; String[] token = null; int i, n, lineNum = 0; if(args.length < 2){ System.out.println("Usage: FileReverse <input file> <output file>"); System.exit(1); } in = new Scanner(new File(args[0])); out = new PrintWriter(new FileWriter(args[1])); while(in.hasNextLine()){ lineNum++; line = in.nextLine().trim()+" "; token = line.split("\\s+"); n = token.length; for(i=0; i<n; i++){ out.println(stringReverse(token[i],token[i].length())); } } in.close(); out.close(); } public static String stringReverse(String s, int n){ if(n<1) return ""; return s.charAt(n-1)+stringReverse(s,n-1); } }
UTF-8
Java
1,033
java
FileReverse.java
Java
[ { "context": "//FileReverse.java\r\n//Jack Liu\r\n//dliu34\r\n//lab2\r\n//This program reads every wor", "end": 30, "score": 0.9996859431266785, "start": 22, "tag": "NAME", "value": "Jack Liu" } ]
null
[]
//FileReverse.java //<NAME> //dliu34 //lab2 //This program reads every word in a file and prints out the reversed version of them to another file. import java.lang.*; import java.io.*; import java.util.*; class FileReverse{ public static void main(String[] args) throws IOException{ Scanner in = null; PrintWriter out = null; String line = null; String[] token = null; int i, n, lineNum = 0; if(args.length < 2){ System.out.println("Usage: FileReverse <input file> <output file>"); System.exit(1); } in = new Scanner(new File(args[0])); out = new PrintWriter(new FileWriter(args[1])); while(in.hasNextLine()){ lineNum++; line = in.nextLine().trim()+" "; token = line.split("\\s+"); n = token.length; for(i=0; i<n; i++){ out.println(stringReverse(token[i],token[i].length())); } } in.close(); out.close(); } public static String stringReverse(String s, int n){ if(n<1) return ""; return s.charAt(n-1)+stringReverse(s,n-1); } }
1,031
0.619555
0.607938
40
23.875
21.309843
102
false
false
0
0
0
0
0
0
2.325
false
false
5
a51a002abb8b637167b33bdcedb0aa7261c9180b
21,749,714,417,792
b6b3ca8229fc9aa228c75f080ec46bb63b7a3f51
/apps/tm/src/java/org/hypergraphdb/app/tm/HGTopicMapSystem.java
a88e4425ef04e21c052e8b05e095a4853a06f675
[]
no_license
xingh/hypergraphdb
https://github.com/xingh/hypergraphdb
533229be26323d693c84268cfc92f0ece0f0abd7
e8ae87743a916d90d039fcefe393824dee13ed9c
refs/heads/master
2019-01-02T04:02:06.217000
2015-03-20T03:06:36
2015-03-20T03:06:36
32,645,146
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.hypergraphdb.app.tm; import java.util.HashSet; import java.util.List; import java.util.Set; import org.tmapi.core.FeatureNotRecognizedException; import org.tmapi.core.Locator; import org.tmapi.core.TMAPIRuntimeException; import org.tmapi.core.Topic; import org.tmapi.core.TopicMap; import org.tmapi.core.TopicMapExistsException; import org.tmapi.core.TopicMapObject; import org.tmapi.core.TopicMapSystem; import org.hypergraphdb.*; import org.hypergraphdb.HGQuery.hg; import org.hypergraphdb.query.AtomProjectionCondition; import org.hypergraphdb.query.OrderedLinkCondition; import org.hypergraphdb.query.impl.DefaultKeyBasedQuery; import org.hypergraphdb.query.impl.PipeQuery; import org.hypergraphdb.util.ValueSetter; public final class HGTopicMapSystem implements TopicMapSystem { private HyperGraph graph; private boolean closeHGOnExit = false; public HGTopicMapSystem(HyperGraph hg) { this.graph = hg; } public HyperGraph getGraph() { return graph; } public void close() { if (closeHGOnExit) graph.close(); } public Locator toLocator(String reference) { return U.ensureLocator(graph, null, reference); } public Locator toLocator(String base, String reference) { return U.ensureLocator(graph, base, reference); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locate(Locator itemIdentifier) { HGHandle lh = graph.getHandle(itemIdentifier); if (lh == null) lh = U.ensureLocator(graph, itemIdentifier); return (T) U.getOneRelated(graph, HGTM.hSourceLocator, lh, null); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locate(String itemIdentifier) { return (T)locate(U.ensureLocator(graph, null, itemIdentifier)); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locateByIndicator(Locator subjectIdentifier) { HGHandle lh = graph.getHandle(subjectIdentifier); if (lh == null) lh = U.ensureLocator(graph, subjectIdentifier); return (T) U.getOneRelated(graph, HGTM.hSubjectIdentifier, lh, null); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locateByIndicator(String subjectIdentifier) { return (T)locate(U.ensureLocator(graph, null, subjectIdentifier)); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locateBySubject(Locator subjectLocator) { HGHandle lh = graph.getHandle(subjectLocator); if (lh == null) lh = U.ensureLocator(graph, subjectLocator); return (T) U.getOneRelated(graph, HGTM.hSubjectLocator, lh, null); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locateBySubject(String subjectLocator) { return (T)locate(U.ensureLocator(graph, null, subjectLocator)); } public List<TopicMap> getTopicMaps() { return hg.<TopicMap>findAll(graph, hg.apply(hg.deref(graph), hg.type(HGTopicMap.class))); } public TopicMap createTopicMap(String uri) throws TopicMapExistsException { Locator l = U.findLocator(graph, uri); if (l == null) { l = U.makeLocator(uri); } HGTopicMap result = new HGTopicMap(); result.setBaseLocator(l); result.graph = graph; graph.add(result); result.system = this; return result; } public TopicMap createTopicMap(String baseLocatorReference, String baseLocatorNotation) throws TopicMapExistsException { if (!baseLocatorNotation.equals("URI")) throw new TMAPIRuntimeException("Unsupported locator notation '" + baseLocatorNotation + "'"); return createTopicMap(baseLocatorReference); } public Set getBaseLocators() { HashSet<Object> result = new HashSet<Object>(); for (HGHandle h : hg.<HGHandle>findAll(graph, new AtomProjectionCondition("baseLocator", hg.type(HGTopicMap.class)))) { result.add(graph.get(h)); } return result; } public boolean getFeature(String featureName) throws FeatureNotRecognizedException { return false; } public String getProperty(String propertyName) { return null; } public TopicMap getTopicMap(String baseLocatorReference) { Locator l = U.findLocator(graph, baseLocatorReference); return l == null ? null : getTopicMap(l); } public TopicMap getTopicMap(Locator baseLocator) { HGHandle h = hg.findOne(graph, hg.and(hg.type(HGTopicMap.class), hg.eq("baseLocator", baseLocator))); if (h == null) return null; else { HGTopicMap map = (HGTopicMap)graph.get(h); map.system = this; return map; } } public TopicMap getTopicMap(String baseLocatorReference, String baseLocatorNotation) { if (!baseLocatorNotation.equals("URI")) throw new TMAPIRuntimeException("Unsupported locator notation '" + baseLocatorNotation + "'"); else return getTopicMap(baseLocatorReference); } public void load(String uri) { // TMXMLUtils.load(uri, this); } // Search utilities /** * <p> * Find all topics associated to a given type according to prescribed role types. There are * two versions of this method, one taking <code>HGHandle</code> identifying the topics * and the other taking <code>Topic</code> instances. * </p> * * @param t The topic whose associated topics are being sought. * @param roleType The type of the role of <code>t</code> in the associations. * @param targetRoleType The type of the role of associated topics to be returned. * @return A list of topics associated to <code>t</code> with role type <code>targetRoleType</code>. */ public List<Topic> findAssociated(HGHandle ht, HGHandle hRoleType, HGHandle hTargetRoleType) { // q1 will produce all associations in which 'item' is part HGQuery q1 = HGQuery.make(graph, hg.apply(HGQuery.hg.targetAt(graph, 2), hg.and(hg.type(HGAssociationRole.class), hg.orderedLink(ht, hRoleType, graph.getHandleFactory().anyHandle())))); // A link condition constraining roles such that the role type is 'h' and the association is set as a key // to a piped query final OrderedLinkCondition linkCondition = HGQuery.hg.orderedLink(graph.getHandleFactory().anyHandle(), hTargetRoleType, graph.getHandleFactory().anyHandle()); DefaultKeyBasedQuery pipe = new DefaultKeyBasedQuery( graph, HGQuery.hg.apply(HGQuery.hg.targetAt(graph, 0), hg.and(HGQuery.hg.type(HGAssociationRole.class), linkCondition)), new ValueSetter() { public void set(Object value) { linkCondition.setTarget(2, (HGHandle)value); } }); HGQuery query = new PipeQuery(q1, pipe); query.setHyperGraph(graph); return hg.findAll(query); } /** * <p> * Find all topics associated to a given type according to prescribed role types. * </p> * * @param t The topic whose associated topics are being sought. * @param roleType The type of the role of <code>t</code> in the associations. * @param targetRoleType The type of the role of associated topics to be returned. * @return A list of topics associated to <code>t</code> with role type <code>targetRoleType</code>. */ public List<Topic> findAssociated(Topic t, Topic roleType, Topic targetRoleType) { return findAssociated(graph.getHandle(t), graph.getHandle(roleType), graph.getHandle(targetRoleType)); } }
UTF-8
Java
7,645
java
HGTopicMapSystem.java
Java
[]
null
[]
package org.hypergraphdb.app.tm; import java.util.HashSet; import java.util.List; import java.util.Set; import org.tmapi.core.FeatureNotRecognizedException; import org.tmapi.core.Locator; import org.tmapi.core.TMAPIRuntimeException; import org.tmapi.core.Topic; import org.tmapi.core.TopicMap; import org.tmapi.core.TopicMapExistsException; import org.tmapi.core.TopicMapObject; import org.tmapi.core.TopicMapSystem; import org.hypergraphdb.*; import org.hypergraphdb.HGQuery.hg; import org.hypergraphdb.query.AtomProjectionCondition; import org.hypergraphdb.query.OrderedLinkCondition; import org.hypergraphdb.query.impl.DefaultKeyBasedQuery; import org.hypergraphdb.query.impl.PipeQuery; import org.hypergraphdb.util.ValueSetter; public final class HGTopicMapSystem implements TopicMapSystem { private HyperGraph graph; private boolean closeHGOnExit = false; public HGTopicMapSystem(HyperGraph hg) { this.graph = hg; } public HyperGraph getGraph() { return graph; } public void close() { if (closeHGOnExit) graph.close(); } public Locator toLocator(String reference) { return U.ensureLocator(graph, null, reference); } public Locator toLocator(String base, String reference) { return U.ensureLocator(graph, base, reference); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locate(Locator itemIdentifier) { HGHandle lh = graph.getHandle(itemIdentifier); if (lh == null) lh = U.ensureLocator(graph, itemIdentifier); return (T) U.getOneRelated(graph, HGTM.hSourceLocator, lh, null); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locate(String itemIdentifier) { return (T)locate(U.ensureLocator(graph, null, itemIdentifier)); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locateByIndicator(Locator subjectIdentifier) { HGHandle lh = graph.getHandle(subjectIdentifier); if (lh == null) lh = U.ensureLocator(graph, subjectIdentifier); return (T) U.getOneRelated(graph, HGTM.hSubjectIdentifier, lh, null); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locateByIndicator(String subjectIdentifier) { return (T)locate(U.ensureLocator(graph, null, subjectIdentifier)); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locateBySubject(Locator subjectLocator) { HGHandle lh = graph.getHandle(subjectLocator); if (lh == null) lh = U.ensureLocator(graph, subjectLocator); return (T) U.getOneRelated(graph, HGTM.hSubjectLocator, lh, null); } @SuppressWarnings("unchecked") public <T extends TopicMapObject> T locateBySubject(String subjectLocator) { return (T)locate(U.ensureLocator(graph, null, subjectLocator)); } public List<TopicMap> getTopicMaps() { return hg.<TopicMap>findAll(graph, hg.apply(hg.deref(graph), hg.type(HGTopicMap.class))); } public TopicMap createTopicMap(String uri) throws TopicMapExistsException { Locator l = U.findLocator(graph, uri); if (l == null) { l = U.makeLocator(uri); } HGTopicMap result = new HGTopicMap(); result.setBaseLocator(l); result.graph = graph; graph.add(result); result.system = this; return result; } public TopicMap createTopicMap(String baseLocatorReference, String baseLocatorNotation) throws TopicMapExistsException { if (!baseLocatorNotation.equals("URI")) throw new TMAPIRuntimeException("Unsupported locator notation '" + baseLocatorNotation + "'"); return createTopicMap(baseLocatorReference); } public Set getBaseLocators() { HashSet<Object> result = new HashSet<Object>(); for (HGHandle h : hg.<HGHandle>findAll(graph, new AtomProjectionCondition("baseLocator", hg.type(HGTopicMap.class)))) { result.add(graph.get(h)); } return result; } public boolean getFeature(String featureName) throws FeatureNotRecognizedException { return false; } public String getProperty(String propertyName) { return null; } public TopicMap getTopicMap(String baseLocatorReference) { Locator l = U.findLocator(graph, baseLocatorReference); return l == null ? null : getTopicMap(l); } public TopicMap getTopicMap(Locator baseLocator) { HGHandle h = hg.findOne(graph, hg.and(hg.type(HGTopicMap.class), hg.eq("baseLocator", baseLocator))); if (h == null) return null; else { HGTopicMap map = (HGTopicMap)graph.get(h); map.system = this; return map; } } public TopicMap getTopicMap(String baseLocatorReference, String baseLocatorNotation) { if (!baseLocatorNotation.equals("URI")) throw new TMAPIRuntimeException("Unsupported locator notation '" + baseLocatorNotation + "'"); else return getTopicMap(baseLocatorReference); } public void load(String uri) { // TMXMLUtils.load(uri, this); } // Search utilities /** * <p> * Find all topics associated to a given type according to prescribed role types. There are * two versions of this method, one taking <code>HGHandle</code> identifying the topics * and the other taking <code>Topic</code> instances. * </p> * * @param t The topic whose associated topics are being sought. * @param roleType The type of the role of <code>t</code> in the associations. * @param targetRoleType The type of the role of associated topics to be returned. * @return A list of topics associated to <code>t</code> with role type <code>targetRoleType</code>. */ public List<Topic> findAssociated(HGHandle ht, HGHandle hRoleType, HGHandle hTargetRoleType) { // q1 will produce all associations in which 'item' is part HGQuery q1 = HGQuery.make(graph, hg.apply(HGQuery.hg.targetAt(graph, 2), hg.and(hg.type(HGAssociationRole.class), hg.orderedLink(ht, hRoleType, graph.getHandleFactory().anyHandle())))); // A link condition constraining roles such that the role type is 'h' and the association is set as a key // to a piped query final OrderedLinkCondition linkCondition = HGQuery.hg.orderedLink(graph.getHandleFactory().anyHandle(), hTargetRoleType, graph.getHandleFactory().anyHandle()); DefaultKeyBasedQuery pipe = new DefaultKeyBasedQuery( graph, HGQuery.hg.apply(HGQuery.hg.targetAt(graph, 0), hg.and(HGQuery.hg.type(HGAssociationRole.class), linkCondition)), new ValueSetter() { public void set(Object value) { linkCondition.setTarget(2, (HGHandle)value); } }); HGQuery query = new PipeQuery(q1, pipe); query.setHyperGraph(graph); return hg.findAll(query); } /** * <p> * Find all topics associated to a given type according to prescribed role types. * </p> * * @param t The topic whose associated topics are being sought. * @param roleType The type of the role of <code>t</code> in the associations. * @param targetRoleType The type of the role of associated topics to be returned. * @return A list of topics associated to <code>t</code> with role type <code>targetRoleType</code>. */ public List<Topic> findAssociated(Topic t, Topic roleType, Topic targetRoleType) { return findAssociated(graph.getHandle(t), graph.getHandle(roleType), graph.getHandle(targetRoleType)); } }
7,645
0.687639
0.686854
243
29.469135
30.113129
119
false
false
0
0
0
0
0
0
2.123457
false
false
5
fe9f286090cb4a3f61bc9be67a027ca144551c0c
13,245,679,141,174
7eb9f21ad71f5690ed23672904133b6648b4af1e
/AppLexcomConfig/src/java/lexcom/app/Pago_List.java
dbc94302461700e3c37e0e7a4fa644d978a7f5e5
[]
no_license
edvinnavas/bitnet
https://github.com/edvinnavas/bitnet
ecd01509574675d1dadd82bcde027616241e525f
75b2bed4a5fb721b60e7061ad5327d3c4e187568
refs/heads/master
2023-07-25T07:17:55.652000
2023-07-11T05:35:51
2023-07-11T05:35:51
160,252,250
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lexcom.app; import java.io.Serializable; import java.util.Date; public class Pago_List implements Serializable { private static final long serialVersionUID = 1L; private Integer indice; private String actor; private String deudor; private String banco; private Date fecha; private Double monto; private String no_boleta; private Date fecha_registro; public Pago_List(Integer indice, String actor, String deudor, String banco, Date fecha, Double monto, String no_boleta, Date fecha_registro) { this.indice = indice; this.actor = actor; this.deudor = deudor; this.banco = banco; this.fecha = fecha; this.monto = monto; this.no_boleta = no_boleta; this.fecha_registro = fecha_registro; } public Integer getIndice() { return indice; } public void setIndice(Integer indice) { this.indice = indice; } public String getActor() { return actor; } public void setActor(String actor) { this.actor = actor; } public String getDeudor() { return deudor; } public void setDeudor(String deudor) { this.deudor = deudor; } public String getBanco() { return banco; } public void setBanco(String banco) { this.banco = banco; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public Double getMonto() { return monto; } public void setMonto(Double monto) { this.monto = monto; } public String getNo_boleta() { return no_boleta; } public void setNo_boleta(String no_boleta) { this.no_boleta = no_boleta; } public Date getFecha_registro() { return fecha_registro; } public void setFecha_registro(Date fecha_registro) { this.fecha_registro = fecha_registro; } }
UTF-8
Java
2,081
java
Pago_List.java
Java
[]
null
[]
package lexcom.app; import java.io.Serializable; import java.util.Date; public class Pago_List implements Serializable { private static final long serialVersionUID = 1L; private Integer indice; private String actor; private String deudor; private String banco; private Date fecha; private Double monto; private String no_boleta; private Date fecha_registro; public Pago_List(Integer indice, String actor, String deudor, String banco, Date fecha, Double monto, String no_boleta, Date fecha_registro) { this.indice = indice; this.actor = actor; this.deudor = deudor; this.banco = banco; this.fecha = fecha; this.monto = monto; this.no_boleta = no_boleta; this.fecha_registro = fecha_registro; } public Integer getIndice() { return indice; } public void setIndice(Integer indice) { this.indice = indice; } public String getActor() { return actor; } public void setActor(String actor) { this.actor = actor; } public String getDeudor() { return deudor; } public void setDeudor(String deudor) { this.deudor = deudor; } public String getBanco() { return banco; } public void setBanco(String banco) { this.banco = banco; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public Double getMonto() { return monto; } public void setMonto(Double monto) { this.monto = monto; } public String getNo_boleta() { return no_boleta; } public void setNo_boleta(String no_boleta) { this.no_boleta = no_boleta; } public Date getFecha_registro() { return fecha_registro; } public void setFecha_registro(Date fecha_registro) { this.fecha_registro = fecha_registro; } }
2,081
0.58001
0.579529
93
20.376345
20.403412
146
false
false
0
0
0
0
0
0
0.462366
false
false
5
b25b9f37b96f6d10ffb149390720811459e88dae
22,522,808,567,189
7f1507545bcf954eed3566498cea12bfa81d4991
/src/com/javaex/basic/practice1/PracticeLoop.java
738be20103a5f689230f0fcb41de8ecf50e96e76
[]
no_license
mkyu0917/JavaEX
https://github.com/mkyu0917/JavaEX
762b41a56975b2c2bff4786205fb744b33e52953
98d9add7e5753b65915e480051039069a9f2ab87
refs/heads/master
2020-03-19T13:10:03.434000
2018-06-08T04:11:07
2018-06-08T04:11:07
136,564,821
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javaex.basic.practice1; public class PracticeLoop { public static void main(String[] args){ int dan ; int i = 1; for(i=2; i<10; i++){ // 1부터 9까지 반복 1번 for(int j=1; j<10; j++){ // 2번 System.out.print(i); System.out.print("\t"); } System.out.println(); //3번 } } }
UHC
Java
347
java
PracticeLoop.java
Java
[]
null
[]
package com.javaex.basic.practice1; public class PracticeLoop { public static void main(String[] args){ int dan ; int i = 1; for(i=2; i<10; i++){ // 1부터 9까지 반복 1번 for(int j=1; j<10; j++){ // 2번 System.out.print(i); System.out.print("\t"); } System.out.println(); //3번 } } }
347
0.531915
0.492401
17
17.352942
14.580169
40
false
false
0
0
0
0
0
0
2.588235
false
false
5
b133f615c299e325e8208a37061e6eec31dffa4c
1,065,151,947,750
9e3867cbadbaf967d3ffff64cd402bc6ddfd3915
/src/main/java/com/cobee/bookstore/component/listener/AuctionListener.java
df5d0303fbcb486c6feeb9f21fec37d7172028bc
[]
no_license
litterforest/bookstore
https://github.com/litterforest/bookstore
2765b76bd59f05c5d7961f0efb5140d314906109
943463ed52c22d255a9a3e5c6c0252df5eaa9da7
refs/heads/master
2021-09-06T11:32:26.179000
2018-02-06T03:36:23
2018-02-06T03:36:23
113,053,202
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cobee.bookstore.component.listener; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import javax.servlet.AsyncContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.util.CollectionUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.cobee.bookstore.component.JedisBean; import com.cobee.bookstore.vo.AuctionResult; import com.fasterxml.jackson.databind.ObjectMapper; import redis.clients.jedis.Jedis; /** * Application Lifecycle Listener implementation class AuctionListener * */ public class AuctionListener implements ServletContextListener { private static final Logger logger = LoggerFactory.getLogger(AuctionListener.class); // private static final BlockingQueue<AsyncContext> queue = new LinkedBlockingQueue<>(); public static final Map<String, AuctionResult> auctionResultMap = new HashMap<String, AuctionResult>(); private volatile Thread thread; private WebApplicationContext springContext; private JedisBean jedisBean; private Jedis jedis; // public static void addAsyncContext(AsyncContext asyncContext) // { // queue.add(asyncContext); // } /** * Default constructor. */ public AuctionListener() { } @Override public void contextInitialized(ServletContextEvent sce) { springContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); jedisBean = springContext.getBean(JedisBean.class); jedis = jedisBean.getJedis(); logger.info("秒杀抢购功能已起动..."); thread = new Thread(new Runnable() { // private ObjectMapper mapper = new ObjectMapper(); @Override public void run() { while(true) { // try { // Thread.sleep(500); // } catch (InterruptedException e) { // e.printStackTrace(); // } // 1, 查找所有图书抢购队列 Set<String> keys = jedis.keys("auction:book:queue:*"); if (!CollectionUtils.isEmpty(keys)) { for (String auctionKey : keys) { String isbn = StringUtils.substringAfterLast(auctionKey, ":"); // 弹出一个userno数据 String userno = ""; List<String> resultList = jedis.blpop(1000, auctionKey); if (!CollectionUtils.isEmpty(resultList)) { userno = resultList.get(1); } // String userno = jedis.lpop(auctionKey); if (StringUtils.isNotBlank(userno)) { // 判断是否能抢到图书,auction:book:inventory Double inventoryQuantityD = jedis.zscore("auction:book:inventory", isbn); Integer inventoryQuantityI = inventoryQuantityD == null ? 0 : inventoryQuantityD.intValue(); AuctionResult result = new AuctionResult(); result.setIsbn(isbn); result.setUserno(userno); if (inventoryQuantityI > 0) { result.setQuality(1); result.setLeftQuality(inventoryQuantityI - 1); // 更新库存 jedis.zadd("auction:book:inventory", inventoryQuantityI - 1, isbn); } else { result.setQuality(0); result.setLeftQuality(0); } auctionResultMap.put(userno + ":" + isbn, result); } } } } /*while(true) { AsyncContext asyncContext = null; while (queue.peek() != null) { try { asyncContext = queue.poll(); ServletRequest request = asyncContext.getRequest(); ServletResponse response = asyncContext.getResponse(); response.setContentType(MediaType.APPLICATION_JSON_VALUE); PrintWriter writer = response.getWriter(); Thread.sleep(1000); String userno = request.getParameter("userno"); String threadName = Thread.currentThread().getName(); // 模拟计算时间 long startTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis(); String duration = String.valueOf((endTime - startTime) / 1000); Map<String, Object> map = new HashMap<String, Object>(); map.put("status", "success"); map.put("userno", userno); map.put("threadName", threadName); map.put("duration", duration); String jsonStr = mapper.writeValueAsString(map); writer.println(jsonStr); writer.close(); } catch (Exception e) { logger.error("", e); } finally { if (asyncContext != null) { try { asyncContext.complete(); } catch (Exception e) { logger.error("", e); } } } } }*/ } }); thread.start(); } @Override public void contextDestroyed(ServletContextEvent sce) { if (jedis != null) { jedis.keys("auction:book:queue:*"); jedisBean.closeJedis(jedis); } } }
UTF-8
Java
5,743
java
AuctionListener.java
Java
[]
null
[]
package com.cobee.bookstore.component.listener; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import javax.servlet.AsyncContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.util.CollectionUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.cobee.bookstore.component.JedisBean; import com.cobee.bookstore.vo.AuctionResult; import com.fasterxml.jackson.databind.ObjectMapper; import redis.clients.jedis.Jedis; /** * Application Lifecycle Listener implementation class AuctionListener * */ public class AuctionListener implements ServletContextListener { private static final Logger logger = LoggerFactory.getLogger(AuctionListener.class); // private static final BlockingQueue<AsyncContext> queue = new LinkedBlockingQueue<>(); public static final Map<String, AuctionResult> auctionResultMap = new HashMap<String, AuctionResult>(); private volatile Thread thread; private WebApplicationContext springContext; private JedisBean jedisBean; private Jedis jedis; // public static void addAsyncContext(AsyncContext asyncContext) // { // queue.add(asyncContext); // } /** * Default constructor. */ public AuctionListener() { } @Override public void contextInitialized(ServletContextEvent sce) { springContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); jedisBean = springContext.getBean(JedisBean.class); jedis = jedisBean.getJedis(); logger.info("秒杀抢购功能已起动..."); thread = new Thread(new Runnable() { // private ObjectMapper mapper = new ObjectMapper(); @Override public void run() { while(true) { // try { // Thread.sleep(500); // } catch (InterruptedException e) { // e.printStackTrace(); // } // 1, 查找所有图书抢购队列 Set<String> keys = jedis.keys("auction:book:queue:*"); if (!CollectionUtils.isEmpty(keys)) { for (String auctionKey : keys) { String isbn = StringUtils.substringAfterLast(auctionKey, ":"); // 弹出一个userno数据 String userno = ""; List<String> resultList = jedis.blpop(1000, auctionKey); if (!CollectionUtils.isEmpty(resultList)) { userno = resultList.get(1); } // String userno = jedis.lpop(auctionKey); if (StringUtils.isNotBlank(userno)) { // 判断是否能抢到图书,auction:book:inventory Double inventoryQuantityD = jedis.zscore("auction:book:inventory", isbn); Integer inventoryQuantityI = inventoryQuantityD == null ? 0 : inventoryQuantityD.intValue(); AuctionResult result = new AuctionResult(); result.setIsbn(isbn); result.setUserno(userno); if (inventoryQuantityI > 0) { result.setQuality(1); result.setLeftQuality(inventoryQuantityI - 1); // 更新库存 jedis.zadd("auction:book:inventory", inventoryQuantityI - 1, isbn); } else { result.setQuality(0); result.setLeftQuality(0); } auctionResultMap.put(userno + ":" + isbn, result); } } } } /*while(true) { AsyncContext asyncContext = null; while (queue.peek() != null) { try { asyncContext = queue.poll(); ServletRequest request = asyncContext.getRequest(); ServletResponse response = asyncContext.getResponse(); response.setContentType(MediaType.APPLICATION_JSON_VALUE); PrintWriter writer = response.getWriter(); Thread.sleep(1000); String userno = request.getParameter("userno"); String threadName = Thread.currentThread().getName(); // 模拟计算时间 long startTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis(); String duration = String.valueOf((endTime - startTime) / 1000); Map<String, Object> map = new HashMap<String, Object>(); map.put("status", "success"); map.put("userno", userno); map.put("threadName", threadName); map.put("duration", duration); String jsonStr = mapper.writeValueAsString(map); writer.println(jsonStr); writer.close(); } catch (Exception e) { logger.error("", e); } finally { if (asyncContext != null) { try { asyncContext.complete(); } catch (Exception e) { logger.error("", e); } } } } }*/ } }); thread.start(); } @Override public void contextDestroyed(ServletContextEvent sce) { if (jedis != null) { jedis.keys("auction:book:queue:*"); jedisBean.closeJedis(jedis); } } }
5,743
0.610119
0.605342
182
29.06044
23.813646
106
false
false
0
0
0
0
0
0
3.994505
false
false
2
25f03f2cf0ccfd38cb05c90ff980b7b43495ce0d
16,372,415,399,041
38d2ded3bfc43ca841a281c734531f359daca0e2
/src/unalcol/agents/NetworkSim/DataReplicationGraphBuilderScenario.java
8973d441c48217d5a5dedef7f37404d506f06a9a
[ "MIT" ]
permissive
arleserp/networkSimUN
https://github.com/arleserp/networkSimUN
8b34c30dd5e957c331e74dbf4d06100abb24bb18
64b72ac7aec7c19507253af8784e7ae9fb835de4
refs/heads/master
2021-01-23T12:57:43.236000
2019-03-15T14:06:29
2019-03-15T14:06:29
50,948,531
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package unalcol.agents.NetworkSim; import edu.uci.ics.jung.graph.Graph; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.Map; import java.util.Observer; // unalcol.agent.networkSim.reports.GraphicReportHealingObserver; import unalcol.agents.Agent; import unalcol.agents.AgentProgram; import unalcol.agents.simulate.util.SimpleLanguage; import java.util.Vector; import unalcol.agents.NetworkSim.environment.NetworkEnvironmentPheromoneReplicationTopologyBuilder; import unalcol.agents.NetworkSim.environment.NetworkEnvironmentReplicationTopologyBuilder; import unalcol.agents.NetworkSim.environment.NetworkMessageBuffer; import unalcol.agents.NetworkSim.util.GraphStats; //import unalcol.agents.NetworkSim.util.GraphStatistics; import unalcol.agents.NetworkSim.util.DataReplicationObserver; import unalcol.agents.NetworkSim.util.StringSerializer; /** * Creates a simulation without graphic interface * * @author arles.rodriguez */ public class DataReplicationGraphBuilderScenario implements Runnable { private NetworkEnvironmentReplicationTopologyBuilder world; public boolean renderAnts = true; public boolean renderSeeking = true; public boolean renderCarrying = true; int modo = 0; // GraphicReportHealingObserver greport; int executions = 0; int population = 100; int vertexNumber = 100; int channelNumber = 100; float probFailure = (float) 0.1; Hashtable<String, Object> positions; int width; int height; private Observer graphVisualization; ArrayList<GraphElements.MyVertex> locations; int indexLoc; /** * Creates a simulation without graphic interface * * @param pop * @param pf * @param width * @param height * @return */ DataReplicationGraphBuilderScenario(int pop, float pf) { population = pop; probFailure = pf; positions = new Hashtable<>(); //vertexNumber = nv; //channelNumber = ne; System.out.println("Pop: " + population); System.out.println("Pf: " + pf); System.out.println("Movement: " + SimulationParameters.motionAlg); indexLoc = 0; //System.out.println("Vertex Number: " + vertexNumber); //System.out.println("Channel Number: " + channelNumber); } /** * * Initializes simulation. */ public void init() { Vector<Agent> agents = new Vector(); System.out.println("fp" + probFailure); String[] _percepts = {"data", "neighbors"}; String[] _actions = {"move", "die"}; SimpleLanguage languaje = new SimpleLanguage(_percepts, _actions); //report = new reportHealingProgram(population, probFailure, this); //greport = new GraphicReportHealingObserver(probFailure); //Create graph Graph<GraphElements.MyVertex, String> g = graphSimpleFactory.createGraph(SimulationParameters.graphMode); //maybe to fix: alldata must have getter System.out.println("All data" + SimulationParameters.globalData); System.out.println("All data size" + SimulationParameters.globalData.size()); // System.out.println("Average Path Length: " + GraphStatistics.computeAveragePathLength(g)); Map<GraphElements.MyVertex, Double> m = GraphStats.clusteringCoefficients(g); System.out.println("Clustering coeficients:" + m); System.out.println("Average Clustering Coefficient: " + GraphStats.averageCC(g)); System.out.println("Average degree: " + GraphStats.averageDegree(g)); if (SimulationParameters.filenameLoc.length() > 1) { loadLocations(); } //Creates "Agents" for (int i = 0; i < population; i++) { AgentProgram program = MotionProgramSimpleFactory.createMotionProgram(probFailure, SimulationParameters.motionAlg); MobileAgent a = new MobileAgent(program, i); GraphElements.MyVertex tmp = getLocation(g); System.out.println("tmp" + tmp); a.setLocation(tmp); a.setProgram(program); a.setAttribute("infi", new ArrayList<String>()); NetworkMessageBuffer.getInstance().createBuffer(a.getId()); agents.add(a); } graphVisualization = new DataReplicationObserver(); world = new NetworkEnvironmentPheromoneReplicationTopologyBuilder(agents, languaje, g); world.addObserver(graphVisualization); //greport.addObserver(world); world.not(); world.run(); executions++; /* world.updateSandC(); world.calculateGlobalInfo(); world.nObservers(); */ } /** * Runs a simulation. * */ @Override public void run() { try { while (true) { //!world.isFinished()) { Thread.sleep(30); //System.out.println("halo"); /* world.updateSandC(); world.calculateGlobalInfo(); if (world.getAge() % 2 == 0 || world.getAgentsDie() == world.getAgents().size() || world.getRoundGetInfo() != -1) { world.nObservers(); } */ if (world instanceof NetworkEnvironmentPheromoneReplicationTopologyBuilder && SimulationParameters.motionAlg.equals("carriers")) { ((NetworkEnvironmentPheromoneReplicationTopologyBuilder) world).evaporatePheromone(); } /* if (world instanceof WorldTemperaturesOneStepOnePheromoneHybridLWEvaporationImpl) { ((WorldTemperaturesOneStepOnePheromoneHybridLWEvaporationImpl) world).evaporatePheromone(); } if (world instanceof WorldTemperaturesOneStepOnePheromoneHybridLWEvaporationImpl2) { ((WorldTemperaturesOneStepOnePheromoneHybridLWEvaporationImpl2) world).evaporatePheromone(); } if (world instanceof WorldLwphCLwEvapImpl) { ((WorldLwphCLwEvapImpl) world).evaporatePheromone(); }*/ } } catch (InterruptedException e) { System.out.println("interrupted!"); } /* System.out.println("End WorldThread");*/ } public void loadLocations() { StringSerializer s = new StringSerializer(); locations = (ArrayList<GraphElements.MyVertex>) s.loadDeserializeObject(SimulationParameters.filenameLoc); } private GraphElements.MyVertex getLocation(Graph<GraphElements.MyVertex, String> g) { if (SimulationParameters.filenameLoc.length() > 1) { GraphElements.MyVertex tmp = locations.get(indexLoc++); for (GraphElements.MyVertex v : g.getVertices()) { if (v.toString().equals(tmp.toString())) { return v; } } System.out.println("null???"); return null; } else { int pos = (int) (Math.random() * g.getVertexCount()); Collection E = g.getVertices(); return (GraphElements.MyVertex) E.toArray()[pos]; } } }
UTF-8
Java
7,548
java
DataReplicationGraphBuilderScenario.java
Java
[ { "context": "mulation without graphic interface\r\n *\r\n * @author arles.rodriguez\r\n */\r\npublic class DataReplicationGraphBuilderSce", "end": 1197, "score": 0.9779571890830994, "start": 1182, "tag": "NAME", "value": "arles.rodriguez" } ]
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 unalcol.agents.NetworkSim; import edu.uci.ics.jung.graph.Graph; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.Map; import java.util.Observer; // unalcol.agent.networkSim.reports.GraphicReportHealingObserver; import unalcol.agents.Agent; import unalcol.agents.AgentProgram; import unalcol.agents.simulate.util.SimpleLanguage; import java.util.Vector; import unalcol.agents.NetworkSim.environment.NetworkEnvironmentPheromoneReplicationTopologyBuilder; import unalcol.agents.NetworkSim.environment.NetworkEnvironmentReplicationTopologyBuilder; import unalcol.agents.NetworkSim.environment.NetworkMessageBuffer; import unalcol.agents.NetworkSim.util.GraphStats; //import unalcol.agents.NetworkSim.util.GraphStatistics; import unalcol.agents.NetworkSim.util.DataReplicationObserver; import unalcol.agents.NetworkSim.util.StringSerializer; /** * Creates a simulation without graphic interface * * @author arles.rodriguez */ public class DataReplicationGraphBuilderScenario implements Runnable { private NetworkEnvironmentReplicationTopologyBuilder world; public boolean renderAnts = true; public boolean renderSeeking = true; public boolean renderCarrying = true; int modo = 0; // GraphicReportHealingObserver greport; int executions = 0; int population = 100; int vertexNumber = 100; int channelNumber = 100; float probFailure = (float) 0.1; Hashtable<String, Object> positions; int width; int height; private Observer graphVisualization; ArrayList<GraphElements.MyVertex> locations; int indexLoc; /** * Creates a simulation without graphic interface * * @param pop * @param pf * @param width * @param height * @return */ DataReplicationGraphBuilderScenario(int pop, float pf) { population = pop; probFailure = pf; positions = new Hashtable<>(); //vertexNumber = nv; //channelNumber = ne; System.out.println("Pop: " + population); System.out.println("Pf: " + pf); System.out.println("Movement: " + SimulationParameters.motionAlg); indexLoc = 0; //System.out.println("Vertex Number: " + vertexNumber); //System.out.println("Channel Number: " + channelNumber); } /** * * Initializes simulation. */ public void init() { Vector<Agent> agents = new Vector(); System.out.println("fp" + probFailure); String[] _percepts = {"data", "neighbors"}; String[] _actions = {"move", "die"}; SimpleLanguage languaje = new SimpleLanguage(_percepts, _actions); //report = new reportHealingProgram(population, probFailure, this); //greport = new GraphicReportHealingObserver(probFailure); //Create graph Graph<GraphElements.MyVertex, String> g = graphSimpleFactory.createGraph(SimulationParameters.graphMode); //maybe to fix: alldata must have getter System.out.println("All data" + SimulationParameters.globalData); System.out.println("All data size" + SimulationParameters.globalData.size()); // System.out.println("Average Path Length: " + GraphStatistics.computeAveragePathLength(g)); Map<GraphElements.MyVertex, Double> m = GraphStats.clusteringCoefficients(g); System.out.println("Clustering coeficients:" + m); System.out.println("Average Clustering Coefficient: " + GraphStats.averageCC(g)); System.out.println("Average degree: " + GraphStats.averageDegree(g)); if (SimulationParameters.filenameLoc.length() > 1) { loadLocations(); } //Creates "Agents" for (int i = 0; i < population; i++) { AgentProgram program = MotionProgramSimpleFactory.createMotionProgram(probFailure, SimulationParameters.motionAlg); MobileAgent a = new MobileAgent(program, i); GraphElements.MyVertex tmp = getLocation(g); System.out.println("tmp" + tmp); a.setLocation(tmp); a.setProgram(program); a.setAttribute("infi", new ArrayList<String>()); NetworkMessageBuffer.getInstance().createBuffer(a.getId()); agents.add(a); } graphVisualization = new DataReplicationObserver(); world = new NetworkEnvironmentPheromoneReplicationTopologyBuilder(agents, languaje, g); world.addObserver(graphVisualization); //greport.addObserver(world); world.not(); world.run(); executions++; /* world.updateSandC(); world.calculateGlobalInfo(); world.nObservers(); */ } /** * Runs a simulation. * */ @Override public void run() { try { while (true) { //!world.isFinished()) { Thread.sleep(30); //System.out.println("halo"); /* world.updateSandC(); world.calculateGlobalInfo(); if (world.getAge() % 2 == 0 || world.getAgentsDie() == world.getAgents().size() || world.getRoundGetInfo() != -1) { world.nObservers(); } */ if (world instanceof NetworkEnvironmentPheromoneReplicationTopologyBuilder && SimulationParameters.motionAlg.equals("carriers")) { ((NetworkEnvironmentPheromoneReplicationTopologyBuilder) world).evaporatePheromone(); } /* if (world instanceof WorldTemperaturesOneStepOnePheromoneHybridLWEvaporationImpl) { ((WorldTemperaturesOneStepOnePheromoneHybridLWEvaporationImpl) world).evaporatePheromone(); } if (world instanceof WorldTemperaturesOneStepOnePheromoneHybridLWEvaporationImpl2) { ((WorldTemperaturesOneStepOnePheromoneHybridLWEvaporationImpl2) world).evaporatePheromone(); } if (world instanceof WorldLwphCLwEvapImpl) { ((WorldLwphCLwEvapImpl) world).evaporatePheromone(); }*/ } } catch (InterruptedException e) { System.out.println("interrupted!"); } /* System.out.println("End WorldThread");*/ } public void loadLocations() { StringSerializer s = new StringSerializer(); locations = (ArrayList<GraphElements.MyVertex>) s.loadDeserializeObject(SimulationParameters.filenameLoc); } private GraphElements.MyVertex getLocation(Graph<GraphElements.MyVertex, String> g) { if (SimulationParameters.filenameLoc.length() > 1) { GraphElements.MyVertex tmp = locations.get(indexLoc++); for (GraphElements.MyVertex v : g.getVertices()) { if (v.toString().equals(tmp.toString())) { return v; } } System.out.println("null???"); return null; } else { int pos = (int) (Math.random() * g.getVertexCount()); Collection E = g.getVertices(); return (GraphElements.MyVertex) E.toArray()[pos]; } } }
7,548
0.628908
0.625729
194
36.907215
30.509787
146
false
false
0
0
0
0
0
0
0.649485
false
false
2
a008d8301ed91fd308a9a2885dc9f2e7273745f1
27,410,481,332,490
552baf16cf2a259937e01cd56a59d2824b22859b
/src/main/java/info/beastsoftware/beastcore/command/MobHoppersCommand.java
8a6132ac4d3a5b36a9db07fd9244f8a34509f4c0
[]
no_license
daniel097541/ThaBeastCore
https://github.com/daniel097541/ThaBeastCore
7f335653a912a04682d277b865022cb9075595fd
f5565147fcf52ae25bd35be4309a0190c9856a1c
refs/heads/master
2021-03-24T19:48:27.066000
2020-07-18T21:36:44
2020-07-18T21:36:44
247,560,629
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package info.beastsoftware.beastcore.command; import info.beastsoftware.beastcore.BeastCore; import info.beastsoftware.beastcore.beastutils.config.IConfig; import info.beastsoftware.beastcore.beastutils.utils.IInventoryUtil; import info.beastsoftware.beastcore.struct.CommandType; import info.beastsoftware.beastcore.struct.FeatureType; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.util.List; public class MobHoppersCommand extends BeastCommand { public MobHoppersCommand(BeastCore plugin, IConfig config) { super(plugin, config, CommandType.MOB_HOPPER, FeatureType.MOB_HOPPERS); addAlias("mobh"); } @Override public void run(CommandSender sender, String[] args) { if (args.length < 4 || !args[0].equalsIgnoreCase("give")) { for (String message : config.getConfig().getStringList("Mob-Hoppers.command.formats")) plugin.sms(sender, message); return; } Player player = Bukkit.getPlayer(args[1]); //not online if (player == null) { plugin.sms(sender, config.getConfig().getString("Mob-Hoppers.command.player-not-online")); return; } //not a mob String MOBPLACEHOLDER = "{mob}"; if (!config.getConfig().getStringList("Mob-Hoppers.Settings.mob-list").contains(args[2].toUpperCase())) { //send error in mob message String message = config.getConfig().getString("Mob-Hoppers.command.not-allowed-mob"); message = stringUtils.replacePlaceholder(message, MOBPLACEHOLDER, args[2].toUpperCase()); plugin.sms(sender, message); return; } int number = 1; if (args.length == 4) { try { number = Integer.parseInt(args[3]); } catch (NumberFormatException e) { plugin.sms(player, "Introduce a number!"); return; } } //info for the hopper String basePath = "Mob-Hoppers.Item."; String name = ChatColor.translateAlternateColorCodes('&', stringUtils.replacePlaceholder(config.getConfig().getString(basePath + "name"), MOBPLACEHOLDER, args[2].toUpperCase())); List<String> lore = stringUtils.translateLore(config.getConfig().getStringList(basePath + "lore")); //create the hopper ItemStack itemStack = IInventoryUtil.createItem(1, Material.HOPPER, name, lore, true); //check empty slots int slot = IInventoryUtil.hasEmptySlot(player.getInventory(), itemStack); boolean empty = IInventoryUtil.hasEmptySlot(player.getInventory()); //no empty slots if (!empty && slot < 0 || number > 64) { plugin.sms(sender, config.getConfig().getString("Mob-Hoppers.command.no-slot")); return; } //add item to the inventory IInventoryUtil.addItem(itemStack, player, empty, number, slot); //send messages to sender and reciever String recieveMessage = config.getConfig().getString("Mob-Hoppers.command.recieve-message"); recieveMessage = stringUtils.replacePlaceholder(recieveMessage, MOBPLACEHOLDER, args[2].toUpperCase()); plugin.sms(player, stringUtils.replacePlaceholder(recieveMessage, "{number}", number + "")); String giveMessage = config.getConfig().getString("Mob-Hoppers.command.give-message"); giveMessage = stringUtils.replacePlaceholder(giveMessage, "{number}", number + ""); giveMessage = stringUtils.replacePlaceholder(giveMessage, "{player}", player.getName()); giveMessage = stringUtils.replacePlaceholder(giveMessage, MOBPLACEHOLDER, args[2].toUpperCase()); plugin.sms(sender, giveMessage); } }
UTF-8
Java
3,907
java
MobHoppersCommand.java
Java
[]
null
[]
package info.beastsoftware.beastcore.command; import info.beastsoftware.beastcore.BeastCore; import info.beastsoftware.beastcore.beastutils.config.IConfig; import info.beastsoftware.beastcore.beastutils.utils.IInventoryUtil; import info.beastsoftware.beastcore.struct.CommandType; import info.beastsoftware.beastcore.struct.FeatureType; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.util.List; public class MobHoppersCommand extends BeastCommand { public MobHoppersCommand(BeastCore plugin, IConfig config) { super(plugin, config, CommandType.MOB_HOPPER, FeatureType.MOB_HOPPERS); addAlias("mobh"); } @Override public void run(CommandSender sender, String[] args) { if (args.length < 4 || !args[0].equalsIgnoreCase("give")) { for (String message : config.getConfig().getStringList("Mob-Hoppers.command.formats")) plugin.sms(sender, message); return; } Player player = Bukkit.getPlayer(args[1]); //not online if (player == null) { plugin.sms(sender, config.getConfig().getString("Mob-Hoppers.command.player-not-online")); return; } //not a mob String MOBPLACEHOLDER = "{mob}"; if (!config.getConfig().getStringList("Mob-Hoppers.Settings.mob-list").contains(args[2].toUpperCase())) { //send error in mob message String message = config.getConfig().getString("Mob-Hoppers.command.not-allowed-mob"); message = stringUtils.replacePlaceholder(message, MOBPLACEHOLDER, args[2].toUpperCase()); plugin.sms(sender, message); return; } int number = 1; if (args.length == 4) { try { number = Integer.parseInt(args[3]); } catch (NumberFormatException e) { plugin.sms(player, "Introduce a number!"); return; } } //info for the hopper String basePath = "Mob-Hoppers.Item."; String name = ChatColor.translateAlternateColorCodes('&', stringUtils.replacePlaceholder(config.getConfig().getString(basePath + "name"), MOBPLACEHOLDER, args[2].toUpperCase())); List<String> lore = stringUtils.translateLore(config.getConfig().getStringList(basePath + "lore")); //create the hopper ItemStack itemStack = IInventoryUtil.createItem(1, Material.HOPPER, name, lore, true); //check empty slots int slot = IInventoryUtil.hasEmptySlot(player.getInventory(), itemStack); boolean empty = IInventoryUtil.hasEmptySlot(player.getInventory()); //no empty slots if (!empty && slot < 0 || number > 64) { plugin.sms(sender, config.getConfig().getString("Mob-Hoppers.command.no-slot")); return; } //add item to the inventory IInventoryUtil.addItem(itemStack, player, empty, number, slot); //send messages to sender and reciever String recieveMessage = config.getConfig().getString("Mob-Hoppers.command.recieve-message"); recieveMessage = stringUtils.replacePlaceholder(recieveMessage, MOBPLACEHOLDER, args[2].toUpperCase()); plugin.sms(player, stringUtils.replacePlaceholder(recieveMessage, "{number}", number + "")); String giveMessage = config.getConfig().getString("Mob-Hoppers.command.give-message"); giveMessage = stringUtils.replacePlaceholder(giveMessage, "{number}", number + ""); giveMessage = stringUtils.replacePlaceholder(giveMessage, "{player}", player.getName()); giveMessage = stringUtils.replacePlaceholder(giveMessage, MOBPLACEHOLDER, args[2].toUpperCase()); plugin.sms(sender, giveMessage); } }
3,907
0.664192
0.660353
93
41.010754
37.230896
186
false
false
0
0
0
0
0
0
0.924731
false
false
2
7c67631a85a839fbd1ba8b64b3ca915604c4db2f
8,478,265,506,364
51a1ea8a44f8509e86e9381d053925fc3dfa8897
/src/main/java/com/dzzxjl/本地方法/Main.java
0dc0629580b8b7a451bf99a7965a83cec6aa4dd4
[]
no_license
dzzxjl/get-along-with-java
https://github.com/dzzxjl/get-along-with-java
1bd4603fcf3fe52f792ad4de6fad8cfe3df2eee9
fb526707913a09163de0dbc775dea57e636e7ab0
refs/heads/master
2021-01-02T08:13:42.543000
2017-09-10T14:30:16
2017-09-10T14:30:16
98,966,846
0
0
null
false
2017-08-13T10:11:01
2017-08-01T06:21:02
2017-08-09T03:41:34
2017-08-13T10:11:01
108
0
0
0
Java
null
null
package com.dzzxjl.本地方法; public class Main { public static void main(String[] args) { String string1 = "helloworld"; System.out.println(string1.hashCode()); String string2 = "helloworld"; System.out.println(string2.hashCode()); System.out.println(string2.intern().hashCode()); } }
UTF-8
Java
339
java
Main.java
Java
[ { "context": "d main(String[] args) {\n String string1 = \"helloworld\";\n System.out.println(string1.hashCode());", "end": 127, "score": 0.9809767603874207, "start": 117, "tag": "USERNAME", "value": "helloworld" }, { "context": "n(string1.hashCode());\n\n String string2 = \"helloworld\";\n System.out.println(string2.hashCode());", "end": 215, "score": 0.8222339749336243, "start": 205, "tag": "USERNAME", "value": "helloworld" } ]
null
[]
package com.dzzxjl.本地方法; public class Main { public static void main(String[] args) { String string1 = "helloworld"; System.out.println(string1.hashCode()); String string2 = "helloworld"; System.out.println(string2.hashCode()); System.out.println(string2.intern().hashCode()); } }
339
0.634441
0.619335
12
26.583334
20.126509
56
false
false
0
0
0
0
0
0
0.5
false
false
2
00a586ed09a3b023fdcecb291fbf95df6047666f
6,158,983,164,363
642d875a27ccc0dab6d9e81c9b09e3b6d5fcaf1a
/src/main/java/com/shiroapache/config/ShiroConfig.java
81b58b66b72b10b1f0db9f79b8ae42a384d9173f
[]
no_license
yiSmilehow/springboot_shiro
https://github.com/yiSmilehow/springboot_shiro
dea4ea2d053ff7bc23e100a935b620692543f1f1
402b58824f701a71221c9c6f4e5783793098c585
refs/heads/master
2022-07-07T00:27:20.522000
2020-05-19T14:49:30
2020-05-19T14:49:30
247,225,158
0
0
null
false
2022-06-21T02:59:02
2020-03-14T06:34:22
2020-05-19T14:50:13
2022-06-21T02:58:59
66
0
0
2
Java
false
false
package com.shiroapache.config; import com.shiroapache.pojo.Resources; import com.shiroapache.service.ResourcesService; import com.shiroapache.web.shiro.ShiroRealm; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.Resource; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * spring_shrio.xml整合到springboot */ @Configuration public class ShiroConfig { @Resource private ResourcesService resourcesService; /** * 构造securityManager * 核心组件 * * @return */ @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(realm()); return securityManager; } /** * 自定义realm类 * * @return */ @Bean public ShiroRealm realm() { ShiroRealm realm = new ShiroRealm(); realm.setCredentialsMatcher(credentialsMatcher()); return realm; } /** * 构造加密算法 * * @return */ @Bean public HashedCredentialsMatcher credentialsMatcher() { HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(); credentialsMatcher.setHashAlgorithmName("MD5"); credentialsMatcher.setHashIterations(1000); return credentialsMatcher; } /** * 自定义资源权限 * * @return */ @Bean public ShiroFilterChainDefinition filterChainDefinition() { DefaultShiroFilterChainDefinition filterChainDefinition = new DefaultShiroFilterChainDefinition(); filterChainDefinition.addPathDefinitions(builder()); return filterChainDefinition; } /** * 查询所有的资源权限 * * @return */ public Map<String, String> builder() { Map<String, String> map = new LinkedHashMap<String, String>(); List<Resources> resourcesList = resourcesService.selectAllByStatusAndSortNumAsc(); for (Resources resources : resourcesList) { map.put(resources.getKey(), resources.getVal()); } return map; } }
UTF-8
Java
2,528
java
ShiroConfig.java
Java
[]
null
[]
package com.shiroapache.config; import com.shiroapache.pojo.Resources; import com.shiroapache.service.ResourcesService; import com.shiroapache.web.shiro.ShiroRealm; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.Resource; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * spring_shrio.xml整合到springboot */ @Configuration public class ShiroConfig { @Resource private ResourcesService resourcesService; /** * 构造securityManager * 核心组件 * * @return */ @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(realm()); return securityManager; } /** * 自定义realm类 * * @return */ @Bean public ShiroRealm realm() { ShiroRealm realm = new ShiroRealm(); realm.setCredentialsMatcher(credentialsMatcher()); return realm; } /** * 构造加密算法 * * @return */ @Bean public HashedCredentialsMatcher credentialsMatcher() { HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(); credentialsMatcher.setHashAlgorithmName("MD5"); credentialsMatcher.setHashIterations(1000); return credentialsMatcher; } /** * 自定义资源权限 * * @return */ @Bean public ShiroFilterChainDefinition filterChainDefinition() { DefaultShiroFilterChainDefinition filterChainDefinition = new DefaultShiroFilterChainDefinition(); filterChainDefinition.addPathDefinitions(builder()); return filterChainDefinition; } /** * 查询所有的资源权限 * * @return */ public Map<String, String> builder() { Map<String, String> map = new LinkedHashMap<String, String>(); List<Resources> resourcesList = resourcesService.selectAllByStatusAndSortNumAsc(); for (Resources resources : resourcesList) { map.put(resources.getKey(), resources.getVal()); } return map; } }
2,528
0.69406
0.692026
90
26.311111
25.433418
106
false
false
0
0
0
0
0
0
0.4
false
false
2
97dd0b37b388b4dacbf1950b6f91d3a779aa0b0f
27,762,668,655,860
eb201a0afe4859bfd1ac7b12291a4ab2cdfc36a1
/Subasta/src/main/java/App/NotificacionSubasta.java
a3c9df5ea344fcd310e8a9d9e61dd69837c61f54
[]
no_license
nanococo/Proyecto4_POO
https://github.com/nanococo/Proyecto4_POO
9bd627e6f75d16325890dd8d56ba95ed91f39e87
3cda346435c81b037623e09c36fd6b3787382d6f
refs/heads/master
2022-12-05T18:27:24.726000
2020-08-09T02:07:18
2020-08-09T02:07:18
286,145,177
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package Subastas; import Observer.Notification; public class NotificacionSubasta extends Notification { NotificacionSubasta(){ } }
UTF-8
Java
145
java
NotificacionSubasta.java
Java
[]
null
[]
package Subastas; import Observer.Notification; public class NotificacionSubasta extends Notification { NotificacionSubasta(){ } }
145
0.751724
0.751724
11
12.090909
17.185905
55
false
false
0
0
0
0
0
0
0.181818
false
false
2