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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eb726151fb15bf331ca40b47e294cbc0db41942e | 867,583,420,179 | 74c348a21bd71279d09a01f4be4a7912f5f4faf6 | /src/main/java/com/example/time/leetcode/FindTargetSumWays.java | 625bcba2f4101b8249e537cd247fb67b9302a6f6 | []
| no_license | jiafeng123456/Demo | https://github.com/jiafeng123456/Demo | 848257d84d1530fdff3d102b30c2fc39e7bd1931 | 8fe2b328ef65596df98f373a7c059dd6aeb3f214 | refs/heads/master | 2022-07-06T19:41:50.262000 | 2021-02-18T06:53:22 | 2021-02-18T06:53:22 | 215,752,044 | 0 | 0 | null | false | 2020-10-10T07:24:19 | 2019-10-17T09:18:17 | 2020-10-10T07:24:01 | 2020-10-10T07:24:18 | 6,816 | 0 | 0 | 1 | Java | false | false | package com.example.time.leetcode;
/*
*@description:
*@author jiafeng
*@date 2020/10/9 0009 08:54
*/
public class FindTargetSumWays {
public static void main(String[] args) {
}
public static int findTargetSumWays(int[] nums, int S) {
return 0;
}
}
| UTF-8 | Java | 281 | java | FindTargetSumWays.java | Java | [
{
"context": "ample.time.leetcode;\n\n/*\n *@description:\n *@author jiafeng\n *@date 2020/10/9 0009 08:54\n */\npublic class Fin",
"end": 72,
"score": 0.9862048625946045,
"start": 65,
"tag": "USERNAME",
"value": "jiafeng"
}
]
| null | []
| package com.example.time.leetcode;
/*
*@description:
*@author jiafeng
*@date 2020/10/9 0009 08:54
*/
public class FindTargetSumWays {
public static void main(String[] args) {
}
public static int findTargetSumWays(int[] nums, int S) {
return 0;
}
}
| 281 | 0.640569 | 0.58363 | 18 | 14.611111 | 17.518684 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 15 |
ca6e057af2718232562bdedc423ff7fb34a547f6 | 35,785,667,510,880 | 91377530e214896d6ed1989c9a106277f7ebd9fc | /src/ui/InterfaceCPCadastro.java | a3cc9231d18a3e6404054f251cc7ab7011e7c02b | []
| no_license | jhenriquedsilva/final-project-oop | https://github.com/jhenriquedsilva/final-project-oop | ce0fdeca4f61578caf3dd552626c9fdc85274860 | a19a8b593cd1ced14ce3b2756252259e0386f4d0 | refs/heads/master | 2023-08-07T22:01:01.830000 | 2021-10-04T14:20:57 | 2021-10-04T14:20:57 | 410,104,421 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ui;
import recursos.Cores;
import java.util.Scanner;
import db.Banco;
import humanos.Cliente;
public class InterfaceCPCadastro extends Cadastro implements Interface {
private Scanner scanner = new Scanner(System.in);
private Banco db = Banco.instancia();
private Cliente cliente;
@Override
public void fazerCadastro() {
return;
}
/**
* Exibe a interface de login para o usuário
*/
@Override
public void entrarComCadastro() {
String senhaCliente;
String eMailCliente;
do {
System.out.println(Cores.ANSI_YELLOW_2 + " CADASTRO" + Cores.ANSI_RESET);
System.out.print(Cores.ANSI_GREEN_2 + """
[E-mail]: """ + Cores.ANSI_RESET);
eMailCliente = scanner.nextLine();
System.out.print(Cores.ANSI_GREEN_2 + """
[Senha]: """ + Cores.ANSI_RESET);
senhaCliente = scanner.nextLine();
cliente = db.buscarCliente(eMailCliente, senhaCliente);
} while (cliente == null);
}
/**
* Exibe a interface de login para o usuário
*/
@Override
public void mostrarInterface() {
entrarComCadastro();
new InterfaceProdutos().mostrarInterface(cliente);
new InterfaceFinalizarCompra().mostrarInterface(cliente);
}
}
| UTF-8 | Java | 1,236 | java | InterfaceCPCadastro.java | Java | []
| null | []
| package ui;
import recursos.Cores;
import java.util.Scanner;
import db.Banco;
import humanos.Cliente;
public class InterfaceCPCadastro extends Cadastro implements Interface {
private Scanner scanner = new Scanner(System.in);
private Banco db = Banco.instancia();
private Cliente cliente;
@Override
public void fazerCadastro() {
return;
}
/**
* Exibe a interface de login para o usuário
*/
@Override
public void entrarComCadastro() {
String senhaCliente;
String eMailCliente;
do {
System.out.println(Cores.ANSI_YELLOW_2 + " CADASTRO" + Cores.ANSI_RESET);
System.out.print(Cores.ANSI_GREEN_2 + """
[E-mail]: """ + Cores.ANSI_RESET);
eMailCliente = scanner.nextLine();
System.out.print(Cores.ANSI_GREEN_2 + """
[Senha]: """ + Cores.ANSI_RESET);
senhaCliente = scanner.nextLine();
cliente = db.buscarCliente(eMailCliente, senhaCliente);
} while (cliente == null);
}
/**
* Exibe a interface de login para o usuário
*/
@Override
public void mostrarInterface() {
entrarComCadastro();
new InterfaceProdutos().mostrarInterface(cliente);
new InterfaceFinalizarCompra().mostrarInterface(cliente);
}
}
| 1,236 | 0.666126 | 0.663695 | 51 | 23.196079 | 21.6605 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.431373 | false | false | 15 |
ba5e1fa9868d7e028cad71c5c5d5d5b4993d9548 | 29,841,432,830,510 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/22/22_22cdd9bdb68a6d573e649575409121a8be2f92d2/PtuSettings/22_22cdd9bdb68a6d573e649575409121a8be2f92d2_PtuSettings_t.java | f351145330e79a61ee915e7ed3f3212a2da81e5f | []
| no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | package ch.cern.atlas.apvs.client.settings;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import ch.cern.atlas.apvs.client.ui.CameraView;
/**
*
* @author duns
*
*/
public class PtuSettings implements Serializable {
private static final long serialVersionUID = -5390424254145424045L;
private static final String videoServer = "pcatlaswpss02";
private Map<String, Entry> entries = new HashMap<String, Entry>();
public static class Entry implements Serializable {
private static final long serialVersionUID = 1L;
Boolean enabled;
String dosimeterSerialNo;
String helmetUrl;
String handUrl;
public Entry() {
// Serializable
}
public Entry(String ptuId) {
enabled = true;
dosimeterSerialNo = "";
String id = Integer.toHexString(Integer.parseInt(ptuId.substring(ptuId.length()-1, ptuId.length())));
helmetUrl = "http://"+videoServer+":8"+id+"90/worker"+id+".mjpg";
handUrl = "http://"+videoServer+":8"+id+"91/worker"+id+".mjpg";
}
@Override
public String toString() {
return "PtuSetting: enabled=" + enabled + " dosimeterNo="
+ dosimeterSerialNo + " helmetUrl=" + helmetUrl
+ " handUrl=" + handUrl;
}
}
public PtuSettings() {
}
public HashMap<String, String> getDosimeterToPtuMap() {
HashMap<String, String> dosimeterToPtu = new HashMap<String, String>();
// takes the last proper value
for (Iterator<String> i = entries.keySet().iterator(); i.hasNext();) {
String ptuId = i.next();
String serialNo = entries.get(ptuId).dosimeterSerialNo;
if ((ptuId != null) && (serialNo != null)) {
dosimeterToPtu.put(serialNo, ptuId);
}
}
return dosimeterToPtu;
}
public Boolean isEnabled(String ptuId) {
Entry entry = entries.get(ptuId);
return entry != null ? entry.enabled : false;
}
public void setEnabled(String object, Boolean value) {
entries.get(object).enabled = value;
}
public String getDosimeterSerialNumber(String ptuId) {
Entry entry = entries.get(ptuId);
return entry != null ? entry.dosimeterSerialNo : "";
}
public void setDosimeterSerialNumber(String object, String value) {
entries.get(object).dosimeterSerialNo = value;
}
public String getCameraUrl(String ptuId, String type) {
Entry entry = entries.get(ptuId);
return entry != null ? type.equals(CameraView.HELMET) ? entry.helmetUrl
: entry.handUrl : "";
}
public void setCameraUrl(String ptuId, String type, String value) {
if (type.equals(CameraView.HELMET)) {
entries.get(ptuId).helmetUrl = value;
} else {
entries.get(ptuId).handUrl = value;
}
}
public List<String> getPtuIds() {
List<String> list = new ArrayList<String>();
list.addAll(entries.keySet());
return list;
}
public boolean add(String ptuId) {
if (!entries.containsKey(ptuId)) {
entries.put(ptuId, new Entry(ptuId));
return true;
}
return false;
}
// Returns ptuId associated to dosimeterSerialNo
public String getPtuId(String dosimeterSerialNo) {
return getDosimeterToPtuMap().get(dosimeterSerialNo);
}
}
| UTF-8 | Java | 3,235 | java | 22_22cdd9bdb68a6d573e649575409121a8be2f92d2_PtuSettings_t.java | Java | [
{
"context": "apvs.client.ui.CameraView;\n \n /**\n * \n * @author duns\n * \n */\n public class PtuSettings implements Se",
"end": 287,
"score": 0.9992045164108276,
"start": 283,
"tag": "USERNAME",
"value": "duns"
}
]
| null | []
| package ch.cern.atlas.apvs.client.settings;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import ch.cern.atlas.apvs.client.ui.CameraView;
/**
*
* @author duns
*
*/
public class PtuSettings implements Serializable {
private static final long serialVersionUID = -5390424254145424045L;
private static final String videoServer = "pcatlaswpss02";
private Map<String, Entry> entries = new HashMap<String, Entry>();
public static class Entry implements Serializable {
private static final long serialVersionUID = 1L;
Boolean enabled;
String dosimeterSerialNo;
String helmetUrl;
String handUrl;
public Entry() {
// Serializable
}
public Entry(String ptuId) {
enabled = true;
dosimeterSerialNo = "";
String id = Integer.toHexString(Integer.parseInt(ptuId.substring(ptuId.length()-1, ptuId.length())));
helmetUrl = "http://"+videoServer+":8"+id+"90/worker"+id+".mjpg";
handUrl = "http://"+videoServer+":8"+id+"91/worker"+id+".mjpg";
}
@Override
public String toString() {
return "PtuSetting: enabled=" + enabled + " dosimeterNo="
+ dosimeterSerialNo + " helmetUrl=" + helmetUrl
+ " handUrl=" + handUrl;
}
}
public PtuSettings() {
}
public HashMap<String, String> getDosimeterToPtuMap() {
HashMap<String, String> dosimeterToPtu = new HashMap<String, String>();
// takes the last proper value
for (Iterator<String> i = entries.keySet().iterator(); i.hasNext();) {
String ptuId = i.next();
String serialNo = entries.get(ptuId).dosimeterSerialNo;
if ((ptuId != null) && (serialNo != null)) {
dosimeterToPtu.put(serialNo, ptuId);
}
}
return dosimeterToPtu;
}
public Boolean isEnabled(String ptuId) {
Entry entry = entries.get(ptuId);
return entry != null ? entry.enabled : false;
}
public void setEnabled(String object, Boolean value) {
entries.get(object).enabled = value;
}
public String getDosimeterSerialNumber(String ptuId) {
Entry entry = entries.get(ptuId);
return entry != null ? entry.dosimeterSerialNo : "";
}
public void setDosimeterSerialNumber(String object, String value) {
entries.get(object).dosimeterSerialNo = value;
}
public String getCameraUrl(String ptuId, String type) {
Entry entry = entries.get(ptuId);
return entry != null ? type.equals(CameraView.HELMET) ? entry.helmetUrl
: entry.handUrl : "";
}
public void setCameraUrl(String ptuId, String type, String value) {
if (type.equals(CameraView.HELMET)) {
entries.get(ptuId).helmetUrl = value;
} else {
entries.get(ptuId).handUrl = value;
}
}
public List<String> getPtuIds() {
List<String> list = new ArrayList<String>();
list.addAll(entries.keySet());
return list;
}
public boolean add(String ptuId) {
if (!entries.containsKey(ptuId)) {
entries.put(ptuId, new Entry(ptuId));
return true;
}
return false;
}
// Returns ptuId associated to dosimeterSerialNo
public String getPtuId(String dosimeterSerialNo) {
return getDosimeterToPtuMap().get(dosimeterSerialNo);
}
}
| 3,235 | 0.678516 | 0.669552 | 121 | 25.727272 | 24.015835 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.818182 | false | false | 15 |
1df9266e98c1ca705749cb8722e36090a0be3efd | 12,446,815,224,349 | 59f442cadad246481e69ff89c721817b18a5d8ed | /LibVedioview/src/main/java/com/dy/libvedioview/loveview/LoveItem.java | 403ebea929bc19f3a6905a95abce4625cd7e106c | []
| no_license | dy60420667/VedioViewSpeciallyEffect | https://github.com/dy60420667/VedioViewSpeciallyEffect | 6e7174ffac3ed070ce3c98d4a6ab3e4c67245535 | 2933404b8dc2bc4c4aa0677d4ca318fff5ca954f | refs/heads/master | 2021-09-05T21:28:19.632000 | 2018-01-31T04:52:44 | 2018-01-31T04:52:44 | 119,629,251 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dy.libvedioview.loveview;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.dy.libvedioview.R;
import java.util.Random;
/**
* Descripty:
* Auth: 邓渊 dymh21342@163.com
* Date: 2018/1/30.13:51
*/
public class LoveItem {
public ImageView imageLove;
public boolean isShow = false;//是否已经显示
public LoveItem(ViewGroup viewGroup){
imageLove = new ImageView(viewGroup.getContext());
imageLove.setLayoutParams(new ViewGroup.LayoutParams(200,200));
imageLove.setVisibility(View.GONE);
imageLove.setPadding(30,30,30,30);
imageLove.setBackgroundResource(R.drawable.bg_white_gray_round);
}
public void setRandomImage(){
switch (new Random().nextInt(5)){
case 0:
imageLove.setImageResource(R.drawable.love_girl_ggx);
break;
case 1:
imageLove.setImageResource(R.drawable.love_girl_lyq);
break;
case 2:
imageLove.setImageResource(R.drawable.love_heart);
break;
case 3:
imageLove.setImageResource(R.drawable.love_mac);
break;
case 4:
imageLove.setImageResource(R.drawable.love_pig);
break;
}
}
}
| UTF-8 | Java | 1,402 | java | LoveItem.java | Java | [
{
"context": "rt java.util.Random;\n\n/**\n * Descripty:\n * Auth: 邓渊 dymh21342@163.com\n * Date: 2018/1/30.13:51\n */\n\n",
"end": 249,
"score": 0.9997174739837646,
"start": 247,
"tag": "NAME",
"value": "邓渊"
},
{
"context": "java.util.Random;\n\n/**\n * Descripty:\n * Auth: 邓渊 dymh21342@163.com\n * Date: 2018/1/30.13:51\n */\n\npublic class LoveIt",
"end": 268,
"score": 0.9999256730079651,
"start": 251,
"tag": "EMAIL",
"value": "dymh21342@163.com"
}
]
| null | []
| package com.dy.libvedioview.loveview;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.dy.libvedioview.R;
import java.util.Random;
/**
* Descripty:
* Auth: 邓渊 <EMAIL>
* Date: 2018/1/30.13:51
*/
public class LoveItem {
public ImageView imageLove;
public boolean isShow = false;//是否已经显示
public LoveItem(ViewGroup viewGroup){
imageLove = new ImageView(viewGroup.getContext());
imageLove.setLayoutParams(new ViewGroup.LayoutParams(200,200));
imageLove.setVisibility(View.GONE);
imageLove.setPadding(30,30,30,30);
imageLove.setBackgroundResource(R.drawable.bg_white_gray_round);
}
public void setRandomImage(){
switch (new Random().nextInt(5)){
case 0:
imageLove.setImageResource(R.drawable.love_girl_ggx);
break;
case 1:
imageLove.setImageResource(R.drawable.love_girl_lyq);
break;
case 2:
imageLove.setImageResource(R.drawable.love_heart);
break;
case 3:
imageLove.setImageResource(R.drawable.love_mac);
break;
case 4:
imageLove.setImageResource(R.drawable.love_pig);
break;
}
}
}
| 1,392 | 0.61039 | 0.582251 | 50 | 26.719999 | 21.751358 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.56 | false | false | 15 |
18f8ad2d8b027e4558285098e6f0e7575b0c85f9 | 12,446,815,224,265 | 637a77be50d8ef64cb15863fdc29ead83f0b4326 | /src/ToolsClass/DataOperate.java | 87084cea68b50bd82015d7af2d97d45e2aa65664 | []
| no_license | cxhqzl/ChatAppServer | https://github.com/cxhqzl/ChatAppServer | b0d859490a50ca41b8570be8f8d685b4319f1ee0 | 90d60c0e9f2158c9069d504c47ba36845d92afad | refs/heads/master | 2022-12-07T06:29:28.508000 | 2020-08-27T05:56:21 | 2020-08-27T05:56:21 | 290,688,959 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ToolsClass;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import DatabaseOperate.DatabaseLinkSetting;
import net.sf.json.JSONObject;
/**
* 与数据库进行数据交互
* @author Xinhai Cao
*
*/
public class DataOperate {
public DataOperate(){
}
/**登录信息匹配*/
public String Login(String uid,String password) throws SQLException{
Connection con = null;
String returnData = null;
try {
con = DatabaseLinkSetting.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM t_user WHERE uid=?");
ps.setString(1, uid);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
if(rs.getInt("state")==0) {//0登录成功
if(rs.getString("password").equals(password)) {
returnData = rs.getString(1);
}else {//1密码不匹配
returnData = "密码错误!";
}
}else {//3账户被冻结
returnData = "账户被冻结!";
}
}else {//2用户不存在
returnData = "用户不存在!";
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
con.close();
}
return returnData;
}
/**获取好友列表*/
public Vector<FriendInfo> getFriendInfo(String uid) throws SQLException{
Vector<FriendInfo> v = new Vector<FriendInfo>();
Connection con = null;
PreparedStatement ps = null;
try {
con = DatabaseLinkSetting.getConnection();
ps = con.prepareStatement("SELECT u.uid,u.image,u.netName,u.info FROM t_friend f INNER JOIN t_user u ON u.uid=f.firendID AND f.uid=?");
ps.setString(1, uid);
ResultSet rs = ps.executeQuery();
while(rs.next()){
FriendInfo f = new FriendInfo();
f.setUid(rs.getString("uid"));
f.setNetName(rs.getString("netName"));
f.setImage(rs.getString("image"));
f.setInfo(rs.getString("info"));
v.add(f);
}
} catch (SQLException e) {
}finally {
con.close();
ps.close();
}
return v;
}
/**更新个人资料*/
public PersonInfo getPersonInfo(String uid) throws SQLException {
PersonInfo personInfo = new PersonInfo();
Connection con = null;
try {
con = DatabaseLinkSetting.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM t_user WHERE uid=?");
ps.setString(1, uid);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
personInfo.setUid(rs.getString("uid"));
personInfo.setNetName(rs.getString("netName"));
personInfo.setSex(rs.getString("sex"));
personInfo.setDd(rs.getInt("dd"));
personInfo.setImage(rs.getString("image"));
personInfo.setInfo(rs.getString("info"));
personInfo.setMm(rs.getInt("mm"));
personInfo.setYy(rs.getInt("yy"));
personInfo.setName(rs.getString("name"));
personInfo.setPhoneNumber(rs.getString("phoneNumber"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
con.close();
}
return personInfo;
}
/**注册*/
public String regUser(String uid,String password) throws SQLException{
String str = "";
Connection con = null;
try {
con = DatabaseLinkSetting.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM t_user WHERE uid=?");
ps.setString(1, uid);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
str = "用户已存在!";
}
ps = con.prepareStatement("INSERT INTO t_user(uid,password,createTime) VALUES(?,?,NOW())");
ps.setString(1, uid);
ps.setString(2, password);
if(ps.executeUpdate()<=0) {
throw new SQLException();
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
con.close();
}
return str;
}
/**所有注册用户*/
public Vector<FriendInfo> getAllUserInfo() throws SQLException{
Vector<FriendInfo> v = new Vector<FriendInfo>();
Connection con = null;
PreparedStatement ps = null;
try {
con = DatabaseLinkSetting.getConnection();
ps = con.prepareStatement("SELECT uid,netName,image,info FROM t_user");
ResultSet rs = ps.executeQuery();
while(rs.next()){
FriendInfo f = new FriendInfo();
f.setUid(rs.getString("uid"));
f.setNetName(rs.getString("netName"));
f.setImage(rs.getString("image"));
f.setInfo(rs.getString("info"));
v.add(f);
}
} catch (SQLException e) {
}finally {
con.close();
ps.close();
}
return v;
}
/**修改个人资料*/
public static void updataPerson(String str) {
JSONObject jsonO = JSONObject.fromObject(str);
Connection con = null;
PreparedStatement ps = null;
try {
con = DatabaseLinkSetting.getConnection();
String sql = "UPDATE t_user SET netName=?,sex=?,phoneNumber=?,info=?,yy=?,mm=?,dd=?,name=?,image=? WHERE uid=?";
ps = con.prepareStatement(sql);
ps.setString(1, jsonO.getString("netName"));
ps.setString(2, jsonO.getString("sex"));
ps.setString(3, jsonO.getString("phoneNumber"));
ps.setString(4, jsonO.getString("info"));
ps.setInt(5, jsonO.getInt("yy"));
ps.setInt(6, jsonO.getInt("mm"));
ps.setInt(7, jsonO.getInt("dd"));
ps.setString(8, jsonO.getString("name"));
ps.setString(9, jsonO.getString("image"));
ps.setString(10, jsonO.getString("uid"));
ps.executeUpdate();
} catch (SQLException e) {
}finally {
try {
con.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**查询分数*/
public static Vector<TankeSourceInfo> selectSource() {
Vector<TankeSourceInfo> v = new Vector<TankeSourceInfo>();
Connection con = null;
try {
con = DatabaseLinkSetting.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT uid,source,netName FROM t_user ORDER BY source DESC");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
TankeSourceInfo t = new TankeSourceInfo();
t.setUid(rs.getString("uid"));
t.setSource(rs.getInt("source"));
t.setName(rs.getString("netName"));
v.add(t);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (SQLException e) {
}
}
return v;
}
/**更新数据库分数*/
public static void updateSource(String uid,int source) {
Connection con = null;
PreparedStatement ps = null;
try {
con = DatabaseLinkSetting.getConnection();
String sql = "UPDATE t_user SET source=? WHERE uid=?";
ps = con.prepareStatement(sql);
ps.setInt(1, source);
ps.setString(2, uid);
ps.executeUpdate();
} catch (SQLException e) {
}finally {
try {
con.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
| GB18030 | Java | 6,847 | java | DataOperate.java | Java | [
{
"context": "f.json.JSONObject;\r\n/**\r\n * 与数据库进行数据交互\r\n * @author Xinhai Cao\r\n *\r\n */\r\npublic class DataOperate {\r\n\tpublic Dat",
"end": 293,
"score": 0.999821662902832,
"start": 283,
"tag": "NAME",
"value": "Xinhai Cao"
}
]
| null | []
| package ToolsClass;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import DatabaseOperate.DatabaseLinkSetting;
import net.sf.json.JSONObject;
/**
* 与数据库进行数据交互
* @author <NAME>
*
*/
public class DataOperate {
public DataOperate(){
}
/**登录信息匹配*/
public String Login(String uid,String password) throws SQLException{
Connection con = null;
String returnData = null;
try {
con = DatabaseLinkSetting.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM t_user WHERE uid=?");
ps.setString(1, uid);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
if(rs.getInt("state")==0) {//0登录成功
if(rs.getString("password").equals(password)) {
returnData = rs.getString(1);
}else {//1密码不匹配
returnData = "密码错误!";
}
}else {//3账户被冻结
returnData = "账户被冻结!";
}
}else {//2用户不存在
returnData = "用户不存在!";
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
con.close();
}
return returnData;
}
/**获取好友列表*/
public Vector<FriendInfo> getFriendInfo(String uid) throws SQLException{
Vector<FriendInfo> v = new Vector<FriendInfo>();
Connection con = null;
PreparedStatement ps = null;
try {
con = DatabaseLinkSetting.getConnection();
ps = con.prepareStatement("SELECT u.uid,u.image,u.netName,u.info FROM t_friend f INNER JOIN t_user u ON u.uid=f.firendID AND f.uid=?");
ps.setString(1, uid);
ResultSet rs = ps.executeQuery();
while(rs.next()){
FriendInfo f = new FriendInfo();
f.setUid(rs.getString("uid"));
f.setNetName(rs.getString("netName"));
f.setImage(rs.getString("image"));
f.setInfo(rs.getString("info"));
v.add(f);
}
} catch (SQLException e) {
}finally {
con.close();
ps.close();
}
return v;
}
/**更新个人资料*/
public PersonInfo getPersonInfo(String uid) throws SQLException {
PersonInfo personInfo = new PersonInfo();
Connection con = null;
try {
con = DatabaseLinkSetting.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM t_user WHERE uid=?");
ps.setString(1, uid);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
personInfo.setUid(rs.getString("uid"));
personInfo.setNetName(rs.getString("netName"));
personInfo.setSex(rs.getString("sex"));
personInfo.setDd(rs.getInt("dd"));
personInfo.setImage(rs.getString("image"));
personInfo.setInfo(rs.getString("info"));
personInfo.setMm(rs.getInt("mm"));
personInfo.setYy(rs.getInt("yy"));
personInfo.setName(rs.getString("name"));
personInfo.setPhoneNumber(rs.getString("phoneNumber"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
con.close();
}
return personInfo;
}
/**注册*/
public String regUser(String uid,String password) throws SQLException{
String str = "";
Connection con = null;
try {
con = DatabaseLinkSetting.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM t_user WHERE uid=?");
ps.setString(1, uid);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
str = "用户已存在!";
}
ps = con.prepareStatement("INSERT INTO t_user(uid,password,createTime) VALUES(?,?,NOW())");
ps.setString(1, uid);
ps.setString(2, password);
if(ps.executeUpdate()<=0) {
throw new SQLException();
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
con.close();
}
return str;
}
/**所有注册用户*/
public Vector<FriendInfo> getAllUserInfo() throws SQLException{
Vector<FriendInfo> v = new Vector<FriendInfo>();
Connection con = null;
PreparedStatement ps = null;
try {
con = DatabaseLinkSetting.getConnection();
ps = con.prepareStatement("SELECT uid,netName,image,info FROM t_user");
ResultSet rs = ps.executeQuery();
while(rs.next()){
FriendInfo f = new FriendInfo();
f.setUid(rs.getString("uid"));
f.setNetName(rs.getString("netName"));
f.setImage(rs.getString("image"));
f.setInfo(rs.getString("info"));
v.add(f);
}
} catch (SQLException e) {
}finally {
con.close();
ps.close();
}
return v;
}
/**修改个人资料*/
public static void updataPerson(String str) {
JSONObject jsonO = JSONObject.fromObject(str);
Connection con = null;
PreparedStatement ps = null;
try {
con = DatabaseLinkSetting.getConnection();
String sql = "UPDATE t_user SET netName=?,sex=?,phoneNumber=?,info=?,yy=?,mm=?,dd=?,name=?,image=? WHERE uid=?";
ps = con.prepareStatement(sql);
ps.setString(1, jsonO.getString("netName"));
ps.setString(2, jsonO.getString("sex"));
ps.setString(3, jsonO.getString("phoneNumber"));
ps.setString(4, jsonO.getString("info"));
ps.setInt(5, jsonO.getInt("yy"));
ps.setInt(6, jsonO.getInt("mm"));
ps.setInt(7, jsonO.getInt("dd"));
ps.setString(8, jsonO.getString("name"));
ps.setString(9, jsonO.getString("image"));
ps.setString(10, jsonO.getString("uid"));
ps.executeUpdate();
} catch (SQLException e) {
}finally {
try {
con.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**查询分数*/
public static Vector<TankeSourceInfo> selectSource() {
Vector<TankeSourceInfo> v = new Vector<TankeSourceInfo>();
Connection con = null;
try {
con = DatabaseLinkSetting.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT uid,source,netName FROM t_user ORDER BY source DESC");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
TankeSourceInfo t = new TankeSourceInfo();
t.setUid(rs.getString("uid"));
t.setSource(rs.getInt("source"));
t.setName(rs.getString("netName"));
v.add(t);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (SQLException e) {
}
}
return v;
}
/**更新数据库分数*/
public static void updateSource(String uid,int source) {
Connection con = null;
PreparedStatement ps = null;
try {
con = DatabaseLinkSetting.getConnection();
String sql = "UPDATE t_user SET source=? WHERE uid=?";
ps = con.prepareStatement(sql);
ps.setInt(1, source);
ps.setString(2, uid);
ps.executeUpdate();
} catch (SQLException e) {
}finally {
try {
con.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
| 6,843 | 0.626108 | 0.622202 | 243 | 25.395061 | 21.515434 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.209877 | false | false | 15 |
164cf85eb8161dd1913ee048763cd1da47bd6f86 | 25,348,897,019,365 | ea18a2320b32079d94dc004c76947e1c9535dd8f | /GoFloraGrowApp/GoFloraGrowUi/src/eu/hansolo/flora/app/data/FloraEventListener.java | 738b06a8898ce1905039a59927a3df412424d99e | []
| no_license | stevendavelaar/ephac3 | https://github.com/stevendavelaar/ephac3 | 91c17edd5337eb109494098a482c9da88ed5afba | 250c8ccb8f2a89aa913ddf9f3b17af3decedfc0a | refs/heads/master | 2019-04-23T14:48:51.197000 | 2015-09-16T13:22:23 | 2015-09-16T13:22:23 | 42,454,236 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package eu.hansolo.flora.app.data;
import java.util.EventListener;
/**
* Created by hansolo on 11.09.15.
*/
public interface FloraEventListener extends EventListener {
public void onEvent(FloraEvent event);
}
| UTF-8 | Java | 218 | java | FloraEventListener.java | Java | [
{
"context": "mport java.util.EventListener;\n\n\n/**\n * Created by hansolo on 11.09.15.\n */\npublic interface FloraEventListe",
"end": 95,
"score": 0.9917464256286621,
"start": 88,
"tag": "USERNAME",
"value": "hansolo"
}
]
| null | []
| package eu.hansolo.flora.app.data;
import java.util.EventListener;
/**
* Created by hansolo on 11.09.15.
*/
public interface FloraEventListener extends EventListener {
public void onEvent(FloraEvent event);
}
| 218 | 0.752294 | 0.724771 | 11 | 18.818182 | 20.541834 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 15 |
bb4779120af61ee59891642fcf24c47ad4090481 | 13,065,290,547,365 | 66e5b4b0c9a561937f430f8034269b4681c7dda4 | /app/src/main/java/pl/dailyveryapp/utils/Constants.java | 81fc8803d16fbfd540a8815b9c908b55ee971767 | []
| no_license | wladyslawmajdanik/DailyveryApp | https://github.com/wladyslawmajdanik/DailyveryApp | 574038afb4be5e5cf4b190d2504bc1dd31736f42 | 53a6f10ed46ac4c5ccebed0f24fd7c7289f9a347 | refs/heads/master | 2021-01-25T11:57:26.686000 | 2018-03-02T16:21:51 | 2018-03-02T16:21:51 | 123,449,809 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.dailyveryapp.utils;
import pl.dailyveryapp.BuildConfig;
public class Constants {
public final static String SHARED_PREFERENCES = "shared_preferences";
public final static String RESTAURANT_DATA = "restaurant_data";
public static String getBaseUrl() {
return BuildConfig.BASE_URL;
}
}
| UTF-8 | Java | 325 | java | Constants.java | Java | []
| null | []
| package pl.dailyveryapp.utils;
import pl.dailyveryapp.BuildConfig;
public class Constants {
public final static String SHARED_PREFERENCES = "shared_preferences";
public final static String RESTAURANT_DATA = "restaurant_data";
public static String getBaseUrl() {
return BuildConfig.BASE_URL;
}
}
| 325 | 0.729231 | 0.729231 | 15 | 20.666666 | 24.434038 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 15 |
ac3d0c2d6997b08c85bdc97159c1a248d46491a8 | 33,569,464,441,322 | a2881dfb3246eebda78c695ede7f5aa0b426aec9 | /1.8 obfuscated/b/bhl.java | 907323573220d9c2b4154d8c53d60c81f25df29c | []
| no_license | Jckf/mc-dev | https://github.com/Jckf/mc-dev | ca03c1907b4b33c94a7bcb7a2067e3963bbf05d2 | 128dae1fe7e2b7772d89dcf130a49210bfd06aa3 | refs/heads/master | 2016-09-05T11:14:19.324000 | 2014-10-01T00:53:05 | 2014-10-01T00:53:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Random;
public class bhl extends bhp {
private atr a;
private int b;
public bhl(int var1) {
this.a = aty.aL;
this.b = var1;
}
public boolean b(aqu var1, Random var2, dt var3) {
if(var1.p(var3).c().r() != bof.h) {
return false;
} else {
int var4 = var2.nextInt(this.b - 2) + 2;
byte var5 = 1;
for(int var6 = var3.n() - var4; var6 <= var3.n() + var4; ++var6) {
for(int var7 = var3.p() - var4; var7 <= var3.p() + var4; ++var7) {
int var8 = var6 - var3.n();
int var9 = var7 - var3.p();
if(var8 * var8 + var9 * var9 <= var4 * var4) {
for(int var10 = var3.o() - var5; var10 <= var3.o() + var5; ++var10) {
dt var11 = new dt(var6, var10, var7);
atr var12 = var1.p(var11).c();
if(var12 == aty.d || var12 == aty.aL) {
var1.a(var11, this.a.P(), 2);
}
}
}
}
}
return true;
}
}
}
| UTF-8 | Java | 1,121 | java | bhl.java | Java | []
| null | []
| import java.util.Random;
public class bhl extends bhp {
private atr a;
private int b;
public bhl(int var1) {
this.a = aty.aL;
this.b = var1;
}
public boolean b(aqu var1, Random var2, dt var3) {
if(var1.p(var3).c().r() != bof.h) {
return false;
} else {
int var4 = var2.nextInt(this.b - 2) + 2;
byte var5 = 1;
for(int var6 = var3.n() - var4; var6 <= var3.n() + var4; ++var6) {
for(int var7 = var3.p() - var4; var7 <= var3.p() + var4; ++var7) {
int var8 = var6 - var3.n();
int var9 = var7 - var3.p();
if(var8 * var8 + var9 * var9 <= var4 * var4) {
for(int var10 = var3.o() - var5; var10 <= var3.o() + var5; ++var10) {
dt var11 = new dt(var6, var10, var7);
atr var12 = var1.p(var11).c();
if(var12 == aty.d || var12 == aty.aL) {
var1.a(var11, this.a.P(), 2);
}
}
}
}
}
return true;
}
}
}
| 1,121 | 0.414808 | 0.354148 | 40 | 27.025 | 24.105484 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 15 |
8a10aa468c84432b361ee331dadfd0715d8cc033 | 25,262,997,673,732 | 76155dda23d3d675d26b480496e23fcc64c300f0 | /src/main/java/com/datinko/prototype/bigdata2/core/factories/SelectionFactory.java | a30d4f6e93f7031d2894e2cf8749253ffea569fa | []
| no_license | neildunlop/bigdata2 | https://github.com/neildunlop/bigdata2 | 7b8040c5ffbc81c316293db95595afd9573dc4f8 | 87e48d7fa71cb11589f0fe41c4fe8a6c85a8b532 | refs/heads/master | 2020-03-30T17:28:58.473000 | 2015-09-10T11:04:38 | 2015-09-10T11:04:38 | 41,702,761 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.datinko.prototype.bigdata2.core.factories;
import com.datinko.prototype.bigdata2.core.Market;
import com.datinko.prototype.bigdata2.core.Selection;
import java.util.UUID;
/**
* Created by Neil on 25/08/2015.
*/
public class SelectionFactory {
public static Selection getBristolToWin() {
UUID id = UUID.fromString("5bc5be63-de7e-4304-bb56-bebbda60c060");
EventFactory.getBristolVsDerby();
Market market = MarketFactory.getBristolDerbyToWin();
String price = "8/5";
String name = "Bristol";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getDerbyToWin() {
UUID id = UUID.fromString("3b10cbc1-d79c-4186-b60e-39c6462f2374");
EventFactory.getBristolVsDerby();
Market market = MarketFactory.getBristolDerbyToWin();
String price = "15/8";
String name = "Derby";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getBristolDerbyToDraw() {
UUID id = UUID.fromString("d9dd89d7-bd0c-4618-ad7e-800ae4883ef9");
EventFactory.getBristolVsDerby();
Market market = MarketFactory.getBristolDerbyToDraw();
String price = "21/8";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getMiddlesbroughToWin() {
UUID id = UUID.fromString("a4e7ea00-7514-4a08-98b0-0ee7d389cc9d");
EventFactory.getMiddlesbroughVsHull();
Market market = MarketFactory.getMiddlesbroughHullToWin();
String price = "5/4";
String name = "Middlesbrough";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getHullToWin() {
UUID id = UUID.fromString("7f4c18e3-16e8-47d5-804b-9b4aa6deb318");
EventFactory.getMiddlesbroughVsHull();
Market market = MarketFactory.getMiddlesbroughHullToWin();
String price = "11/5";
String name = "Hull";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getMiddlesbroughHullToDraw() {
UUID id = UUID.fromString("7d0cc327-cd8e-494e-908f-c1bb9da1e298");
EventFactory.getMiddlesbroughVsHull();
Market market = MarketFactory.getMiddlesbroughHullToDraw();
String price = "23/10";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getLeedsToWin() {
UUID id = UUID.fromString("9e8239bb-7ceb-4334-b300-b9dd7ecb80df");
EventFactory.getLeedsVsBlackburn();
Market market = MarketFactory.getLeedsBlackburnToWin();
String price = "12/5";
String name = "Leeds";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getBlackburnToWin() {
UUID id = UUID.fromString("c58cc59c-9ce1-4ad1-8b12-99f6537ef080");
EventFactory.getLeedsVsBlackburn();
Market market = MarketFactory.getLeedsBlackburnToWin();
String price = "23/20";
String name = "Blackburn";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getLeedsBlackburnToDraw() {
UUID id = UUID.fromString("af76f513-f149-4c2a-904f-82b90dc67800");
EventFactory.getLeedsVsBlackburn();
Market market = MarketFactory.getLeedsBlackburnToDraw();
String price = "23/10";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getCharltonToWin() {
UUID id = UUID.fromString("a5460227-186f-4733-a2fe-521c4da2e66c");
EventFactory.getChartonVsBurnley();
Market market = MarketFactory.getCharltonBurnleyToWin();
String price = "5/6";
String name = "Charlton";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getBurnleyToWin() {
UUID id = UUID.fromString("9793bc47-5564-4692-957b-57d8407597b5");
EventFactory.getChartonVsBurnley();
Market market = MarketFactory.getCharltonBurnleyToWin();
String price = "15/4";
String name = "Burnley";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getCharltonBurnleyToDraw() {
UUID id = UUID.fromString("b36d1151-e860-4fc3-a499-ff36d672d9ea");
EventFactory.getChartonVsBurnley();
Market market = MarketFactory.getCharltonBurnleyToDraw();
String price = "23/10";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getRotherhamToWin() {
UUID id = UUID.fromString("04eca3e0-35df-4d95-a8ac-9dee70113241");
EventFactory.getRotherhamVsBolton();
Market market = MarketFactory.getRotherhamBoltonToWin();
String price = "12/1";
String name = "Rotherham";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getBoltonToWin() {
UUID id = UUID.fromString("973202cd-da84-4112-9043-ef5175dc65e8");
EventFactory.getBristolVsDerby();
Market market = MarketFactory.getRotherhamBoltonToWin();
String price = "1/4";
String name = "Bolton";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getRotherhamBoltonToDraw() {
UUID id = UUID.fromString("39cd368b-3c43-454e-a139-188fc54591f0");
EventFactory.getRotherhamVsBolton();
Market market = MarketFactory.getRotherhamBoltonToDraw();
String price = "9/2";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getWolvesToWin() {
UUID id = UUID.fromString("83f5c195-6c8d-4db9-918d-3af23ebaed9e");
EventFactory.getWolvesVsReading();
Market market = MarketFactory.getWolvesReadingToWin();
String price = "2/5";
String name = "Wolves";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getReadingToWin() {
UUID id = UUID.fromString("0dbf73a5-64db-4c45-b686-f0169f4ab060");
EventFactory.getWolvesVsReading();
Market market = MarketFactory.getWolvesReadingToWin();
String price = "17/2";
String name = "Reading";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getWolvesReadingToDraw() {
UUID id = UUID.fromString("61433299-19ad-4ef9-bc4b-6f3e64bdfb37");
EventFactory.getWolvesVsReading();
Market market = MarketFactory.getWolvesReadingToDraw();
String price = "16/5";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
}
| UTF-8 | Java | 10,103 | java | SelectionFactory.java | Java | [
{
"context": "ection;\n\nimport java.util.UUID;\n\n/**\n * Created by Neil on 25/08/2015.\n */\npublic class SelectionFactory ",
"end": 209,
"score": 0.9978877902030945,
"start": 205,
"tag": "NAME",
"value": "Neil"
},
{
"context": " String price = \"15/8\";\n String name = \"Derby\";\n\n Selection result = Selection.newBuilde",
"end": 1086,
"score": 0.9624490141868591,
"start": 1081,
"tag": "NAME",
"value": "Derby"
},
{
"context": " String price = \"5/4\";\n String name = \"Middlesbrough\";\n\n Selection result = Selection.newBuilde",
"end": 2191,
"score": 0.9962175488471985,
"start": 2178,
"tag": "NAME",
"value": "Middlesbrough"
},
{
"context": " String price = \"11/5\";\n String name = \"Hull\";\n\n Selection result = Selection.newBuilde",
"end": 2735,
"score": 0.5286322236061096,
"start": 2732,
"tag": "NAME",
"value": "ull"
},
{
"context": " String price = \"5/6\";\n String name = \"Charlton\";\n\n Selection result = Selection.newBuilde",
"end": 5481,
"score": 0.9992659687995911,
"start": 5473,
"tag": "NAME",
"value": "Charlton"
},
{
"context": " String price = \"15/4\";\n String name = \"Burnley\";\n\n Selection result = Selection.newBuilde",
"end": 6026,
"score": 0.9899802207946777,
"start": 6019,
"tag": "NAME",
"value": "Burnley"
},
{
"context": " String price = \"12/1\";\n String name = \"Rotherham\";\n\n Selection result = Selection.newBuilde",
"end": 7129,
"score": 0.9991900324821472,
"start": 7120,
"tag": "NAME",
"value": "Rotherham"
},
{
"context": " String price = \"1/4\";\n String name = \"Bolton\";\n\n Selection result = Selection.newBuilde",
"end": 7669,
"score": 0.9881935119628906,
"start": 7663,
"tag": "NAME",
"value": "Bolton"
},
{
"context": " String price = \"2/5\";\n String name = \"Wolves\";\n\n Selection result = Selection.newBuilde",
"end": 8760,
"score": 0.7391031980514526,
"start": 8754,
"tag": "NAME",
"value": "Wolves"
},
{
"context": " String price = \"17/2\";\n String name = \"Reading\";\n\n Selection result = Selection.newBuilde",
"end": 9302,
"score": 0.5750024914741516,
"start": 9295,
"tag": "NAME",
"value": "Reading"
}
]
| null | []
| package com.datinko.prototype.bigdata2.core.factories;
import com.datinko.prototype.bigdata2.core.Market;
import com.datinko.prototype.bigdata2.core.Selection;
import java.util.UUID;
/**
* Created by Neil on 25/08/2015.
*/
public class SelectionFactory {
public static Selection getBristolToWin() {
UUID id = UUID.fromString("5bc5be63-de7e-4304-bb56-bebbda60c060");
EventFactory.getBristolVsDerby();
Market market = MarketFactory.getBristolDerbyToWin();
String price = "8/5";
String name = "Bristol";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getDerbyToWin() {
UUID id = UUID.fromString("3b10cbc1-d79c-4186-b60e-39c6462f2374");
EventFactory.getBristolVsDerby();
Market market = MarketFactory.getBristolDerbyToWin();
String price = "15/8";
String name = "Derby";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getBristolDerbyToDraw() {
UUID id = UUID.fromString("d9dd89d7-bd0c-4618-ad7e-800ae4883ef9");
EventFactory.getBristolVsDerby();
Market market = MarketFactory.getBristolDerbyToDraw();
String price = "21/8";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getMiddlesbroughToWin() {
UUID id = UUID.fromString("a4e7ea00-7514-4a08-98b0-0ee7d389cc9d");
EventFactory.getMiddlesbroughVsHull();
Market market = MarketFactory.getMiddlesbroughHullToWin();
String price = "5/4";
String name = "Middlesbrough";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getHullToWin() {
UUID id = UUID.fromString("7f4c18e3-16e8-47d5-804b-9b4aa6deb318");
EventFactory.getMiddlesbroughVsHull();
Market market = MarketFactory.getMiddlesbroughHullToWin();
String price = "11/5";
String name = "Hull";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getMiddlesbroughHullToDraw() {
UUID id = UUID.fromString("7d0cc327-cd8e-494e-908f-c1bb9da1e298");
EventFactory.getMiddlesbroughVsHull();
Market market = MarketFactory.getMiddlesbroughHullToDraw();
String price = "23/10";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getLeedsToWin() {
UUID id = UUID.fromString("9e8239bb-7ceb-4334-b300-b9dd7ecb80df");
EventFactory.getLeedsVsBlackburn();
Market market = MarketFactory.getLeedsBlackburnToWin();
String price = "12/5";
String name = "Leeds";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getBlackburnToWin() {
UUID id = UUID.fromString("c58cc59c-9ce1-4ad1-8b12-99f6537ef080");
EventFactory.getLeedsVsBlackburn();
Market market = MarketFactory.getLeedsBlackburnToWin();
String price = "23/20";
String name = "Blackburn";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getLeedsBlackburnToDraw() {
UUID id = UUID.fromString("af76f513-f149-4c2a-904f-82b90dc67800");
EventFactory.getLeedsVsBlackburn();
Market market = MarketFactory.getLeedsBlackburnToDraw();
String price = "23/10";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getCharltonToWin() {
UUID id = UUID.fromString("a5460227-186f-4733-a2fe-521c4da2e66c");
EventFactory.getChartonVsBurnley();
Market market = MarketFactory.getCharltonBurnleyToWin();
String price = "5/6";
String name = "Charlton";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getBurnleyToWin() {
UUID id = UUID.fromString("9793bc47-5564-4692-957b-57d8407597b5");
EventFactory.getChartonVsBurnley();
Market market = MarketFactory.getCharltonBurnleyToWin();
String price = "15/4";
String name = "Burnley";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getCharltonBurnleyToDraw() {
UUID id = UUID.fromString("b36d1151-e860-4fc3-a499-ff36d672d9ea");
EventFactory.getChartonVsBurnley();
Market market = MarketFactory.getCharltonBurnleyToDraw();
String price = "23/10";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getRotherhamToWin() {
UUID id = UUID.fromString("04eca3e0-35df-4d95-a8ac-9dee70113241");
EventFactory.getRotherhamVsBolton();
Market market = MarketFactory.getRotherhamBoltonToWin();
String price = "12/1";
String name = "Rotherham";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getBoltonToWin() {
UUID id = UUID.fromString("973202cd-da84-4112-9043-ef5175dc65e8");
EventFactory.getBristolVsDerby();
Market market = MarketFactory.getRotherhamBoltonToWin();
String price = "1/4";
String name = "Bolton";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getRotherhamBoltonToDraw() {
UUID id = UUID.fromString("39cd368b-3c43-454e-a139-188fc54591f0");
EventFactory.getRotherhamVsBolton();
Market market = MarketFactory.getRotherhamBoltonToDraw();
String price = "9/2";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getWolvesToWin() {
UUID id = UUID.fromString("83f5c195-6c8d-4db9-918d-3af23ebaed9e");
EventFactory.getWolvesVsReading();
Market market = MarketFactory.getWolvesReadingToWin();
String price = "2/5";
String name = "Wolves";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getReadingToWin() {
UUID id = UUID.fromString("0dbf73a5-64db-4c45-b686-f0169f4ab060");
EventFactory.getWolvesVsReading();
Market market = MarketFactory.getWolvesReadingToWin();
String price = "17/2";
String name = "Reading";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
public static Selection getWolvesReadingToDraw() {
UUID id = UUID.fromString("61433299-19ad-4ef9-bc4b-6f3e64bdfb37");
EventFactory.getWolvesVsReading();
Market market = MarketFactory.getWolvesReadingToDraw();
String price = "16/5";
String name = "Draw";
Selection result = Selection.newBuilder()
.withId(id)
.withMarket(market)
.withSelectionValue(name)
.withPrice(price)
.build();
return result;
}
}
| 10,103 | 0.573493 | 0.531327 | 339 | 28.802361 | 21.852669 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.383481 | false | false | 15 |
a0c14074714fef749407576b689e9af027f1f6f3 | 8,323,646,641,096 | 0961421ad0b82a50dad55bbecf43e516f99c7268 | /src/main/java/com/bjsxt/service/FeelService.java | d6ea016a5cbf3f07734a77293cd684a2674c09f8 | []
| no_license | huangge70/feel | https://github.com/huangge70/feel | 0860aa81c904c67e1fdb9f83b86206310af333df | 4baa56d8f669ad8891e4482a3cc1cf85c3ea49dc | refs/heads/master | 2020-04-13T03:36:29.683000 | 2018-12-24T01:32:28 | 2018-12-24T01:32:28 | 162,936,927 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bjsxt.service;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;
import com.bjsxt.pojo.Feel;
public interface FeelService {
Map<String,Object> upload(MultipartFile imgFile) throws IOException;
int insFeel(Feel feel,List<String> imgs);
}
| UTF-8 | Java | 338 | java | FeelService.java | Java | []
| null | []
| package com.bjsxt.service;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;
import com.bjsxt.pojo.Feel;
public interface FeelService {
Map<String,Object> upload(MultipartFile imgFile) throws IOException;
int insFeel(Feel feel,List<String> imgs);
}
| 338 | 0.789941 | 0.789941 | 16 | 20.125 | 20.963882 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false | 15 |
8b2e8c19f2473b01c2adba365b2aeb4eb2a818b3 | 5,368,709,131,795 | 226bae6a22036fbaf198357ea4921c29ee984070 | /webclient/src/main/java/com/ecg/webclient/feature/administration/persistence/modell/Client.java | 01250ecdf30fec05203109f7eda9d265732abfba | []
| no_license | benciao/webclient.modules | https://github.com/benciao/webclient.modules | 707adf30636b17a355b2abaf9671009015800ec2 | dbedf932f250f77049442264e251112cccf7ad17 | refs/heads/master | 2021-01-10T14:07:31.933000 | 2016-03-31T14:19:11 | 2016-03-31T14:19:11 | 45,912,180 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ecg.webclient.feature.administration.persistence.modell;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* Entität eines Mandanten.
*
* @author arndtmar
*/
@Entity
@Table(name = "SEC_CLIENT")
public class Client
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String color;
private String description;
@Column(unique = true)
private String name;
private boolean enabled;
public Client()
{}
@Transient
public Client bind(Client newClient)
{
setColor(newClient.getColor());
setName(newClient.getName());
setDescription(newClient.getDescription());
setEnabled(newClient.isEnabled());
return this;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof Client))
{
return false;
}
Client other = (Client) obj;
if (description == null)
{
if (other.description != null)
{
return false;
}
}
else if (!description.equals(other.description))
{
return false;
}
if (id != other.id)
{
return false;
}
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
return true;
}
public String getColor()
{
return color;
}
public String getDescription()
{
return description;
}
public long getId()
{
return id;
}
public String getName()
{
return name;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean isEnabled()
{
return enabled;
}
public void setColor(String color)
{
this.color = color;
}
public void setDescription(String description)
{
this.description = description;
}
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
public void setId(long id)
{
if (id != -1)
{
this.id = id;
}
}
public void setName(String name)
{
this.name = name;
}
}
| UTF-8 | Java | 3,218 | java | Client.java | Java | [
{
"context": "\n/**\r\n * Entität eines Mandanten.\r\n * \r\n * @author arndtmar\r\n */\r\n@Entity\r\n@Table(name = \"SEC_CLIENT\")\r\npublic ",
"end": 384,
"score": 0.898079514503479,
"start": 376,
"tag": "USERNAME",
"value": "arndtmar"
}
]
| null | []
| package com.ecg.webclient.feature.administration.persistence.modell;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* Entität eines Mandanten.
*
* @author arndtmar
*/
@Entity
@Table(name = "SEC_CLIENT")
public class Client
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String color;
private String description;
@Column(unique = true)
private String name;
private boolean enabled;
public Client()
{}
@Transient
public Client bind(Client newClient)
{
setColor(newClient.getColor());
setName(newClient.getName());
setDescription(newClient.getDescription());
setEnabled(newClient.isEnabled());
return this;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof Client))
{
return false;
}
Client other = (Client) obj;
if (description == null)
{
if (other.description != null)
{
return false;
}
}
else if (!description.equals(other.description))
{
return false;
}
if (id != other.id)
{
return false;
}
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
return true;
}
public String getColor()
{
return color;
}
public String getDescription()
{
return description;
}
public long getId()
{
return id;
}
public String getName()
{
return name;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean isEnabled()
{
return enabled;
}
public void setColor(String color)
{
this.color = color;
}
public void setDescription(String description)
{
this.description = description;
}
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
public void setId(long id)
{
if (id != -1)
{
this.id = id;
}
}
public void setName(String name)
{
this.name = name;
}
}
| 3,218 | 0.490208 | 0.487721 | 151 | 19.304636 | 16.795614 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.291391 | false | false | 15 |
e9ad3347699870dddede5f7a2f17243af7b8592d | 7,181,185,323,275 | 5dc88d185e2c10b4272c7bb49b3fc183cb822a27 | /src/main/java/com/github/nitin/kafka/tutorial1/ConsumerThread.java | b961c4dbea0f9e794b94f3402b7f0992ec2205b6 | []
| no_license | nitin023/kafka-beginner | https://github.com/nitin023/kafka-beginner | 7e49bc4b4d57b09c8cc35852f8aaab6642b6887a | 61b6bc4daded5dd24f8f82e529f1f4c6418355a2 | refs/heads/master | 2020-09-11T12:31:58.882000 | 2019-11-20T16:57:16 | 2019-11-20T16:57:16 | 222,065,671 | 0 | 0 | null | false | 2023-09-05T22:02:30 | 2019-11-16T07:52:01 | 2019-11-20T16:57:28 | 2023-09-05T22:02:29 | 46 | 0 | 0 | 1 | Java | false | false | package com.github.nitin.kafka.tutorial1;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.errors.WakeupException;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
public class ConsumerThread implements Runnable {
private CountDownLatch latch;
private KafkaConsumer<String,String> consumer;
public ConsumerThread(CountDownLatch latch,String topic , String bootStrapServers ,String groupId)
{
Properties properties = new Properties();
properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,bootStrapServers);
properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG,groupId);
properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
this.latch = latch;
consumer = new KafkaConsumer<String, String>(properties);
consumer.subscribe(Arrays.asList(topic));
}
public ConsumerThread(Runnable myConsumerThread) {
}
@Override
public void run() {
try {
while (true) {
ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(100L));
for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
System.out.println("Topic : " + consumerRecord.topic() + "key : " + consumerRecord.key() + " value : " + consumerRecord.value());
System.out.println("Partition : " + consumerRecord.partition() + " Offset : " + consumerRecord.offset());
}
}
}
catch (WakeupException ex)
{
System.out.println("Received shutdown Signal");
}
finally {
consumer.close();
latch.countDown();
}
}
public void shutDown()
{
consumer.wakeup();
}
}
| UTF-8 | Java | 2,372 | java | ConsumerThread.java | Java | [
{
"context": "package com.github.nitin.kafka.tutorial1;\n\nimport org.apache.kafka.clients",
"end": 24,
"score": 0.9979122281074524,
"start": 19,
"tag": "USERNAME",
"value": "nitin"
}
]
| null | []
| package com.github.nitin.kafka.tutorial1;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.errors.WakeupException;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
public class ConsumerThread implements Runnable {
private CountDownLatch latch;
private KafkaConsumer<String,String> consumer;
public ConsumerThread(CountDownLatch latch,String topic , String bootStrapServers ,String groupId)
{
Properties properties = new Properties();
properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,bootStrapServers);
properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG,groupId);
properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
this.latch = latch;
consumer = new KafkaConsumer<String, String>(properties);
consumer.subscribe(Arrays.asList(topic));
}
public ConsumerThread(Runnable myConsumerThread) {
}
@Override
public void run() {
try {
while (true) {
ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(100L));
for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
System.out.println("Topic : " + consumerRecord.topic() + "key : " + consumerRecord.key() + " value : " + consumerRecord.value());
System.out.println("Partition : " + consumerRecord.partition() + " Offset : " + consumerRecord.offset());
}
}
}
catch (WakeupException ex)
{
System.out.println("Received shutdown Signal");
}
finally {
consumer.close();
latch.countDown();
}
}
public void shutDown()
{
consumer.wakeup();
}
}
| 2,372 | 0.686762 | 0.685076 | 61 | 37.885246 | 36.025536 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672131 | false | false | 15 |
deb24f8a403c0441e393e9e0c78d71f4879501d7 | 32,547,262,193,358 | f45951ef0666689face822a14ee761c2e09bb15d | /src/character/character.java | 90ffad16931ee90cc20c25dc3d1bf6f70a7de73c | []
| no_license | BryGuz/MonedaPersonaje | https://github.com/BryGuz/MonedaPersonaje | 3e0beb36051db846f77d8b498bfe309a1107af37 | 3a8b57c56f47343cb32503eecc556ad1450a2ef1 | refs/heads/master | 2021-06-21T19:23:53.572000 | 2017-05-19T04:41:09 | 2017-05-19T04:41:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package character;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
import java.awt.Polygon;
import java.awt.Shape;
import java.util.logging.Level;
import java.util.logging.Logger;
public class character extends JPanel implements ActionListener,MouseListener {
private Timer timer;
private int mx=500;
private int my=500;
private int sec = 0;
private int px =60;
private int py =575;
private int cs = 0;
private int cs1 = 0;
private int cs2 = 0;
private int s =0;
private int MN =0;
public character() {
addKeyListener(new TAdapter());
setFocusable(true);
timer = new Timer(25, this);
timer.start();
}
@Override
protected void paintComponent(Graphics g){
Image fondo = loadImage("blue_background.png");
Image piso = loadImage("ground_loop.png");
Image p = loadImage("walking.png");
Image c = loadImage("clouds.png");
Image m = loadImage("coin.png");
for (int i = 0; i < 100; i++) {
g.drawImage(fondo, 0+(i*22), 0, null);
}
for (int i = 0; i < 100; i++) {
g.drawImage(piso, 0+(i*112), 700, null);
}
int t = s*96;
int t2 = t+96;
Font fuente=new Font("TimesRoman", Font.BOLD, 30);
g.setColor(Color.WHITE);
g.setFont(fuente);
g.drawString("MONEDAS: " + MN, 700, 50);
g.drawImage(p, px, py,(px) + 96,py +134,t,0,t2,134, null);
// g.drawRect(px, py, 100, 134);
g.drawImage(c, 400-cs, 200, null);
g.drawImage(c, 700-cs1, 300, null);
g.drawImage(c, 1000-cs2, 100, null);
g.drawImage(m,mx ,my , null);
g.setColor(Color.red);
g.fillRect(900, 610, 90, 90);
g.setColor(Color.WHITE);
g.drawString("META", 905, 670);
// g.drawRect(mx, my, 55, 55);
}
public Image loadImage(String imageName){
ImageIcon ii = new ImageIcon(imageName);
Image image = ii.getImage();
return image;
}
@Override
public void actionPerformed(ActionEvent e) {
checkcolision();
if (cs ==900) {
cs = -500;
}else{
cs+=10;
}
if (cs1 ==1200) {
cs1 = -700;
}else{
cs1+=20;
}
if (cs2 ==1500) {
cs2 = -1000;
}else{
cs2+=8;
}
repaint();
}
public Rectangle getBounds(){
return new Rectangle(px, py, 100, 134);
}
public Rectangle getBoundsobjeto(){
return new Rectangle(mx, my, 55, 55);
}
public Rectangle getBoundObjeto2(){
return new Rectangle(0,732,1000,68);
}
public Rectangle getBoundObjeto3(){
return new Rectangle(900, 610, 90, 90);
}
@Override
public void mouseClicked(MouseEvent e) {
Point mo = e.getPoint();
if (getBounds().contains(mo)) {
timer.stop();
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(character.class.getName()).log(Level.SEVERE, null, ex);
}
timer.start();
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
private class TAdapter extends KeyAdapter {
@Override
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
for (int j = 4; j > 0; j--) {
py+=10*j;
px+=10*j;
repaint();
}
}
}
@Override
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
for (int j = 0; j < 5; j++) {
px+=10*j;
py-=10*j;
repaint();
}
}
if (key == KeyEvent.VK_RIGHT) {
px+=15;
if(s==3){
s =0;
}else{
s++;
}
}
if (key == KeyEvent.VK_UP) {
py-=5;
}
if (key == KeyEvent.VK_DOWN) {
py+=5;
}
}
}
public void checkcolision(){
Rectangle Character = this.getBounds();
Rectangle coin = this.getBoundsobjeto();
Rectangle piso = this.getBoundObjeto2();
Rectangle meta = this.getBoundObjeto3();
if(Character.intersects(coin)){
mx = 60000;
my = 60000;
MN += 1;
}
if(Character.intersects(meta)){
py=10000;
px=10000;
// JOptionPane.showMessageDialog(null,"¡GANASTE!");
if(Character.intersects(piso)){
//AQUI NO SE COMO va :C
}
}
}
}
| UTF-8 | Java | 6,106 | java | character.java | Java | []
| null | []
|
package character;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
import java.awt.Polygon;
import java.awt.Shape;
import java.util.logging.Level;
import java.util.logging.Logger;
public class character extends JPanel implements ActionListener,MouseListener {
private Timer timer;
private int mx=500;
private int my=500;
private int sec = 0;
private int px =60;
private int py =575;
private int cs = 0;
private int cs1 = 0;
private int cs2 = 0;
private int s =0;
private int MN =0;
public character() {
addKeyListener(new TAdapter());
setFocusable(true);
timer = new Timer(25, this);
timer.start();
}
@Override
protected void paintComponent(Graphics g){
Image fondo = loadImage("blue_background.png");
Image piso = loadImage("ground_loop.png");
Image p = loadImage("walking.png");
Image c = loadImage("clouds.png");
Image m = loadImage("coin.png");
for (int i = 0; i < 100; i++) {
g.drawImage(fondo, 0+(i*22), 0, null);
}
for (int i = 0; i < 100; i++) {
g.drawImage(piso, 0+(i*112), 700, null);
}
int t = s*96;
int t2 = t+96;
Font fuente=new Font("TimesRoman", Font.BOLD, 30);
g.setColor(Color.WHITE);
g.setFont(fuente);
g.drawString("MONEDAS: " + MN, 700, 50);
g.drawImage(p, px, py,(px) + 96,py +134,t,0,t2,134, null);
// g.drawRect(px, py, 100, 134);
g.drawImage(c, 400-cs, 200, null);
g.drawImage(c, 700-cs1, 300, null);
g.drawImage(c, 1000-cs2, 100, null);
g.drawImage(m,mx ,my , null);
g.setColor(Color.red);
g.fillRect(900, 610, 90, 90);
g.setColor(Color.WHITE);
g.drawString("META", 905, 670);
// g.drawRect(mx, my, 55, 55);
}
public Image loadImage(String imageName){
ImageIcon ii = new ImageIcon(imageName);
Image image = ii.getImage();
return image;
}
@Override
public void actionPerformed(ActionEvent e) {
checkcolision();
if (cs ==900) {
cs = -500;
}else{
cs+=10;
}
if (cs1 ==1200) {
cs1 = -700;
}else{
cs1+=20;
}
if (cs2 ==1500) {
cs2 = -1000;
}else{
cs2+=8;
}
repaint();
}
public Rectangle getBounds(){
return new Rectangle(px, py, 100, 134);
}
public Rectangle getBoundsobjeto(){
return new Rectangle(mx, my, 55, 55);
}
public Rectangle getBoundObjeto2(){
return new Rectangle(0,732,1000,68);
}
public Rectangle getBoundObjeto3(){
return new Rectangle(900, 610, 90, 90);
}
@Override
public void mouseClicked(MouseEvent e) {
Point mo = e.getPoint();
if (getBounds().contains(mo)) {
timer.stop();
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(character.class.getName()).log(Level.SEVERE, null, ex);
}
timer.start();
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
private class TAdapter extends KeyAdapter {
@Override
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
for (int j = 4; j > 0; j--) {
py+=10*j;
px+=10*j;
repaint();
}
}
}
@Override
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
for (int j = 0; j < 5; j++) {
px+=10*j;
py-=10*j;
repaint();
}
}
if (key == KeyEvent.VK_RIGHT) {
px+=15;
if(s==3){
s =0;
}else{
s++;
}
}
if (key == KeyEvent.VK_UP) {
py-=5;
}
if (key == KeyEvent.VK_DOWN) {
py+=5;
}
}
}
public void checkcolision(){
Rectangle Character = this.getBounds();
Rectangle coin = this.getBoundsobjeto();
Rectangle piso = this.getBoundObjeto2();
Rectangle meta = this.getBoundObjeto3();
if(Character.intersects(coin)){
mx = 60000;
my = 60000;
MN += 1;
}
if(Character.intersects(meta)){
py=10000;
px=10000;
// JOptionPane.showMessageDialog(null,"¡GANASTE!");
if(Character.intersects(piso)){
//AQUI NO SE COMO va :C
}
}
}
}
| 6,106 | 0.441278 | 0.405733 | 242 | 23.219007 | 16.13699 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.673554 | false | false | 15 |
a80ebc32d4602723ee155574b0601f04536150b9 | 26,448,408,654,537 | f227522b7a10012d38c09821384e04465bf04c02 | /TextToSpeech/app/src/main/java/com/example/texttospeech/MainActivity.java | c2b103c9d79d1c5272e574f65b0267ffeb9161c6 | []
| no_license | mohdsameer7408/new_android_projects | https://github.com/mohdsameer7408/new_android_projects | 27bff54d097738fc922d1043c4bf34986e2c6f00 | 1bdb830980d5dcaff50538ce24af70f890fc2850 | refs/heads/master | 2022-11-28T01:31:54.740000 | 2020-08-03T15:22:33 | 2020-08-03T15:22:33 | 284,734,723 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.texttospeech;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
private static final int tts_engine_request = 101;
private TextToSpeech textToSpeech;
private EditText text_for_speech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_for_speech = findViewById(R.id.speech_text);
}
public void performSpeech(View view) {
Intent intent = new Intent();
intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(intent, tts_engine_request);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == tts_engine_request && resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
textToSpeech = new TextToSpeech(this, this);
}
else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int language_status = textToSpeech.setLanguage(Locale.US);
if (language_status == TextToSpeech.LANG_MISSING_DATA || language_status == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(this, "Language isn't supported...", Toast.LENGTH_SHORT).show();
}
else {
String data = text_for_speech.getText().toString();
int speech_status = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null);
if (speech_status == TextToSpeech.ERROR) {
Toast.makeText(this, "Error while speech...", Toast.LENGTH_SHORT).show();
}
}
}
else {
Toast.makeText(this, "Text to speech engine failed...", Toast.LENGTH_SHORT).show();
}
}
} | UTF-8 | Java | 2,465 | java | MainActivity.java | Java | []
| null | []
| package com.example.texttospeech;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
private static final int tts_engine_request = 101;
private TextToSpeech textToSpeech;
private EditText text_for_speech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_for_speech = findViewById(R.id.speech_text);
}
public void performSpeech(View view) {
Intent intent = new Intent();
intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(intent, tts_engine_request);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == tts_engine_request && resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
textToSpeech = new TextToSpeech(this, this);
}
else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int language_status = textToSpeech.setLanguage(Locale.US);
if (language_status == TextToSpeech.LANG_MISSING_DATA || language_status == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(this, "Language isn't supported...", Toast.LENGTH_SHORT).show();
}
else {
String data = text_for_speech.getText().toString();
int speech_status = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null);
if (speech_status == TextToSpeech.ERROR) {
Toast.makeText(this, "Error while speech...", Toast.LENGTH_SHORT).show();
}
}
}
else {
Toast.makeText(this, "Text to speech engine failed...", Toast.LENGTH_SHORT).show();
}
}
} | 2,465 | 0.657606 | 0.656389 | 70 | 34.228573 | 31.791361 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657143 | false | false | 15 |
07c05c03fb1b732a12fe4d316b5c8b45d09095cd | 7,404,523,641,229 | 3aa5def116045abfd6274299d97372c90efaf560 | /src/main/java/com/laonstory/service/CommentService.java | c6e02a8f1bcdcf95b1c3a0da06ef498b079d469a | []
| no_license | SeunghyeonSin/CCProj-backend | https://github.com/SeunghyeonSin/CCProj-backend | 6c15f29bb6dc87ae679e1bd9a7a0339d55ec5196 | 67defde58c9ba30d4eab65225f190373f3f65c10 | refs/heads/main | 2023-06-22T08:21:49.421000 | 2021-07-20T06:40:12 | 2021-07-20T06:40:12 | 384,040,191 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.laonstory.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.laonstory.mapper.CommentMapper;
import com.laonstory.vo.CommentVO;
@Service
public class CommentService implements CommentMapper{
@Autowired
private CommentMapper mapper;
@Override
public int countComment(int boardid) {
return mapper.countComment(boardid);
}
@Override
public CommentVO getComment(CommentVO vo) {
return mapper.getComment(vo);
}
@Override
public List<CommentVO> getListComment(int boardid) {
return mapper.getListComment(boardid);
}
@Override
public List<CommentVO> getListUserComment(CommentVO vo) {
return mapper.getListUserComment(vo);
}
@Override
public String insertComment(CommentVO vo) {
return mapper.insertComment(vo);
}
@Override
public String updateComment(CommentVO vo) {
return mapper.updateComment(vo);
}
@Override
public int deleteComment(int commentid) {
return mapper.deleteComment(commentid);
}
@Override
public int boardDeleteComment(int boardid) {
return mapper.boardDeleteComment(boardid);
}
}
| UTF-8 | Java | 1,163 | java | CommentService.java | Java | []
| null | []
| package com.laonstory.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.laonstory.mapper.CommentMapper;
import com.laonstory.vo.CommentVO;
@Service
public class CommentService implements CommentMapper{
@Autowired
private CommentMapper mapper;
@Override
public int countComment(int boardid) {
return mapper.countComment(boardid);
}
@Override
public CommentVO getComment(CommentVO vo) {
return mapper.getComment(vo);
}
@Override
public List<CommentVO> getListComment(int boardid) {
return mapper.getListComment(boardid);
}
@Override
public List<CommentVO> getListUserComment(CommentVO vo) {
return mapper.getListUserComment(vo);
}
@Override
public String insertComment(CommentVO vo) {
return mapper.insertComment(vo);
}
@Override
public String updateComment(CommentVO vo) {
return mapper.updateComment(vo);
}
@Override
public int deleteComment(int commentid) {
return mapper.deleteComment(commentid);
}
@Override
public int boardDeleteComment(int boardid) {
return mapper.boardDeleteComment(boardid);
}
}
| 1,163 | 0.77902 | 0.77902 | 56 | 19.767857 | 19.78635 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.053571 | false | false | 15 |
a4af42585d459adc08be56a15384c88a59592722 | 22,720,377,017,588 | 37dd58627b60e55487b190408629ea69e86a8f3b | /app/src/main/java/com/ug/eon/android/tv/infoserver/entities/VodAsset.java | d542b25164291ef810c02c18e9026cddc879640c | []
| no_license | srbro/socblogstb | https://github.com/srbro/socblogstb | c57db81db9bb202b3465a563e8fc18c59646426c | 3f4a39596f4c767565939a5a34f0774a33904823 | refs/heads/master | 2020-03-18T06:28:43.061000 | 2018-05-30T10:03:53 | 2018-05-30T10:03:53 | 134,398,227 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ug.eon.android.tv.infoserver.entities;
/**
* Created by goran.arandjelovic on 4/4/18.
*/
public class VodAsset extends Asset {
private int year;
private long duration;
public VodAsset() {
super(AssetType.VOD);
}
public int getYear() { return year; }
public long getDuration() { return duration; }
}
| UTF-8 | Java | 349 | java | VodAsset.java | Java | [
{
"context": "android.tv.infoserver.entities;\n\n/**\n * Created by goran.arandjelovic on 4/4/18.\n */\n\npublic class VodAsset extends Ass",
"end": 88,
"score": 0.9705782532691956,
"start": 70,
"tag": "NAME",
"value": "goran.arandjelovic"
}
]
| null | []
| package com.ug.eon.android.tv.infoserver.entities;
/**
* Created by goran.arandjelovic on 4/4/18.
*/
public class VodAsset extends Asset {
private int year;
private long duration;
public VodAsset() {
super(AssetType.VOD);
}
public int getYear() { return year; }
public long getDuration() { return duration; }
}
| 349 | 0.659026 | 0.647564 | 17 | 19.529411 | 18.702368 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 15 |
0e4ddaea8978bbfd9ae2c09824e86e89cb5ac982 | 29,308,856,852,202 | e7d44a7762bd1e345a36f38ba80feefa284ce56c | /process-portal/src/main/java/org/eclipse/stardust/ui/web/processportal/view/manual/IppDocumentInputController.java | 6e9e90bf96fda420b4abca4547ef3632ef69647e | []
| no_license | robsman/stardust.ui.web | https://github.com/robsman/stardust.ui.web | 3463f16f010b23a1dd8efed073b0e09b82801ef6 | c6e670f98ef84a2e589971751a4571c42127d89e | refs/heads/master | 2021-01-01T19:48:26.459000 | 2016-02-22T15:24:18 | 2016-02-22T15:24:18 | 11,172,029 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright (c) 2011 SunGard CSA LLC and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* SunGard CSA LLC - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.stardust.ui.web.processportal.view.manual;
import java.util.Map;
import org.eclipse.stardust.common.CollectionUtils;
import org.eclipse.stardust.engine.api.model.DataMapping;
import org.eclipse.stardust.engine.api.runtime.ActivityInstance;
import org.eclipse.stardust.engine.api.runtime.Document;
import org.eclipse.stardust.ui.common.form.jsf.DocumentInputController;
import org.eclipse.stardust.ui.common.form.jsf.DocumentPath;
import org.eclipse.stardust.ui.web.common.app.PortalApplication;
import org.eclipse.stardust.ui.web.common.app.View;
import org.eclipse.stardust.ui.web.common.app.View.ViewState;
import org.eclipse.stardust.ui.web.common.dialogs.ConfirmationDialogHandler;
import org.eclipse.stardust.ui.web.common.dialogs.ConfirmationDialog.DialogActionType;
import org.eclipse.stardust.ui.web.common.dialogs.ConfirmationDialog.DialogContentType;
import org.eclipse.stardust.ui.web.common.event.ViewDataEvent;
import org.eclipse.stardust.ui.web.common.event.ViewDataEventHandler;
import org.eclipse.stardust.ui.web.common.log.LogManager;
import org.eclipse.stardust.ui.web.common.log.Logger;
import org.eclipse.stardust.ui.web.common.util.StringUtils;
import org.eclipse.stardust.ui.web.processportal.common.MessagePropertiesBean;
import org.eclipse.stardust.ui.web.processportal.view.ActivityDetailsBean.WorkflowAction;
import org.eclipse.stardust.ui.web.processportal.view.manual.DocumentInputEventHandler.DocumentInputEvent;
import org.eclipse.stardust.ui.web.processportal.view.manual.DocumentInputEventHandler.DocumentInputEvent.DocumentInputEventType;
import org.eclipse.stardust.ui.web.viewscommon.core.ResourcePaths;
import org.eclipse.stardust.ui.web.viewscommon.dialogs.ConfirmationDialogWithOptionsBean;
import org.eclipse.stardust.ui.web.viewscommon.docmgmt.DocumentMgmtUtility;
import org.eclipse.stardust.ui.web.viewscommon.docmgmt.DocumentViewUtil;
import org.eclipse.stardust.ui.web.viewscommon.docmgmt.ResourceNotFoundException;
import org.eclipse.stardust.ui.web.viewscommon.docmgmt.upload.FileWrapper;
import org.eclipse.stardust.ui.web.viewscommon.messages.MessagesViewsCommonBean;
import org.eclipse.stardust.ui.web.viewscommon.utils.ActivityInstanceUtils;
import org.eclipse.stardust.ui.web.viewscommon.utils.DMSHelper;
import org.eclipse.stardust.ui.web.viewscommon.utils.IceComponentUtil;
import org.eclipse.stardust.ui.web.viewscommon.utils.MIMEType;
import org.eclipse.stardust.ui.web.viewscommon.utils.MimeTypesHelper;
import org.eclipse.stardust.ui.web.viewscommon.views.doctree.CommonFileUploadDialog;
import org.eclipse.stardust.ui.web.viewscommon.views.doctree.CommonFileUploadDialog.FileUploadCallbackHandler;
import org.eclipse.stardust.ui.web.viewscommon.views.doctree.CommonFileUploadDialog.FileUploadDialogAttributes;
import org.eclipse.stardust.ui.web.viewscommon.views.document.FileSystemJCRDocument;
import org.eclipse.stardust.ui.web.viewscommon.views.document.IDocumentContentInfo;
import org.eclipse.stardust.ui.web.viewscommon.views.document.JCRDocument;
/**
* @author Subodh.Godbole
*
*/
public class IppDocumentInputController extends DocumentInputController implements ViewDataEventHandler
{
private static final Logger trace = LogManager.getLogger(IppDocumentInputController.class);
private static final String DELETE_DOCUMENT_OPTIONS_PREFIX = "views.activityPanel.deleteDocument.options.";
private static enum RemoveDocumentOptions {
MOVE_TO_PROCESS_ATTACHMENTS, DELETE_PERMANENTLY;
}
private View documentView;
private ActivityInstance activityInstance;
private DataMapping dataMapping;
private DocumentInputEventHandler handler;
private boolean openDocument = true;
private boolean enableOpenDocument = true;
private Document documentToBeMoved;
private Document documentToBeDeleted;
private boolean disableAutoDownload;
private Boolean readable = null;
/**
* @param path
* @param activityInstance
* @param dataMapping
*/
public IppDocumentInputController(DocumentPath path, ActivityInstance activityInstance, DataMapping dataMapping,
DocumentInputEventHandler handler)
{
super(path);
this.activityInstance = activityInstance;
this.dataMapping = dataMapping;
this.handler = handler;
setDeleteIcon("/plugins/views-common/images/icons/page_white_delete.png");
setDeleteLabel(MessagesViewsCommonBean.getInstance().getString("views.genericRepositoryView.treeMenuItem.delete"));
}
@Override
public void setValue(Object object)
{
super.setValue(object);
// It's observed that sometimes document is not received as null
// So check with obvious attributes (id or name), if any of them are empty then consider document as null
// Scenario is -
// - Open Activity where document is already assigned to Data Mapping.
// - Delete Document And save the Activity
// - Now open Activity again - It returns non null document, but actually document should be null
if (null != document && (StringUtils.isEmpty(document.getId()) || StringUtils.isEmpty(document.getName())))
{
document = null;
}
if (null != document)
{
setOpenLabel(document.getName());
MIMEType mimeType = MimeTypesHelper.detectMimeType(document.getName(), document.getContentType());
setOpenIcon(mimeType.getCompleteIconPath());
readable = true;
if (!(document instanceof RawDocument))
{
// TODO : review later
if (null == DocumentMgmtUtility.getDocumentManagementService().getDocument(document.getId()))
{
readable = false;
}
}
}
else
{
setOpenLabel(MessagesViewsCommonBean.getInstance().getString("views.common.document.noDocument"));
setOpenIcon(ResourcePaths.I_EMPTY_CORE_DOCUMENT);
}
}
@Override
public void viewDocument()
{
if (null != document && isReadable())
{
if (!fireEvent(DocumentInputEventType.TO_BE_VIEWED, null))
{
unregisterHandler();
IDocumentContentInfo docInfo = (document instanceof RawDocument) ? getFileSystemDocument() : getJCRDocument();
Map<String, Object> params = CollectionUtils.newMap();
params.put("processInstance", activityInstance.getProcessInstance());
params.put("dataPathId", dataMapping.getDataPath());
params.put("dataId", dataMapping.getDataId());
if(disableAutoDownload)
{
params.put("disableAutoDownload", disableAutoDownload);
}
documentView = DocumentViewUtil.openDataMappingDocument(activityInstance.getProcessInstance(),
dataMapping.getDataId(), docInfo, params);
PortalApplication.getInstance().registerViewDataEventHandler(documentView, this);
refreshPortalSession();
fireEvent(DocumentInputEventType.VIEWED, null);
}
}
}
/* (non-Javadoc)
* @see org.eclipse.stardust.ui.common.form.jsf.DocumentInputController#saveDocument()
*/
public boolean saveDocument()
{
// Save Document only if it's Raw/Unsaved Document
if (document instanceof RawDocument)
{
FileSystemJCRDocument fsDoc = getFileSystemDocument();
JCRDocument jcrDoc = (JCRDocument)fsDoc.save(fsDoc.retrieveContent());
setValue(jcrDoc.getDocument());
return true;
}
return false;
}
/* (non-Javadoc)
* @see org.eclipse.stardust.ui.common.form.jsf.DocumentInputController#closeDocument()
*/
public void closeDocument()
{
if (isDocumentViewerOpened())
{
PortalApplication.getInstance().closeView(documentView);
unregisterHandler();
refreshPortalSession();
}
}
@Override
protected void uploadDocument()
{
MessagesViewsCommonBean propsBean = MessagesViewsCommonBean.getInstance();
CommonFileUploadDialog fileUploadDialog = CommonFileUploadDialog.getInstance();
fileUploadDialog.initializeBean();
FileUploadDialogAttributes attributes = fileUploadDialog.getAttributes();
attributes.setDocumentType(getPath().getDocumentType());
attributes.setHeaderMessage(propsBean.getParamString(
"views.genericRepositoryView.specificDocument.uploadFile", label));
attributes.setOpenDocumentFlag(openDocument);
attributes.setEnableOpenDocument(enableOpenDocument);
fileUploadDialog.setCallbackHandler(new FileUploadCallbackHandler()
{
public void handleEvent(FileUploadEvent eventType)
{
if (eventType == FileUploadEvent.FILE_UPLOADED)
{
try
{
FileWrapper fileWrapper = getFileWrapper();
RawDocument rawDocument = new RawDocument(fileWrapper.getFileInfo());
rawDocument.setDescription(fileWrapper.getDescription());
rawDocument.setComments(fileWrapper.getComments());
rawDocument.setDocumentType(fileWrapper.getDocumentType());
if(fileWrapper.isOpenDocument())
{
// disableAutoDownload : To Suppress autoDownload for
// unsupportedFileType on DocumentViewer open after upload
disableAutoDownload = true;
}
if (!fireEvent(DocumentInputEventType.TO_BE_UPLOADED, getFileSystemDocument(rawDocument)))
{
setValue(rawDocument);
fireEvent(DocumentInputEventType.UPLOADED, null);
if (fileWrapper.isOpenDocument())
{
disableAutoDownload = true;
viewDocument();
}
}
refreshPortalSession();
disableAutoDownload = false;
}
catch (Exception e)
{
}
}
}
});
fileUploadDialog.openPopup();
refreshPortalSession();
}
/**
* Display confirmation dialog only in case of JCR document, else just update activity panel
*
* @author Yogesh.Manware
*
*/
@Override
public void deleteDocument()
{
// check if the document is JCR document
if (!(document instanceof RawDocument) && isReadable())
{
MessagePropertiesBean propsBean = MessagePropertiesBean.getInstance();
ConfirmationDialogWithOptionsBean confirmationDialog = ConfirmationDialogWithOptionsBean.getInstance();
confirmationDialog.setContentType(DialogContentType.WARNING);
confirmationDialog.setActionType(DialogActionType.OK_CANCEL);
confirmationDialog.setTitle(MessagesViewsCommonBean.getInstance().getString("common.confirm"));
// If process supports process attachments
if (DMSHelper.existsProcessAttachmentsDataPath(activityInstance.getProcessInstance()))
{
confirmationDialog.setMessage(propsBean.getString("views.activityPanel.deleteDocument.message"));
confirmationDialog.setIncludePath(ResourcePaths.V_CONFIRMATION_DIALOG_OPTIONS);
// set available options
String[] keys = {RemoveDocumentOptions.MOVE_TO_PROCESS_ATTACHMENTS.name(), RemoveDocumentOptions.DELETE_PERMANENTLY.name()};
confirmationDialog.setOptions(IceComponentUtil.buildSelectItemArray(DELETE_DOCUMENT_OPTIONS_PREFIX, keys,
MessagePropertiesBean.getInstance()));
confirmationDialog.setSelectedOption(DELETE_DOCUMENT_OPTIONS_PREFIX
+ RemoveDocumentOptions.MOVE_TO_PROCESS_ATTACHMENTS.name());
confirmationDialog.setHandler(new ConfirmationDialogHandler()
{
public boolean cancel()
{
return true;
}
public boolean accept()
{
if (ConfirmationDialogWithOptionsBean.getInstance().getSelectedOption()
.contains(RemoveDocumentOptions.MOVE_TO_PROCESS_ATTACHMENTS.name()))
{
handleDocumentToBeMoved(document);
}
else
{
handleDocumentToBeDeleted(document);
}
updateActivityPanel();
return true;
}
});
}
// If process does not supports process attachments
else
{
confirmationDialog.setMessage(MessagesViewsCommonBean.getInstance().getString(
"common.confirmDeleteRes.message.label"));
confirmationDialog.setActionType(DialogActionType.YES_NO);
confirmationDialog.setHandler(new ConfirmationDialogHandler()
{
public boolean cancel()
{
return true;
}
public boolean accept()
{
handleDocumentToBeDeleted(document);
updateActivityPanel();
return true;
}
});
}
confirmationDialog.openPopup();
}
else
{
updateActivityPanel();
}
}
/**
* @param document
*/
private void handleDocumentToBeDeleted(Document document)
{
if (null != documentToBeMoved || null != documentToBeDeleted)
{
DocumentMgmtUtility.getDocumentManagementService().removeDocument(documentToBeDeleted.getId());
}
else
{
documentToBeDeleted = document;
}
}
/**
* @param documentMoved
*/
private void handleDocumentToBeMoved(Document documentMoved)
{
if (null != documentToBeMoved || null != documentToBeDeleted)
{
DMSHelper.addAndSaveProcessAttachment(activityInstance.getProcessInstance(), documentMoved, true);
}
else
{
documentToBeMoved = documentMoved;
}
}
/**
* @param action
*/
private void processJCRDocuments(String action)
{
if (WorkflowAction.COMPLETE.name().equals(action) || WorkflowAction.SAVE.name().equals(action))
{
if (null != documentToBeDeleted)
{
DocumentMgmtUtility.getDocumentManagementService().removeDocument(documentToBeDeleted.getId());
}
if (null != documentToBeMoved)
{
DMSHelper.addAndSaveProcessAttachment(activityInstance.getProcessInstance(), documentToBeMoved, true);
}
}
}
private void updateActivityPanel()
{
if (!fireEvent(DocumentInputEventType.TO_BE_DELETED, null))
{
setValue(null);
closeDocument();
fireEvent(DocumentInputEventType.DELETED, null);
}
}
@Override
public void destroy(String action)
{
processJCRDocuments(action);
super.destroy(action);
unregisterHandler();
}
/* (non-Javadoc)
* @see org.eclipse.stardust.ui.web.common.event.ViewDataEventHandler#handleEvent(org.eclipse.stardust.ui.web.common.event.ViewDataEvent)
*/
public void handleEvent(ViewDataEvent event)
{
switch (event.getType())
{
case DATA_MODIFIED:
Object payload = event.getPayload();
if (payload instanceof JCRDocument)
{
setValue(((JCRDocument)payload).getDocument());
}
else
{
// Ideally, this should not happen
trace.error("Received Document is not instanceof JCRDocument");
}
break;
}
}
/**
* @return
*/
public boolean isDocumentViewerOpened()
{
return (null != documentView && ViewState.CLOSED != documentView.getViewState()) ? true : false;
}
/**
* @return
*/
public IDocumentContentInfo getDocumentContentInfo()
{
if (document instanceof RawDocument)
{
return getFileSystemDocument();
}
else
{
return getJCRDocument();
}
}
/**
* @param doc
* @return
*/
private FileSystemJCRDocument getFileSystemDocument(Document doc)
{
if (doc instanceof RawDocument)
{
RawDocument rawDocument = (RawDocument) doc;
String parentFolder = DocumentMgmtUtility.getTypedDocumentsFolderPath(activityInstance.getProcessInstance());
return new FileSystemJCRDocument(rawDocument.getFileInfo().getPhysicalPath(), doc.getDocumentType(),
parentFolder, rawDocument.getDescription(), rawDocument.getComments());
}
return null;
}
/**
* @return
*/
private FileSystemJCRDocument getFileSystemDocument()
{
return getFileSystemDocument(document);
}
/**
* @return
*/
private JCRDocument getJCRDocument()
{
try
{
document = DocumentMgmtUtility.getDocument(document.getId());
}
catch (ResourceNotFoundException e)
{
// should never occur
}
return new JCRDocument(document, getPath().isReadonly());
}
/**
*
*/
private void unregisterHandler()
{
if (null != documentView)
{
PortalApplication.getInstance().unregisterViewDataEventHandler(documentView, this);
}
}
/**
*
*/
private void refreshPortalSession()
{
if (ActivityInstanceUtils.isIframeBased(activityInstance))
{
PortalApplication.getInstance().renderPortalSession();
}
}
/**
* @param eventType
* @param newDocument
* @return
*/
private boolean fireEvent(DocumentInputEventType eventType, IDocumentContentInfo newDocument)
{
if (null != handler)
{
DocumentInputEvent event = new DocumentInputEvent(this, eventType, newDocument);
handler.handleEvent(event);
return event.isVetoed();
}
return false;
}
public DataMapping getDataMapping()
{
return dataMapping;
}
public void setOpenDocument(boolean openDocument)
{
this.openDocument = openDocument;
}
public void setEnableOpenDocument(boolean enableOpenDocument)
{
this.enableOpenDocument = enableOpenDocument;
}
public boolean isReadable()
{
return readable;
}
}
| UTF-8 | Java | 19,662 | java | IppDocumentInputController.java | Java | [
{
"context": "views.document.JCRDocument;\r\n\r\n\r\n\r\n/**\r\n * @author Subodh.Godbole\r\n *\r\n */\r\npublic class IppDocumentInputController",
"end": 3686,
"score": 0.999862551689148,
"start": 3672,
"tag": "NAME",
"value": "Subodh.Godbole"
},
{
"context": " just update activity panel\r\n * \r\n * @author Yogesh.Manware\r\n * \r\n */\r\n @Override\r\n public void del",
"end": 11220,
"score": 0.9998729825019836,
"start": 11206,
"tag": "NAME",
"value": "Yogesh.Manware"
}
]
| null | []
| /*******************************************************************************
* Copyright (c) 2011 SunGard CSA LLC and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* SunGard CSA LLC - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.stardust.ui.web.processportal.view.manual;
import java.util.Map;
import org.eclipse.stardust.common.CollectionUtils;
import org.eclipse.stardust.engine.api.model.DataMapping;
import org.eclipse.stardust.engine.api.runtime.ActivityInstance;
import org.eclipse.stardust.engine.api.runtime.Document;
import org.eclipse.stardust.ui.common.form.jsf.DocumentInputController;
import org.eclipse.stardust.ui.common.form.jsf.DocumentPath;
import org.eclipse.stardust.ui.web.common.app.PortalApplication;
import org.eclipse.stardust.ui.web.common.app.View;
import org.eclipse.stardust.ui.web.common.app.View.ViewState;
import org.eclipse.stardust.ui.web.common.dialogs.ConfirmationDialogHandler;
import org.eclipse.stardust.ui.web.common.dialogs.ConfirmationDialog.DialogActionType;
import org.eclipse.stardust.ui.web.common.dialogs.ConfirmationDialog.DialogContentType;
import org.eclipse.stardust.ui.web.common.event.ViewDataEvent;
import org.eclipse.stardust.ui.web.common.event.ViewDataEventHandler;
import org.eclipse.stardust.ui.web.common.log.LogManager;
import org.eclipse.stardust.ui.web.common.log.Logger;
import org.eclipse.stardust.ui.web.common.util.StringUtils;
import org.eclipse.stardust.ui.web.processportal.common.MessagePropertiesBean;
import org.eclipse.stardust.ui.web.processportal.view.ActivityDetailsBean.WorkflowAction;
import org.eclipse.stardust.ui.web.processportal.view.manual.DocumentInputEventHandler.DocumentInputEvent;
import org.eclipse.stardust.ui.web.processportal.view.manual.DocumentInputEventHandler.DocumentInputEvent.DocumentInputEventType;
import org.eclipse.stardust.ui.web.viewscommon.core.ResourcePaths;
import org.eclipse.stardust.ui.web.viewscommon.dialogs.ConfirmationDialogWithOptionsBean;
import org.eclipse.stardust.ui.web.viewscommon.docmgmt.DocumentMgmtUtility;
import org.eclipse.stardust.ui.web.viewscommon.docmgmt.DocumentViewUtil;
import org.eclipse.stardust.ui.web.viewscommon.docmgmt.ResourceNotFoundException;
import org.eclipse.stardust.ui.web.viewscommon.docmgmt.upload.FileWrapper;
import org.eclipse.stardust.ui.web.viewscommon.messages.MessagesViewsCommonBean;
import org.eclipse.stardust.ui.web.viewscommon.utils.ActivityInstanceUtils;
import org.eclipse.stardust.ui.web.viewscommon.utils.DMSHelper;
import org.eclipse.stardust.ui.web.viewscommon.utils.IceComponentUtil;
import org.eclipse.stardust.ui.web.viewscommon.utils.MIMEType;
import org.eclipse.stardust.ui.web.viewscommon.utils.MimeTypesHelper;
import org.eclipse.stardust.ui.web.viewscommon.views.doctree.CommonFileUploadDialog;
import org.eclipse.stardust.ui.web.viewscommon.views.doctree.CommonFileUploadDialog.FileUploadCallbackHandler;
import org.eclipse.stardust.ui.web.viewscommon.views.doctree.CommonFileUploadDialog.FileUploadDialogAttributes;
import org.eclipse.stardust.ui.web.viewscommon.views.document.FileSystemJCRDocument;
import org.eclipse.stardust.ui.web.viewscommon.views.document.IDocumentContentInfo;
import org.eclipse.stardust.ui.web.viewscommon.views.document.JCRDocument;
/**
* @author Subodh.Godbole
*
*/
public class IppDocumentInputController extends DocumentInputController implements ViewDataEventHandler
{
private static final Logger trace = LogManager.getLogger(IppDocumentInputController.class);
private static final String DELETE_DOCUMENT_OPTIONS_PREFIX = "views.activityPanel.deleteDocument.options.";
private static enum RemoveDocumentOptions {
MOVE_TO_PROCESS_ATTACHMENTS, DELETE_PERMANENTLY;
}
private View documentView;
private ActivityInstance activityInstance;
private DataMapping dataMapping;
private DocumentInputEventHandler handler;
private boolean openDocument = true;
private boolean enableOpenDocument = true;
private Document documentToBeMoved;
private Document documentToBeDeleted;
private boolean disableAutoDownload;
private Boolean readable = null;
/**
* @param path
* @param activityInstance
* @param dataMapping
*/
public IppDocumentInputController(DocumentPath path, ActivityInstance activityInstance, DataMapping dataMapping,
DocumentInputEventHandler handler)
{
super(path);
this.activityInstance = activityInstance;
this.dataMapping = dataMapping;
this.handler = handler;
setDeleteIcon("/plugins/views-common/images/icons/page_white_delete.png");
setDeleteLabel(MessagesViewsCommonBean.getInstance().getString("views.genericRepositoryView.treeMenuItem.delete"));
}
@Override
public void setValue(Object object)
{
super.setValue(object);
// It's observed that sometimes document is not received as null
// So check with obvious attributes (id or name), if any of them are empty then consider document as null
// Scenario is -
// - Open Activity where document is already assigned to Data Mapping.
// - Delete Document And save the Activity
// - Now open Activity again - It returns non null document, but actually document should be null
if (null != document && (StringUtils.isEmpty(document.getId()) || StringUtils.isEmpty(document.getName())))
{
document = null;
}
if (null != document)
{
setOpenLabel(document.getName());
MIMEType mimeType = MimeTypesHelper.detectMimeType(document.getName(), document.getContentType());
setOpenIcon(mimeType.getCompleteIconPath());
readable = true;
if (!(document instanceof RawDocument))
{
// TODO : review later
if (null == DocumentMgmtUtility.getDocumentManagementService().getDocument(document.getId()))
{
readable = false;
}
}
}
else
{
setOpenLabel(MessagesViewsCommonBean.getInstance().getString("views.common.document.noDocument"));
setOpenIcon(ResourcePaths.I_EMPTY_CORE_DOCUMENT);
}
}
@Override
public void viewDocument()
{
if (null != document && isReadable())
{
if (!fireEvent(DocumentInputEventType.TO_BE_VIEWED, null))
{
unregisterHandler();
IDocumentContentInfo docInfo = (document instanceof RawDocument) ? getFileSystemDocument() : getJCRDocument();
Map<String, Object> params = CollectionUtils.newMap();
params.put("processInstance", activityInstance.getProcessInstance());
params.put("dataPathId", dataMapping.getDataPath());
params.put("dataId", dataMapping.getDataId());
if(disableAutoDownload)
{
params.put("disableAutoDownload", disableAutoDownload);
}
documentView = DocumentViewUtil.openDataMappingDocument(activityInstance.getProcessInstance(),
dataMapping.getDataId(), docInfo, params);
PortalApplication.getInstance().registerViewDataEventHandler(documentView, this);
refreshPortalSession();
fireEvent(DocumentInputEventType.VIEWED, null);
}
}
}
/* (non-Javadoc)
* @see org.eclipse.stardust.ui.common.form.jsf.DocumentInputController#saveDocument()
*/
public boolean saveDocument()
{
// Save Document only if it's Raw/Unsaved Document
if (document instanceof RawDocument)
{
FileSystemJCRDocument fsDoc = getFileSystemDocument();
JCRDocument jcrDoc = (JCRDocument)fsDoc.save(fsDoc.retrieveContent());
setValue(jcrDoc.getDocument());
return true;
}
return false;
}
/* (non-Javadoc)
* @see org.eclipse.stardust.ui.common.form.jsf.DocumentInputController#closeDocument()
*/
public void closeDocument()
{
if (isDocumentViewerOpened())
{
PortalApplication.getInstance().closeView(documentView);
unregisterHandler();
refreshPortalSession();
}
}
@Override
protected void uploadDocument()
{
MessagesViewsCommonBean propsBean = MessagesViewsCommonBean.getInstance();
CommonFileUploadDialog fileUploadDialog = CommonFileUploadDialog.getInstance();
fileUploadDialog.initializeBean();
FileUploadDialogAttributes attributes = fileUploadDialog.getAttributes();
attributes.setDocumentType(getPath().getDocumentType());
attributes.setHeaderMessage(propsBean.getParamString(
"views.genericRepositoryView.specificDocument.uploadFile", label));
attributes.setOpenDocumentFlag(openDocument);
attributes.setEnableOpenDocument(enableOpenDocument);
fileUploadDialog.setCallbackHandler(new FileUploadCallbackHandler()
{
public void handleEvent(FileUploadEvent eventType)
{
if (eventType == FileUploadEvent.FILE_UPLOADED)
{
try
{
FileWrapper fileWrapper = getFileWrapper();
RawDocument rawDocument = new RawDocument(fileWrapper.getFileInfo());
rawDocument.setDescription(fileWrapper.getDescription());
rawDocument.setComments(fileWrapper.getComments());
rawDocument.setDocumentType(fileWrapper.getDocumentType());
if(fileWrapper.isOpenDocument())
{
// disableAutoDownload : To Suppress autoDownload for
// unsupportedFileType on DocumentViewer open after upload
disableAutoDownload = true;
}
if (!fireEvent(DocumentInputEventType.TO_BE_UPLOADED, getFileSystemDocument(rawDocument)))
{
setValue(rawDocument);
fireEvent(DocumentInputEventType.UPLOADED, null);
if (fileWrapper.isOpenDocument())
{
disableAutoDownload = true;
viewDocument();
}
}
refreshPortalSession();
disableAutoDownload = false;
}
catch (Exception e)
{
}
}
}
});
fileUploadDialog.openPopup();
refreshPortalSession();
}
/**
* Display confirmation dialog only in case of JCR document, else just update activity panel
*
* @author Yogesh.Manware
*
*/
@Override
public void deleteDocument()
{
// check if the document is JCR document
if (!(document instanceof RawDocument) && isReadable())
{
MessagePropertiesBean propsBean = MessagePropertiesBean.getInstance();
ConfirmationDialogWithOptionsBean confirmationDialog = ConfirmationDialogWithOptionsBean.getInstance();
confirmationDialog.setContentType(DialogContentType.WARNING);
confirmationDialog.setActionType(DialogActionType.OK_CANCEL);
confirmationDialog.setTitle(MessagesViewsCommonBean.getInstance().getString("common.confirm"));
// If process supports process attachments
if (DMSHelper.existsProcessAttachmentsDataPath(activityInstance.getProcessInstance()))
{
confirmationDialog.setMessage(propsBean.getString("views.activityPanel.deleteDocument.message"));
confirmationDialog.setIncludePath(ResourcePaths.V_CONFIRMATION_DIALOG_OPTIONS);
// set available options
String[] keys = {RemoveDocumentOptions.MOVE_TO_PROCESS_ATTACHMENTS.name(), RemoveDocumentOptions.DELETE_PERMANENTLY.name()};
confirmationDialog.setOptions(IceComponentUtil.buildSelectItemArray(DELETE_DOCUMENT_OPTIONS_PREFIX, keys,
MessagePropertiesBean.getInstance()));
confirmationDialog.setSelectedOption(DELETE_DOCUMENT_OPTIONS_PREFIX
+ RemoveDocumentOptions.MOVE_TO_PROCESS_ATTACHMENTS.name());
confirmationDialog.setHandler(new ConfirmationDialogHandler()
{
public boolean cancel()
{
return true;
}
public boolean accept()
{
if (ConfirmationDialogWithOptionsBean.getInstance().getSelectedOption()
.contains(RemoveDocumentOptions.MOVE_TO_PROCESS_ATTACHMENTS.name()))
{
handleDocumentToBeMoved(document);
}
else
{
handleDocumentToBeDeleted(document);
}
updateActivityPanel();
return true;
}
});
}
// If process does not supports process attachments
else
{
confirmationDialog.setMessage(MessagesViewsCommonBean.getInstance().getString(
"common.confirmDeleteRes.message.label"));
confirmationDialog.setActionType(DialogActionType.YES_NO);
confirmationDialog.setHandler(new ConfirmationDialogHandler()
{
public boolean cancel()
{
return true;
}
public boolean accept()
{
handleDocumentToBeDeleted(document);
updateActivityPanel();
return true;
}
});
}
confirmationDialog.openPopup();
}
else
{
updateActivityPanel();
}
}
/**
* @param document
*/
private void handleDocumentToBeDeleted(Document document)
{
if (null != documentToBeMoved || null != documentToBeDeleted)
{
DocumentMgmtUtility.getDocumentManagementService().removeDocument(documentToBeDeleted.getId());
}
else
{
documentToBeDeleted = document;
}
}
/**
* @param documentMoved
*/
private void handleDocumentToBeMoved(Document documentMoved)
{
if (null != documentToBeMoved || null != documentToBeDeleted)
{
DMSHelper.addAndSaveProcessAttachment(activityInstance.getProcessInstance(), documentMoved, true);
}
else
{
documentToBeMoved = documentMoved;
}
}
/**
* @param action
*/
private void processJCRDocuments(String action)
{
if (WorkflowAction.COMPLETE.name().equals(action) || WorkflowAction.SAVE.name().equals(action))
{
if (null != documentToBeDeleted)
{
DocumentMgmtUtility.getDocumentManagementService().removeDocument(documentToBeDeleted.getId());
}
if (null != documentToBeMoved)
{
DMSHelper.addAndSaveProcessAttachment(activityInstance.getProcessInstance(), documentToBeMoved, true);
}
}
}
private void updateActivityPanel()
{
if (!fireEvent(DocumentInputEventType.TO_BE_DELETED, null))
{
setValue(null);
closeDocument();
fireEvent(DocumentInputEventType.DELETED, null);
}
}
@Override
public void destroy(String action)
{
processJCRDocuments(action);
super.destroy(action);
unregisterHandler();
}
/* (non-Javadoc)
* @see org.eclipse.stardust.ui.web.common.event.ViewDataEventHandler#handleEvent(org.eclipse.stardust.ui.web.common.event.ViewDataEvent)
*/
public void handleEvent(ViewDataEvent event)
{
switch (event.getType())
{
case DATA_MODIFIED:
Object payload = event.getPayload();
if (payload instanceof JCRDocument)
{
setValue(((JCRDocument)payload).getDocument());
}
else
{
// Ideally, this should not happen
trace.error("Received Document is not instanceof JCRDocument");
}
break;
}
}
/**
* @return
*/
public boolean isDocumentViewerOpened()
{
return (null != documentView && ViewState.CLOSED != documentView.getViewState()) ? true : false;
}
/**
* @return
*/
public IDocumentContentInfo getDocumentContentInfo()
{
if (document instanceof RawDocument)
{
return getFileSystemDocument();
}
else
{
return getJCRDocument();
}
}
/**
* @param doc
* @return
*/
private FileSystemJCRDocument getFileSystemDocument(Document doc)
{
if (doc instanceof RawDocument)
{
RawDocument rawDocument = (RawDocument) doc;
String parentFolder = DocumentMgmtUtility.getTypedDocumentsFolderPath(activityInstance.getProcessInstance());
return new FileSystemJCRDocument(rawDocument.getFileInfo().getPhysicalPath(), doc.getDocumentType(),
parentFolder, rawDocument.getDescription(), rawDocument.getComments());
}
return null;
}
/**
* @return
*/
private FileSystemJCRDocument getFileSystemDocument()
{
return getFileSystemDocument(document);
}
/**
* @return
*/
private JCRDocument getJCRDocument()
{
try
{
document = DocumentMgmtUtility.getDocument(document.getId());
}
catch (ResourceNotFoundException e)
{
// should never occur
}
return new JCRDocument(document, getPath().isReadonly());
}
/**
*
*/
private void unregisterHandler()
{
if (null != documentView)
{
PortalApplication.getInstance().unregisterViewDataEventHandler(documentView, this);
}
}
/**
*
*/
private void refreshPortalSession()
{
if (ActivityInstanceUtils.isIframeBased(activityInstance))
{
PortalApplication.getInstance().renderPortalSession();
}
}
/**
* @param eventType
* @param newDocument
* @return
*/
private boolean fireEvent(DocumentInputEventType eventType, IDocumentContentInfo newDocument)
{
if (null != handler)
{
DocumentInputEvent event = new DocumentInputEvent(this, eventType, newDocument);
handler.handleEvent(event);
return event.isVetoed();
}
return false;
}
public DataMapping getDataMapping()
{
return dataMapping;
}
public void setOpenDocument(boolean openDocument)
{
this.openDocument = openDocument;
}
public void setEnableOpenDocument(boolean enableOpenDocument)
{
this.enableOpenDocument = enableOpenDocument;
}
public boolean isReadable()
{
return readable;
}
}
| 19,662 | 0.637677 | 0.63727 | 550 | 33.749092 | 32.778412 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.403636 | false | false | 15 |
7ca8292fe40f18805b2591ea6522925be8551f46 | 29,308,856,854,197 | 5da11477903c4d538ce8e45c0b6f410b6742034a | /src/main/io/pixelinc/bigbrother/events/InteractEvent.java | bad5f730cc4853da0d1b5ff1a2c5b5bab8c6af3f | []
| no_license | PixeLInc/BigBrother | https://github.com/PixeLInc/BigBrother | ac239d9b89039f0585f9140d52f6d76052e557fd | f3c188cc35fc4d25b9c26c79eb6d16af7ccd5725 | refs/heads/master | 2021-09-20T10:46:50.854000 | 2018-08-08T08:44:16 | 2018-08-08T08:44:16 | 143,982,661 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.pixelinc.bigbrother.events;
import io.pixelinc.bigbrother.BigBrother;
import org.spongepowered.api.data.type.HandType;
import org.spongepowered.api.data.type.HandTypes;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.InteractBlockEvent;
import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import java.util.Optional;
public class InteractEvent extends BasicEvent{
public InteractEvent(BigBrother plugin) {
super(plugin);
}
@Listener
public void onInteract(InteractBlockEvent.Secondary.MainHand event) {
Player player = event.getCause().first(Player.class).orElse(null);
if (player == null)
return;
String blockName = event.getTargetBlock().getState().getType().getName();
Location<World> location = event.getTargetBlock().getLocation().orElse(null);
if (!blockName.equalsIgnoreCase("minecraft:air") && location == null) {
plugin.logger.error("Location is null of " + blockName);
return;
}
if (plugin.activeInspectors.contains(player.getUniqueId())) {
// make sure they're not holding anything so they can place and inspect things nd such.
// maybe limit to a tool? :<
Optional<ItemStack> heldItem = player.getItemInHand(HandTypes.MAIN_HAND);
if (!heldItem.isPresent() || heldItem.get().getType().equals(ItemTypes.NONE)) {
// send it off to our async service
plugin.asyncService.lookup(player, location);
event.setCancelled(true);
}
}
}
}
| UTF-8 | Java | 1,822 | java | InteractEvent.java | Java | []
| null | []
| package io.pixelinc.bigbrother.events;
import io.pixelinc.bigbrother.BigBrother;
import org.spongepowered.api.data.type.HandType;
import org.spongepowered.api.data.type.HandTypes;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.InteractBlockEvent;
import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import java.util.Optional;
public class InteractEvent extends BasicEvent{
public InteractEvent(BigBrother plugin) {
super(plugin);
}
@Listener
public void onInteract(InteractBlockEvent.Secondary.MainHand event) {
Player player = event.getCause().first(Player.class).orElse(null);
if (player == null)
return;
String blockName = event.getTargetBlock().getState().getType().getName();
Location<World> location = event.getTargetBlock().getLocation().orElse(null);
if (!blockName.equalsIgnoreCase("minecraft:air") && location == null) {
plugin.logger.error("Location is null of " + blockName);
return;
}
if (plugin.activeInspectors.contains(player.getUniqueId())) {
// make sure they're not holding anything so they can place and inspect things nd such.
// maybe limit to a tool? :<
Optional<ItemStack> heldItem = player.getItemInHand(HandTypes.MAIN_HAND);
if (!heldItem.isPresent() || heldItem.get().getType().equals(ItemTypes.NONE)) {
// send it off to our async service
plugin.asyncService.lookup(player, location);
event.setCancelled(true);
}
}
}
}
| 1,822 | 0.684962 | 0.684962 | 46 | 38.608696 | 29.096899 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.543478 | false | false | 15 |
aec9031f2aaac321adc693491b6caeb2d55fc523 | 42,949,705,433 | 87f74bd3cdee42d337c72c94cb600e0346a63dcb | /src/main/java/AopCglib/LogRecord.java | b23df4c877d316cba1f291a39afdf97b06417753 | []
| no_license | jidanbing/Spring | https://github.com/jidanbing/Spring | 5a8c6e5e2b483b0d6778ad70c24e96774106aca2 | 7ded05739f968ce0b1fc8cef406f3d663e29a1f6 | refs/heads/master | 2022-12-23T19:56:42.341000 | 2020-09-08T12:28:08 | 2020-09-08T12:28:08 | 293,802,778 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package AopCglib;
//日志记录功能
public class LogRecord {
/**
* 增强 :在切入点处要执行的代码(方法)
* 织入 :将增强应用到切入点的过程叫做织入
* 代理类: 织入之后会产生一个代理类,一般此代理类是目标类的子类
* 切面 : 增强 + 切入点 组成了切面
*/
//增强
public void start() {
System.out.println("CglibProxy日志记录的开启");
}
//增强
public void close() {
System.out.println("CglibProxy日志记录的关闭");
}
}
| UTF-8 | Java | 586 | java | LogRecord.java | Java | []
| null | []
| package AopCglib;
//日志记录功能
public class LogRecord {
/**
* 增强 :在切入点处要执行的代码(方法)
* 织入 :将增强应用到切入点的过程叫做织入
* 代理类: 织入之后会产生一个代理类,一般此代理类是目标类的子类
* 切面 : 增强 + 切入点 组成了切面
*/
//增强
public void start() {
System.out.println("CglibProxy日志记录的开启");
}
//增强
public void close() {
System.out.println("CglibProxy日志记录的关闭");
}
}
| 586 | 0.566138 | 0.566138 | 21 | 17 | 15.02062 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 15 |
4db3c956407c9d91295c19efcf8afcfe61b6af42 | 7,842,610,336,317 | 58381242351a7b6724a248adaa51b51b39ea365c | /src/main/java/edu/tamu/eider/app/model/validator/BeforeSaveIdentifierValidator.java | fecd23f13f1ad389e4f211b87015a804a4807cc1 | [
"MIT"
]
| permissive | TAMULib/EIDER | https://github.com/TAMULib/EIDER | d428c8a2ad9b2f078d51b205288ef8d947608f87 | 27bca1cacfe60ad1e8139ca62a4446750b49dd06 | refs/heads/main | 2023-01-09T01:54:10.130000 | 2022-11-04T19:39:28 | 2022-11-04T19:39:28 | 248,798,037 | 3 | 0 | MIT | false | 2023-01-07T19:34:58 | 2020-03-20T16:08:14 | 2022-01-05T05:12:49 | 2023-01-07T19:34:56 | 214 | 1 | 0 | 9 | Java | false | false | package edu.tamu.eider.app.model.validator;
import org.springframework.stereotype.Component;
@Component
public class BeforeSaveIdentifierValidator extends IdentifierUniqueUrlValidator {
}
| UTF-8 | Java | 191 | java | BeforeSaveIdentifierValidator.java | Java | []
| null | []
| package edu.tamu.eider.app.model.validator;
import org.springframework.stereotype.Component;
@Component
public class BeforeSaveIdentifierValidator extends IdentifierUniqueUrlValidator {
}
| 191 | 0.853403 | 0.853403 | 8 | 22.875 | 28.785576 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 15 |
e4e8f77a7f7445f761b97427551cf244e02b6e9e | 29,721,173,727,172 | 0bbada7f12bf181a6155adb4754985b1680d8096 | /hlu-master/taskman/taskman-api/src/main/java/com/globits/taskman/service/TaskFlowService.java | dba2d3cb3432878ad7a273fa532ab9e27d5b331d | []
| no_license | haiduong07137/hlu-master-angularJS | https://github.com/haiduong07137/hlu-master-angularJS | 173b30b50fa737ec2c46cf43a2ff8b8c168bad44 | 98d7fe3a6dc945f122b79d8e030bcf6716d05c98 | refs/heads/master | 2023-01-28T02:34:40.997000 | 2020-12-04T14:06:44 | 2020-12-04T14:06:44 | 318,525,604 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.globits.taskman.service;
import java.util.List;
import org.springframework.data.domain.Page;
import com.globits.core.service.GenericService;
import com.globits.taskman.domain.TaskFlow;
import com.globits.taskman.dto.TaskFlowDto;
public interface TaskFlowService extends GenericService<TaskFlow, Long> {
public TaskFlowDto getTaskFlowByCode(String code);
public TaskFlowDto getTaskFlow(Long id);
public TaskFlow getFullTaskFlowById(Long id);
public TaskFlowDto saveTaskFlow(TaskFlowDto dto);
public Boolean deleteTaskFlow(Long id);
public Page<TaskFlowDto> getListTaskFlow(int pageSize, int pageIndex);
public List<TaskFlowDto> getAll();
}
| UTF-8 | Java | 664 | java | TaskFlowService.java | Java | []
| null | []
| package com.globits.taskman.service;
import java.util.List;
import org.springframework.data.domain.Page;
import com.globits.core.service.GenericService;
import com.globits.taskman.domain.TaskFlow;
import com.globits.taskman.dto.TaskFlowDto;
public interface TaskFlowService extends GenericService<TaskFlow, Long> {
public TaskFlowDto getTaskFlowByCode(String code);
public TaskFlowDto getTaskFlow(Long id);
public TaskFlow getFullTaskFlowById(Long id);
public TaskFlowDto saveTaskFlow(TaskFlowDto dto);
public Boolean deleteTaskFlow(Long id);
public Page<TaskFlowDto> getListTaskFlow(int pageSize, int pageIndex);
public List<TaskFlowDto> getAll();
}
| 664 | 0.819277 | 0.819277 | 20 | 32.200001 | 23.43203 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.15 | false | false | 15 |
65ebb6f87a2df7a9eec7ff0638bfff5b76fce8b5 | 7,335,804,142,188 | 53d66b46e4cc076d182972c24f9782108f2448f5 | /src/main/java/com/usda/fmsc/geospatial/nmea41/SentenceFormats.java | 0be5289b054ec7f746deeac97e400bc6eb3ac440 | []
| no_license | FMSC-Measurements/FMSC-GeoSpatial | https://github.com/FMSC-Measurements/FMSC-GeoSpatial | a723527c12bbf39fdd631097b3de65e9f287c489 | 1fda5843fb6f4e3388be129df25f6a355051d4a0 | refs/heads/master | 2023-08-31T01:04:57.216000 | 2022-08-18T21:16:43 | 2022-08-18T21:16:43 | 51,477,097 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.usda.fmsc.geospatial.nmea41;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class SentenceFormats {
public static final DateTimeFormatter DateTimeFormatter = DateTimeFormat.forPattern("HHmmss.SSS ddMMYY");
public static final DateTimeFormatter DateTimeFormatterAlt = DateTimeFormat.forPattern("HHmmss ddMMYY");
public static final DateTimeFormatter TimeFormatter = DateTimeFormat.forPattern("HHmmss.SSS");
public static final DateTimeFormatter TimeFormatterAlt = DateTimeFormat.forPattern("HHmmss");
}
| UTF-8 | Java | 584 | java | SentenceFormats.java | Java | []
| null | []
| package com.usda.fmsc.geospatial.nmea41;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class SentenceFormats {
public static final DateTimeFormatter DateTimeFormatter = DateTimeFormat.forPattern("HHmmss.SSS ddMMYY");
public static final DateTimeFormatter DateTimeFormatterAlt = DateTimeFormat.forPattern("HHmmss ddMMYY");
public static final DateTimeFormatter TimeFormatter = DateTimeFormat.forPattern("HHmmss.SSS");
public static final DateTimeFormatter TimeFormatterAlt = DateTimeFormat.forPattern("HHmmss");
}
| 584 | 0.816781 | 0.813356 | 12 | 47.666668 | 42.581947 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 15 |
c88c91d783441bd1500e08a851a7bc28ae3c62a1 | 16,595,753,634,191 | 41939569391976e5df40a3986e833a849fbc3403 | /3-BinaryTreeAndDivideAndConquer/src/binaryTreeAndDivideConquer/MaximumDepthOfBinaryTree.java | ff3e3e8f49b107fe9b0d2febd7613c439a643fc8 | []
| no_license | lovelyllh/lintcode | https://github.com/lovelyllh/lintcode | a94328efd7e37f449d45f753b614acd190ec1ce2 | ab2e02bfeb3b12e830987fee48671e6277599a40 | refs/heads/master | 2021-01-10T21:11:51.258000 | 2015-10-30T20:09:00 | 2015-10-30T20:09:00 | 41,653,908 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package binaryTreeAndDivideConquer;
/*Maximum Depth of Binary Tree
question: http://www.lintcode.com/en/problem/maximum-depth-of-binary-tree/
answer: http://www.jiuzhang.com/solutions/maximum-depth-of-binary-tree/
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example
Given a binary tree as follow:
1
/ \
2 3
/ \
4 5
The maximum depth is 3.
*/
//version1: recursive
public class MaximumDepthOfBinaryTree {
public static int maximumDepth(TreeNode root){
if (root == null){
return 0;
}
int leftValue;
int rightValue;
leftValue= maximumDepth(root.left);
rightValue = maximumDepth(root.right);
return Math.max(leftValue, rightValue) + 1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode r1 = new TreeNode(1);
TreeNode r2 = new TreeNode(2);
TreeNode r3 = new TreeNode(3);
TreeNode r4 = new TreeNode(4);
TreeNode r5 = new TreeNode(5);
r1.left = r2;
r1.right = r3;
r2.left = null;
r2.right = null;
r3.left = r4;
r3.right = r5;
r4.left = null;
r4.right = null;
r5.left = null;
r5.right = null;
System.out.println(maximumDepth(r1));
}
}
| UTF-8 | Java | 1,251 | java | MaximumDepthOfBinaryTree.java | Java | []
| null | []
| package binaryTreeAndDivideConquer;
/*Maximum Depth of Binary Tree
question: http://www.lintcode.com/en/problem/maximum-depth-of-binary-tree/
answer: http://www.jiuzhang.com/solutions/maximum-depth-of-binary-tree/
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example
Given a binary tree as follow:
1
/ \
2 3
/ \
4 5
The maximum depth is 3.
*/
//version1: recursive
public class MaximumDepthOfBinaryTree {
public static int maximumDepth(TreeNode root){
if (root == null){
return 0;
}
int leftValue;
int rightValue;
leftValue= maximumDepth(root.left);
rightValue = maximumDepth(root.right);
return Math.max(leftValue, rightValue) + 1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode r1 = new TreeNode(1);
TreeNode r2 = new TreeNode(2);
TreeNode r3 = new TreeNode(3);
TreeNode r4 = new TreeNode(4);
TreeNode r5 = new TreeNode(5);
r1.left = r2;
r1.right = r3;
r2.left = null;
r2.right = null;
r3.left = r4;
r3.right = r5;
r4.left = null;
r4.right = null;
r5.left = null;
r5.right = null;
System.out.println(maximumDepth(r1));
}
}
| 1,251 | 0.698641 | 0.671463 | 50 | 24.02 | 21.46764 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.6 | false | false | 15 |
ea4bc7959eb379cbc71baf2cf443a6a8b4b2e5ab | 16,363,825,454,875 | 4c3fedbd07da995dafac7c77668cd447fcd42a88 | /app-erppy-model/src/main/java/py/com/erppy/model/base/Departamento.java | 4e4b9a11f5b9f85d5acaf931c99b2ebc477fb00f | []
| no_license | rorogarcete/ERP | https://github.com/rorogarcete/ERP | 6314e105b7dc636477874198e27549405c64a7bf | 5db349e9843b180a8392d841514e61cafe9cec72 | refs/heads/master | 2015-08-23T14:01:01.631000 | 2015-04-21T15:58:33 | 2015-04-21T15:58:33 | 34,333,085 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package py.com.erppy.model.base;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* Entidad Departamento, cada objeto representa un registro de la respectiva tabla
* @author Rodrigo Garcete
* @since 23/11/2013
* Se ha utilizado JPA Proyections para optimizar la consulta
*/
//@Entity
//@Table(name = "departamentos")
public class Departamento extends NamedEntity {
private static final long serialVersionUID = 1L;
private String abreviatura;
//@ManyToOne
//@JoinColumn(name = "paisId")
//@Basic(optional = false)
//private Pais pais;
private int activo;
// Constructor por Defecto
public Departamento() {
super();
//his.pais = new Pais();
}
public Departamento(Long codigo, String nombre){
this.codigo = codigo;
this.nombre = nombre;
}
//Metodos Getters and Setters
public String getAbreviatura() {
return abreviatura;
}
public void setAbreviatura(String abreviatura) {
this.abreviatura = abreviatura;
}
public int getActivo() {
return activo;
}
public void setActivo(int activo) {
this.activo = activo;
}
// public Pais getPais() {
// return pais;
// }
//
// public void setPais(Pais pais) {
// this.pais = pais;
// }
} | UTF-8 | Java | 1,304 | java | Departamento.java | Java | [
{
"context": "enta un registro de la respectiva tabla\n * @author Rodrigo Garcete \n * @since 23/11/2013\n * Se ha utilizado JPA Proy",
"end": 317,
"score": 0.9998636841773987,
"start": 302,
"tag": "NAME",
"value": "Rodrigo Garcete"
}
]
| null | []
| package py.com.erppy.model.base;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* Entidad Departamento, cada objeto representa un registro de la respectiva tabla
* @author <NAME>
* @since 23/11/2013
* Se ha utilizado JPA Proyections para optimizar la consulta
*/
//@Entity
//@Table(name = "departamentos")
public class Departamento extends NamedEntity {
private static final long serialVersionUID = 1L;
private String abreviatura;
//@ManyToOne
//@JoinColumn(name = "paisId")
//@Basic(optional = false)
//private Pais pais;
private int activo;
// Constructor por Defecto
public Departamento() {
super();
//his.pais = new Pais();
}
public Departamento(Long codigo, String nombre){
this.codigo = codigo;
this.nombre = nombre;
}
//Metodos Getters and Setters
public String getAbreviatura() {
return abreviatura;
}
public void setAbreviatura(String abreviatura) {
this.abreviatura = abreviatura;
}
public int getActivo() {
return activo;
}
public void setActivo(int activo) {
this.activo = activo;
}
// public Pais getPais() {
// return pais;
// }
//
// public void setPais(Pais pais) {
// this.pais = pais;
// }
} | 1,295 | 0.717025 | 0.710123 | 65 | 19.076923 | 17.738535 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.046154 | false | false | 15 |
5bfe136a1f24ec705c402c7d640165d7524d863f | 7,370,163,909,727 | ac5fab606704d7c8fd70c07db6025d923e7ce424 | /src/tipo/Tipo.java | c3f2f29450f86f05c45af4d43e7b7f2fac9e4ebf | []
| no_license | aabarbosa/compiler | https://github.com/aabarbosa/compiler | 2ad6c8fd0fd1554fd4afe02437e75dc60f49f5ea | 13c92a95729b452381f66987ae590bd1181275a9 | refs/heads/master | 2020-03-30T17:06:50.046000 | 2018-12-04T23:13:43 | 2018-12-04T23:13:43 | 151,441,702 | 0 | 0 | null | false | 2018-11-03T14:40:25 | 2018-10-03T16:10:00 | 2018-10-24T11:41:04 | 2018-11-03T14:40:25 | 2,098 | 0 | 0 | 0 | Pascal | false | null | package tipo;
import java.util.HashMap;
public class Tipo {
public static final int CHAR = 1;
public static final int INTEGER = 2;
public static final int REAL = 3;
public static final int BOOLEAN = 4;
public static final int TIPO_VOID = 5;
public static final int ERRO = 6;
public static final int NOME = 7;
public static final int ARRAY = 8;
public static final int STRING = 9;
public static final int BYTE = 10;
public static final int SHORTINT = 11;
public static final int DOUBLE = 12;
public static final int LONGINT = 13;
public static final int WORD = 14;
public static final int REFERENCIA = 90;
public static final int PRODUCT = 91;
public static final int FUNCAO = 93;
public static final int NIL = 0;
static HashMap<String, Tipo> tipos = new HashMap<String, Tipo>();
int tag;
int width = 0;
String val;
public Tipo(int tag, int width, String val) {
this.tag = tag;
this.width = width;
this.val = val;
}
public int getWidth() {
return width;
}
public int getTag() {
return tag;
}
public String getVal() {
return val;
}
public static void criaTipos() {
tipos.put(INTEGER+"", new Tipo(INTEGER, 2, "integer"));
tipos.put(LONGINT+"", new Tipo(LONGINT, 4, "longint"));
tipos.put(SHORTINT+"", new Tipo(SHORTINT, 1, "integer"));
tipos.put(REAL+"", new Tipo(REAL, 6, "real"));
tipos.put(DOUBLE+"", new Tipo(DOUBLE, 8, "double"));
tipos.put(WORD+"", new Tipo(WORD, 2, "word"));
tipos.put(BYTE+"", new Tipo(BYTE, 1, "byte"));
tipos.put(CHAR+"", new Tipo(CHAR, 1, "char"));
tipos.put(STRING+"", new Tipo(STRING, 8, "string"));
tipos.put(BOOLEAN+"", new Tipo(BOOLEAN, 1, "boolean"));
tipos.put(TIPO_VOID+"", new Tipo(TIPO_VOID, 0, "void"));
tipos.put(NIL+"", new Tipo(NIL, 0, "nil"));
tipos.put(ERRO+"", new Tipo(ERRO, 0, "error"));
}
public static Tipo getTipo(int tag) {
return tipos.get(""+tag);
}
public static Tipo getTipo(String val) {
for(Tipo tipo : tipos.values()) {
if(tipo.getVal().equals(val))
return tipo;
}
return null;
}
public static Tipo maximo(Tipo t1, Tipo t2) {
return t1.width > t2.width ? t1 : t2;
}
}
| UTF-8 | Java | 2,140 | java | Tipo.java | Java | []
| null | []
| package tipo;
import java.util.HashMap;
public class Tipo {
public static final int CHAR = 1;
public static final int INTEGER = 2;
public static final int REAL = 3;
public static final int BOOLEAN = 4;
public static final int TIPO_VOID = 5;
public static final int ERRO = 6;
public static final int NOME = 7;
public static final int ARRAY = 8;
public static final int STRING = 9;
public static final int BYTE = 10;
public static final int SHORTINT = 11;
public static final int DOUBLE = 12;
public static final int LONGINT = 13;
public static final int WORD = 14;
public static final int REFERENCIA = 90;
public static final int PRODUCT = 91;
public static final int FUNCAO = 93;
public static final int NIL = 0;
static HashMap<String, Tipo> tipos = new HashMap<String, Tipo>();
int tag;
int width = 0;
String val;
public Tipo(int tag, int width, String val) {
this.tag = tag;
this.width = width;
this.val = val;
}
public int getWidth() {
return width;
}
public int getTag() {
return tag;
}
public String getVal() {
return val;
}
public static void criaTipos() {
tipos.put(INTEGER+"", new Tipo(INTEGER, 2, "integer"));
tipos.put(LONGINT+"", new Tipo(LONGINT, 4, "longint"));
tipos.put(SHORTINT+"", new Tipo(SHORTINT, 1, "integer"));
tipos.put(REAL+"", new Tipo(REAL, 6, "real"));
tipos.put(DOUBLE+"", new Tipo(DOUBLE, 8, "double"));
tipos.put(WORD+"", new Tipo(WORD, 2, "word"));
tipos.put(BYTE+"", new Tipo(BYTE, 1, "byte"));
tipos.put(CHAR+"", new Tipo(CHAR, 1, "char"));
tipos.put(STRING+"", new Tipo(STRING, 8, "string"));
tipos.put(BOOLEAN+"", new Tipo(BOOLEAN, 1, "boolean"));
tipos.put(TIPO_VOID+"", new Tipo(TIPO_VOID, 0, "void"));
tipos.put(NIL+"", new Tipo(NIL, 0, "nil"));
tipos.put(ERRO+"", new Tipo(ERRO, 0, "error"));
}
public static Tipo getTipo(int tag) {
return tipos.get(""+tag);
}
public static Tipo getTipo(String val) {
for(Tipo tipo : tipos.values()) {
if(tipo.getVal().equals(val))
return tipo;
}
return null;
}
public static Tipo maximo(Tipo t1, Tipo t2) {
return t1.width > t2.width ? t1 : t2;
}
}
| 2,140 | 0.653738 | 0.632243 | 81 | 25.419754 | 19.323027 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.395062 | false | false | 15 |
0c4002f8b27137301eef46f3079430e0036817bd | 32,512,902,459,292 | c87ea1d1e96d4d4f533aa517f6d5f6bb41dc7dab | /cluster/src/main/java/com/argo/cluster/app/AppNodeRegister.java | 006aee970ae7f1bea902f94c49a14d74f526ce86 | [
"Apache-2.0"
]
| permissive | 343829084/argo | https://github.com/343829084/argo | 4055dc3bdade46e4f27768fd901d5c0985aad5e0 | 319e836d9daeb70742c1876af72f9345129dfdc7 | refs/heads/master | 2020-12-26T03:43:39.915000 | 2015-12-03T13:36:47 | 2015-12-03T13:36:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.argo.cluster.app;
import com.argo.core.ContextConfig;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import com.argo.cluster.ZKClientBeanBase;
import com.argo.cluster.server.ZookeeperConfig;
/**
* 注册应用运行实例(如Jetty,Tomcat)
* @author yaming_deng
*
*/
public class AppNodeRegister extends ZKClientBeanBase {
public static final String FOLDER_CONFIGS = "/servers";
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
this.setRootPath(this.getRootPath()+"/"+ ContextConfig.getRunning()+FOLDER_CONFIGS);
}
@Override
protected void onConnected() {
String path = this.getRootPath() + "/" + ZookeeperConfig.instance.getAppName();
try {
this.zkServer.createFolderNodes(path, CreateMode.PERSISTENT);
this.zkServer.createDataNode(path + "/node", ZookeeperConfig.instance.getAppURI().getBytes(), CreateMode.EPHEMERAL_SEQUENTIAL);
} catch (KeeperException e) {
this.logger.error("Add Node Error. path="+path, e);
} catch (InterruptedException e) {
this.logger.error("Add Node Error. path="+path, e);
}
}
@Override
protected void onNodeChanged(WatchedEvent event) {
this.logger.warn("onNodeChanged. event={}", event);
}
}
| UTF-8 | Java | 1,313 | java | AppNodeRegister.java | Java | [
{
"context": "Config;\n\n/**\n * 注册应用运行实例(如Jetty,Tomcat)\n * @author yaming_deng\n *\n */\npublic class AppNodeRegister extends ZKCli",
"end": 339,
"score": 0.9988646507263184,
"start": 328,
"tag": "USERNAME",
"value": "yaming_deng"
}
]
| null | []
| package com.argo.cluster.app;
import com.argo.core.ContextConfig;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import com.argo.cluster.ZKClientBeanBase;
import com.argo.cluster.server.ZookeeperConfig;
/**
* 注册应用运行实例(如Jetty,Tomcat)
* @author yaming_deng
*
*/
public class AppNodeRegister extends ZKClientBeanBase {
public static final String FOLDER_CONFIGS = "/servers";
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
this.setRootPath(this.getRootPath()+"/"+ ContextConfig.getRunning()+FOLDER_CONFIGS);
}
@Override
protected void onConnected() {
String path = this.getRootPath() + "/" + ZookeeperConfig.instance.getAppName();
try {
this.zkServer.createFolderNodes(path, CreateMode.PERSISTENT);
this.zkServer.createDataNode(path + "/node", ZookeeperConfig.instance.getAppURI().getBytes(), CreateMode.EPHEMERAL_SEQUENTIAL);
} catch (KeeperException e) {
this.logger.error("Add Node Error. path="+path, e);
} catch (InterruptedException e) {
this.logger.error("Add Node Error. path="+path, e);
}
}
@Override
protected void onNodeChanged(WatchedEvent event) {
this.logger.warn("onNodeChanged. event={}", event);
}
}
| 1,313 | 0.744402 | 0.744402 | 44 | 28.431818 | 29.103575 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.409091 | false | false | 15 |
deac2c71e10977a178b169afa63736ed9fb2a605 | 25,503,515,868,550 | 66c594c11058d3c27fdf682e5504e5b4b19c7ac8 | /app/src/main/java/com/sinjvf/tetris/MainActivity.java | e02c34daf987dd154f88db353aad33295df5db69 | []
| no_license | Sinjvf/asTet | https://github.com/Sinjvf/asTet | 68667e1ef36e0dac8d81dd1ebfe64eaee6f9e80d | fabbaaa7395a93ae41d7a273ff829a602ff922aa | refs/heads/master | 2021-01-10T15:43:36.392000 | 2016-02-01T15:20:06 | 2016-02-01T15:20:06 | 48,169,763 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sinjvf.tetris;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.Query;
import com.google.android.gms.drive.query.SearchableField;
import com.google.android.gms.games.Games;
import com.google.android.gms.plus.Plus;
import com.google.example.games.basegameutils.BaseGameActivity;
import com.google.example.games.basegameutils.BaseGameUtils;
public class MainActivity extends Activity implements View.OnClickListener {
private Button buttonNewGame,
buttonRating,
buttonSettings,
buttonAbout,
buttonFinish;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initAPI();
setContentView(R.layout.main_layout);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
buttonNewGame = (Button)findViewById(R.id.button_new_game_layout);
buttonRating = (Button)findViewById(R.id.button_results_layout);
buttonSettings = (Button)findViewById(R.id.button_settings_layout);
buttonAbout = (Button)findViewById(R.id.button_about_layout);
buttonFinish = (Button)findViewById(R.id.button_finish_main);
// buttonSignIn = (Button) findViewById(R.id.sign_in_button);
// buttonSignOut = (Button)findViewById(R.id.sign_out_button);
if (Const.Connect )
{buttonRating.setVisibility(View.VISIBLE);}
buttonNewGame.setOnClickListener(this);
buttonRating.setOnClickListener(this);
buttonSettings.setOnClickListener(this);
buttonAbout.setOnClickListener(this);
buttonFinish.setOnClickListener(this);
// buttonSignIn.setOnClickListener(this);
// buttonSignOut.setOnClickListener(this);
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.logo_small);
ActivityManager.TaskDescription taskDesc =
new ActivityManager.TaskDescription(getString(R.string.app_name),
icon, ContextCompat.getColor(this, R.color.dark_primary));
this.setTaskDescription(taskDesc);
}
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
@Override
public void onClick(View v) {
switch (v.getId()) {/*
case R.id.sign_in_button:
// start the asynchronous sign in flow
initAPI();
mSignInClicked = true;
mGoogleApiClient.connect();
break;
case R.id.sign_out_button:
// sign out.
mSignInClicked = false;
Games.signOut(mGoogleApiClient);
// show sign-in button, hide the sign-out button
buttonSignIn.setVisibility(View.VISIBLE);
buttonSignOut.setVisibility(View.GONE);
buttonRating.setVisibility(View.GONE);
break;*/
case R.id.button_new_game_layout:
intent = new Intent(this, ChoiceActivity.class);
intent.putExtra(Const.LAYOUT, Const.NEW_GAME_LAYOUT);
startActivity(intent);
finish();
break;
case R.id.button_results_layout:
intent = new Intent(this, ChoiceActivity.class);
intent.putExtra(Const.LAYOUT, Const.RESULTS_LAYOUT);
startActivity(intent);
finish();
break;
case R.id.button_settings_layout:
intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
finish();
break;
case R.id.button_about_layout:
intent = new Intent(this, AboutActivity.class);
startActivity(intent);
finish();
break;
case R.id.button_finish_main:
finish();
break;
}
}
} | UTF-8 | Java | 5,259 | java | MainActivity.java | Java | []
| null | []
| package com.sinjvf.tetris;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.Query;
import com.google.android.gms.drive.query.SearchableField;
import com.google.android.gms.games.Games;
import com.google.android.gms.plus.Plus;
import com.google.example.games.basegameutils.BaseGameActivity;
import com.google.example.games.basegameutils.BaseGameUtils;
public class MainActivity extends Activity implements View.OnClickListener {
private Button buttonNewGame,
buttonRating,
buttonSettings,
buttonAbout,
buttonFinish;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initAPI();
setContentView(R.layout.main_layout);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
buttonNewGame = (Button)findViewById(R.id.button_new_game_layout);
buttonRating = (Button)findViewById(R.id.button_results_layout);
buttonSettings = (Button)findViewById(R.id.button_settings_layout);
buttonAbout = (Button)findViewById(R.id.button_about_layout);
buttonFinish = (Button)findViewById(R.id.button_finish_main);
// buttonSignIn = (Button) findViewById(R.id.sign_in_button);
// buttonSignOut = (Button)findViewById(R.id.sign_out_button);
if (Const.Connect )
{buttonRating.setVisibility(View.VISIBLE);}
buttonNewGame.setOnClickListener(this);
buttonRating.setOnClickListener(this);
buttonSettings.setOnClickListener(this);
buttonAbout.setOnClickListener(this);
buttonFinish.setOnClickListener(this);
// buttonSignIn.setOnClickListener(this);
// buttonSignOut.setOnClickListener(this);
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.logo_small);
ActivityManager.TaskDescription taskDesc =
new ActivityManager.TaskDescription(getString(R.string.app_name),
icon, ContextCompat.getColor(this, R.color.dark_primary));
this.setTaskDescription(taskDesc);
}
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
@Override
public void onClick(View v) {
switch (v.getId()) {/*
case R.id.sign_in_button:
// start the asynchronous sign in flow
initAPI();
mSignInClicked = true;
mGoogleApiClient.connect();
break;
case R.id.sign_out_button:
// sign out.
mSignInClicked = false;
Games.signOut(mGoogleApiClient);
// show sign-in button, hide the sign-out button
buttonSignIn.setVisibility(View.VISIBLE);
buttonSignOut.setVisibility(View.GONE);
buttonRating.setVisibility(View.GONE);
break;*/
case R.id.button_new_game_layout:
intent = new Intent(this, ChoiceActivity.class);
intent.putExtra(Const.LAYOUT, Const.NEW_GAME_LAYOUT);
startActivity(intent);
finish();
break;
case R.id.button_results_layout:
intent = new Intent(this, ChoiceActivity.class);
intent.putExtra(Const.LAYOUT, Const.RESULTS_LAYOUT);
startActivity(intent);
finish();
break;
case R.id.button_settings_layout:
intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
finish();
break;
case R.id.button_about_layout:
intent = new Intent(this, AboutActivity.class);
startActivity(intent);
finish();
break;
case R.id.button_finish_main:
finish();
break;
}
}
} | 5,259 | 0.618749 | 0.618559 | 125 | 41.080002 | 22.019482 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 15 |
6aab6baa815051c9263a1fe80f55b14946ce097e | 8,392,366,123,403 | 4ac1f13b0ae845739cea56a46b9cf4d512a7e02d | /Casa/src/main/Programma.java | c37ad07647cc7c65dde1848a8123924f9ede662d | []
| no_license | PieroVaghi/CorsoJava | https://github.com/PieroVaghi/CorsoJava | 207d6a2851199d4b2bfd8e19855eef00f8c8c259 | 67ffe33ceadb5103fdce4ea88ab2d053ea0cd685 | refs/heads/master | 2020-08-05T02:04:58.137000 | 2019-12-05T11:37:50 | 2019-12-05T11:37:50 | 212,356,801 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main;
import entities.Stanza;
public class Programma {
public static void main(String[] args) {
// Qui dentro solo inserimento input
Stanza s1 = new Stanza();
s1.altezza = 6.0;
s1.base = 5.0;
s1.tipo = "Cucina";
// la "chiamata a funzioni"
// la stampa dell'output
System.out.println(s1.descrizione());
}
}
| UTF-8 | Java | 362 | java | Programma.java | Java | []
| null | []
| package main;
import entities.Stanza;
public class Programma {
public static void main(String[] args) {
// Qui dentro solo inserimento input
Stanza s1 = new Stanza();
s1.altezza = 6.0;
s1.base = 5.0;
s1.tipo = "Cucina";
// la "chiamata a funzioni"
// la stampa dell'output
System.out.println(s1.descrizione());
}
}
| 362 | 0.618785 | 0.593923 | 22 | 14.454545 | 14.227781 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.227273 | false | false | 15 |
3a66ab168c265f33219954bf529bc98d968923dc | 16,209,206,613,350 | e9d39747a5f602d6a73dc1e5e6a950cc2aace0be | /2016-jm-group-02-master/src/main/java/grupo2/tpAnual/Web/Models/SingletonDatosBusquedaRepository.java | 774c70d05be264ecc77da13da8f73e84df7bb9cf | []
| no_license | aailenm/tpDiseno | https://github.com/aailenm/tpDiseno | 54a527ae2c411d1534fc9ad7231d2c4f1f68cafc | 33ced92614a4b27479abf351eaf07fab77c8885e | refs/heads/master | 2019-03-20T17:10:46.405000 | 2018-03-05T23:28:10 | 2018-03-05T23:28:10 | 123,991,912 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package grupo2.tpAnual.Web.Models;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.uqbar.geodds.Point;
import org.uqbarproject.jpa.java8.extras.WithGlobalEntityManager;
import org.uqbarproject.jpa.java8.extras.test.AbstractPersistenceTest;
import grupo2.tpAnual.MorphiaService;
import grupo2.tpAnual.AccesoriosPois.Rango;
import grupo2.tpAnual.Pois.Comercio;
import grupo2.tpAnual.Pois.POI;
import grupo2.tpAnual.Repositorios.DatosBusquedaRepositoryMemory;
import grupo2.tpAnual.Repositorios.DatosBusquedaRepositoryMongoDB;
import grupo2.tpAnual.Repositorios.DatosDeBusqueda;
import grupo2.tpAnual.Repositorios.DatosDeBusquedaRepository;
import grupo2.tpAnual.Web.Server;
public class SingletonDatosBusquedaRepository extends AbstractPersistenceTest implements WithGlobalEntityManager{
private static DatosDeBusquedaRepository instance;
//private static EntityManager em;
private static MorphiaService morphia;
private static DatosDeBusqueda datoBuscado;
private static DatosDeBusqueda datoBuscado2;
private static DatosDeBusqueda datoBuscado3;
private static Comercio comercio;
private static Rango unRango;
private static Rango otroRango;
private static Rango rango;
private static List<Rango> listaRangos;
private static List<POI> pois;
public static DatosDeBusquedaRepository get() {
if (instance == null) {
if (Server.inMemory == true)
inMemory();
else
inDB();
}
return instance;
}
private static void inDB() {
LocalDate today=LocalDate.now();
unRango = new Rango(1, LocalTime.of(9, 0, 0), LocalTime.of(18, 0, 0));
otroRango = new Rango(3, LocalTime.of(9, 0, 0), LocalTime.of(13, 0, 0));
rango = new Rango(3, LocalTime.of(15, 0, 0), LocalTime.of(18, 30, 0));
listaRangos = Arrays.asList(unRango, otroRango, rango);
comercio = new Comercio("Supermercado argenChino", Point.and(-34.664837, -58.385674), listaRangos);
comercio.setId(4);
pois = new ArrayList<>();
pois.add(comercio);
datoBuscado = new DatosDeBusqueda("lasHeras", "libros", 10, 10, today , pois);
datoBuscado2 = new DatosDeBusqueda("flores", "carpetas", 14, 15, today.minusDays(1), pois);
datoBuscado3 = new DatosDeBusqueda("flores", "lapices", 14, 15, today.minusDays(2), pois);
morphia = new MorphiaService();
instance = new DatosBusquedaRepositoryMongoDB(DatosDeBusqueda.class, morphia.getDatastore());
instance.agregarDatosBusqueda(datoBuscado);
instance.agregarDatosBusqueda(datoBuscado2);
instance.agregarDatosBusqueda(datoBuscado3);
}
private static void inMemory() {
LocalDate today=LocalDate.now();
unRango = new Rango(1, LocalTime.of(9, 0, 0), LocalTime.of(18, 0, 0));
otroRango = new Rango(3, LocalTime.of(9, 0, 0), LocalTime.of(13, 0, 0));
rango = new Rango(3, LocalTime.of(15, 0, 0), LocalTime.of(18, 30, 0));
listaRangos = Arrays.asList(unRango, otroRango, rango);
comercio = new Comercio("Supermercado argenChino", Point.and(-34.664837, -58.385674), listaRangos);
comercio.setId(4);
pois = new ArrayList<>();
pois.add(comercio);
datoBuscado = new DatosDeBusqueda("lasHeras", "libros", 10, 15, today , pois);
datoBuscado2 = new DatosDeBusqueda("flores", "carpetas", 14, 15, today.minusDays(1), pois);
datoBuscado3 = new DatosDeBusqueda("flores", "lapices", 14, 15, today.minusDays(2), pois);
instance = new DatosBusquedaRepositoryMemory();
instance.agregarDatosBusqueda(datoBuscado);
instance.agregarDatosBusqueda(datoBuscado2);
instance.agregarDatosBusqueda(datoBuscado3);
}
}
| UTF-8 | Java | 3,603 | java | SingletonDatosBusquedaRepository.java | Java | []
| null | []
| package grupo2.tpAnual.Web.Models;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.uqbar.geodds.Point;
import org.uqbarproject.jpa.java8.extras.WithGlobalEntityManager;
import org.uqbarproject.jpa.java8.extras.test.AbstractPersistenceTest;
import grupo2.tpAnual.MorphiaService;
import grupo2.tpAnual.AccesoriosPois.Rango;
import grupo2.tpAnual.Pois.Comercio;
import grupo2.tpAnual.Pois.POI;
import grupo2.tpAnual.Repositorios.DatosBusquedaRepositoryMemory;
import grupo2.tpAnual.Repositorios.DatosBusquedaRepositoryMongoDB;
import grupo2.tpAnual.Repositorios.DatosDeBusqueda;
import grupo2.tpAnual.Repositorios.DatosDeBusquedaRepository;
import grupo2.tpAnual.Web.Server;
public class SingletonDatosBusquedaRepository extends AbstractPersistenceTest implements WithGlobalEntityManager{
private static DatosDeBusquedaRepository instance;
//private static EntityManager em;
private static MorphiaService morphia;
private static DatosDeBusqueda datoBuscado;
private static DatosDeBusqueda datoBuscado2;
private static DatosDeBusqueda datoBuscado3;
private static Comercio comercio;
private static Rango unRango;
private static Rango otroRango;
private static Rango rango;
private static List<Rango> listaRangos;
private static List<POI> pois;
public static DatosDeBusquedaRepository get() {
if (instance == null) {
if (Server.inMemory == true)
inMemory();
else
inDB();
}
return instance;
}
private static void inDB() {
LocalDate today=LocalDate.now();
unRango = new Rango(1, LocalTime.of(9, 0, 0), LocalTime.of(18, 0, 0));
otroRango = new Rango(3, LocalTime.of(9, 0, 0), LocalTime.of(13, 0, 0));
rango = new Rango(3, LocalTime.of(15, 0, 0), LocalTime.of(18, 30, 0));
listaRangos = Arrays.asList(unRango, otroRango, rango);
comercio = new Comercio("Supermercado argenChino", Point.and(-34.664837, -58.385674), listaRangos);
comercio.setId(4);
pois = new ArrayList<>();
pois.add(comercio);
datoBuscado = new DatosDeBusqueda("lasHeras", "libros", 10, 10, today , pois);
datoBuscado2 = new DatosDeBusqueda("flores", "carpetas", 14, 15, today.minusDays(1), pois);
datoBuscado3 = new DatosDeBusqueda("flores", "lapices", 14, 15, today.minusDays(2), pois);
morphia = new MorphiaService();
instance = new DatosBusquedaRepositoryMongoDB(DatosDeBusqueda.class, morphia.getDatastore());
instance.agregarDatosBusqueda(datoBuscado);
instance.agregarDatosBusqueda(datoBuscado2);
instance.agregarDatosBusqueda(datoBuscado3);
}
private static void inMemory() {
LocalDate today=LocalDate.now();
unRango = new Rango(1, LocalTime.of(9, 0, 0), LocalTime.of(18, 0, 0));
otroRango = new Rango(3, LocalTime.of(9, 0, 0), LocalTime.of(13, 0, 0));
rango = new Rango(3, LocalTime.of(15, 0, 0), LocalTime.of(18, 30, 0));
listaRangos = Arrays.asList(unRango, otroRango, rango);
comercio = new Comercio("Supermercado argenChino", Point.and(-34.664837, -58.385674), listaRangos);
comercio.setId(4);
pois = new ArrayList<>();
pois.add(comercio);
datoBuscado = new DatosDeBusqueda("lasHeras", "libros", 10, 15, today , pois);
datoBuscado2 = new DatosDeBusqueda("flores", "carpetas", 14, 15, today.minusDays(1), pois);
datoBuscado3 = new DatosDeBusqueda("flores", "lapices", 14, 15, today.minusDays(2), pois);
instance = new DatosBusquedaRepositoryMemory();
instance.agregarDatosBusqueda(datoBuscado);
instance.agregarDatosBusqueda(datoBuscado2);
instance.agregarDatosBusqueda(datoBuscado3);
}
}
| 3,603 | 0.754926 | 0.71718 | 98 | 35.765305 | 29.280069 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.77551 | false | false | 15 |
3c412cb05880e17b21105f5a5f58d5d6f918eb7e | 4,337,917,035,884 | a4b9bcf602647bf48a5412ad0f7d274b1bb147a9 | /chapter9/filters/TEST.java | 9394a11fde9325dd9acc196fc8d1b17aef58e65b | []
| no_license | huangketsudou/javalearning | https://github.com/huangketsudou/javalearning | 5680884584771b6c9a9fb1ba5838824cd0ebb550 | 6a5b751e50007702641d14588cb90c0ea0ca0f4c | refs/heads/master | 2022-11-10T14:50:08.716000 | 2020-06-25T09:12:02 | 2020-06-25T09:12:02 | 264,204,472 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chapter9.filters;
import chapter9.Applicator;
public class TEST {
public static void main(){
//Applicator.apply(new Filter(),'a');会报错
}
}
| UTF-8 | Java | 170 | java | TEST.java | Java | []
| null | []
| package chapter9.filters;
import chapter9.Applicator;
public class TEST {
public static void main(){
//Applicator.apply(new Filter(),'a');会报错
}
}
| 170 | 0.664634 | 0.652439 | 9 | 17.222221 | 15.900928 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 15 |
430050ebfaf550fd13403417262603bd21cbd354 | 15,290,083,610,703 | 1b0ef32e5f6e64699d503905b943f8ea02cfbbd1 | /src/servlets/ListeClients.java | f5a17590cd518999f0341bd52e9a78bc0a1a738c | []
| no_license | SangVUDINH/JPA_EclipseLink_espaceMembre | https://github.com/SangVUDINH/JPA_EclipseLink_espaceMembre | 491f0ddd94c9c9580a78995e52e84b59441895cb | a3abd6f3eb1be33df63e3e895f15258b5857ba11 | refs/heads/main | 2023-01-20T04:08:55.822000 | 2020-12-05T10:48:05 | 2020-12-05T10:48:05 | 318,763,117 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package servlets;
import static dao.DAOUtilitaire.listToMapClient;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
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 javax.servlet.http.HttpSession;
import dao.ClientDao;
import entities.Client;
/**
* Servlet implementation class ListeClients
*/
@WebServlet( "/listeClients" )
public class ListeClients extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String VUE = "/WEB-INF/listerClients.jsp";
public static final String CONF_DAO_FACTORY = "daofactory";
private static final String ATT_LISTE_CLIENTS = "clients";
@EJB
private ClientDao clientDao;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
List<Client> listClients = clientDao.lister();
HttpSession session = request.getSession();
Map<Long, Client> clients = listToMapClient( listClients );
if ( !listClients.isEmpty() ) {
session.setAttribute( ATT_LISTE_CLIENTS, clients );
} else {
System.out.println( "lister() a echoué" );
}
this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet( request, response );
}
}
| ISO-8859-1 | Java | 1,979 | java | ListeClients.java | Java | []
| null | []
| package servlets;
import static dao.DAOUtilitaire.listToMapClient;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
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 javax.servlet.http.HttpSession;
import dao.ClientDao;
import entities.Client;
/**
* Servlet implementation class ListeClients
*/
@WebServlet( "/listeClients" )
public class ListeClients extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String VUE = "/WEB-INF/listerClients.jsp";
public static final String CONF_DAO_FACTORY = "daofactory";
private static final String ATT_LISTE_CLIENTS = "clients";
@EJB
private ClientDao clientDao;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
List<Client> listClients = clientDao.lister();
HttpSession session = request.getSession();
Map<Long, Client> clients = listToMapClient( listClients );
if ( !listClients.isEmpty() ) {
session.setAttribute( ATT_LISTE_CLIENTS, clients );
} else {
System.out.println( "lister() a echoué" );
}
this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet( request, response );
}
}
| 1,979 | 0.694641 | 0.694135 | 65 | 29.430769 | 26.74263 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.553846 | false | false | 15 |
0cfec559061f221d4cb963fae06c38043aa8e85b | 10,780,367,913,173 | 81e80c7e9cbcc37d0aa15fa14bfcb4a30fa4ed1d | /src/studentTransactions/SelectNotification.java | 74401bed83ddae25706738d4230e3ae07d419d69 | []
| no_license | ZMullins/Course-Register | https://github.com/ZMullins/Course-Register | b96666103651c78721755966ca3cf07a5b34d3ac | f480ed0d0d38f367a22ebc93e09ba8305af398d4 | refs/heads/master | 2020-03-08T16:06:27.025000 | 2018-04-09T21:33:44 | 2018-04-09T21:33:44 | 128,230,637 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package studentTransactions;
import authenticationServer.AuthenticationToken;
import customDatatypes.NotificationTypes;
import systemUsers.StudentModel;
import transaction.Transaction;
public class SelectNotification extends Transaction {
static {
type = "SelectNotification";
}
private NotificationTypes notificationType;
public NotificationTypes getNotificationType() {
return notificationType;
}
private StudentModel student;
public StudentModel getStudent() {
return student;
}
public void setStudent(StudentModel student) {
this.student = student;
}
public void setNotificationType(NotificationTypes notificationType) {
this.notificationType = notificationType;
}
public SelectNotification(NotificationTypes notificationType, StudentModel student, AuthenticationToken token) {
this.notificationType=notificationType;
this.student = student;
setToken(token);
}
}
| UTF-8 | Java | 900 | java | SelectNotification.java | Java | []
| null | []
| package studentTransactions;
import authenticationServer.AuthenticationToken;
import customDatatypes.NotificationTypes;
import systemUsers.StudentModel;
import transaction.Transaction;
public class SelectNotification extends Transaction {
static {
type = "SelectNotification";
}
private NotificationTypes notificationType;
public NotificationTypes getNotificationType() {
return notificationType;
}
private StudentModel student;
public StudentModel getStudent() {
return student;
}
public void setStudent(StudentModel student) {
this.student = student;
}
public void setNotificationType(NotificationTypes notificationType) {
this.notificationType = notificationType;
}
public SelectNotification(NotificationTypes notificationType, StudentModel student, AuthenticationToken token) {
this.notificationType=notificationType;
this.student = student;
setToken(token);
}
}
| 900 | 0.815556 | 0.815556 | 32 | 27.125 | 24.643394 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.46875 | false | false | 15 |
725b06f9b7661bc757e86cb08bea77999654a6d9 | 15,126,874,851,292 | 417764cdb4924c326d9e22d1e8595a11260fad10 | /gzzn-fgw-web/src/main/java/com/gzzn/fgw/action/BaseAction.java | 171266dc4136e07567bcff4c1af5d2f2a57b2831 | []
| no_license | amzhangam/gzzn-fgw-model | https://github.com/amzhangam/gzzn-fgw-model | b29a34708eec6c22d45e77e36b9616b5ae4c95c4 | 0af46e8acd019c16b5f6aefe72491077ad2fc3be | refs/heads/master | 2020-03-31T08:40:06.711000 | 2014-10-23T03:23:10 | 2014-10-23T03:23:10 | 25,617,297 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gzzn.fgw.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gzzn.fgw.aop.LogObject;
import com.gzzn.fgw.webUtil.CommonFiled;
import com.gzzn.fgw.model.SysUser;
import com.gzzn.util.common.MessageUtil;
//import com.gzzn.util.json.GsonIntegerTypeAdapter;
import com.gzzn.util.json.JSONUtil;
import com.gzzn.util.web.HTMLFilter;
import com.opensymphony.xwork2.ModelDriven;
/**
*
* <p>Title: BaseAction</p>
* <p>Description:ModelDriven 实现getModel()方法,struts2就能自动把数据赋给模型对象,页面直接取值不需要model.xxx<p>
* SessionAware 通过的Map对象来注入session<p>
* ServletRequestAware 得到request对象<p>
* ServletResponseAware 得到Respone对象<p>
* <p>Copyright: Copyright (c) 2013 ITDCL All right reserved.</p>
* <p>Company: ITDCL</p>
* @author ChengZhi
* @version 1.0<p>
* 修改记录:<p>
* 下面填写修改的内容以及修改的日期
* 1.2013-8-20下午5:50:14 ChengZhi new<p>
*/
@ParentPackage(value = "struts-default")
public class BaseAction<T> implements ServletRequestAware, ServletResponseAware, SessionAware,ParameterAware,
ModelDriven<T> {
protected static Logger logger = LoggerFactory.getLogger(BaseAction.class);
protected HttpServletRequest request;
protected HttpServletResponse response;
protected Map<String, Object> session;
protected LogObject logObject;//记录日志的对象
private String isShowAlone;//用于控制页面是否为单位显示
public LogObject getLogObject() {
return logObject;
}
public void setLogObject(LogObject logObject) {
this.logObject = logObject;
}
public String getIsShowAlone() {
return isShowAlone;
}
public void setIsShowAlone(String isShowAlone) {
this.isShowAlone = isShowAlone;
}
/**
* 返回已登录用户
*
* @return
*/
public SysUser getLoginUser() {
return (SysUser) session.get(CommonFiled.SESSION_LOGIN_USER);
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
/**
* 获取HttpSession的session作用域
* @return
*/
public HttpSession getHttpSession() {
return request.getSession();
}
/**
* 对请求进行编码
*/
public void setCharacterEncodingForUtf8() {
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setCharacterEncoding("UTF-8");
}
// /**
// * GSON:jdbc查询结果转换成Json串
// * @param Long->String,Date->"yyyy-MM-dd HH:mm:ss",Integer->String
// * @return
// */
// public String toJDBCJsonStr(List<Map<String, Object>> list) {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setLongSerializationPolicy(LongSerializationPolicy.STRING);
// gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm");
// gsonBuilder.registerTypeAdapter(Integer.class, new GsonIntegerTypeAdapter());
// return gsonBuilder.create().toJson(list);
// }
/**
* 获取WebRoot路径
* @return
*/
public String getWebRootPath() {
return ServletActionContext.getServletContext().getRealPath("/");
}
/**
* 将字符JSON串返回至浏览器(多用于Ajax返回),不使用缓存
* @param ajString 需要返回的数据(JSON串)
*/
public void outPutJSON(String ajaxString) {
outPutJSON(ajaxString, true);
}
/**
* 将字符JSON串返回至浏览器(多用于Ajax返回)
* ajString 需要返回的数据(JSON串)
* @param noCache 是否使用缓存,true不使用
*/
public void outPutJSON(String ajaxString, boolean noCache) {
outPutString(ajaxString, noCache, "text/html");
}
/**
* 将字符串返回至浏览器(多用于JSON串或Ajax返回)
* @param ajString 需要返回的数据(JSON串)
* @param noCache 是否使用缓存,true不使用
* @param type 返回类型,参见ajax返回类型说明:text/javascript或application/json为json数据;text/xml或application/xml为xml数据;text/html
*/
public void outPutString(String ajString, boolean noCache, String type) {
response.setContentType(type + ";charset=utf-8");
try {
setCharacterEncodingForUtf8();
if (noCache) {
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
}
PrintWriter pw = response.getWriter();
logger.debug("out put json data:{}", ajString);
pw.write(ajString);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 返回字符串到浏览器
* @param str
*/
public void outPutString(String str) {
outPutString(str, true, "text/html");
}
/**
* 将操作消息,返回数据条数,操作返回数据组装成json串
* @param json 操作返回数据
* @param count 返回数据条数
* @param msgFlag 操作类型(成功:true,失败:false)
* @param msgCode 操作消息代码
* @return
*/
public String assemblyJson(String json, int count, Boolean msgFlag, int... msgCode) {
//LogUtil.getLogger().debug(MessageUtil.getMsg(msgCode));
return assemblyJson(json, count, MessageUtil.getMsg(msgCode), msgFlag);
}
/**
* 将操作消息,返回数据条数,操作返回数据组装成json串
* @param json 操作返回数据
* @param count 返回数据条数
* @param msg 操作消息
* @param msgFlag 操作类型(成功:true,失败:false)
* @return
*/
public String assemblyJson(String json, int count, String msg, Boolean msgFlag) {
return "{\"count\":" + count + ",\"msg\":\"" + msg + "\",\"flag\":" + msgFlag
+ ",\"result\":" + json + "}";
}
/**
* 将对象以json的形式返回到客户端
* @param obj 操作数据
* @param msgFlag 操作类型(成功:true,失败:false)
* @param msgCode 操作消息代码
*/
public <T> void outPutObject(T obj, Boolean msgFlag, int... msgCode) {
outPutJSON(assemblyJson(JSONUtil.getJSONObject(obj, null).toString(), 1, msgFlag, msgCode));
}
/**
* 将对象以json的形式返回到客户端
* @param obj 操作数据
* @param msgFlag 操作类型(成功:true,失败:false)
* @param msg 操作消息代码
*/
public <T> void outPutObject(T obj, Boolean msgFlag, String msg) {
outPutJSON(assemblyJson(JSONUtil.getJSONObject(obj, null).toString(), 1, msg, msgFlag));
}
/**
* 将对象集合以json的形式返回到客户端
* @param list 操作数据
* @param msgFlag 操作类型(成功:true,失败:false)
* @param msgCode 操作消息代码
*/
public <T> void outPutList(Collection<T> list, Boolean msgFlag, int... msgCode) {
outPutJSON(assemblyJson(JSONUtil.getJSONArray(list, null).toString(), list.size(), msgFlag,
msgCode));
}
/**
* 将对象以json的形式返回到客户端,操作类型:成功(true)
* @param obj 对象
*/
public <T> void outPutObject(T obj) {
outPutObject(obj, true, MessageUtil.MSG_SUCCESS);
}
/**
* 将对象集合以json的形式返回到客户端,操作类型:成功(true)
* @param list 集合
*/
public <T> void outPutList(Collection<T> list) {
outPutList(list, true, MessageUtil.MSG_SUCCESS);
}
/**
* 将操作消息以json的形式返回到客户端
* @param msgCode 操作消息
* @param msgFlag 操作类型:true为成功,false是失败
*/
public void outPutMsg(Boolean msgFlag, int... msgCode) {
outPutJSON(assemblyJson(null, 1, msgFlag, msgCode));
}
/**
* 将操作消息以json的形式返回到客户端
* @param msgFlag 操作类型:true为成功,false是失败
* @param msg 操作消息
*/
public void outPutMsg(Boolean msgFlag, String msg) {
outPutJSON(assemblyJson(null, 1, msg, msgFlag));
}
/**
* 将操作消息以json的形式返回到客户端,操作类型(false失败)
* @param msgCode 操作消息
*/
public void outPutError(int... msgCode) {
//LogUtil.getLogger().debug(msgCode);
outPutJSON(assemblyJson("\"error\"", 0, false, msgCode));
}
/**
* 将操作消息以json的形式返回到客户端,操作类型(false失败)
* @param msg 操作消息
*/
public void outPutError(String msg) {
outPutJSON(assemblyJson("\"error\"", 0, msg, false));
}
/**
* 将操作消息以json的形式返回到客户端,操作类型(false失败)
* @param msgCode 操作消息
*/
public void outPutErrorLogin(int... msgCode) {
outPutJSON(assemblyJson("\"login\"", 0, false, msgCode));
}
/**
* 将操作消息以json的形式返回到客户端,操作类型(false失败)
* @param msg 操作消息
*/
public void outPutErrorLogin(String msg) {
outPutJSON(assemblyJson("\"login\"", 0, msg, false));
}
public void outJsonString(String str) {
PrintWriter out = null;
try {
out = response.getWriter();
out.write(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
public SysUser getUser(){
SysUser sysUser=(SysUser)this.getHttpSession().getAttribute(CommonFiled.SESSION_LOGIN_USER);
return sysUser;
}
@Override
public T getModel() {
// TODO Auto-generated method stub
return null;
}
public String downFileNameTranscode(String fileName){
try {
String agent = request.getHeader("user-agent");//判断浏览器类型
if (agent.contains("MSIE")) {//IE浏览器 --- URL编码
fileName = URLEncoder.encode(fileName, "utf-8");
} else if (agent.contains("Firefox")) {//火狐浏览器 --- Base64编码
fileName = base64EncodeFileName(fileName);
} else {
fileName = URLEncoder.encode(fileName, "utf-8");
}
} catch (UnsupportedEncodingException e1) { }
return fileName;
}
/**
* 火狐要用base64解决编码问题
* @param fileName
* @return
*/
@SuppressWarnings("restriction")
public static String base64EncodeFileName(String fileName) {
//BASE64Encoder base64Encoder = new BASE64Encoder();
sun.misc.BASE64Encoder base64Encoder = new sun.misc.BASE64Encoder();
try {
//return "=?UTF-8?B?"+ new String(base64Encoder.encode(fileName.getBytes("UTF-8"))) + "?=";
return "=?UTF-8?B?"+ new String(base64Encoder.encode(fileName.getBytes("UTF-8"))).replaceAll("[\\t\\n\\r]", "") + "?=";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
public void setParameters(Map<String, String[]> parameters) {
Map<String, String[]> map = request.getParameterMap();
for(Entry<String, String[]> e :map.entrySet()){
String [] aa = e.getValue();
for(int i=0;i<aa.length;i++){
aa[i] = HTMLFilter.filter(aa[i]);
}
e.setValue(aa);
parameters.put(e.getKey(), e.getValue());
}
}
}
| UTF-8 | Java | 11,774 | java | BaseAction.java | Java | [
{
"context": "eserved.</p>\r\n * <p>Company: ITDCL</p>\r\n * @author ChengZhi\r\n * @version 1.0<p>\r\n * 修改记录:<p>\r\n * 下面填写修改的内容以及修",
"end": 1481,
"score": 0.9997475743293762,
"start": 1473,
"tag": "NAME",
"value": "ChengZhi"
},
{
"context": "<p>\r\n * 下面填写修改的内容以及修改的日期\r\n * 1.2013-8-20下午5:50:14 ChengZhi new<p>\r\n */\r\n@ParentPackage(value = \"struts-de",
"end": 1570,
"score": 0.9989702105522156,
"start": 1562,
"tag": "NAME",
"value": "ChengZhi"
}
]
| null | []
| package com.gzzn.fgw.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gzzn.fgw.aop.LogObject;
import com.gzzn.fgw.webUtil.CommonFiled;
import com.gzzn.fgw.model.SysUser;
import com.gzzn.util.common.MessageUtil;
//import com.gzzn.util.json.GsonIntegerTypeAdapter;
import com.gzzn.util.json.JSONUtil;
import com.gzzn.util.web.HTMLFilter;
import com.opensymphony.xwork2.ModelDriven;
/**
*
* <p>Title: BaseAction</p>
* <p>Description:ModelDriven 实现getModel()方法,struts2就能自动把数据赋给模型对象,页面直接取值不需要model.xxx<p>
* SessionAware 通过的Map对象来注入session<p>
* ServletRequestAware 得到request对象<p>
* ServletResponseAware 得到Respone对象<p>
* <p>Copyright: Copyright (c) 2013 ITDCL All right reserved.</p>
* <p>Company: ITDCL</p>
* @author ChengZhi
* @version 1.0<p>
* 修改记录:<p>
* 下面填写修改的内容以及修改的日期
* 1.2013-8-20下午5:50:14 ChengZhi new<p>
*/
@ParentPackage(value = "struts-default")
public class BaseAction<T> implements ServletRequestAware, ServletResponseAware, SessionAware,ParameterAware,
ModelDriven<T> {
protected static Logger logger = LoggerFactory.getLogger(BaseAction.class);
protected HttpServletRequest request;
protected HttpServletResponse response;
protected Map<String, Object> session;
protected LogObject logObject;//记录日志的对象
private String isShowAlone;//用于控制页面是否为单位显示
public LogObject getLogObject() {
return logObject;
}
public void setLogObject(LogObject logObject) {
this.logObject = logObject;
}
public String getIsShowAlone() {
return isShowAlone;
}
public void setIsShowAlone(String isShowAlone) {
this.isShowAlone = isShowAlone;
}
/**
* 返回已登录用户
*
* @return
*/
public SysUser getLoginUser() {
return (SysUser) session.get(CommonFiled.SESSION_LOGIN_USER);
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
/**
* 获取HttpSession的session作用域
* @return
*/
public HttpSession getHttpSession() {
return request.getSession();
}
/**
* 对请求进行编码
*/
public void setCharacterEncodingForUtf8() {
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setCharacterEncoding("UTF-8");
}
// /**
// * GSON:jdbc查询结果转换成Json串
// * @param Long->String,Date->"yyyy-MM-dd HH:mm:ss",Integer->String
// * @return
// */
// public String toJDBCJsonStr(List<Map<String, Object>> list) {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setLongSerializationPolicy(LongSerializationPolicy.STRING);
// gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm");
// gsonBuilder.registerTypeAdapter(Integer.class, new GsonIntegerTypeAdapter());
// return gsonBuilder.create().toJson(list);
// }
/**
* 获取WebRoot路径
* @return
*/
public String getWebRootPath() {
return ServletActionContext.getServletContext().getRealPath("/");
}
/**
* 将字符JSON串返回至浏览器(多用于Ajax返回),不使用缓存
* @param ajString 需要返回的数据(JSON串)
*/
public void outPutJSON(String ajaxString) {
outPutJSON(ajaxString, true);
}
/**
* 将字符JSON串返回至浏览器(多用于Ajax返回)
* ajString 需要返回的数据(JSON串)
* @param noCache 是否使用缓存,true不使用
*/
public void outPutJSON(String ajaxString, boolean noCache) {
outPutString(ajaxString, noCache, "text/html");
}
/**
* 将字符串返回至浏览器(多用于JSON串或Ajax返回)
* @param ajString 需要返回的数据(JSON串)
* @param noCache 是否使用缓存,true不使用
* @param type 返回类型,参见ajax返回类型说明:text/javascript或application/json为json数据;text/xml或application/xml为xml数据;text/html
*/
public void outPutString(String ajString, boolean noCache, String type) {
response.setContentType(type + ";charset=utf-8");
try {
setCharacterEncodingForUtf8();
if (noCache) {
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
}
PrintWriter pw = response.getWriter();
logger.debug("out put json data:{}", ajString);
pw.write(ajString);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 返回字符串到浏览器
* @param str
*/
public void outPutString(String str) {
outPutString(str, true, "text/html");
}
/**
* 将操作消息,返回数据条数,操作返回数据组装成json串
* @param json 操作返回数据
* @param count 返回数据条数
* @param msgFlag 操作类型(成功:true,失败:false)
* @param msgCode 操作消息代码
* @return
*/
public String assemblyJson(String json, int count, Boolean msgFlag, int... msgCode) {
//LogUtil.getLogger().debug(MessageUtil.getMsg(msgCode));
return assemblyJson(json, count, MessageUtil.getMsg(msgCode), msgFlag);
}
/**
* 将操作消息,返回数据条数,操作返回数据组装成json串
* @param json 操作返回数据
* @param count 返回数据条数
* @param msg 操作消息
* @param msgFlag 操作类型(成功:true,失败:false)
* @return
*/
public String assemblyJson(String json, int count, String msg, Boolean msgFlag) {
return "{\"count\":" + count + ",\"msg\":\"" + msg + "\",\"flag\":" + msgFlag
+ ",\"result\":" + json + "}";
}
/**
* 将对象以json的形式返回到客户端
* @param obj 操作数据
* @param msgFlag 操作类型(成功:true,失败:false)
* @param msgCode 操作消息代码
*/
public <T> void outPutObject(T obj, Boolean msgFlag, int... msgCode) {
outPutJSON(assemblyJson(JSONUtil.getJSONObject(obj, null).toString(), 1, msgFlag, msgCode));
}
/**
* 将对象以json的形式返回到客户端
* @param obj 操作数据
* @param msgFlag 操作类型(成功:true,失败:false)
* @param msg 操作消息代码
*/
public <T> void outPutObject(T obj, Boolean msgFlag, String msg) {
outPutJSON(assemblyJson(JSONUtil.getJSONObject(obj, null).toString(), 1, msg, msgFlag));
}
/**
* 将对象集合以json的形式返回到客户端
* @param list 操作数据
* @param msgFlag 操作类型(成功:true,失败:false)
* @param msgCode 操作消息代码
*/
public <T> void outPutList(Collection<T> list, Boolean msgFlag, int... msgCode) {
outPutJSON(assemblyJson(JSONUtil.getJSONArray(list, null).toString(), list.size(), msgFlag,
msgCode));
}
/**
* 将对象以json的形式返回到客户端,操作类型:成功(true)
* @param obj 对象
*/
public <T> void outPutObject(T obj) {
outPutObject(obj, true, MessageUtil.MSG_SUCCESS);
}
/**
* 将对象集合以json的形式返回到客户端,操作类型:成功(true)
* @param list 集合
*/
public <T> void outPutList(Collection<T> list) {
outPutList(list, true, MessageUtil.MSG_SUCCESS);
}
/**
* 将操作消息以json的形式返回到客户端
* @param msgCode 操作消息
* @param msgFlag 操作类型:true为成功,false是失败
*/
public void outPutMsg(Boolean msgFlag, int... msgCode) {
outPutJSON(assemblyJson(null, 1, msgFlag, msgCode));
}
/**
* 将操作消息以json的形式返回到客户端
* @param msgFlag 操作类型:true为成功,false是失败
* @param msg 操作消息
*/
public void outPutMsg(Boolean msgFlag, String msg) {
outPutJSON(assemblyJson(null, 1, msg, msgFlag));
}
/**
* 将操作消息以json的形式返回到客户端,操作类型(false失败)
* @param msgCode 操作消息
*/
public void outPutError(int... msgCode) {
//LogUtil.getLogger().debug(msgCode);
outPutJSON(assemblyJson("\"error\"", 0, false, msgCode));
}
/**
* 将操作消息以json的形式返回到客户端,操作类型(false失败)
* @param msg 操作消息
*/
public void outPutError(String msg) {
outPutJSON(assemblyJson("\"error\"", 0, msg, false));
}
/**
* 将操作消息以json的形式返回到客户端,操作类型(false失败)
* @param msgCode 操作消息
*/
public void outPutErrorLogin(int... msgCode) {
outPutJSON(assemblyJson("\"login\"", 0, false, msgCode));
}
/**
* 将操作消息以json的形式返回到客户端,操作类型(false失败)
* @param msg 操作消息
*/
public void outPutErrorLogin(String msg) {
outPutJSON(assemblyJson("\"login\"", 0, msg, false));
}
public void outJsonString(String str) {
PrintWriter out = null;
try {
out = response.getWriter();
out.write(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
public SysUser getUser(){
SysUser sysUser=(SysUser)this.getHttpSession().getAttribute(CommonFiled.SESSION_LOGIN_USER);
return sysUser;
}
@Override
public T getModel() {
// TODO Auto-generated method stub
return null;
}
public String downFileNameTranscode(String fileName){
try {
String agent = request.getHeader("user-agent");//判断浏览器类型
if (agent.contains("MSIE")) {//IE浏览器 --- URL编码
fileName = URLEncoder.encode(fileName, "utf-8");
} else if (agent.contains("Firefox")) {//火狐浏览器 --- Base64编码
fileName = base64EncodeFileName(fileName);
} else {
fileName = URLEncoder.encode(fileName, "utf-8");
}
} catch (UnsupportedEncodingException e1) { }
return fileName;
}
/**
* 火狐要用base64解决编码问题
* @param fileName
* @return
*/
@SuppressWarnings("restriction")
public static String base64EncodeFileName(String fileName) {
//BASE64Encoder base64Encoder = new BASE64Encoder();
sun.misc.BASE64Encoder base64Encoder = new sun.misc.BASE64Encoder();
try {
//return "=?UTF-8?B?"+ new String(base64Encoder.encode(fileName.getBytes("UTF-8"))) + "?=";
return "=?UTF-8?B?"+ new String(base64Encoder.encode(fileName.getBytes("UTF-8"))).replaceAll("[\\t\\n\\r]", "") + "?=";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
public void setParameters(Map<String, String[]> parameters) {
Map<String, String[]> map = request.getParameterMap();
for(Entry<String, String[]> e :map.entrySet()){
String [] aa = e.getValue();
for(int i=0;i<aa.length;i++){
aa[i] = HTMLFilter.filter(aa[i]);
}
e.setValue(aa);
parameters.put(e.getKey(), e.getValue());
}
}
}
| 11,774 | 0.67457 | 0.667495 | 393 | 24.615776 | 24.101725 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.712468 | false | false | 15 |
65f21471357a77a544c0ee48c4d42f1c942e2dcf | 12,524,124,638,846 | 2da334be1eafa19edc319f4307822801685aab30 | /src/com/setsuna/nebula/action/ItemStoreAction.java | bf6147f5466029a6eb2b872c3c182684d7021ee5 | [
"Apache-2.0"
]
| permissive | nebulaqueen/TraSuaBTXanhWeb | https://github.com/nebulaqueen/TraSuaBTXanhWeb | bd2306a9b513ab72a1cb91b0e1eace1fdf41b06a | 58c047ff3c5f605d6161e4dcdc27f059bc1712e1 | refs/heads/master | 2018-09-06T14:09:17.715000 | 2018-07-07T09:20:11 | 2018-07-07T09:20:11 | 108,752,052 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.setsuna.nebula.action;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator;
import com.setsuna.nebula.entity.BaseEntity;
import com.setsuna.nebula.entity.ItemStore;
import com.setsuna.nebula.entity.ItemStoreInOut;
import com.setsuna.nebula.entity.SimpleItem;
import com.setsuna.nebula.logic.ItemStoreInOutLogic;
import com.setsuna.nebula.logic.ItemStoreLogic;
import com.setsuna.nebula.util.CommonUtils;
import com.setsuna.nebula.util.Constants;
/**
* View list
* Insert
* Update
*
* @author MrTuan
*
*/
public class ItemStoreAction extends BaseAction implements Preparable {
private static final long serialVersionUID = 5074664319445593102L;
/**
* Add new item to store
*/
public static final String INSERT_TYPE_0 = "0";
/**
* Add quantity to store
*/
public static final String INSERT_TYPE_1 = "1";
private Logger log = Logger.getLogger(ItemStoreAction.class);
@Autowired
private ItemStoreLogic itemStoreLogic;
private ItemStore itemStore;
private List<ItemStore> listItemStore;
private ArrayList<HashMap<String, Object>> listData;
/**
* For update itemstore.
*/
private String itemStoreId;
private String insertType;
private List<SimpleItem> listInsertType;
@Autowired
private ItemStoreInOutLogic itemStoreInOutLogic;
public String insertInit() {
return SUCCESS;
}
/**
* Action
*
* @return
*/
public String insert() {
try {
if (!checkInputData(true)) {
return INPUT;
}
if (StringUtils.equals(INSERT_TYPE_0, insertType)) {
// case insert new item to store
// check item exist in store
HashMap<String, Object> param = new HashMap<>();
param.put("name", itemStore.getName());
listItemStore = itemStoreLogic.selectBy(param);
if (listItemStore != null && listItemStore.size() > 0) {
param = new HashMap<>();
initListItemStore();
addActionError(getText(Constants.ERROR_DUPLICATE, new String[] { "Tên sản phẩm" }));
return INPUT;
}
// get id inserted
itemStore.setStatus(BaseEntity.STATUS_NORMAL);
itemStoreLogic.insert(itemStore);
} else {
// case insert quantity to item in store.
itemStore.setId(Long.valueOf(itemStoreId));
}
ItemStoreInOut item = ItemStoreInOut.createItemIn();
item.setItemStoreId(itemStore.getId());
item.setQuantity(itemStore.getQuantity());
itemStoreInOutLogic.insert(item);
} catch (Exception e) {
log.error(e.getMessage(), e);
return INPUT;
}
return SUCCESS;
}
/**
* Action
*
* @return
*/
public String updateInit() {
try {
HashMap<String, Object> param = new HashMap<>();
param.put("id", itemStoreId);
ArrayList<ItemStore> list = itemStoreLogic.selectBy(param);
if (list != null && list.size() > 0) {
itemStore = list.get(0);
} else {
return INPUT;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return INPUT;
}
return SUCCESS;
}
/**
* Action
*
* @return
*/
public String update() {
try {
if (!checkInputData(false)) {
return INPUT;
}
itemStore.setUnitPrice(itemStore.getUnitPrice());
itemStoreLogic.update(itemStore);
} catch (Exception e) {
log.error(e.getMessage(), e);
return INPUT;
}
return SUCCESS;
}
/**
*
* Action
* @return
*/
public String viewList() {
try {
HashMap<String, Object> param = new HashMap<>();
param.put("status", BaseEntity.STATUS_NORMAL);
listData = itemStoreLogic.selectStatistic(param);
} catch (Exception e) {
log.error(e.getMessage(), e);
return INPUT;
}
return SUCCESS;
}
public void prepare() throws Exception {
try {
listInsertType = new ArrayList<>();
listInsertType.add(new SimpleItem(INSERT_TYPE_0, "Thêm sản phẩm mới vào kho"));
listInsertType.add(new SimpleItem(INSERT_TYPE_1, "Nhập kho"));
initListItemStore();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private void initListItemStore() {
try {
HashMap<String, Object> param = new HashMap<>();
param.put("status", BaseEntity.STATUS_NORMAL);
listItemStore = itemStoreLogic.selectBy(param);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
/***********************************************/
private boolean checkInputData(boolean isInsert) {
boolean ret = true;
if (isInsert) {
if (StringUtils.equals(INSERT_TYPE_0, insertType)) {
if (StringUtils.isBlank(itemStore.getName())) {
addActionError(getText(Constants.ERROR_REQUIRED_ITEM, new String[] { "Tên sản phẩm" }));
ret = false;
}
}
if (CommonUtils.isLessThanOrEqual(itemStore.getQuantity(), BigDecimal.ZERO)) {
addActionError(getText(Constants.ERROR_NOT_VALID_NUMBER, new String[] { "Số lượng" }));
ret = false;
}
} else {
// update
if (StringUtils.isBlank(itemStore.getName())) {
addActionError(getText(Constants.ERROR_REQUIRED_ITEM, new String[] { "Tên sản phẩm" }));
ret = false;
}
}
if (CommonUtils.isLessThanOrEqual(itemStore.getUnitPrice(), BigDecimal.ZERO)) {
addActionError(getText(Constants.ERROR_NOT_VALID_NUMBER, new String[] { "Đơn giá" }));
ret = false;
}
if (StringUtils.isBlank(itemStore.getUnit())) {
addActionError(getText(Constants.ERROR_REQUIRED_ITEM, new String[] { "Đơn vị" }));
ret = false;
}
return ret;
}
/**
* @return the itemStore
*/
@VisitorFieldValidator(message="",appendPrefix=true)
public ItemStore getItemStore() {
return itemStore;
}
/**
* @param itemStore the itemStore to set
*/
public void setItemStore(ItemStore itemStore) {
this.itemStore = itemStore;
}
/**
* @return the itemStoreId
*/
public String getItemStoreId() {
return itemStoreId;
}
/**
* @param itemStoreId the itemStoreId to set
*/
public void setItemStoreId(String itemStoreId) {
this.itemStoreId = itemStoreId;
}
/**
* @return the listItemStore
*/
public List<ItemStore> getListItemStore() {
return listItemStore;
}
/**
* @param listItemStore the listItemStore to set
*/
public void setListItemStore(List<ItemStore> listItemStore) {
this.listItemStore = listItemStore;
}
/**
* @return the listData
*/
public ArrayList<HashMap<String, Object>> getListData() {
return listData;
}
/**
* @param listData the listData to set
*/
public void setListData(ArrayList<HashMap<String, Object>> listData) {
this.listData = listData;
}
/**
* @return the insertType
*/
public String getInsertType() {
return insertType;
}
/**
* @param insertType the insertType to set
*/
public void setInsertType(String insertType) {
this.insertType = insertType;
}
/**
* @return the listInsertType
*/
public List<SimpleItem> getListInsertType() {
return listInsertType;
}
/**
* @param listInsertType the listInsertType to set
*/
public void setListInsertType(List<SimpleItem> listInsertType) {
this.listInsertType = listInsertType;
}
}
| UTF-8 | Java | 7,595 | java | ItemStoreAction.java | Java | [
{
"context": "* View list\r\n * Insert\r\n * Update\r\n * \r\n * @author MrTuan\r\n *\r\n */\r\npublic class ItemStoreAction extend",
"end": 855,
"score": 0.6773463487625122,
"start": 853,
"tag": "NAME",
"value": "Mr"
},
{
"context": "iew list\r\n * Insert\r\n * Update\r\n * \r\n * @author MrTuan\r\n *\r\n */\r\npublic class ItemStoreAction extends",
"end": 856,
"score": 0.5707594156265259,
"start": 855,
"tag": "USERNAME",
"value": "T"
},
{
"context": "ew list\r\n * Insert\r\n * Update\r\n * \r\n * @author MrTuan\r\n *\r\n */\r\npublic class ItemStoreAction extends Ba",
"end": 859,
"score": 0.5352148413658142,
"start": 856,
"tag": "NAME",
"value": "uan"
}
]
| null | []
| package com.setsuna.nebula.action;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator;
import com.setsuna.nebula.entity.BaseEntity;
import com.setsuna.nebula.entity.ItemStore;
import com.setsuna.nebula.entity.ItemStoreInOut;
import com.setsuna.nebula.entity.SimpleItem;
import com.setsuna.nebula.logic.ItemStoreInOutLogic;
import com.setsuna.nebula.logic.ItemStoreLogic;
import com.setsuna.nebula.util.CommonUtils;
import com.setsuna.nebula.util.Constants;
/**
* View list
* Insert
* Update
*
* @author MrTuan
*
*/
public class ItemStoreAction extends BaseAction implements Preparable {
private static final long serialVersionUID = 5074664319445593102L;
/**
* Add new item to store
*/
public static final String INSERT_TYPE_0 = "0";
/**
* Add quantity to store
*/
public static final String INSERT_TYPE_1 = "1";
private Logger log = Logger.getLogger(ItemStoreAction.class);
@Autowired
private ItemStoreLogic itemStoreLogic;
private ItemStore itemStore;
private List<ItemStore> listItemStore;
private ArrayList<HashMap<String, Object>> listData;
/**
* For update itemstore.
*/
private String itemStoreId;
private String insertType;
private List<SimpleItem> listInsertType;
@Autowired
private ItemStoreInOutLogic itemStoreInOutLogic;
public String insertInit() {
return SUCCESS;
}
/**
* Action
*
* @return
*/
public String insert() {
try {
if (!checkInputData(true)) {
return INPUT;
}
if (StringUtils.equals(INSERT_TYPE_0, insertType)) {
// case insert new item to store
// check item exist in store
HashMap<String, Object> param = new HashMap<>();
param.put("name", itemStore.getName());
listItemStore = itemStoreLogic.selectBy(param);
if (listItemStore != null && listItemStore.size() > 0) {
param = new HashMap<>();
initListItemStore();
addActionError(getText(Constants.ERROR_DUPLICATE, new String[] { "Tên sản phẩm" }));
return INPUT;
}
// get id inserted
itemStore.setStatus(BaseEntity.STATUS_NORMAL);
itemStoreLogic.insert(itemStore);
} else {
// case insert quantity to item in store.
itemStore.setId(Long.valueOf(itemStoreId));
}
ItemStoreInOut item = ItemStoreInOut.createItemIn();
item.setItemStoreId(itemStore.getId());
item.setQuantity(itemStore.getQuantity());
itemStoreInOutLogic.insert(item);
} catch (Exception e) {
log.error(e.getMessage(), e);
return INPUT;
}
return SUCCESS;
}
/**
* Action
*
* @return
*/
public String updateInit() {
try {
HashMap<String, Object> param = new HashMap<>();
param.put("id", itemStoreId);
ArrayList<ItemStore> list = itemStoreLogic.selectBy(param);
if (list != null && list.size() > 0) {
itemStore = list.get(0);
} else {
return INPUT;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return INPUT;
}
return SUCCESS;
}
/**
* Action
*
* @return
*/
public String update() {
try {
if (!checkInputData(false)) {
return INPUT;
}
itemStore.setUnitPrice(itemStore.getUnitPrice());
itemStoreLogic.update(itemStore);
} catch (Exception e) {
log.error(e.getMessage(), e);
return INPUT;
}
return SUCCESS;
}
/**
*
* Action
* @return
*/
public String viewList() {
try {
HashMap<String, Object> param = new HashMap<>();
param.put("status", BaseEntity.STATUS_NORMAL);
listData = itemStoreLogic.selectStatistic(param);
} catch (Exception e) {
log.error(e.getMessage(), e);
return INPUT;
}
return SUCCESS;
}
public void prepare() throws Exception {
try {
listInsertType = new ArrayList<>();
listInsertType.add(new SimpleItem(INSERT_TYPE_0, "Thêm sản phẩm mới vào kho"));
listInsertType.add(new SimpleItem(INSERT_TYPE_1, "Nhập kho"));
initListItemStore();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private void initListItemStore() {
try {
HashMap<String, Object> param = new HashMap<>();
param.put("status", BaseEntity.STATUS_NORMAL);
listItemStore = itemStoreLogic.selectBy(param);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
/***********************************************/
private boolean checkInputData(boolean isInsert) {
boolean ret = true;
if (isInsert) {
if (StringUtils.equals(INSERT_TYPE_0, insertType)) {
if (StringUtils.isBlank(itemStore.getName())) {
addActionError(getText(Constants.ERROR_REQUIRED_ITEM, new String[] { "Tên sản phẩm" }));
ret = false;
}
}
if (CommonUtils.isLessThanOrEqual(itemStore.getQuantity(), BigDecimal.ZERO)) {
addActionError(getText(Constants.ERROR_NOT_VALID_NUMBER, new String[] { "Số lượng" }));
ret = false;
}
} else {
// update
if (StringUtils.isBlank(itemStore.getName())) {
addActionError(getText(Constants.ERROR_REQUIRED_ITEM, new String[] { "Tên sản phẩm" }));
ret = false;
}
}
if (CommonUtils.isLessThanOrEqual(itemStore.getUnitPrice(), BigDecimal.ZERO)) {
addActionError(getText(Constants.ERROR_NOT_VALID_NUMBER, new String[] { "Đơn giá" }));
ret = false;
}
if (StringUtils.isBlank(itemStore.getUnit())) {
addActionError(getText(Constants.ERROR_REQUIRED_ITEM, new String[] { "Đơn vị" }));
ret = false;
}
return ret;
}
/**
* @return the itemStore
*/
@VisitorFieldValidator(message="",appendPrefix=true)
public ItemStore getItemStore() {
return itemStore;
}
/**
* @param itemStore the itemStore to set
*/
public void setItemStore(ItemStore itemStore) {
this.itemStore = itemStore;
}
/**
* @return the itemStoreId
*/
public String getItemStoreId() {
return itemStoreId;
}
/**
* @param itemStoreId the itemStoreId to set
*/
public void setItemStoreId(String itemStoreId) {
this.itemStoreId = itemStoreId;
}
/**
* @return the listItemStore
*/
public List<ItemStore> getListItemStore() {
return listItemStore;
}
/**
* @param listItemStore the listItemStore to set
*/
public void setListItemStore(List<ItemStore> listItemStore) {
this.listItemStore = listItemStore;
}
/**
* @return the listData
*/
public ArrayList<HashMap<String, Object>> getListData() {
return listData;
}
/**
* @param listData the listData to set
*/
public void setListData(ArrayList<HashMap<String, Object>> listData) {
this.listData = listData;
}
/**
* @return the insertType
*/
public String getInsertType() {
return insertType;
}
/**
* @param insertType the insertType to set
*/
public void setInsertType(String insertType) {
this.insertType = insertType;
}
/**
* @return the listInsertType
*/
public List<SimpleItem> getListInsertType() {
return listInsertType;
}
/**
* @param listInsertType the listInsertType to set
*/
public void setListInsertType(List<SimpleItem> listInsertType) {
this.listInsertType = listInsertType;
}
}
| 7,595 | 0.651231 | 0.646732 | 333 | 20.696697 | 22.218702 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.834835 | false | false | 15 |
014eadd327dcd181e6e635d7d49126e035c6c2a4 | 31,327,491,484,314 | 2af9bfc86b7ccbc5b34dfb35d6523f6d9108956b | /Ilovepooq/app/src/main/java/com/sh/ilovepooq/main/repository/MainRepository.java | fe41d6fa2999f451b6e9e887bee1b6d23017a698 | []
| no_license | oemilk/ilovepooq | https://github.com/oemilk/ilovepooq | 4c0b872ddc6e7da5463b9e8fddcfe41584dbe471 | b60d009be4797fe4ccb3807bdf9a679d5f809b12 | refs/heads/master | 2022-05-21T23:05:05.137000 | 2018-02-13T02:14:04 | 2018-02-13T02:14:04 | 57,479,974 | 5 | 2 | null | false | 2017-01-15T04:46:20 | 2016-05-01T04:13:05 | 2016-05-01T04:26:18 | 2017-01-15T04:46:19 | 90 | 0 | 2 | 0 | Java | null | null | package com.sh.ilovepooq.main.repository;
import com.sh.ilovepooq.main.MainGridContract;
import com.sh.ilovepooq.main.MainListContract;
import com.sh.ilovepooq.remote.HTMLParser;
import com.sh.ilovepooq.model.ContentInfoModel;
import java.util.List;
import io.reactivex.Single;
public class MainRepository implements MainGridContract.Repository, MainListContract.Repository {
private HTMLParser parser;
public MainRepository(HTMLParser parser) {
this.parser = parser;
}
@Override
public Single<List<ContentInfoModel>> parsing() {
return parser.getContentInfoModelArrayList();
}
}
| UTF-8 | Java | 628 | java | MainRepository.java | Java | []
| null | []
| package com.sh.ilovepooq.main.repository;
import com.sh.ilovepooq.main.MainGridContract;
import com.sh.ilovepooq.main.MainListContract;
import com.sh.ilovepooq.remote.HTMLParser;
import com.sh.ilovepooq.model.ContentInfoModel;
import java.util.List;
import io.reactivex.Single;
public class MainRepository implements MainGridContract.Repository, MainListContract.Repository {
private HTMLParser parser;
public MainRepository(HTMLParser parser) {
this.parser = parser;
}
@Override
public Single<List<ContentInfoModel>> parsing() {
return parser.getContentInfoModelArrayList();
}
}
| 628 | 0.767516 | 0.767516 | 25 | 24.120001 | 25.026897 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44 | false | false | 15 |
a4300dc28010ab3ac88eac3ebb22a24cdb98a358 | 13,400,298,004,446 | 9f286bf910c28e02514c98accc3e92e0cea58bb9 | /src/cards/activators/VelitesParams.java | 65974d766634f25ca8b505f187c5b6970d35c45d | []
| no_license | Supalosa/RomaProject2911 | https://github.com/Supalosa/RomaProject2911 | 95846d95494b81453a02595d475889836fac8430 | 6ed4d7edf5b005b19a2be57532ed7465f5255f9a | refs/heads/master | 2020-04-06T07:10:32.328000 | 2012-05-22T03:58:57 | 2012-05-22T03:58:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cards.activators;
import java.util.ArrayList;
import java.util.List;
import cards.Card;
import roma.Game;
import roma.GameVisor;
public class VelitesParams extends CardParams {
private int battleDie;
private int positionToAttack;
private boolean valid;
public VelitesParams() {
valid = true;
}
/**
* Returns the battle die that was specified to be used in the battle
* calculation.
*
* This value can is pre-modification by Centurio's extra battle dice
* effect.
*
* @return value of battleDie
*/
public int getBattleDie() {
return battleDie;
}
/**
* Sets the battle die to be used for battle calculation.
*
* Defining it here and keeping it constant makes acceptance testing
* possible (the result is kept constant) and also enables replays to have
* the exact same outcome.
*
* @param dieValue
* Dice value of the base battle value.
*/
public void setBattleDie(int dieValue) {
battleDie = dieValue;
}
/**
* Gets the Field Position that should be attacked by this card.
*
* Field position ranges from 0..Game.FIELD_SIZE
* @return value of positionToAttack
*/
public int getPositionToAttack() {
return positionToAttack;
}
/**
* Sets the field position to attack.
*
* Field position ranges from 0..Game.FIELD_SIZE
* @param pos the field position this Gladiator should attack
*/
public void setPositionToAttack(int pos) {
this.positionToAttack = pos;
}
@Override
public void query(GameVisor g, int pos) {
valid = false;
int enemy = (g.whoseTurn() + 1) % Game.MAX_PLAYERS;
List<Card> enemyField = g.getField().getSideAsList(enemy);
List<Card> characters = new ArrayList<Card>();
for (Card c : enemyField) {
if (!c.isBuilding()) {
characters.add(c);
}
}
Card target = null;
target = g.getController().getCard(characters, "Which opposing character card do you wish to attack?");
if (target != null) {
setPositionToAttack(g.getField().findCardPosition(target));
int diceRoll = g.rollDice();
setBattleDie(diceRoll);
valid = true;
}
}
@Override
public boolean isValid() {
return valid;
}
}
| UTF-8 | Java | 2,235 | java | VelitesParams.java | Java | []
| null | []
| package cards.activators;
import java.util.ArrayList;
import java.util.List;
import cards.Card;
import roma.Game;
import roma.GameVisor;
public class VelitesParams extends CardParams {
private int battleDie;
private int positionToAttack;
private boolean valid;
public VelitesParams() {
valid = true;
}
/**
* Returns the battle die that was specified to be used in the battle
* calculation.
*
* This value can is pre-modification by Centurio's extra battle dice
* effect.
*
* @return value of battleDie
*/
public int getBattleDie() {
return battleDie;
}
/**
* Sets the battle die to be used for battle calculation.
*
* Defining it here and keeping it constant makes acceptance testing
* possible (the result is kept constant) and also enables replays to have
* the exact same outcome.
*
* @param dieValue
* Dice value of the base battle value.
*/
public void setBattleDie(int dieValue) {
battleDie = dieValue;
}
/**
* Gets the Field Position that should be attacked by this card.
*
* Field position ranges from 0..Game.FIELD_SIZE
* @return value of positionToAttack
*/
public int getPositionToAttack() {
return positionToAttack;
}
/**
* Sets the field position to attack.
*
* Field position ranges from 0..Game.FIELD_SIZE
* @param pos the field position this Gladiator should attack
*/
public void setPositionToAttack(int pos) {
this.positionToAttack = pos;
}
@Override
public void query(GameVisor g, int pos) {
valid = false;
int enemy = (g.whoseTurn() + 1) % Game.MAX_PLAYERS;
List<Card> enemyField = g.getField().getSideAsList(enemy);
List<Card> characters = new ArrayList<Card>();
for (Card c : enemyField) {
if (!c.isBuilding()) {
characters.add(c);
}
}
Card target = null;
target = g.getController().getCard(characters, "Which opposing character card do you wish to attack?");
if (target != null) {
setPositionToAttack(g.getField().findCardPosition(target));
int diceRoll = g.rollDice();
setBattleDie(diceRoll);
valid = true;
}
}
@Override
public boolean isValid() {
return valid;
}
}
| 2,235 | 0.66443 | 0.663087 | 121 | 17.471075 | 21.399805 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.553719 | false | false | 15 |
89953555065625b9b1a1355c2082344f3c840334 | 28,793,460,787,880 | e9b3dcc93f51e068862c1bc386b49b5d8c54c1cc | /src/main/java/de/melonigemelone/miktoyaapi/repository/lib/minecraft/holograms/HologramHandler.java | a75dd00b3983609ad097e0dc9ae42d48a0a23785 | []
| no_license | MelonigeMelone/MiktoyaAPI | https://github.com/MelonigeMelone/MiktoyaAPI | ddfdc76e492566d1278de5835945e2f6e40f4593 | 5ac4cbbfec817d75cdcd9dc71bb0c3c8b1dfc53c | refs/heads/master | 2023-03-20T10:02:12.258000 | 2021-01-21T06:13:35 | 2021-01-21T06:13:35 | 328,780,795 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.melonigemelone.miktoyaapi.repository.lib.minecraft.holograms;
import de.melonigemelone.miktoyaapi.repository.lib.configuration.yaml.YamlFileBuilder;
public class HologramHandler {
public void loadHologramsFromFile(String path, String file) {
YamlFileBuilder fb = new YamlFileBuilder(path, file);
for (String name : fb.getKeys(false)) {
HologramBuilder hb = new HologramBuilder(name, fb.getString(String.valueOf(name) + ".World"), fb.getDouble(String.valueOf(name) + ".X"), fb.getDouble(String.valueOf(name) + ".Y"), fb.getDouble(String.valueOf(name) + ".Z"));
for (String line : fb.getStringList(String.valueOf(name) + ".Lines"))
hb.addLine(line);
hb.spawn();
}
}
}
| UTF-8 | Java | 764 | java | HologramHandler.java | Java | []
| null | []
| package de.melonigemelone.miktoyaapi.repository.lib.minecraft.holograms;
import de.melonigemelone.miktoyaapi.repository.lib.configuration.yaml.YamlFileBuilder;
public class HologramHandler {
public void loadHologramsFromFile(String path, String file) {
YamlFileBuilder fb = new YamlFileBuilder(path, file);
for (String name : fb.getKeys(false)) {
HologramBuilder hb = new HologramBuilder(name, fb.getString(String.valueOf(name) + ".World"), fb.getDouble(String.valueOf(name) + ".X"), fb.getDouble(String.valueOf(name) + ".Y"), fb.getDouble(String.valueOf(name) + ".Z"));
for (String line : fb.getStringList(String.valueOf(name) + ".Lines"))
hb.addLine(line);
hb.spawn();
}
}
}
| 764 | 0.676702 | 0.676702 | 16 | 46.75 | 57.105713 | 235 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 15 |
400eb95899b6675b4d8fa4463683ef0ed90f765e | 21,251,498,219,892 | c0ff084bb7a82b1ac14303717b3e64b01d556074 | /java/android/nnstreamer/src/androidTest/java/org/nnsuite/nnstreamer/APITestTensorsInfo.java | 738c4b5dcaf2f890a09864e8c7a334ba97e875ca | [
"Apache-2.0"
]
| permissive | wooksong/api | https://github.com/wooksong/api | b1d40c7927abc77c68a798c5d828a6e90d533adb | 66f31272694e203147907005cc67ac320d8125b5 | refs/heads/main | 2023-07-06T05:09:28.569000 | 2023-06-27T07:00:28 | 2023-06-27T07:03:53 | 341,819,071 | 0 | 0 | Apache-2.0 | true | 2023-04-19T05:14:15 | 2021-02-24T07:43:09 | 2023-03-29T01:13:04 | 2023-04-19T05:14:15 | 9,127 | 0 | 0 | 1 | C | false | false | package org.nnsuite.nnstreamer;
import android.support.test.runner.AndroidJUnit4;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Testcases for TensorsInfo.
*/
@RunWith(AndroidJUnit4.class)
public class APITestTensorsInfo {
private TensorsInfo mInfo;
@Before
public void setUp() {
APITestCommon.initNNStreamer();
mInfo = new TensorsInfo();
}
@After
public void tearDown() {
mInfo.close();
}
@Test
public void testAddInfo() {
try {
mInfo.addTensorInfo("name1", NNStreamer.TensorType.INT8, new int[]{1});
assertEquals(1, mInfo.getTensorsCount());
mInfo.addTensorInfo("name2", NNStreamer.TensorType.UINT8, new int[]{2,2});
assertEquals(2, mInfo.getTensorsCount());
mInfo.addTensorInfo(NNStreamer.TensorType.FLOAT32, new int[]{3,3,3});
assertEquals(3, mInfo.getTensorsCount());
} catch (Exception e) {
fail();
}
}
@Test
public void testGetInfo() {
try {
testAddInfo();
assertEquals("name1", mInfo.getTensorName(0));
assertEquals(NNStreamer.TensorType.INT8, mInfo.getTensorType(0));
assertArrayEquals(new int[]{1,1,1,1}, mInfo.getTensorDimension(0));
assertEquals("name2", mInfo.getTensorName(1));
assertEquals(NNStreamer.TensorType.UINT8, mInfo.getTensorType(1));
assertArrayEquals(new int[]{2,2,1,1}, mInfo.getTensorDimension(1));
assertNull(mInfo.getTensorName(2));
assertEquals(NNStreamer.TensorType.FLOAT32, mInfo.getTensorType(2));
assertArrayEquals(new int[]{3,3,3,1}, mInfo.getTensorDimension(2));
assertEquals(3, mInfo.getTensorsCount());
} catch (Exception e) {
fail();
}
}
@Test
public void testClone() {
try {
testAddInfo();
/* clone */
TensorsInfo cloned = mInfo.clone();
/* update info */
mInfo.setTensorName(0, "updated1");
mInfo.setTensorType(0, NNStreamer.TensorType.INT16);
mInfo.setTensorDimension(0, new int[]{10,1,1,1});
mInfo.setTensorName(1, "updated2");
mInfo.setTensorType(1, NNStreamer.TensorType.UINT16);
mInfo.setTensorDimension(1, new int[]{20,1,1,1});
mInfo.setTensorName(2, "updated3");
mInfo.setTensorType(2, NNStreamer.TensorType.FLOAT64);
mInfo.setTensorDimension(2, new int[]{30,1,1,1});
mInfo.addTensorInfo("updated4", NNStreamer.TensorType.INT64, new int[]{40,1,1,1});
/* check cloned info */
assertEquals("name1", cloned.getTensorName(0));
assertEquals(NNStreamer.TensorType.INT8, cloned.getTensorType(0));
assertArrayEquals(new int[]{1,1,1,1}, cloned.getTensorDimension(0));
assertEquals("name2", cloned.getTensorName(1));
assertEquals(NNStreamer.TensorType.UINT8, cloned.getTensorType(1));
assertArrayEquals(new int[]{2,2,1,1}, cloned.getTensorDimension(1));
assertNull(cloned.getTensorName(2));
assertEquals(NNStreamer.TensorType.FLOAT32, cloned.getTensorType(2));
assertArrayEquals(new int[]{3,3,3,1}, cloned.getTensorDimension(2));
assertEquals(3, cloned.getTensorsCount());
} catch (Exception e) {
fail();
}
}
@Test
public void testGetSize() {
try {
testAddInfo();
/* index 0: 1 int8 */
assertEquals(1, mInfo.getTensorSize(0));
/* index 1: 2:2 uint8 */
assertEquals(4, mInfo.getTensorSize(1));
/* index 2: 3:3:3 float32 */
assertEquals(108, mInfo.getTensorSize(2));
} catch (Exception e) {
fail();
}
}
@Test
public void testAllocate() {
try {
testAddInfo();
TensorsData data = mInfo.allocate();
assertEquals(3, data.getTensorsCount());
assertEquals(1, data.getTensorData(0).capacity());
assertEquals(4, data.getTensorData(1).capacity());
assertEquals(108, data.getTensorData(2).capacity());
} catch (Exception e) {
fail();
}
}
@Test
public void testAllocateEmpty_n() {
try {
TensorsInfo info = new TensorsInfo();
info.allocate();
fail();
} catch (Exception e) {
/* expected */
}
}
@Test
public void testUpdateInfo() {
try {
testAddInfo();
mInfo.setTensorName(2, "name3");
assertEquals("name1", mInfo.getTensorName(0));
assertEquals("name2", mInfo.getTensorName(1));
assertEquals("name3", mInfo.getTensorName(2));
mInfo.setTensorType(2, NNStreamer.TensorType.INT64);
assertEquals(NNStreamer.TensorType.INT8, mInfo.getTensorType(0));
assertEquals(NNStreamer.TensorType.UINT8, mInfo.getTensorType(1));
assertEquals(NNStreamer.TensorType.INT64, mInfo.getTensorType(2));
mInfo.setTensorDimension(2, new int[]{2,3});
assertArrayEquals(new int[]{1,1,1,1}, mInfo.getTensorDimension(0));
assertArrayEquals(new int[]{2,2,1,1}, mInfo.getTensorDimension(1));
assertArrayEquals(new int[]{2,3,1,1}, mInfo.getTensorDimension(2));
} catch (Exception e) {
fail();
}
}
@Test
public void testAddUnknownType_n() {
try {
mInfo.addTensorInfo(NNStreamer.TensorType.UNKNOWN, new int[]{2,2,2,2});
fail();
} catch (Exception e) {
/* expected */
}
assertEquals(0, mInfo.getTensorsCount());
}
@Test
public void testAddInvalidRank_n() {
try {
mInfo.addTensorInfo(NNStreamer.TensorType.INT32, new int[]{2,2,2,2,2});
fail();
} catch (Exception e) {
/* expected */
}
assertEquals(0, mInfo.getTensorsCount());
}
@Test
public void testAddInvalidDimension_n() {
try {
mInfo.addTensorInfo(NNStreamer.TensorType.INT32, new int[]{1,1,-1});
fail();
} catch (Exception e) {
/* expected */
}
assertEquals(0, mInfo.getTensorsCount());
}
@Test
public void testAddNullDimension_n() {
try {
mInfo.addTensorInfo(NNStreamer.TensorType.UINT8, null);
fail();
} catch (Exception e) {
/* expected */
}
assertEquals(0, mInfo.getTensorsCount());
}
@Test
public void testGetInvalidIndex_n() {
try {
mInfo.getTensorType(0);
fail();
} catch (Exception e) {
/* expected */
}
}
@Test
public void testAddMaxInfo_n() {
try {
for (int i = 0; i <= NNStreamer.TENSOR_SIZE_LIMIT; i++) {
mInfo.addTensorInfo(NNStreamer.TensorType.FLOAT32, new int[]{2,2,2,2});
}
fail();
} catch (Exception e) {
/* expected */
}
}
}
| UTF-8 | Java | 7,367 | java | APITestTensorsInfo.java | Java | []
| null | []
| package org.nnsuite.nnstreamer;
import android.support.test.runner.AndroidJUnit4;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Testcases for TensorsInfo.
*/
@RunWith(AndroidJUnit4.class)
public class APITestTensorsInfo {
private TensorsInfo mInfo;
@Before
public void setUp() {
APITestCommon.initNNStreamer();
mInfo = new TensorsInfo();
}
@After
public void tearDown() {
mInfo.close();
}
@Test
public void testAddInfo() {
try {
mInfo.addTensorInfo("name1", NNStreamer.TensorType.INT8, new int[]{1});
assertEquals(1, mInfo.getTensorsCount());
mInfo.addTensorInfo("name2", NNStreamer.TensorType.UINT8, new int[]{2,2});
assertEquals(2, mInfo.getTensorsCount());
mInfo.addTensorInfo(NNStreamer.TensorType.FLOAT32, new int[]{3,3,3});
assertEquals(3, mInfo.getTensorsCount());
} catch (Exception e) {
fail();
}
}
@Test
public void testGetInfo() {
try {
testAddInfo();
assertEquals("name1", mInfo.getTensorName(0));
assertEquals(NNStreamer.TensorType.INT8, mInfo.getTensorType(0));
assertArrayEquals(new int[]{1,1,1,1}, mInfo.getTensorDimension(0));
assertEquals("name2", mInfo.getTensorName(1));
assertEquals(NNStreamer.TensorType.UINT8, mInfo.getTensorType(1));
assertArrayEquals(new int[]{2,2,1,1}, mInfo.getTensorDimension(1));
assertNull(mInfo.getTensorName(2));
assertEquals(NNStreamer.TensorType.FLOAT32, mInfo.getTensorType(2));
assertArrayEquals(new int[]{3,3,3,1}, mInfo.getTensorDimension(2));
assertEquals(3, mInfo.getTensorsCount());
} catch (Exception e) {
fail();
}
}
@Test
public void testClone() {
try {
testAddInfo();
/* clone */
TensorsInfo cloned = mInfo.clone();
/* update info */
mInfo.setTensorName(0, "updated1");
mInfo.setTensorType(0, NNStreamer.TensorType.INT16);
mInfo.setTensorDimension(0, new int[]{10,1,1,1});
mInfo.setTensorName(1, "updated2");
mInfo.setTensorType(1, NNStreamer.TensorType.UINT16);
mInfo.setTensorDimension(1, new int[]{20,1,1,1});
mInfo.setTensorName(2, "updated3");
mInfo.setTensorType(2, NNStreamer.TensorType.FLOAT64);
mInfo.setTensorDimension(2, new int[]{30,1,1,1});
mInfo.addTensorInfo("updated4", NNStreamer.TensorType.INT64, new int[]{40,1,1,1});
/* check cloned info */
assertEquals("name1", cloned.getTensorName(0));
assertEquals(NNStreamer.TensorType.INT8, cloned.getTensorType(0));
assertArrayEquals(new int[]{1,1,1,1}, cloned.getTensorDimension(0));
assertEquals("name2", cloned.getTensorName(1));
assertEquals(NNStreamer.TensorType.UINT8, cloned.getTensorType(1));
assertArrayEquals(new int[]{2,2,1,1}, cloned.getTensorDimension(1));
assertNull(cloned.getTensorName(2));
assertEquals(NNStreamer.TensorType.FLOAT32, cloned.getTensorType(2));
assertArrayEquals(new int[]{3,3,3,1}, cloned.getTensorDimension(2));
assertEquals(3, cloned.getTensorsCount());
} catch (Exception e) {
fail();
}
}
@Test
public void testGetSize() {
try {
testAddInfo();
/* index 0: 1 int8 */
assertEquals(1, mInfo.getTensorSize(0));
/* index 1: 2:2 uint8 */
assertEquals(4, mInfo.getTensorSize(1));
/* index 2: 3:3:3 float32 */
assertEquals(108, mInfo.getTensorSize(2));
} catch (Exception e) {
fail();
}
}
@Test
public void testAllocate() {
try {
testAddInfo();
TensorsData data = mInfo.allocate();
assertEquals(3, data.getTensorsCount());
assertEquals(1, data.getTensorData(0).capacity());
assertEquals(4, data.getTensorData(1).capacity());
assertEquals(108, data.getTensorData(2).capacity());
} catch (Exception e) {
fail();
}
}
@Test
public void testAllocateEmpty_n() {
try {
TensorsInfo info = new TensorsInfo();
info.allocate();
fail();
} catch (Exception e) {
/* expected */
}
}
@Test
public void testUpdateInfo() {
try {
testAddInfo();
mInfo.setTensorName(2, "name3");
assertEquals("name1", mInfo.getTensorName(0));
assertEquals("name2", mInfo.getTensorName(1));
assertEquals("name3", mInfo.getTensorName(2));
mInfo.setTensorType(2, NNStreamer.TensorType.INT64);
assertEquals(NNStreamer.TensorType.INT8, mInfo.getTensorType(0));
assertEquals(NNStreamer.TensorType.UINT8, mInfo.getTensorType(1));
assertEquals(NNStreamer.TensorType.INT64, mInfo.getTensorType(2));
mInfo.setTensorDimension(2, new int[]{2,3});
assertArrayEquals(new int[]{1,1,1,1}, mInfo.getTensorDimension(0));
assertArrayEquals(new int[]{2,2,1,1}, mInfo.getTensorDimension(1));
assertArrayEquals(new int[]{2,3,1,1}, mInfo.getTensorDimension(2));
} catch (Exception e) {
fail();
}
}
@Test
public void testAddUnknownType_n() {
try {
mInfo.addTensorInfo(NNStreamer.TensorType.UNKNOWN, new int[]{2,2,2,2});
fail();
} catch (Exception e) {
/* expected */
}
assertEquals(0, mInfo.getTensorsCount());
}
@Test
public void testAddInvalidRank_n() {
try {
mInfo.addTensorInfo(NNStreamer.TensorType.INT32, new int[]{2,2,2,2,2});
fail();
} catch (Exception e) {
/* expected */
}
assertEquals(0, mInfo.getTensorsCount());
}
@Test
public void testAddInvalidDimension_n() {
try {
mInfo.addTensorInfo(NNStreamer.TensorType.INT32, new int[]{1,1,-1});
fail();
} catch (Exception e) {
/* expected */
}
assertEquals(0, mInfo.getTensorsCount());
}
@Test
public void testAddNullDimension_n() {
try {
mInfo.addTensorInfo(NNStreamer.TensorType.UINT8, null);
fail();
} catch (Exception e) {
/* expected */
}
assertEquals(0, mInfo.getTensorsCount());
}
@Test
public void testGetInvalidIndex_n() {
try {
mInfo.getTensorType(0);
fail();
} catch (Exception e) {
/* expected */
}
}
@Test
public void testAddMaxInfo_n() {
try {
for (int i = 0; i <= NNStreamer.TENSOR_SIZE_LIMIT; i++) {
mInfo.addTensorInfo(NNStreamer.TensorType.FLOAT32, new int[]{2,2,2,2});
}
fail();
} catch (Exception e) {
/* expected */
}
}
}
| 7,367 | 0.559658 | 0.531288 | 250 | 28.468 | 26.015091 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.88 | false | false | 15 |
ca1a39512d0c58dbd9454018082c486ed004c0dd | 22,960,895,224,901 | 2e75bb9159d01dc37bb00028d1dc3adffd968c66 | /demo/src/main/java/WorldCupFragment/LiveFragment.java | 7756d51fccaba09cb90ae3a41e1e29bbece05aa2 | [
"MIT"
]
| permissive | Toqeer12/AndroidImageSlider-master | https://github.com/Toqeer12/AndroidImageSlider-master | 398cbb98dca9dd61eca0f134a41af9ea6df69fc6 | 0b4dd905078bb96ca4ad7e091aafcf457107e995 | refs/heads/master | 2020-05-26T02:45:41.715000 | 2017-03-14T19:12:54 | 2017-03-14T19:13:03 | 84,986,892 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package WorldCupFragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.koherent.pdlapps.cricketworldcup2015live.Advertise;
import com.koherent.pdlapps.cricketworldcup2015live.R;
import com.koherent.pdlapps.cricketworldcup2015live.TestActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import Model.LivelistItem;
import adapter.LiveListAdapter;
import adapter.ServiceHandler;
import utilities.CommonMethods;
import utilities.Constants;
/**
* Created by TOQEER on 9/16/2015.
*/
public class LiveFragment extends Fragment{
ListView listview;
ArrayList<LivelistItem> livelistArray = new ArrayList<LivelistItem>();
String team1 = "teamAname";
String team2 = "teamBname";
String key = "match_key";
String date="start_date";
// String Check="Check";
String status="status";
String jsonStr;
String statuss;
String link;
JSONArray arr = null;
JSONArray contacts = null;
ServiceHandler sh;
LiveListAdapter adapter;
TextView tv;
Advertise advertise;
LinearLayout layout;
String url= Constants.LiveMatchDetail_URLWC;
public LiveFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.livefragmentwc, container,
false);
advertise=new Advertise();
advertise.InterstitialAd(getActivity());
tv = (TextView)view.findViewById(R.id.marque);
listview=(ListView)view.findViewById(R.id.livelistwc);
if(CommonMethods.isNetworkAvailable(getActivity())) {
new GetContacts().execute();
}
else
{
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LivelistItem livelistItem;
livelistItem = livelistArray.get(position);
Log.d("out IF", "" + livelistItem.getKey());
// if(livelistItem.getCheck().equalsIgnoreCase("true"))
// {
// Bundle b = new Bundle();
//
Intent i = new Intent(getActivity(), TestActivity.class);
i.putExtra("key", livelistItem.getKey());
i.putExtra("date", livelistItem.getDate());
i.putExtra("Live", "wc");
startActivity(i);
}
});
return view;
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
livelistArray.clear();
super.onPreExecute();
// Showing progress dialog
CommonMethods.showProgressDialog(getActivity());
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
sh = new ServiceHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("Response: ", "> " + jsonStr);
if(jsonStr!=null)
{
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("Toqeer");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String team = c.getString(team1);
String teamttwo = c.getString(team2);
String match_key = c.getString(key);
String dateformat=c.getString(date);
String season = c.getString("season_name");
String ven = c.getString("venue");
String related=c.getString("related_name");
statuss=c.getString(status);
if(statuss.equalsIgnoreCase("0"))
{
listview.setVisibility(View.GONE);
tv.setText("No Live Match Today");
CommonMethods.hideProgressDialog();
}
// Phone node is JSON Object
else {
tv.setVisibility(View.GONE);
livelistArray.add(new LivelistItem(team, teamttwo, statuss, match_key, dateformat, season, ven, related));
adapter = new LiveListAdapter(getActivity(), livelistArray);
listview.setAdapter(adapter);
CommonMethods.hideProgressDialog();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Internet is not Available", Toast.LENGTH_LONG).show();
//String json2 = sharedPrefs.getString(LIST_2_KEY, null);
}
}
}
}
}
| UTF-8 | Java | 5,901 | java | LiveFragment.java | Java | [
{
"context": "ds;\nimport utilities.Constants;\n\n/**\n * Created by TOQEER on 9/16/2015.\n */\npublic class LiveFragment exten",
"end": 912,
"score": 0.9990798830986023,
"start": 906,
"tag": "USERNAME",
"value": "TOQEER"
}
]
| null | []
| package WorldCupFragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.koherent.pdlapps.cricketworldcup2015live.Advertise;
import com.koherent.pdlapps.cricketworldcup2015live.R;
import com.koherent.pdlapps.cricketworldcup2015live.TestActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import Model.LivelistItem;
import adapter.LiveListAdapter;
import adapter.ServiceHandler;
import utilities.CommonMethods;
import utilities.Constants;
/**
* Created by TOQEER on 9/16/2015.
*/
public class LiveFragment extends Fragment{
ListView listview;
ArrayList<LivelistItem> livelistArray = new ArrayList<LivelistItem>();
String team1 = "teamAname";
String team2 = "teamBname";
String key = "match_key";
String date="start_date";
// String Check="Check";
String status="status";
String jsonStr;
String statuss;
String link;
JSONArray arr = null;
JSONArray contacts = null;
ServiceHandler sh;
LiveListAdapter adapter;
TextView tv;
Advertise advertise;
LinearLayout layout;
String url= Constants.LiveMatchDetail_URLWC;
public LiveFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.livefragmentwc, container,
false);
advertise=new Advertise();
advertise.InterstitialAd(getActivity());
tv = (TextView)view.findViewById(R.id.marque);
listview=(ListView)view.findViewById(R.id.livelistwc);
if(CommonMethods.isNetworkAvailable(getActivity())) {
new GetContacts().execute();
}
else
{
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LivelistItem livelistItem;
livelistItem = livelistArray.get(position);
Log.d("out IF", "" + livelistItem.getKey());
// if(livelistItem.getCheck().equalsIgnoreCase("true"))
// {
// Bundle b = new Bundle();
//
Intent i = new Intent(getActivity(), TestActivity.class);
i.putExtra("key", livelistItem.getKey());
i.putExtra("date", livelistItem.getDate());
i.putExtra("Live", "wc");
startActivity(i);
}
});
return view;
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
livelistArray.clear();
super.onPreExecute();
// Showing progress dialog
CommonMethods.showProgressDialog(getActivity());
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
sh = new ServiceHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("Response: ", "> " + jsonStr);
if(jsonStr!=null)
{
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("Toqeer");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String team = c.getString(team1);
String teamttwo = c.getString(team2);
String match_key = c.getString(key);
String dateformat=c.getString(date);
String season = c.getString("season_name");
String ven = c.getString("venue");
String related=c.getString("related_name");
statuss=c.getString(status);
if(statuss.equalsIgnoreCase("0"))
{
listview.setVisibility(View.GONE);
tv.setText("No Live Match Today");
CommonMethods.hideProgressDialog();
}
// Phone node is JSON Object
else {
tv.setVisibility(View.GONE);
livelistArray.add(new LivelistItem(team, teamttwo, statuss, match_key, dateformat, season, ven, related));
adapter = new LiveListAdapter(getActivity(), livelistArray);
listview.setAdapter(adapter);
CommonMethods.hideProgressDialog();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Internet is not Available", Toast.LENGTH_LONG).show();
//String json2 = sharedPrefs.getString(LIST_2_KEY, null);
}
}
}
}
}
| 5,901 | 0.5677 | 0.562786 | 198 | 28.80303 | 25.972141 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false | 15 |
b4e03903cbcf7d91fe9add6c77453c00c3768117 | 23,167,053,645,287 | f46ff4bba9fde2dbb615bac5b1762b79d39c3162 | /src/main/java/com/jason/base/system/dictionary/service/impl/DictionaryServiceImpl.java | ac9b466317a881c2df0d18706d98027c2bcf24f2 | []
| no_license | jason559han/jasonbase | https://github.com/jason559han/jasonbase | eecbd439fd5b1ac6eb07a1ccf5855d6b2e5056c7 | de7de800c6022afe25f848d34ac3c863ec790c7c | refs/heads/master | 2022-12-21T04:04:03.989000 | 2020-03-23T09:21:43 | 2020-03-23T09:21:43 | 248,912,609 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jason.base.system.dictionary.service.impl;
import com.jason.base.common.dao.BaseDao;
import com.jason.base.entity.SysDictData;
import com.jason.base.entity.SysDictType;
import com.jason.base.system.dictionary.service.DictionaryService;
import com.jason.base.tags.grid.JqGridConstants;
import com.jason.base.tags.grid.bean.GridPageBean;
import com.jason.base.tags.grid.utils.JqCommonDaoUtil;
import com.jason.base.tags.grid.utils.JqGridUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 字典信息维护 service 实例
* @author jason558han
* @date 2020/3/16 10:27 下午
*/
@Transactional
@Service("dictionaryService")
public class DictionaryServiceImpl implements DictionaryService {
@Autowired
private BaseDao<SysDictType> dictTypeDao;
@Autowired
private BaseDao<SysDictData> dictDataDao;
@Override
public List<SysDictType> getSysDictTypeListByGpb(GridPageBean gpb) {
return JqCommonDaoUtil.getPageListByGpb(dictTypeDao, gpb, SysDictType.class);
}
@Override
public String editSysDictTypeByMap(Map<String, String[]> map) {
return JqCommonDaoUtil.defaultEditEntityByMap(map, dictTypeDao, SysDictType.class);
}
@Override
public List<SysDictData> getSysDictDataListByIdGpb(String id, GridPageBean gpb) {
JqGridUtil.addAndSearchRuleToGpb(gpb,"dictTypeId", JqGridConstants.OP_EQUAL, id);
return JqCommonDaoUtil.getPageListByGpb(dictDataDao, gpb, SysDictData.class);
}
@Override
public String editSysDictDataByMap(Map<String, String[]> map) {
return JqCommonDaoUtil.defaultEditEntityByMap(map, dictDataDao, SysDictData.class);
}
@Override
public String getDictDataSelectStrByTypeId(String typeId) {
List<SysDictData> dictDataList = getSysDictDataListByTypeId(Integer.valueOf(typeId));
StringBuilder builder = new StringBuilder("<select>");
if (dictDataList != null && !dictDataList.isEmpty()) {
for (SysDictData dictData : dictDataList) {
builder.append("<option value='");
builder.append(dictData.getId());
builder.append("'>");
builder.append(dictData.getDictName());
builder.append("</option>");
}
}
builder.append("</select>");
return builder.toString();
}
@Override
public String getDictDataSelectStrByTypeCode(String typeCode) {
List<SysDictData> dictDataList = getSysDictDataListByTypeCode(typeCode);
StringBuilder builder = new StringBuilder("<select>");
if (dictDataList != null && !dictDataList.isEmpty()) {
for (SysDictData dictData : dictDataList) {
builder.append("<option value='");
builder.append(dictData.getDictCode());
builder.append("'>");
builder.append(dictData.getDictName());
builder.append("</option>");
}
}
builder.append("</select>");
return builder.toString();
}
@Override
public List<SysDictData> getSysDictDataListByTypeId(Integer typeId) {
Example example = new Example(SysDictData.class);
Example.Criteria cri = example.createCriteria();
cri.andEqualTo("dictTypeId", typeId);
return dictDataDao.selectByExample(example);
}
@Override
public List<SysDictData> getSysDictDataListByTypeCode(String typeCode) {
List<SysDictData> dictDataList = new ArrayList<>();
Example example = new Example(SysDictType.class);
Example.Criteria cri = example.createCriteria();
cri.andEqualTo("typeCode", typeCode);
List<SysDictType> dictTypeList = dictTypeDao.selectByExample(example);
if (dictTypeList != null && !dictTypeList.isEmpty()) {
dictDataList = getSysDictDataListByTypeId(dictTypeList.get(0).getId());
}
return dictDataList;
}
}
| UTF-8 | Java | 4,190 | java | DictionaryServiceImpl.java | Java | [
{
"context": "ava.util.Map;\n\n/**\n * 字典信息维护 service 实例\n * @author jason558han\n * @date 2020/3/16 10:27 下午\n */\n@Transactional\n@S",
"end": 792,
"score": 0.9996852874755859,
"start": 781,
"tag": "USERNAME",
"value": "jason558han"
}
]
| null | []
| package com.jason.base.system.dictionary.service.impl;
import com.jason.base.common.dao.BaseDao;
import com.jason.base.entity.SysDictData;
import com.jason.base.entity.SysDictType;
import com.jason.base.system.dictionary.service.DictionaryService;
import com.jason.base.tags.grid.JqGridConstants;
import com.jason.base.tags.grid.bean.GridPageBean;
import com.jason.base.tags.grid.utils.JqCommonDaoUtil;
import com.jason.base.tags.grid.utils.JqGridUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 字典信息维护 service 实例
* @author jason558han
* @date 2020/3/16 10:27 下午
*/
@Transactional
@Service("dictionaryService")
public class DictionaryServiceImpl implements DictionaryService {
@Autowired
private BaseDao<SysDictType> dictTypeDao;
@Autowired
private BaseDao<SysDictData> dictDataDao;
@Override
public List<SysDictType> getSysDictTypeListByGpb(GridPageBean gpb) {
return JqCommonDaoUtil.getPageListByGpb(dictTypeDao, gpb, SysDictType.class);
}
@Override
public String editSysDictTypeByMap(Map<String, String[]> map) {
return JqCommonDaoUtil.defaultEditEntityByMap(map, dictTypeDao, SysDictType.class);
}
@Override
public List<SysDictData> getSysDictDataListByIdGpb(String id, GridPageBean gpb) {
JqGridUtil.addAndSearchRuleToGpb(gpb,"dictTypeId", JqGridConstants.OP_EQUAL, id);
return JqCommonDaoUtil.getPageListByGpb(dictDataDao, gpb, SysDictData.class);
}
@Override
public String editSysDictDataByMap(Map<String, String[]> map) {
return JqCommonDaoUtil.defaultEditEntityByMap(map, dictDataDao, SysDictData.class);
}
@Override
public String getDictDataSelectStrByTypeId(String typeId) {
List<SysDictData> dictDataList = getSysDictDataListByTypeId(Integer.valueOf(typeId));
StringBuilder builder = new StringBuilder("<select>");
if (dictDataList != null && !dictDataList.isEmpty()) {
for (SysDictData dictData : dictDataList) {
builder.append("<option value='");
builder.append(dictData.getId());
builder.append("'>");
builder.append(dictData.getDictName());
builder.append("</option>");
}
}
builder.append("</select>");
return builder.toString();
}
@Override
public String getDictDataSelectStrByTypeCode(String typeCode) {
List<SysDictData> dictDataList = getSysDictDataListByTypeCode(typeCode);
StringBuilder builder = new StringBuilder("<select>");
if (dictDataList != null && !dictDataList.isEmpty()) {
for (SysDictData dictData : dictDataList) {
builder.append("<option value='");
builder.append(dictData.getDictCode());
builder.append("'>");
builder.append(dictData.getDictName());
builder.append("</option>");
}
}
builder.append("</select>");
return builder.toString();
}
@Override
public List<SysDictData> getSysDictDataListByTypeId(Integer typeId) {
Example example = new Example(SysDictData.class);
Example.Criteria cri = example.createCriteria();
cri.andEqualTo("dictTypeId", typeId);
return dictDataDao.selectByExample(example);
}
@Override
public List<SysDictData> getSysDictDataListByTypeCode(String typeCode) {
List<SysDictData> dictDataList = new ArrayList<>();
Example example = new Example(SysDictType.class);
Example.Criteria cri = example.createCriteria();
cri.andEqualTo("typeCode", typeCode);
List<SysDictType> dictTypeList = dictTypeDao.selectByExample(example);
if (dictTypeList != null && !dictTypeList.isEmpty()) {
dictDataList = getSysDictDataListByTypeId(dictTypeList.get(0).getId());
}
return dictDataList;
}
}
| 4,190 | 0.689209 | 0.685611 | 109 | 37.256882 | 27.572891 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.623853 | false | false | 15 |
ebbe99579eca6e1ae6c4dd87f771730d4d152ec8 | 30,837,865,232,614 | 2d1d08a1fe201544767f0b3b01cad203de39d392 | /esercizi/esercizipearson/capitolo05/esercizio08/Starter.java | daa832a789f4966e20ff8095cd25f29f64d0b575 | []
| no_license | Arcun91/Eserciziario_Roberto | https://github.com/Arcun91/Eserciziario_Roberto | 3a0468d17ef029decabd926d90b7b67d7db2dc63 | 86629894b30cda58e630d18dc6ef1a4de4fbdcda | refs/heads/master | 2015-09-25T01:19:39.977000 | 2015-08-07T15:02:06 | 2015-08-07T15:02:06 | 39,126,076 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package esercizipearson.capitolo05.esercizio08;
import java.util.Scanner;
public class Starter {
public static void main(String[]args){
System.out.println("Benvenuto");
System.out.println("Inseriscimi un intero, ti dirò se è un numero primo");
Scanner keyboard = new Scanner(System.in);
int numero = keyboard.nextInt();
MyClass ready = new MyClass();
if (numero==0){
System.out.println("Errore");
System.exit(-1);
}
if(ready.primo(numero)==true){
System.out.println(numero+" è un numero primo!");
}else{
System.out.println("Non è un numero primo, il suo divisore più piccolo è: "+ready.divisore(numero));
}
keyboard.close();
}
}
| UTF-8 | Java | 707 | java | Starter.java | Java | []
| null | []
| package esercizipearson.capitolo05.esercizio08;
import java.util.Scanner;
public class Starter {
public static void main(String[]args){
System.out.println("Benvenuto");
System.out.println("Inseriscimi un intero, ti dirò se è un numero primo");
Scanner keyboard = new Scanner(System.in);
int numero = keyboard.nextInt();
MyClass ready = new MyClass();
if (numero==0){
System.out.println("Errore");
System.exit(-1);
}
if(ready.primo(numero)==true){
System.out.println(numero+" è un numero primo!");
}else{
System.out.println("Non è un numero primo, il suo divisore più piccolo è: "+ready.divisore(numero));
}
keyboard.close();
}
}
| 707 | 0.664765 | 0.656205 | 33 | 20.242424 | 23.922894 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.242424 | false | false | 15 |
376ce7e54c5a62cad18ff482e2848f3d861b457e | 4,947,802,372,567 | 2c163a81e601426da917b70764b76a90a681f054 | /ecom-web/src/main/java/com/dowhile/frontend/mapping/bean/AddressBean.java | 1b55b5b629e7fba928302c898ab2f763764d1620 | []
| no_license | yameenbashir/svapple | https://github.com/yameenbashir/svapple | a3f864e917d41394a5915fd076de8e31b453ae98 | dff4860db85eb8103683a49da591308b8afd6316 | refs/heads/master | 2022-12-27T07:41:51.454000 | 2021-04-28T07:43:51 | 2021-04-28T07:43:51 | 205,891,660 | 0 | 0 | null | false | 2022-12-16T02:42:20 | 2019-09-02T16:01:44 | 2021-04-28T07:44:00 | 2022-12-16T02:42:16 | 101,857 | 0 | 0 | 53 | JavaScript | false | false | /**
*
*/
package com.dowhile.frontend.mapping.bean;
/**
* @author Yameen Bashir
*
*/
public class AddressBean {
private String addressId;
private String supplierId;
private String customerId;
private String companyId;
private String addressType;
private String contactName;
private String firstName;
private String lastName;
private String email;
private String phone;
private String fax;
private String website;
private String twitter;
private String street;
private String suburb;
private String city;
private String postalCode;
private String state;
private String countryId;
private String country;
private String county;
private String timeZoneId;
private String timeZone;
private String xCoordinate;
private String yCoordinate;
private String activeIndicator;
private String createdDate;
private String lastUpdated;
private String createdById;
private String updatedById;
/**
*
*/
public AddressBean() {
}
/**
* @param addressId
* @param supplierId
* @param customerId
* @param companyId
* @param addressType
* @param contactName
* @param firstName
* @param lastName
* @param email
* @param phone
* @param fax
* @param website
* @param twitter
* @param street
* @param suburb
* @param city
* @param postalCode
* @param state
* @param countryId
* @param country
* @param county
* @param timeZoneId
* @param timeZone
* @param xCoordinate
* @param yCoordinate
* @param activeIndicator
* @param createdDate
* @param lastUpdated
* @param createdById
* @param updatedById
*/
public AddressBean(String addressId, String supplierId, String customerId,
String companyId, String addressType, String contactName,
String firstName, String lastName, String email, String phone,
String fax, String website, String twitter, String street,
String suburb, String city, String postalCode, String state,
String countryId, String country, String county, String timeZoneId,
String timeZone, String xCoordinate, String yCoordinate,
String activeIndicator, String createdDate, String lastUpdated,
String createdById, String updatedById) {
this.addressId = addressId;
this.supplierId = supplierId;
this.customerId = customerId;
this.companyId = companyId;
this.addressType = addressType;
this.contactName = contactName;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phone = phone;
this.fax = fax;
this.website = website;
this.twitter = twitter;
this.street = street;
this.suburb = suburb;
this.city = city;
this.postalCode = postalCode;
this.state = state;
this.countryId = countryId;
this.country = country;
this.county = county;
this.timeZoneId = timeZoneId;
this.timeZone = timeZone;
this.xCoordinate = xCoordinate;
this.yCoordinate = yCoordinate;
this.activeIndicator = activeIndicator;
this.createdDate = createdDate;
this.lastUpdated = lastUpdated;
this.createdById = createdById;
this.updatedById = updatedById;
}
/**
* @return the addressId
*/
public String getAddressId() {
return addressId;
}
/**
* @param addressId the addressId to set
*/
public void setAddressId(String addressId) {
this.addressId = addressId;
}
/**
* @return the supplierId
*/
public String getSupplierId() {
return supplierId;
}
/**
* @param supplierId the supplierId to set
*/
public void setSupplierId(String supplierId) {
this.supplierId = supplierId;
}
/**
* @return the customerId
*/
public String getCustomerId() {
return customerId;
}
/**
* @param customerId the customerId to set
*/
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
/**
* @return the companyId
*/
public String getCompanyId() {
return companyId;
}
/**
* @param companyId the companyId to set
*/
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
/**
* @return the addressType
*/
public String getAddressType() {
return addressType;
}
/**
* @param addressType the addressType to set
*/
public void setAddressType(String addressType) {
this.addressType = addressType;
}
/**
* @return the contactName
*/
public String getContactName() {
return contactName;
}
/**
* @param contactName the contactName to set
*/
public void setContactName(String contactName) {
this.contactName = contactName;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone the phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @return the fax
*/
public String getFax() {
return fax;
}
/**
* @param fax the fax to set
*/
public void setFax(String fax) {
this.fax = fax;
}
/**
* @return the website
*/
public String getWebsite() {
return website;
}
/**
* @param website the website to set
*/
public void setWebsite(String website) {
this.website = website;
}
/**
* @return the twitter
*/
public String getTwitter() {
return twitter;
}
/**
* @param twitter the twitter to set
*/
public void setTwitter(String twitter) {
this.twitter = twitter;
}
/**
* @return the street
*/
public String getStreet() {
return street;
}
/**
* @param street the street to set
*/
public void setStreet(String street) {
this.street = street;
}
/**
* @return the suburb
*/
public String getSuburb() {
return suburb;
}
/**
* @param suburb the suburb to set
*/
public void setSuburb(String suburb) {
this.suburb = suburb;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return the postalCode
*/
public String getPostalCode() {
return postalCode;
}
/**
* @param postalCode the postalCode to set
*/
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
/**
* @return the state
*/
public String getState() {
return state;
}
/**
* @param state the state to set
*/
public void setState(String state) {
this.state = state;
}
/**
* @return the countryId
*/
public String getCountryId() {
return countryId;
}
/**
* @param countryId the countryId to set
*/
public void setCountryId(String countryId) {
this.countryId = countryId;
}
/**
* @return the country
*/
public String getCountry() {
return country;
}
/**
* @param country the country to set
*/
public void setCountry(String country) {
this.country = country;
}
/**
* @return the county
*/
public String getCounty() {
return county;
}
/**
* @param county the county to set
*/
public void setCounty(String county) {
this.county = county;
}
/**
* @return the timeZoneId
*/
public String getTimeZoneId() {
return timeZoneId;
}
/**
* @param timeZoneId the timeZoneId to set
*/
public void setTimeZoneId(String timeZoneId) {
this.timeZoneId = timeZoneId;
}
/**
* @return the timeZone
*/
public String getTimeZone() {
return timeZone;
}
/**
* @param timeZone the timeZone to set
*/
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
/**
* @return the xCoordinate
*/
public String getxCoordinate() {
return xCoordinate;
}
/**
* @param xCoordinate the xCoordinate to set
*/
public void setxCoordinate(String xCoordinate) {
this.xCoordinate = xCoordinate;
}
/**
* @return the yCoordinate
*/
public String getyCoordinate() {
return yCoordinate;
}
/**
* @param yCoordinate the yCoordinate to set
*/
public void setyCoordinate(String yCoordinate) {
this.yCoordinate = yCoordinate;
}
/**
* @return the activeIndicator
*/
public String getActiveIndicator() {
return activeIndicator;
}
/**
* @param activeIndicator the activeIndicator to set
*/
public void setActiveIndicator(String activeIndicator) {
this.activeIndicator = activeIndicator;
}
/**
* @return the createdDate
*/
public String getCreatedDate() {
return createdDate;
}
/**
* @param createdDate the createdDate to set
*/
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
/**
* @return the lastUpdated
*/
public String getLastUpdated() {
return lastUpdated;
}
/**
* @param lastUpdated the lastUpdated to set
*/
public void setLastUpdated(String lastUpdated) {
this.lastUpdated = lastUpdated;
}
/**
* @return the createdById
*/
public String getCreatedById() {
return createdById;
}
/**
* @param createdById the createdById to set
*/
public void setCreatedById(String createdById) {
this.createdById = createdById;
}
/**
* @return the updatedById
*/
public String getUpdatedById() {
return updatedById;
}
/**
* @param updatedById the updatedById to set
*/
public void setUpdatedById(String updatedById) {
this.updatedById = updatedById;
}
}
| UTF-8 | Java | 10,049 | java | AddressBean.java | Java | [
{
"context": "owhile.frontend.mapping.bean;\r\n\r\n\r\n/**\r\n * @author Yameen Bashir\r\n *\r\n */\r\npublic class AddressBean {\r\n\t\r\n\tprivate",
"end": 92,
"score": 0.9998666644096375,
"start": 79,
"tag": "NAME",
"value": "Yameen Bashir"
},
{
"context": "pe;\r\n\tprivate String contactName;\r\n\tprivate String firstName;\r\n\tprivate String lastName;\r\n\tprivate String emai",
"end": 333,
"score": 0.9604524970054626,
"start": 324,
"tag": "NAME",
"value": "firstName"
},
{
"context": "Name;\r\n\tprivate String firstName;\r\n\tprivate String lastName;\r\n\tprivate String email;\r\n\tprivate String phone;\r",
"end": 360,
"score": 0.9170771241188049,
"start": 352,
"tag": "NAME",
"value": "lastName"
},
{
"context": "am addressType\r\n\t * @param contactName\r\n\t * @param firstName\r\n\t * @param lastName\r\n\t * @param email\r\n\t * @para",
"end": 1171,
"score": 0.9979224801063538,
"start": 1162,
"tag": "NAME",
"value": "firstName"
},
{
"context": "aram contactName\r\n\t * @param firstName\r\n\t * @param lastName\r\n\t * @param email\r\n\t * @param phone\r\n\t * @param f",
"end": 1192,
"score": 0.9974561333656311,
"start": 1184,
"tag": "NAME",
"value": "lastName"
},
{
"context": "String addressType, String contactName,\r\n\t\t\tString firstName, String lastName, String email, String phone,\r\n\t\t",
"end": 1823,
"score": 0.9943540096282959,
"start": 1814,
"tag": "NAME",
"value": "firstName"
},
{
"context": ", String contactName,\r\n\t\t\tString firstName, String lastName, String email, String phone,\r\n\t\t\tString fax, Stri",
"end": 1840,
"score": 0.9934559464454651,
"start": 1832,
"tag": "NAME",
"value": "lastName"
},
{
"context": "his.contactName = contactName;\r\n\t\tthis.firstName = firstName;\r\n\t\tthis.lastName = lastName;\r\n\t\tthis.email = ema",
"end": 2472,
"score": 0.9967705607414246,
"start": 2463,
"tag": "NAME",
"value": "firstName"
},
{
"context": "\r\n\t\tthis.firstName = firstName;\r\n\t\tthis.lastName = lastName;\r\n\t\tthis.email = email;\r\n\t\tthis.phone = phone;\r\n\t",
"end": 2501,
"score": 0.9971444010734558,
"start": 2493,
"tag": "NAME",
"value": "lastName"
}
]
| null | []
| /**
*
*/
package com.dowhile.frontend.mapping.bean;
/**
* @author <NAME>
*
*/
public class AddressBean {
private String addressId;
private String supplierId;
private String customerId;
private String companyId;
private String addressType;
private String contactName;
private String firstName;
private String lastName;
private String email;
private String phone;
private String fax;
private String website;
private String twitter;
private String street;
private String suburb;
private String city;
private String postalCode;
private String state;
private String countryId;
private String country;
private String county;
private String timeZoneId;
private String timeZone;
private String xCoordinate;
private String yCoordinate;
private String activeIndicator;
private String createdDate;
private String lastUpdated;
private String createdById;
private String updatedById;
/**
*
*/
public AddressBean() {
}
/**
* @param addressId
* @param supplierId
* @param customerId
* @param companyId
* @param addressType
* @param contactName
* @param firstName
* @param lastName
* @param email
* @param phone
* @param fax
* @param website
* @param twitter
* @param street
* @param suburb
* @param city
* @param postalCode
* @param state
* @param countryId
* @param country
* @param county
* @param timeZoneId
* @param timeZone
* @param xCoordinate
* @param yCoordinate
* @param activeIndicator
* @param createdDate
* @param lastUpdated
* @param createdById
* @param updatedById
*/
public AddressBean(String addressId, String supplierId, String customerId,
String companyId, String addressType, String contactName,
String firstName, String lastName, String email, String phone,
String fax, String website, String twitter, String street,
String suburb, String city, String postalCode, String state,
String countryId, String country, String county, String timeZoneId,
String timeZone, String xCoordinate, String yCoordinate,
String activeIndicator, String createdDate, String lastUpdated,
String createdById, String updatedById) {
this.addressId = addressId;
this.supplierId = supplierId;
this.customerId = customerId;
this.companyId = companyId;
this.addressType = addressType;
this.contactName = contactName;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phone = phone;
this.fax = fax;
this.website = website;
this.twitter = twitter;
this.street = street;
this.suburb = suburb;
this.city = city;
this.postalCode = postalCode;
this.state = state;
this.countryId = countryId;
this.country = country;
this.county = county;
this.timeZoneId = timeZoneId;
this.timeZone = timeZone;
this.xCoordinate = xCoordinate;
this.yCoordinate = yCoordinate;
this.activeIndicator = activeIndicator;
this.createdDate = createdDate;
this.lastUpdated = lastUpdated;
this.createdById = createdById;
this.updatedById = updatedById;
}
/**
* @return the addressId
*/
public String getAddressId() {
return addressId;
}
/**
* @param addressId the addressId to set
*/
public void setAddressId(String addressId) {
this.addressId = addressId;
}
/**
* @return the supplierId
*/
public String getSupplierId() {
return supplierId;
}
/**
* @param supplierId the supplierId to set
*/
public void setSupplierId(String supplierId) {
this.supplierId = supplierId;
}
/**
* @return the customerId
*/
public String getCustomerId() {
return customerId;
}
/**
* @param customerId the customerId to set
*/
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
/**
* @return the companyId
*/
public String getCompanyId() {
return companyId;
}
/**
* @param companyId the companyId to set
*/
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
/**
* @return the addressType
*/
public String getAddressType() {
return addressType;
}
/**
* @param addressType the addressType to set
*/
public void setAddressType(String addressType) {
this.addressType = addressType;
}
/**
* @return the contactName
*/
public String getContactName() {
return contactName;
}
/**
* @param contactName the contactName to set
*/
public void setContactName(String contactName) {
this.contactName = contactName;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone the phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @return the fax
*/
public String getFax() {
return fax;
}
/**
* @param fax the fax to set
*/
public void setFax(String fax) {
this.fax = fax;
}
/**
* @return the website
*/
public String getWebsite() {
return website;
}
/**
* @param website the website to set
*/
public void setWebsite(String website) {
this.website = website;
}
/**
* @return the twitter
*/
public String getTwitter() {
return twitter;
}
/**
* @param twitter the twitter to set
*/
public void setTwitter(String twitter) {
this.twitter = twitter;
}
/**
* @return the street
*/
public String getStreet() {
return street;
}
/**
* @param street the street to set
*/
public void setStreet(String street) {
this.street = street;
}
/**
* @return the suburb
*/
public String getSuburb() {
return suburb;
}
/**
* @param suburb the suburb to set
*/
public void setSuburb(String suburb) {
this.suburb = suburb;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return the postalCode
*/
public String getPostalCode() {
return postalCode;
}
/**
* @param postalCode the postalCode to set
*/
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
/**
* @return the state
*/
public String getState() {
return state;
}
/**
* @param state the state to set
*/
public void setState(String state) {
this.state = state;
}
/**
* @return the countryId
*/
public String getCountryId() {
return countryId;
}
/**
* @param countryId the countryId to set
*/
public void setCountryId(String countryId) {
this.countryId = countryId;
}
/**
* @return the country
*/
public String getCountry() {
return country;
}
/**
* @param country the country to set
*/
public void setCountry(String country) {
this.country = country;
}
/**
* @return the county
*/
public String getCounty() {
return county;
}
/**
* @param county the county to set
*/
public void setCounty(String county) {
this.county = county;
}
/**
* @return the timeZoneId
*/
public String getTimeZoneId() {
return timeZoneId;
}
/**
* @param timeZoneId the timeZoneId to set
*/
public void setTimeZoneId(String timeZoneId) {
this.timeZoneId = timeZoneId;
}
/**
* @return the timeZone
*/
public String getTimeZone() {
return timeZone;
}
/**
* @param timeZone the timeZone to set
*/
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
/**
* @return the xCoordinate
*/
public String getxCoordinate() {
return xCoordinate;
}
/**
* @param xCoordinate the xCoordinate to set
*/
public void setxCoordinate(String xCoordinate) {
this.xCoordinate = xCoordinate;
}
/**
* @return the yCoordinate
*/
public String getyCoordinate() {
return yCoordinate;
}
/**
* @param yCoordinate the yCoordinate to set
*/
public void setyCoordinate(String yCoordinate) {
this.yCoordinate = yCoordinate;
}
/**
* @return the activeIndicator
*/
public String getActiveIndicator() {
return activeIndicator;
}
/**
* @param activeIndicator the activeIndicator to set
*/
public void setActiveIndicator(String activeIndicator) {
this.activeIndicator = activeIndicator;
}
/**
* @return the createdDate
*/
public String getCreatedDate() {
return createdDate;
}
/**
* @param createdDate the createdDate to set
*/
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
/**
* @return the lastUpdated
*/
public String getLastUpdated() {
return lastUpdated;
}
/**
* @param lastUpdated the lastUpdated to set
*/
public void setLastUpdated(String lastUpdated) {
this.lastUpdated = lastUpdated;
}
/**
* @return the createdById
*/
public String getCreatedById() {
return createdById;
}
/**
* @param createdById the createdById to set
*/
public void setCreatedById(String createdById) {
this.createdById = createdById;
}
/**
* @return the updatedById
*/
public String getUpdatedById() {
return updatedById;
}
/**
* @param updatedById the updatedById to set
*/
public void setUpdatedById(String updatedById) {
this.updatedById = updatedById;
}
}
| 10,042 | 0.648224 | 0.648224 | 480 | 18.935417 | 15.484737 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.508333 | false | false | 15 |
f22452a943bfdca0fdeb2806d6e0984ce735b957 | 32,847,909,921,918 | 13fcbf1ff5fb0e7cdb5ab48eabe2c0fc55c0a7d9 | /lab9/poddubka/bookstore-spring-boot/src/main/java/com/hillel/bookstorespringboot/dao/AuthorDao.java | 03da59b3e0af54f90157ec67ec970387b4475ad9 | []
| no_license | dinamio/hillel-javaee | https://github.com/dinamio/hillel-javaee | af69bf4412160ec948f43fbb8fc89ff126d2026e | f959b7c5ad5336129057104078c2171c53d18cb2 | refs/heads/master | 2021-08-28T15:03:37.249000 | 2017-12-11T08:51:53 | 2017-12-11T08:51:53 | 106,819,389 | 1 | 3 | null | false | 2017-12-12T14:25:04 | 2017-10-13T12:05:59 | 2017-11-14T10:09:31 | 2017-12-12T14:24:38 | 37,238 | 1 | 0 | 3 | CSS | false | null | package com.hillel.bookstorespringboot.dao;
import com.hillel.bookstorespringboot.model.Author;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface AuthorDao extends CrudRepository<Author, Integer> {
// List<Author> findAuthorsByAuthorName(List<Author> authorList);
List<Author> findAuthorsByAuthorName(String authorName);
}
| UTF-8 | Java | 384 | java | AuthorDao.java | Java | []
| null | []
| package com.hillel.bookstorespringboot.dao;
import com.hillel.bookstorespringboot.model.Author;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface AuthorDao extends CrudRepository<Author, Integer> {
// List<Author> findAuthorsByAuthorName(List<Author> authorList);
List<Author> findAuthorsByAuthorName(String authorName);
}
| 384 | 0.815104 | 0.815104 | 13 | 28.538462 | 28.499973 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 15 |
a0c4d78e9f46f71dd3af394a17ab203c3491dcbe | 180,388,671,395 | 40269eeb101a9b8f6c485cc5ce42d2ac866cde8b | /src/NewSoftValley/tu/_221_MaximalSquare.java | b11aeedcc2139ff07181c1dc895c1d93e3f8ef98 | []
| no_license | yutongjin/Leetcode | https://github.com/yutongjin/Leetcode | 92051807e401a6092a3be403b1c2166482b6f6bf | 53fe0e23fa41d7d8882227ba70812de62128b254 | refs/heads/master | 2020-03-18T22:36:36.845000 | 2018-08-15T00:51:16 | 2018-08-15T00:51:16 | 135,354,402 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package NewSoftValley.tu;
/**
* @Author : Yutong Jin
* @date : 8/10/18
* @Description :
*/
public class _221_MaximalSquare {
public int maximalSquare(char[][] matrix) {
if(matrix.length == 0 || matrix[0].length == 0)
return 0;
//找定义!!!!找转移方程!!!!
//dp[i][j] = Math.min(dp[i][j - 1],dp[i - 1][j],dp[i - 1][j - 1] ) + 1;
final int n = matrix.length;
final int m = matrix[0].length;
int[]bian = new int[m];
int result = 0;
for(int i = 0 ; i < n ; i++){
for(int j = 0 ;j < m ; j ++){
if(i ==0 || j == 0){
bian[j] = matrix[i][j] - '0';
}
else {
if(bian[j] == bian[j - 1]){
bian[j] = bian[j] + matrix[i-bian[j]][j - bian[j]] - '0';
}
else {
bian[j] = 1 + Math.min(bian[j],bian [j - 1]);
}
bian[j] *= matrix[i][j] - '0';
}
result = Math.max(result,bian[j] * bian[j]);
}
}
return result;
}
}
| UTF-8 | Java | 1,197 | java | _221_MaximalSquare.java | Java | [
{
"context": "package NewSoftValley.tu;\n\n/**\n * @Author : Yutong Jin\n * @date : 8/10/18\n * @Description :\n */\npublic c",
"end": 54,
"score": 0.9998024702072144,
"start": 44,
"tag": "NAME",
"value": "Yutong Jin"
}
]
| null | []
| package NewSoftValley.tu;
/**
* @Author : <NAME>
* @date : 8/10/18
* @Description :
*/
public class _221_MaximalSquare {
public int maximalSquare(char[][] matrix) {
if(matrix.length == 0 || matrix[0].length == 0)
return 0;
//找定义!!!!找转移方程!!!!
//dp[i][j] = Math.min(dp[i][j - 1],dp[i - 1][j],dp[i - 1][j - 1] ) + 1;
final int n = matrix.length;
final int m = matrix[0].length;
int[]bian = new int[m];
int result = 0;
for(int i = 0 ; i < n ; i++){
for(int j = 0 ;j < m ; j ++){
if(i ==0 || j == 0){
bian[j] = matrix[i][j] - '0';
}
else {
if(bian[j] == bian[j - 1]){
bian[j] = bian[j] + matrix[i-bian[j]][j - bian[j]] - '0';
}
else {
bian[j] = 1 + Math.min(bian[j],bian [j - 1]);
}
bian[j] *= matrix[i][j] - '0';
}
result = Math.max(result,bian[j] * bian[j]);
}
}
return result;
}
}
| 1,193 | 0.365665 | 0.340773 | 40 | 28.125 | 21.293411 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 15 |
885f972561003fbceff71a68de2308a98a1899cf | 927,712,986,264 | a1106e24930a469cff676495ab7ec31f51733b49 | /初/Test1.java | c92d6a8a8be2dc3c4b1e4bcaf32fa3be63188f27 | []
| no_license | mengsuliang/JAVA | https://github.com/mengsuliang/JAVA | 62dc7ed987303e9c60d66fa56d969855da6ac894 | 52780de6d243189d06ef6fb2ffb8a7de2cf4932f | refs/heads/master | 2020-06-10T01:17:23.674000 | 2020-05-11T09:35:51 | 2020-05-11T09:35:51 | 181,115,527 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bbo;
public class Test1 {
public static void main(String[]args) {
int a = 90;
int b = 90;
if(a==b || a>8) {System.out.println("ok1");}
b--;
if(a>b && a>45) {System.out.println("ok2");}
if(!(a<=b)) {System.out.println("ok3");}
}
}
| UTF-8 | Java | 254 | java | Test1.java | Java | []
| null | []
| package bbo;
public class Test1 {
public static void main(String[]args) {
int a = 90;
int b = 90;
if(a==b || a>8) {System.out.println("ok1");}
b--;
if(a>b && a>45) {System.out.println("ok2");}
if(!(a<=b)) {System.out.println("ok3");}
}
}
| 254 | 0.562992 | 0.519685 | 13 | 18.538462 | 17.653133 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.769231 | false | false | 15 |
39ec984bdac743da886dca849b8980695caac375 | 1,065,151,921,820 | 8dc71389a2296c83a15e57499aa1f1e427815e0b | /src/main/java/decodes/xml/XmlPlatformStatusDAO.java | 590d3a533f9387ddad6b7bd641626fc50ebb502a | [
"Apache-2.0"
]
| permissive | opendcs/opendcs | https://github.com/opendcs/opendcs | b2a216e0a10b0e09bd6edfc575ea0667bf830db9 | 8ee9e05bbfc1f556d70c2db1d5003070f4d5635c | refs/heads/master | 2023-08-18T20:19:56.906000 | 2023-08-09T21:01:43 | 2023-08-09T21:01:43 | 20,228,381 | 28 | 22 | Apache-2.0 | false | 2023-09-14T19:49:06 | 2014-05-27T17:16:15 | 2023-08-29T14:42:31 | 2023-09-14T19:49:05 | 153,681 | 23 | 21 | 98 | Java | false | false | package decodes.xml;
import ilex.util.Logger;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.xml.sax.SAXException;
import decodes.db.DatabaseObject;
import decodes.db.PlatformStatus;
import decodes.sql.DbKey;
import decodes.tsdb.DbIoException;
import opendcs.dai.PlatformStatusDAI;
public class XmlPlatformStatusDAO
implements PlatformStatusDAI
{
private XmlDatabaseIO parent = null;
private File psDir = null;
public XmlPlatformStatusDAO(XmlDatabaseIO parent)
{
this.parent = parent;
psDir = new File(parent.xmldir, XmlDatabaseIO.PlatformStatusDir);
if (!psDir.isDirectory())
psDir.mkdirs();
}
@Override
public synchronized PlatformStatus readPlatformStatus(DbKey platformId) throws DbIoException
{
File f = new File(psDir, makeFileName(platformId));
try
{
DatabaseObject dbo = parent.getParser().parse(f);
if (dbo instanceof PlatformStatus)
return (PlatformStatus)dbo;
else
Logger.instance().warning("Ignoring non-PlatformStatus "
+ "in file '" + f.getPath() + "'");
}
catch (Exception ex)
{
Logger.instance().warning("Error reading '" + f.getPath() + "': " + ex);
}
return null;
}
private String makeFileName(DbKey platformId)
{
return "ps-" + platformId + ".xml";
}
@Override
public synchronized void writePlatformStatus(PlatformStatus platformStatus) throws DbIoException
{
File f = new File(psDir, makeFileName(platformStatus.getId()));
try
{
TopLevelParser.write(f, platformStatus);
}
catch (IOException ex)
{
throw new DbIoException("Cannot write '" + f.getPath() + "': " + ex);
}
}
@Override
public ArrayList<PlatformStatus> listPlatformStatus() throws DbIoException
{
try
{
ArrayList<PlatformStatus> ret = new ArrayList<PlatformStatus>();
File files[] = psDir.listFiles();
for(File f : files)
{
if (!f.isFile())
continue;
try
{
DatabaseObject dbo = parent.getParser().parse(f);
if (dbo instanceof PlatformStatus)
ret.add((PlatformStatus)dbo);
else
Logger.instance().warning("Ignoring non-PlatformStatus "
+ "in file '" + f.getPath() + "'");
}
catch (SAXException ex)
{
Logger.instance().warning("Error parsing '" + f.getPath() + "': " + ex);
}
}
return ret;
}
catch (IOException ex)
{
throw new DbIoException("Cannot list '" + psDir.getPath() + "' xml directory: " + ex);
}
}
@Override
public void close()
{
}
@Override
public void deletePlatformStatus(DbKey platformId) throws DbIoException
{
File f = new File(psDir, makeFileName(platformId));
if (f.exists())
f.delete();
}
}
| UTF-8 | Java | 2,661 | java | XmlPlatformStatusDAO.java | Java | []
| null | []
| package decodes.xml;
import ilex.util.Logger;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.xml.sax.SAXException;
import decodes.db.DatabaseObject;
import decodes.db.PlatformStatus;
import decodes.sql.DbKey;
import decodes.tsdb.DbIoException;
import opendcs.dai.PlatformStatusDAI;
public class XmlPlatformStatusDAO
implements PlatformStatusDAI
{
private XmlDatabaseIO parent = null;
private File psDir = null;
public XmlPlatformStatusDAO(XmlDatabaseIO parent)
{
this.parent = parent;
psDir = new File(parent.xmldir, XmlDatabaseIO.PlatformStatusDir);
if (!psDir.isDirectory())
psDir.mkdirs();
}
@Override
public synchronized PlatformStatus readPlatformStatus(DbKey platformId) throws DbIoException
{
File f = new File(psDir, makeFileName(platformId));
try
{
DatabaseObject dbo = parent.getParser().parse(f);
if (dbo instanceof PlatformStatus)
return (PlatformStatus)dbo;
else
Logger.instance().warning("Ignoring non-PlatformStatus "
+ "in file '" + f.getPath() + "'");
}
catch (Exception ex)
{
Logger.instance().warning("Error reading '" + f.getPath() + "': " + ex);
}
return null;
}
private String makeFileName(DbKey platformId)
{
return "ps-" + platformId + ".xml";
}
@Override
public synchronized void writePlatformStatus(PlatformStatus platformStatus) throws DbIoException
{
File f = new File(psDir, makeFileName(platformStatus.getId()));
try
{
TopLevelParser.write(f, platformStatus);
}
catch (IOException ex)
{
throw new DbIoException("Cannot write '" + f.getPath() + "': " + ex);
}
}
@Override
public ArrayList<PlatformStatus> listPlatformStatus() throws DbIoException
{
try
{
ArrayList<PlatformStatus> ret = new ArrayList<PlatformStatus>();
File files[] = psDir.listFiles();
for(File f : files)
{
if (!f.isFile())
continue;
try
{
DatabaseObject dbo = parent.getParser().parse(f);
if (dbo instanceof PlatformStatus)
ret.add((PlatformStatus)dbo);
else
Logger.instance().warning("Ignoring non-PlatformStatus "
+ "in file '" + f.getPath() + "'");
}
catch (SAXException ex)
{
Logger.instance().warning("Error parsing '" + f.getPath() + "': " + ex);
}
}
return ret;
}
catch (IOException ex)
{
throw new DbIoException("Cannot list '" + psDir.getPath() + "' xml directory: " + ex);
}
}
@Override
public void close()
{
}
@Override
public void deletePlatformStatus(DbKey platformId) throws DbIoException
{
File f = new File(psDir, makeFileName(platformId));
if (f.exists())
f.delete();
}
}
| 2,661 | 0.681699 | 0.681699 | 117 | 21.743589 | 24.222668 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.188034 | false | false | 15 |
002d4ebe8cf10e04c05bedf766027ce00df0b098 | 1,924,145,368,449 | 4bbfa242353fe0485fb2a1f75fdd749c7ee05adc | /ims-core/framework/com/ailk/openbilling/persistence/imsintf/entity/ProductSeqItemList.java | eba40d22a65220faa79c6510d7afff62fe3c2458 | []
| no_license | 859162000/infosystem | https://github.com/859162000/infosystem | 88b23a5b386600503ec49b14f3b4da4df7a6d091 | 96d4d50cd9964e713bb95520d6eeb7e4aa32c930 | refs/heads/master | 2021-01-20T04:39:24.383000 | 2017-04-01T10:59:24 | 2017-04-01T10:59:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ailk.openbilling.persistence.imsintf.entity;
import javax.persistence.Entity;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.builder.HashCodeBuilder;
import com.ailk.easyframe.web.common.dal.IComplexEntity;
import jef.codegen.support.NotModified;
/**
* This class is generated automatically by Asiainfo-Linkage EasyFrame.
*/
@NotModified
@Entity
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder={"productSeqItem"})
public class ProductSeqItemList implements IComplexEntity{
@XmlElement(name="productSeqItem")
private ProductSeqItem[] productSeqItem;
public void setProductSeqItem(ProductSeqItem[] obj){
this.productSeqItem = obj;
}
public ProductSeqItem[] getProductSeqItem(){
return productSeqItem;
}
public boolean equals(final Object rhs0){
if (rhs0 == null)return false;
ProductSeqItemList rhs=(ProductSeqItemList)rhs0;
if(!ObjectUtils.equals(productSeqItem, rhs.productSeqItem)) return false;
return true;
}
public int hashCode(){
return new HashCodeBuilder()
.append(productSeqItem)
.toHashCode();
}
} | UTF-8 | Java | 1,279 | java | ProductSeqItemList.java | Java | []
| null | []
| package com.ailk.openbilling.persistence.imsintf.entity;
import javax.persistence.Entity;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.builder.HashCodeBuilder;
import com.ailk.easyframe.web.common.dal.IComplexEntity;
import jef.codegen.support.NotModified;
/**
* This class is generated automatically by Asiainfo-Linkage EasyFrame.
*/
@NotModified
@Entity
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder={"productSeqItem"})
public class ProductSeqItemList implements IComplexEntity{
@XmlElement(name="productSeqItem")
private ProductSeqItem[] productSeqItem;
public void setProductSeqItem(ProductSeqItem[] obj){
this.productSeqItem = obj;
}
public ProductSeqItem[] getProductSeqItem(){
return productSeqItem;
}
public boolean equals(final Object rhs0){
if (rhs0 == null)return false;
ProductSeqItemList rhs=(ProductSeqItemList)rhs0;
if(!ObjectUtils.equals(productSeqItem, rhs.productSeqItem)) return false;
return true;
}
public int hashCode(){
return new HashCodeBuilder()
.append(productSeqItem)
.toHashCode();
}
} | 1,279 | 0.795934 | 0.793589 | 47 | 26.234043 | 22.378002 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 15 |
528e215fb2486c7c80ed88a32e39a4e3fd4b9f23 | 27,230,092,708,735 | 9f76e8317eb5723e35d46837fdadd3d04d5240be | /LeetCode Questions/RotateImage.java | 2fa4b7c131abdfcd4b16a2b1a3622c2198d31380 | []
| no_license | LingFZhou/LeetCode-questions | https://github.com/LingFZhou/LeetCode-questions | 05e34e0d9eeee1bfca77725deb138aa261394a14 | 4be85927bee17feba44453ad072a1890f5505a14 | refs/heads/master | 2021-01-25T06:29:31.654000 | 2017-06-07T00:54:03 | 2017-06-07T00:54:03 | 93,575,822 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //2017-3-30
public class RotateImage {
public void rotate(int[][] matrix) {
int n = matrix.length-1;
for(int i = 0; i < n; i++){
for(int j = i; j< n-i; j++){
int lefttop = matrix[i][j];
int righttop = matrix[j][n-i];
int rightbottom = matrix[n-i][n-j];
int leftbottom = matrix[n-j][i];
matrix[i][j] = leftbottom;
matrix[j][n-i] = lefttop;
matrix[n-i][n-j] = righttop;
matrix[n-j][i] = rightbottom;
}
}
for(int i = 0; i <= n; i++){
for(int m : matrix[i])System.out.print(m);
System.out.println();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RotateImage test = new RotateImage();
int[][] matrix = {
{3, 4, 6, 7, 8},
{2, 3, 5, 3, 1},
{8, 5, 3, 2, 9},
{0, 2, 4, 6, 1},
{6, 7, 3, 4, 2}};
test.rotate(matrix);
}
}
| UTF-8 | Java | 940 | java | RotateImage.java | Java | []
| null | []
| //2017-3-30
public class RotateImage {
public void rotate(int[][] matrix) {
int n = matrix.length-1;
for(int i = 0; i < n; i++){
for(int j = i; j< n-i; j++){
int lefttop = matrix[i][j];
int righttop = matrix[j][n-i];
int rightbottom = matrix[n-i][n-j];
int leftbottom = matrix[n-j][i];
matrix[i][j] = leftbottom;
matrix[j][n-i] = lefttop;
matrix[n-i][n-j] = righttop;
matrix[n-j][i] = rightbottom;
}
}
for(int i = 0; i <= n; i++){
for(int m : matrix[i])System.out.print(m);
System.out.println();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RotateImage test = new RotateImage();
int[][] matrix = {
{3, 4, 6, 7, 8},
{2, 3, 5, 3, 1},
{8, 5, 3, 2, 9},
{0, 2, 4, 6, 1},
{6, 7, 3, 4, 2}};
test.rotate(matrix);
}
}
| 940 | 0.470213 | 0.432979 | 35 | 25.828571 | 14.047849 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.771429 | false | false | 15 |
e819e41d3744154010955c8c9591cb71aecf266a | 28,681,791,618,831 | 0bde5f7f09aa537ed1f4828d4e5ebee66475918f | /h2o-core/src/main/java/water/rapids/Query.java | cf50ce90617b83512f7f7010e4088bf038c0d009 | [
"Apache-2.0"
]
| permissive | Winfredemalx54/h2o-3 | https://github.com/Winfredemalx54/h2o-3 | d69f1c07e1f5d2540cb0ce5e6073415fa0780d32 | dfb163c82ff3bfa6f88cdf02465a9bb4c8189cb7 | refs/heads/master | 2022-12-14T08:59:04.109000 | 2020-09-23T08:36:59 | 2020-09-23T08:36:59 | 297,947,978 | 2 | 0 | Apache-2.0 | true | 2020-09-23T11:28:54 | 2020-09-23T11:28:54 | 2020-09-23T10:37:34 | 2020-09-23T09:28:30 | 487,156 | 0 | 0 | 0 | null | false | false | package water.rapids;
import water.H2O;
import water.MRTask;
import water.fvec.Chunk;
import water.util.AtomicUtils;
// Now find groups ...
// Find group sizes when we know the number of groups ...
// long groups[][] = new long[256][]; // at most MAXVEC groups per radix, currently
//// new helper class A extend MRTask. In its reduce it'll get another A. Make another class B extends ICED that wraps a bunch of long arrays (like I have now).
//// A contains B as a member. The long arrays are easy to serialize automatically. As you reduce two A's, do with the two B's. 'this' in the reduce will have the target A.
//// B gets initialized in the setupLocal() of A on each node. Check in A's reduce that the two B's have different pointers else return. See Arno's DeepLearningTask;
//// DeepLearningModelInfo is his B.
class assignG extends H2O.H2OCountedCompleter<assignG> {
private static final int MAXVECLONG = 134217728, MAXVECBYTE = 1073741824;
long _gOut[][]; // wide writing to here, but thread safe due to each location written once only
long _groups[]; // the group sizes
long _nGroup; // length of _groups because we over-allocated it
long _o[][]; // the order for this segment
long _firstGroupNum;
assignG(long gOut[][], long groups[], long nGroup, long firstGroupNum, long o[][]) {
_gOut = gOut;
_groups = groups;
_nGroup = nGroup;
_firstGroupNum = firstGroupNum;
_o = o;
}
@Override
public void compute2() {
int oi = 0, batch=0;
long _ob[] = _o[batch];
long gOutBatch[] = _gOut[batch];
for (int i=0; i<_nGroup; i++) {
for (int j = 0; j < _groups[i]; j++) {
long target = _ob[oi++];
assert target < MAXVECLONG;
gOutBatch[(int)(target)] = _firstGroupNum+i;
if (oi == MAXVECLONG) {
assert false;
_ob = _o[++batch];
oi -= MAXVECLONG;
}
}
}
tryComplete();
}
}
/*
long nGroups = 0;
for (int i = 0; i < 257; i++) {
long tmp = nGroup[i];
nGroup[i] = nGroups;
nGroups += tmp;
}
System.out.println("Time to recursive radix: " + (System.nanoTime() - t0) / 1e9 ); t0 = System.nanoTime();
System.out.println("Total groups found: " + nGroups);
if (!retGrp) return;
// We now have o and x that bmerge() needs
long nrow = DF.numRows();
long g[][] = new long[(int)(1 + nrow / MAXVECLONG)][];
int c;
for (c=0; c<nrow/MAXVECLONG; c++) {
g[c] = new long[MAXVECLONG];
}
g[c] = new long[(int)(nrow % MAXVECLONG)];
fs = new Futures();
for (int i=0; i<256; i++) {
if (reduceHist[i] > 0)
fs.add(H2O.submitTask(new assignG(g, groups[i], nGroup[i+1]-nGroup[i], nGroup[i], o[i])));
// reuse the x vector we allocated before to store the group numbers. i.e. a perfect and ordered hash, stored alongside table
}
fs.blockForPending();
System.out.println("Time to assign group index (length nrows): " + (System.nanoTime() - t0) / 1e9 ); t0 = System.nanoTime();
//Vec res = Vec.makeZero(nGroups); // really slow to assign to
double res[] = new double[(int)nGroups];
new runSum(g, res).doAll(toSum);
// TO DO: Create final frame with 3 columns
System.out.println("Time to sum column: " + (System.nanoTime() - t0) / 1e9 );
System.out.println("Total time: " + (System.nanoTime() - t00) / 1e9);
for (int i = 0; i < 5; i++) System.out.format("%7.0f\n", res[i]);
System.out.println("---");
for (int i = 4; i >= 0; i--) System.out.format("%7.0f\n", res[(int)nGroups-i-1]);
*/
/*
System.out.println("Head and tail:");
int head=10, done=0, batch = -1;
while (done < head) {
while (o[++batch] == null) ;
for (int i = 0; done < head && i < o[batch][0].length; i++)
System.out.format("%7d: %16d\n", done++, vec.at8(o[batch][0][i]));
}
System.out.println("--------");
batch = 256;
done = 0;
while (done < head) {
while (o[--batch] == null) ;
for (int i = o[batch][0].length - 1; done < head && i >= 0; i--)
System.out.format("%7d: %16d\n", vec.length() - ++done, vec.at8(o[batch][0][i]));
}
System.out.print("\n");
*/
/*
void cummulate(long x[][], long a, long b) {
long rollSum = 0;
for (int j=0; j<b; j++)
for (int i=0; i<a; i++) {
long tmp = x[i][j];
x[i][j] = rollSum;
rollSum += tmp;
}
}
*/
class runSum extends MRTask<runSum> {
private static final int MAXVECLONG = 134217728, MAXVECBYTE = 1073741824;
long _g[];
double _res[];
runSum(long g[][], double res[]) { _g = g[0]; _res = res;}
@Override public void map(Chunk chk) {
// TODO: if spans 2 MAXVEC in g. Currently hard coded to g[0]
int j = (int)chk.start();
for (int r=0; r<chk._len; r++) {
AtomicUtils.DoubleArray.add(_res, (int) _g[j++], chk.at8(r));
}
}
}
| UTF-8 | Java | 4,936 | java | Query.java | Java | []
| null | []
| package water.rapids;
import water.H2O;
import water.MRTask;
import water.fvec.Chunk;
import water.util.AtomicUtils;
// Now find groups ...
// Find group sizes when we know the number of groups ...
// long groups[][] = new long[256][]; // at most MAXVEC groups per radix, currently
//// new helper class A extend MRTask. In its reduce it'll get another A. Make another class B extends ICED that wraps a bunch of long arrays (like I have now).
//// A contains B as a member. The long arrays are easy to serialize automatically. As you reduce two A's, do with the two B's. 'this' in the reduce will have the target A.
//// B gets initialized in the setupLocal() of A on each node. Check in A's reduce that the two B's have different pointers else return. See Arno's DeepLearningTask;
//// DeepLearningModelInfo is his B.
class assignG extends H2O.H2OCountedCompleter<assignG> {
private static final int MAXVECLONG = 134217728, MAXVECBYTE = 1073741824;
long _gOut[][]; // wide writing to here, but thread safe due to each location written once only
long _groups[]; // the group sizes
long _nGroup; // length of _groups because we over-allocated it
long _o[][]; // the order for this segment
long _firstGroupNum;
assignG(long gOut[][], long groups[], long nGroup, long firstGroupNum, long o[][]) {
_gOut = gOut;
_groups = groups;
_nGroup = nGroup;
_firstGroupNum = firstGroupNum;
_o = o;
}
@Override
public void compute2() {
int oi = 0, batch=0;
long _ob[] = _o[batch];
long gOutBatch[] = _gOut[batch];
for (int i=0; i<_nGroup; i++) {
for (int j = 0; j < _groups[i]; j++) {
long target = _ob[oi++];
assert target < MAXVECLONG;
gOutBatch[(int)(target)] = _firstGroupNum+i;
if (oi == MAXVECLONG) {
assert false;
_ob = _o[++batch];
oi -= MAXVECLONG;
}
}
}
tryComplete();
}
}
/*
long nGroups = 0;
for (int i = 0; i < 257; i++) {
long tmp = nGroup[i];
nGroup[i] = nGroups;
nGroups += tmp;
}
System.out.println("Time to recursive radix: " + (System.nanoTime() - t0) / 1e9 ); t0 = System.nanoTime();
System.out.println("Total groups found: " + nGroups);
if (!retGrp) return;
// We now have o and x that bmerge() needs
long nrow = DF.numRows();
long g[][] = new long[(int)(1 + nrow / MAXVECLONG)][];
int c;
for (c=0; c<nrow/MAXVECLONG; c++) {
g[c] = new long[MAXVECLONG];
}
g[c] = new long[(int)(nrow % MAXVECLONG)];
fs = new Futures();
for (int i=0; i<256; i++) {
if (reduceHist[i] > 0)
fs.add(H2O.submitTask(new assignG(g, groups[i], nGroup[i+1]-nGroup[i], nGroup[i], o[i])));
// reuse the x vector we allocated before to store the group numbers. i.e. a perfect and ordered hash, stored alongside table
}
fs.blockForPending();
System.out.println("Time to assign group index (length nrows): " + (System.nanoTime() - t0) / 1e9 ); t0 = System.nanoTime();
//Vec res = Vec.makeZero(nGroups); // really slow to assign to
double res[] = new double[(int)nGroups];
new runSum(g, res).doAll(toSum);
// TO DO: Create final frame with 3 columns
System.out.println("Time to sum column: " + (System.nanoTime() - t0) / 1e9 );
System.out.println("Total time: " + (System.nanoTime() - t00) / 1e9);
for (int i = 0; i < 5; i++) System.out.format("%7.0f\n", res[i]);
System.out.println("---");
for (int i = 4; i >= 0; i--) System.out.format("%7.0f\n", res[(int)nGroups-i-1]);
*/
/*
System.out.println("Head and tail:");
int head=10, done=0, batch = -1;
while (done < head) {
while (o[++batch] == null) ;
for (int i = 0; done < head && i < o[batch][0].length; i++)
System.out.format("%7d: %16d\n", done++, vec.at8(o[batch][0][i]));
}
System.out.println("--------");
batch = 256;
done = 0;
while (done < head) {
while (o[--batch] == null) ;
for (int i = o[batch][0].length - 1; done < head && i >= 0; i--)
System.out.format("%7d: %16d\n", vec.length() - ++done, vec.at8(o[batch][0][i]));
}
System.out.print("\n");
*/
/*
void cummulate(long x[][], long a, long b) {
long rollSum = 0;
for (int j=0; j<b; j++)
for (int i=0; i<a; i++) {
long tmp = x[i][j];
x[i][j] = rollSum;
rollSum += tmp;
}
}
*/
class runSum extends MRTask<runSum> {
private static final int MAXVECLONG = 134217728, MAXVECBYTE = 1073741824;
long _g[];
double _res[];
runSum(long g[][], double res[]) { _g = g[0]; _res = res;}
@Override public void map(Chunk chk) {
// TODO: if spans 2 MAXVEC in g. Currently hard coded to g[0]
int j = (int)chk.start();
for (int r=0; r<chk._len; r++) {
AtomicUtils.DoubleArray.add(_res, (int) _g[j++], chk.at8(r));
}
}
}
| 4,936 | 0.578404 | 0.554295 | 143 | 33.517483 | 34.376331 | 174 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.895105 | false | false | 15 |
a8759ca98009e51bb2cb86e6977022471d007331 | 29,016,799,121,665 | 7c646abb88e786356b2616e14b75940244e408a6 | /src/org/cadbox/j2d/scale/CadDrawingEngine.java | e62446e50259ac26c9e57ca0b883c9ef6c5823da | []
| no_license | shaiknoorahamed/Psi-Cad | https://github.com/shaiknoorahamed/Psi-Cad | dbbc6d4dc57f835beddc563eb3a9164403edfe05 | f62749a8a09d0d15f27dd5d035cc6fcc24a8383a | refs/heads/master | 2016-09-01T20:25:22.194000 | 2014-04-16T01:07:53 | 2014-04-16T01:07:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* 1: */ package org.cadbox.j2d.scale;
/* 2: */
/* 3: */ import java.awt.BasicStroke;
/* 4: */ import java.awt.Color;
/* 5: */ import java.awt.Graphics2D;
/* 6: */ import java.awt.Stroke;
/* 7: */ import java.awt.event.KeyEvent;
/* 8: */ import java.awt.event.MouseEvent;
/* 9: */ import java.awt.event.MouseWheelEvent;
/* 10: */ import java.awt.image.BufferedImage;
/* 11: */ import java.beans.PropertyChangeSupport;
/* 12: */ import java.util.ArrayList;
/* 13: */ import java.util.Collection;
/* 14: */ import java.util.HashSet;
/* 15: */ import java.util.Iterator;
/* 16: */ import java.util.List;
/* 17: */ import java.util.Set;
/* 18: */ import org.cadbox.MacroCommand;
/* 19: */ import org.cadbox.SimpleURManager;
/* 20: */ import org.cadbox.UREngine;
/* 21: */ import org.cadbox.URManager;
/* 22: */ import org.cadbox.UndoableCommand;
/* 23: */ import org.cadbox.j2d.CadDocument;
/* 24: */ import org.cadbox.j2d.scale.command.AddShapeCommand;
/* 25: */ import org.cadbox.j2d.scale.command.CopyShapeCommand;
/* 26: */ import org.cadbox.j2d.scale.command.DeleteShapeCommand;
/* 27: */ import org.cadbox.j2d.scale.command.ModifyShapeCommand;
/* 28: */ import org.cadbox.j2d.scale.command.MoveShapeCommand;
/* 29: */ import org.cadbox.j2d.scale.command.RotateShapeCommand;
/* 30: */ import org.cadbox.j2d.scale.core.Circle;
/* 31: */ import org.cadbox.j2d.scale.core.Context;
/* 32: */ import org.cadbox.j2d.scale.core.DrawingContext;
/* 33: */ import org.cadbox.j2d.scale.core.DrawingEngine;
/* 34: */ import org.cadbox.j2d.scale.core.GeometryUtils;
/* 35: */ import org.cadbox.j2d.scale.core.Group;
/* 36: */ import org.cadbox.j2d.scale.core.Layer;
/* 37: */ import org.cadbox.j2d.scale.core.Layout;
/* 38: */ import org.cadbox.j2d.scale.core.LineType;
/* 39: */ import org.cadbox.j2d.scale.core.LineWeight;
/* 40: */ import org.cadbox.j2d.scale.core.PropertyContext;
/* 41: */ import org.cadbox.j2d.scale.core.Shape;
/* 42: */ import org.cadbox.j2d.scale.core.geom.Point2D_;
/* 43: */ import org.cadbox.j2d.scale.core.geom.Point2I;
/* 44: */ import org.cadbox.j2d.scale.core.geom.Rectangle2D_;
/* 45: */ import org.cadbox.j2d.scale.core.unit.MmUnit;
/* 46: */ import org.cadbox.j2d.scale.core.unit.UnitTranslator;
/* 47: */
/* 48: */ public class CadDrawingEngine
/* 49: */ extends DrawingEngine
/* 50: */ {
/* 51: 72 */ CadDocument document = null;
/* 52: */ PropertyChangeSupport propertyChangeSupport;
/* 53: */ private double x_clicked;
/* 54: */ private double y_clicked;
/* 55: */ private int mouseButton;
/* 56: */ private double x_clicked_old;
/* 57: */ private double y_clicked_old;
/* 58: 82 */ private Set selectedShapeList = new HashSet();
/* 59: 85 */ private Color snapPointColor = Color.red;
/* 60: 86 */ private BasicStroke snapPointStroke = new BasicStroke(3.0F);
/* 61: 88 */ private Color shapeDrawingColor = Color.black;
/* 62: 89 */ private BasicStroke shapeDrawingStroke = new BasicStroke(1.0F);
/* 63: 92 */ private Stroke selectedShapeStroke = new BasicStroke(1.0F, 0, 0, 1.0F, new float[] { 5.0F }, 0.0F);
/* 64: 95 */ private Color backgroundColor = Color.white;
/* 65: 96 */ private Color foregroundColor = Color.black;
/* 66: */ public static final int SELECTION_MODE = 1;
/* 67: */ public static final int MOTION_MODE = 2;
/* 68: */ public static final int CREATION_MODE = 3;
/* 69: */ public static final int ZOOM_IN_MODE = 4;
/* 70: */ public static final int ZOOM_OUT_MODE = 5;
/* 71: 104 */ private int mode = 1;
/* 72: */ public static final int SHAPE_NONE = 0;
/* 73: */ public static final int SHAPE_POLYLINE = 1;
/* 74: */ public static final int SHAPE_POLYGONE = 2;
/* 75: */ public static final int SHAPE_CIRCLE = 3;
/* 76: */ public static final int SHAPE_SEGMENT = 4;
/* 77: */ public static final int SHAPE_LINE = 5;
/* 78: 113 */ public int shapeType = 0;
/* 79: 115 */ private int pCount = 0;
/* 80: 117 */ private int snapSensitiveLength = 10;
/* 81: 119 */ private double[] xP = new double[2000];
/* 82: 120 */ private double[] yP = new double[2000];
/* 83: */ public static final int NONE_ACTION = 1;
/* 84: */ public static final int MOVE_ACTION = 2;
/* 85: */ public static final int COPY_ACTION = 3;
/* 86: */ public static final int ROTATE_ACTION = 4;
/* 87: */ public static final int EDIT_ACTION = 5;
/* 88: 128 */ private int action = 1;
/* 89: 130 */ private List actionShapeList = new ArrayList();
/* 90: */ private CadShape actionShape;
/* 91: */ Context context;
/* 92: */ DrawingContext drawingContext;
/* 93: */ PropertyContext propertyContext;
/* 94: 138 */ private List snapList = new ArrayList();
/* 95: */ private SnapPoint currentSnapPoint;
/* 96: */
/* 97: */ public CadDrawingEngine(CadDocument document, PropertyChangeSupport propertyChangeSupport)
/* 98: */ {
/* 99: 143 */ this.document = document;
/* 100: 144 */ this.propertyChangeSupport = propertyChangeSupport;
/* 101: */
/* 102: 146 */ this.context = document.getContext();
/* 103: 147 */ this.drawingContext = this.context.getDrawingContext();
/* 104: 148 */ this.propertyContext = this.context.getPropertyContext();
/* 105: */ }
/* 106: */
/* 107: */ public void reset()
/* 108: */ {
/* 109: 152 */ this.selectedShapeList.clear();
/* 110: 153 */ this.actionShape = null;
/* 111: 154 */ this.actionShapeList.clear();
/* 112: 155 */ this.pCount = 0;
/* 113: */ }
/* 114: */
/* 115: */ public void setMode(int mode)
/* 116: */ {
/* 117: 159 */ this.mode = mode;
/* 118: 160 */ this.selectedShapeList.clear();
/* 119: */ }
/* 120: */
/* 121: */ public int getMode()
/* 122: */ {
/* 123: 164 */ return this.mode;
/* 124: */ }
/* 125: */
/* 126: */ public void setShapeType(int shapeType)
/* 127: */ {
/* 128: 168 */ this.shapeType = shapeType;
/* 129: 169 */ this.selectedShapeList.clear();
/* 130: */ }
/* 131: */
/* 132: */ public int getShapeType()
/* 133: */ {
/* 134: 173 */ return this.shapeType;
/* 135: */ }
/* 136: */
/* 137: */ public void setAction(int action)
/* 138: */ {
/* 139: 178 */ this.action = action;
/* 140: */ }
/* 141: */
/* 142: */ public int getAction()
/* 143: */ {
/* 144: 182 */ return this.action;
/* 145: */ }
/* 146: */
/* 147: */ public void clearSelectedShapes()
/* 148: */ {
/* 149: 186 */ this.selectedShapeList.clear();
/* 150: */ }
/* 151: */
/* 152: */ public Color getSnapPointColor()
/* 153: */ {
/* 154: 190 */ return this.snapPointColor;
/* 155: */ }
/* 156: */
/* 157: */ public void setSnapPointColor(Color snapPointColor)
/* 158: */ {
/* 159: 194 */ this.snapPointColor = snapPointColor;
/* 160: */ }
/* 161: */
/* 162: */ public BasicStroke getSnapPointStroke()
/* 163: */ {
/* 164: 198 */ return this.snapPointStroke;
/* 165: */ }
/* 166: */
/* 167: */ public void setSnapPointStroke(BasicStroke snapPointStroke)
/* 168: */ {
/* 169: 202 */ this.snapPointStroke = snapPointStroke;
/* 170: */ }
/* 171: */
/* 172: */ public Color getShapeDrawingColor()
/* 173: */ {
/* 174: 206 */ return this.shapeDrawingColor;
/* 175: */ }
/* 176: */
/* 177: */ public void setShapeDrawingColor(Color shapeDrawingColor)
/* 178: */ {
/* 179: 210 */ this.shapeDrawingColor = shapeDrawingColor;
/* 180: */ }
/* 181: */
/* 182: */ public BasicStroke getShapeDrawingStroke()
/* 183: */ {
/* 184: 214 */ return this.shapeDrawingStroke;
/* 185: */ }
/* 186: */
/* 187: */ public void setShapeDrawingStroke(BasicStroke shapeDrawingStroke)
/* 188: */ {
/* 189: 218 */ this.shapeDrawingStroke = shapeDrawingStroke;
/* 190: */ }
/* 191: */
/* 192: */ public Collection getSelectedShapeList()
/* 193: */ {
/* 194: 222 */ return this.selectedShapeList;
/* 195: */ }
/* 196: */
/* 197: */ public Stroke getSelectedShapeStroke()
/* 198: */ {
/* 199: 233 */ return this.selectedShapeStroke;
/* 200: */ }
/* 201: */
/* 202: */ public void setSelectedShapeStroke(Stroke selectedShapeStroke)
/* 203: */ {
/* 204: 237 */ this.selectedShapeStroke = selectedShapeStroke;
/* 205: */ }
/* 206: */
/* 207: */ public BufferedImage getImage()
/* 208: */ {
/* 209: 241 */ draw();
/* 210: 242 */ return this.drawingContext.getImage();
/* 211: */ }
/* 212: */
/* 213: */ private synchronized void draw()
/* 214: */ {
/* 215: 246 */ if (this.drawingContext.isChanged())
/* 216: */ {
/* 217: 247 */ paint();
/* 218: 248 */ this.drawingContext.setChanged(false);
/* 219: */ }
/* 220: */ }
/* 221: */
/* 222: */ private void paint()
/* 223: */ {
/* 224: 254 */ Graphics2D big = this.drawingContext.getGraphics();
/* 225: */
/* 226: 256 */ Layout layout = this.document.getLayout();
/* 227: 257 */ if ((layout != null) && (layout.getLayoutType() == 0)) {
/* 228: 258 */ preDraw();
/* 229: */ } else {
/* 230: 260 */ preDraw1();
/* 231: */ }
/* 232: 264 */ Iterator iter1 = this.document.getLayers().iterator();
/* 233: 265 */ while (iter1.hasNext())
/* 234: */ {
/* 235: 266 */ Layer layer = (Layer)iter1.next();
/* 236: 267 */ if (layer.getVisible() == true)
/* 237: */ {
/* 238: 268 */ Iterator iter = layer.getShapes().iterator();
/* 239: 269 */ while (iter.hasNext())
/* 240: */ {
/* 241: 270 */ Shape shape = (Shape)iter.next();
/* 242: */
/* 243: 272 */ big.setColor(shape.getColor());
/* 244: */
/* 245: 274 */ double width = UnitTranslator.lengthUnitToPixel(shape.getLineWeight().getLineWeightValue());
/* 246: 275 */ float w = this.drawingContext.distanseToScreen(width);
/* 247: */
/* 248: 277 */ float[] t = shape.getLineType().getLineTypeValue();
/* 249: 278 */ for (int i = 0; i < t.length; i++) {
/* 250: 279 */ t[i] = this.drawingContext.distanseToScreen(t[i] * 10.0F);
/* 251: */ }
/* 252: 283 */ BasicStroke bs = new BasicStroke(w, 1, 1);
/* 253: 284 */ big.setStroke(bs);
/* 254: 286 */ if ((!this.selectedShapeList.contains(shape)) &&
/* 255: 287 */ (inWindowBounds(shape))) {
/* 256: 288 */ shape.draw(this.context);
/* 257: */ }
/* 258: */ }
/* 259: */ }
/* 260: */ }
/* 261: 297 */ if (this.selectedShapeList.size() > 0)
/* 262: */ {
/* 263: 298 */ big.setStroke(this.selectedShapeStroke);
/* 264: 299 */ Iterator iter = this.selectedShapeList.iterator();
/* 265: 300 */ while (iter.hasNext())
/* 266: */ {
/* 267: 301 */ Shape shape_tmp = (Shape)iter.next();
/* 268: 304 */ if (inWindowBounds(shape_tmp))
/* 269: */ {
/* 270: 310 */ big.setColor(shape_tmp.getColor());
/* 271: 311 */ shape_tmp.drawOptimized(this.context);
/* 272: */
/* 273: 313 */ big.setColor(Color.blue);
/* 274: 314 */ Iterator iter2 = ((CadShape)shape_tmp).getActionPoints().iterator();
/* 275: 315 */ while (iter2.hasNext())
/* 276: */ {
/* 277: 316 */ Point2D_ p = ((ActionPoint)iter2.next()).getPoint();
/* 278: 317 */ Point2I p1 = this.drawingContext.translateToScreen(p.x, p.y);
/* 279: 318 */ big.fillRect(p1.x - 5, p1.y - 5, 10, 10);
/* 280: */ }
/* 281: */ }
/* 282: */ }
/* 283: */ }
/* 284: */ }
/* 285: */
/* 286: */ private boolean inWindowBounds(Shape shape)
/* 287: */ {
/* 288: 327 */ return true;
/* 289: */ }
/* 290: */
/* 291: */ private void preDraw()
/* 292: */ {
/* 293: 332 */ Graphics2D big = this.drawingContext.getGraphics();
/* 294: */
/* 295: 334 */ big.setColor(this.backgroundColor);
/* 296: 335 */ big.setStroke(new BasicStroke(1.0F));
/* 297: */
/* 298: 337 */ big.fillRect(0, 0, this.drawingContext.getWidth(), this.drawingContext.getHeight());
/* 299: */
/* 300: 339 */ Point2I p1 = this.drawingContext.translateToScreen(new Point2D_(this.drawingContext.getLogicalLeft(), this.drawingContext.getLogicalTop()));
/* 301: 340 */ Point2I p2 = this.drawingContext.translateToScreen(new Point2D_(this.drawingContext.getLogicalRight(), this.drawingContext.getLogicalBottom()));
/* 302: */
/* 303: */
/* 304: 343 */ big.setColor(Color.black);
/* 305: 344 */ big.drawRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
/* 306: */
/* 307: */
/* 308: */
/* 309: */
/* 310: */
/* 311: */
/* 312: */
/* 313: */
/* 314: */
/* 315: */
/* 316: */
/* 317: */
/* 318: */
/* 319: */
/* 320: */
/* 321: */
/* 322: */
/* 323: */
/* 324: */
/* 325: */
/* 326: */
/* 327: 366 */ big.setColor(Color.lightGray);
/* 328: 367 */ p1 = this.drawingContext.translateToScreen(new Point2D_(250.0D, 0.0D));
/* 329: 368 */ p2 = this.drawingContext.translateToScreen(new Point2D_(0.0D, 0.0D));
/* 330: 369 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 331: */
/* 332: 371 */ p1 = this.drawingContext.translateToScreen(new Point2D_(250.0D, 0.0D));
/* 333: 372 */ p2 = this.drawingContext.translateToScreen(new Point2D_(240.0D, 5.0D));
/* 334: 373 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 335: 374 */ p1 = this.drawingContext.translateToScreen(new Point2D_(250.0D, 0.0D));
/* 336: 375 */ p2 = this.drawingContext.translateToScreen(new Point2D_(240.0D, -5.0D));
/* 337: 376 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 338: */
/* 339: */
/* 340: 379 */ p1 = this.drawingContext.translateToScreen(new Point2D_(0.0D, 250.0D));
/* 341: 380 */ p2 = this.drawingContext.translateToScreen(new Point2D_(0.0D, 0.0D));
/* 342: 381 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 343: */
/* 344: 383 */ p1 = this.drawingContext.translateToScreen(new Point2D_(0.0D, 250.0D));
/* 345: 384 */ p2 = this.drawingContext.translateToScreen(new Point2D_(5.0D, 240.0D));
/* 346: 385 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 347: */
/* 348: 387 */ p1 = this.drawingContext.translateToScreen(new Point2D_(0.0D, 250.0D));
/* 349: 388 */ p2 = this.drawingContext.translateToScreen(new Point2D_(-5.0D, 240.0D));
/* 350: 389 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 351: */ }
/* 352: */
/* 353: */ private void preDraw1()
/* 354: */ {
/* 355: 397 */ Graphics2D big = this.drawingContext.getGraphics();
/* 356: */
/* 357: */
/* 358: 400 */ big.setColor(Color.gray);
/* 359: 401 */ big.setStroke(new BasicStroke(1.0F));
/* 360: */
/* 361: 403 */ big.fillRect(0, 0, this.drawingContext.getWidth(), this.drawingContext.getHeight());
/* 362: */
/* 363: 405 */ Point2I p1 = this.drawingContext.translateToScreen(new Point2D_(this.drawingContext.getLogicalLeft(), this.drawingContext.getLogicalTop()));
/* 364: 406 */ Point2I p2 = this.drawingContext.translateToScreen(new Point2D_(this.drawingContext.getLogicalRight(), this.drawingContext.getLogicalBottom()));
/* 365: */
/* 366: */
/* 367: 409 */ big.setColor(Color.black);
/* 368: 410 */ big.fillRect(p1.x + 5, p1.y + 5, p2.x - p1.x, p2.y - p1.y);
/* 369: */
/* 370: 412 */ big.setColor(Color.white);
/* 371: 413 */ big.fillRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
/* 372: */
/* 373: 415 */ big.setColor(Color.black);
/* 374: 416 */ big.drawRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
/* 375: */ }
/* 376: */
/* 377: */ protected void actionMoveCopy(Shape shape, double x1, double y1, double x2, double y2)
/* 378: */ {
/* 379: 421 */ Graphics2D big = this.drawingContext.getGraphics();
/* 380: */
/* 381: 423 */ big.setXORMode(Color.white);
/* 382: */
/* 383: 425 */ Point2I p1 = this.drawingContext.translateToScreen(new Point2D_(x1, y1));
/* 384: 426 */ Point2I p2 = this.drawingContext.translateToScreen(new Point2D_(x2, y2));
/* 385: 427 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 386: */
/* 387: 429 */ shape.move(x1 - x2, y1 - y2);
/* 388: 430 */ shape.draw(this.context);
/* 389: 431 */ shape.move(-(x1 - x2), -(y1 - y2));
/* 390: 432 */ big.setPaintMode();
/* 391: */ }
/* 392: */
/* 393: */ protected void actionRotate(Shape shape, double x1, double y1, double x2, double y2)
/* 394: */ {
/* 395: 439 */ Graphics2D big = this.drawingContext.getGraphics();
/* 396: */
/* 397: 441 */ big.setXORMode(Color.white);
/* 398: */
/* 399: 443 */ Point2I p1 = this.drawingContext.translateToScreen(new Point2D_(x1, y1));
/* 400: 444 */ Point2I p2 = this.drawingContext.translateToScreen(new Point2D_(x2, y2));
/* 401: 445 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 402: */
/* 403: 447 */ double A = GeometryUtils.fingAngele(x1, y1, x2, y2);
/* 404: */
/* 405: 449 */ shape.rotate(x1, y1, A);
/* 406: 450 */ shape.draw(this.context);
/* 407: 451 */ shape.rotate(x1, y1, -A);
/* 408: 452 */ big.setPaintMode();
/* 409: */ }
/* 410: */
/* 411: */ public void addShape(Shape shape)
/* 412: */ {
/* 413: 458 */ PropertyContext pContext = this.context.getPropertyContext();
/* 414: */
/* 415: 460 */ UndoableCommand cmd = addShapeAll(shape);
/* 416: 461 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 417: 462 */ cmd.execute();
/* 418: */
/* 419: 464 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 420: */ }
/* 421: */
/* 422: */ public void deleteSelectedShape()
/* 423: */ {
/* 424: 468 */ if (this.selectedShapeList.size() > 0)
/* 425: */ {
/* 426: 469 */ MacroCommand cmd = new MacroCommand();
/* 427: 470 */ Iterator iter = this.selectedShapeList.iterator();
/* 428: 471 */ while (iter.hasNext())
/* 429: */ {
/* 430: 472 */ Shape shape_tmp = (Shape)iter.next();
/* 431: 473 */ Group g = shape_tmp.getParent();
/* 432: 474 */ if (g != null)
/* 433: */ {
/* 434: 476 */ removeStaticSnapPoint((CadShape)shape_tmp);
/* 435: */
/* 436: */
/* 437: */
/* 438: 480 */ DeleteShapeCommand dc = new DeleteShapeCommand(g, shape_tmp);
/* 439: 481 */ cmd.addCommand(dc);
/* 440: */ }
/* 441: */ }
/* 442: 484 */ if (cmd.getCommandCount() > 0)
/* 443: */ {
/* 444: 485 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 445: 486 */ cmd.execute();
/* 446: */ }
/* 447: 488 */ this.selectedShapeList.clear();
/* 448: 489 */ this.document.setModified(true);
/* 449: 490 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 450: */ }
/* 451: */ }
/* 452: */
/* 453: */ public void modifyShape(Shape oldShape, Shape newShape)
/* 454: */ {
/* 455: 496 */ ModifyShapeCommand cmd = new ModifyShapeCommand(oldShape, newShape);
/* 456: 497 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 457: */
/* 458: 499 */ removeStaticSnapPoint((CadShape)oldShape);
/* 459: 500 */ cmd.execute();
/* 460: 501 */ addStaticSnapPoint((CadShape)newShape);
/* 461: */
/* 462: 503 */ this.selectedShapeList.remove(oldShape);
/* 463: 504 */ this.selectedShapeList.add(newShape);
/* 464: 505 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 465: */ }
/* 466: */
/* 467: */ public void moveShape(Shape shape, double vX, double vY)
/* 468: */ {
/* 469: 509 */ UndoableCommand cmd = moveShapeAll(shape, vX, vY);
/* 470: 510 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 471: */
/* 472: 512 */ removeStaticSnapPoint((CadShape)shape);
/* 473: 513 */ cmd.execute();
/* 474: 514 */ addStaticSnapPoint((CadShape)shape);
/* 475: */
/* 476: 516 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 477: */ }
/* 478: */
/* 479: */ public void copyShape(Layer layer, Shape shape)
/* 480: */ {
/* 481: 520 */ UndoableCommand cmd = copyShapeAll(layer, shape);
/* 482: 521 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 483: */
/* 484: */
/* 485: 524 */ cmd.execute();
/* 486: 525 */ addStaticSnapPoint((CadShape)shape);
/* 487: */
/* 488: 527 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 489: */ }
/* 490: */
/* 491: */ public void rotateShape(Shape shape, double x, double y, double angle)
/* 492: */ {
/* 493: 531 */ UndoableCommand cmd = rotateShapeAll(shape, x, y, angle);
/* 494: 532 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 495: */
/* 496: 534 */ removeStaticSnapPoint((CadShape)shape);
/* 497: 535 */ cmd.execute();
/* 498: 536 */ addStaticSnapPoint((CadShape)shape);
/* 499: */
/* 500: 538 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 501: */ }
/* 502: */
/* 503: */ public UndoableCommand addShapeAll(Shape shape)
/* 504: */ {
/* 505: 542 */ PropertyContext pContext = this.context.getPropertyContext();
/* 506: */
/* 507: 544 */ shape.setColor(pContext.getColor());
/* 508: 545 */ shape.setLineWeight(pContext.getLineWeight());
/* 509: 546 */ shape.setLineType(pContext.getLineType());
/* 510: */
/* 511: 548 */ addStaticSnapPoint((CadShape)shape);
/* 512: */
/* 513: 550 */ AddShapeCommand cmd = new AddShapeCommand(shape, this.document.getCurrentLayer());
/* 514: 551 */ return cmd;
/* 515: */ }
/* 516: */
/* 517: */ public UndoableCommand moveShapeAll(Shape shape, double vX, double vY)
/* 518: */ {
/* 519: 555 */ MoveShapeCommand cmd = new MoveShapeCommand(shape, vX, vY);
/* 520: 556 */ return cmd;
/* 521: */ }
/* 522: */
/* 523: */ public UndoableCommand copyShapeAll(Layer layer, Shape shape)
/* 524: */ {
/* 525: 560 */ CopyShapeCommand cmd = new CopyShapeCommand(layer, shape);
/* 526: 561 */ return cmd;
/* 527: */ }
/* 528: */
/* 529: */ public UndoableCommand rotateShapeAll(Shape shape, double x, double y, double angle)
/* 530: */ {
/* 531: 565 */ RotateShapeCommand cmd = new RotateShapeCommand(shape, x, y, angle);
/* 532: 566 */ return cmd;
/* 533: */ }
/* 534: */
/* 535: */ private void addStaticSnapPoint(CadShape shape)
/* 536: */ {
/* 537: 570 */ Collection c = shape.getSnapPoints();
/* 538: 571 */ Iterator iter = c.iterator();
/* 539: 572 */ while (iter.hasNext())
/* 540: */ {
/* 541: 573 */ SnapPoint sp = (SnapPoint)iter.next();
/* 542: 574 */ if (!this.snapList.contains(sp)) {
/* 543: 575 */ this.snapList.add(sp);
/* 544: */ }
/* 545: */ }
/* 546: */ }
/* 547: */
/* 548: */ private void removeStaticSnapPoint(CadShape shape)
/* 549: */ {
/* 550: 580 */ Collection c = shape.getSnapPoints();
/* 551: 581 */ this.snapList.removeAll(c);
/* 552: */ }
/* 553: */
/* 554: */ public void mousePressed(MouseEvent evt)
/* 555: */ {
/* 556: 587 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 557: */
/* 558: 589 */ double x = p2d.x;
/* 559: 590 */ double y = p2d.y;
/* 560: */
/* 561: 592 */ this.x_clicked = (this.x_clicked_old = x);
/* 562: 593 */ this.y_clicked = (this.y_clicked_old = y);
/* 563: */
/* 564: 595 */ this.mouseButton = evt.getButton();
/* 565: 597 */ if ((this.mode == 4) && (this.mouseButton == 1))
/* 566: */ {
/* 567: 599 */ this.drawingContext.changeScaleTo(-1);
/* 568: 600 */ this.document.setModified(true);
/* 569: */ }
/* 570: 603 */ if ((this.mode == 5) && (this.mouseButton == 1))
/* 571: */ {
/* 572: 605 */ this.drawingContext.changeScaleTo(1);
/* 573: 606 */ this.document.setModified(true);
/* 574: */ }
/* 575: 609 */ if (this.pCount == 0)
/* 576: */ {
/* 577: 610 */ startAction(evt);
/* 578: 611 */ return;
/* 579: */ }
/* 580: 614 */ if ((this.pCount > 0) &&
/* 581: 615 */ (this.xP[(this.pCount - 1)] != x) && (this.yP[(this.pCount - 1)] != y)) {
/* 582: 616 */ endAction(evt);
/* 583: */ }
/* 584: 620 */ this.document.setModified(true);
/* 585: */ }
/* 586: */
/* 587: */ public void mouseDragged(MouseEvent evt)
/* 588: */ {
/* 589: 627 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 590: 628 */ double x = p2d.x;
/* 591: 629 */ double y = p2d.y;
/* 592: 631 */ if ((this.mode == 2) || (this.mouseButton == 3))
/* 593: */ {
/* 594: 634 */ boolean redraw = true;
/* 595: */
/* 596: 636 */ double lenX = this.x_clicked - x;
/* 597: 637 */ double lenY = this.y_clicked - y;
/* 598: */
/* 599: */
/* 600: 640 */ this.drawingContext.moveTo(lenX, lenY);
/* 601: */
/* 602: 642 */ this.pCount = 0;
/* 603: 644 */ if (redraw) {
/* 604: 645 */ this.drawingContext.setChanged(true);
/* 605: */ }
/* 606: 646 */ return;
/* 607: */ }
/* 608: 649 */ if (this.pCount == 1) {
/* 609: 650 */ continousAction(evt);
/* 610: */ }
/* 611: */ }
/* 612: */
/* 613: */ public void mouseMoved(MouseEvent evt)
/* 614: */ {
/* 615: 656 */ Graphics2D big = this.drawingContext.getGraphics();
/* 616: */
/* 617: 658 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 618: 659 */ double x = p2d.x;
/* 619: 660 */ double y = p2d.y;
/* 620: */
/* 621: 662 */ this.propertyChangeSupport.firePropertyChange("mouseCoordinateX", Double.valueOf(0.0D), Double.valueOf(UnitTranslator.pixelToMilemetor(p2d.x).getValue()));
/* 622: 663 */ this.propertyChangeSupport.firePropertyChange("mouseCoordinateY", Double.valueOf(0.0D), Double.valueOf(UnitTranslator.pixelToMilemetor(p2d.y).getValue()));
/* 623: */
/* 624: 665 */ this.propertyChangeSupport.firePropertyChange("scale", Double.valueOf(0.0D), Double.valueOf(this.drawingContext.getScale()));
/* 625: 667 */ if (this.pCount > 0) {
/* 626: 668 */ continousAction(evt);
/* 627: */ }
/* 628: 671 */ if (this.mode == 3)
/* 629: */ {
/* 630: 673 */ if (this.currentSnapPoint != null) {
/* 631: 674 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 632: */ }
/* 633: 676 */ this.currentSnapPoint = null;
/* 634: */
/* 635: */
/* 636: 679 */ int minlen = 2147483647;
/* 637: 680 */ for (int i = 0; i < this.snapList.size(); i++)
/* 638: */ {
/* 639: 681 */ SnapPoint sp = (SnapPoint)this.snapList.get(i);
/* 640: 682 */ Point2D_ p = sp.getPoint();
/* 641: */
/* 642: 684 */ double len = GeometryUtils.length(p.x, p.y, x, y);
/* 643: 685 */ int ilen = this.drawingContext.distanseToScreen(len);
/* 644: 687 */ if ((ilen < this.snapSensitiveLength) && (minlen > ilen))
/* 645: */ {
/* 646: 688 */ minlen = ilen;
/* 647: 689 */ this.currentSnapPoint = sp;
/* 648: */ }
/* 649: */ }
/* 650: 692 */ if (this.currentSnapPoint != null) {
/* 651: 693 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 652: */ }
/* 653: */ }
/* 654: */ }
/* 655: */
/* 656: */ protected void startAction(MouseEvent evt)
/* 657: */ {
/* 658: 701 */ Graphics2D big = this.drawingContext.getGraphics();
/* 659: */
/* 660: 703 */ double x = this.x_clicked;
/* 661: 704 */ double y = this.y_clicked;
/* 662: 706 */ if ((this.selectedShapeList.size() > 0) && (this.action == 1))
/* 663: */ {
/* 664: 707 */ Iterator iter = this.selectedShapeList.iterator();
/* 665: 708 */ while (iter.hasNext())
/* 666: */ {
/* 667: 709 */ CadShape shape_tmp = (CadShape)iter.next();
/* 668: */
/* 669: 711 */ Iterator iter1 = shape_tmp.getActionPoints().iterator();
/* 670: 712 */ while (iter1.hasNext())
/* 671: */ {
/* 672: 713 */ ActionPoint ap = (ActionPoint)iter1.next();
/* 673: 714 */ Point2D_ p = ap.getPoint();
/* 674: */
/* 675: 716 */ double dis = this.drawingContext.distanseToLogical(5.0D);
/* 676: 718 */ if ((x >= p.x - dis) && (x <= p.x + dis) && (y >= p.y - dis) && (y <= p.y + dis))
/* 677: */ {
/* 678: 719 */ this.action = 5;
/* 679: 720 */ shape_tmp.setActionPoint(ap);
/* 680: 721 */ this.actionShape = shape_tmp;
/* 681: 722 */ break;
/* 682: */ }
/* 683: */ }
/* 684: */ }
/* 685: */ }
/* 686: 728 */ if ((this.action != 1) && (this.selectedShapeList.size() > 0) && (this.mouseButton == 1))
/* 687: */ {
/* 688: 731 */ this.xP[this.pCount] = this.x_clicked;
/* 689: 732 */ this.yP[this.pCount] = this.y_clicked;
/* 690: 734 */ if (this.action != 5)
/* 691: */ {
/* 692: 735 */ Iterator iter = this.selectedShapeList.iterator();
/* 693: 736 */ while (iter.hasNext())
/* 694: */ {
/* 695: 737 */ Shape shape_tmp = (Shape)iter.next();
/* 696: */
/* 697: 739 */ this.actionShapeList.add(shape_tmp);
/* 698: 742 */ if (this.action == 2) {
/* 699: 743 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 700: */ }
/* 701: 746 */ if (this.action == 3) {
/* 702: 747 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 703: */ }
/* 704: 750 */ if (this.action == 4) {
/* 705: 751 */ actionRotate(shape_tmp, this.x_clicked, this.y_clicked, this.x_clicked_old, this.y_clicked_old);
/* 706: */ }
/* 707: */ }
/* 708: */ }
/* 709: 756 */ if ((this.action == 5) && (this.actionShape != null)) {
/* 710: 758 */ this.actionShape.moveActionPoint(this, this.context, x, y);
/* 711: */ }
/* 712: 761 */ this.pCount += 1;
/* 713: 762 */ return;
/* 714: */ }
/* 715: 764 */ this.action = 1;
/* 716: 767 */ if ((this.mode == 3) && (this.mouseButton == 1))
/* 717: */ {
/* 718: 769 */ if (this.currentSnapPoint != null)
/* 719: */ {
/* 720: 770 */ Point2D_ p = this.currentSnapPoint.getPoint();
/* 721: 771 */ x = p.x;
/* 722: 772 */ y = p.y;
/* 723: */ }
/* 724: 775 */ this.xP[this.pCount] = x;
/* 725: 776 */ this.yP[this.pCount] = y;
/* 726: 779 */ if ((this.shapeType == 3) &&
/* 727: 780 */ (this.pCount == 1))
/* 728: */ {
/* 729: 781 */ double radius = Math.sqrt((this.xP[0] - this.xP[1]) * (this.xP[0] - this.xP[1]) + (this.yP[0] - this.yP[1]) * (this.yP[0] - this.yP[1]));
/* 730: 782 */ Shape shape = new Circle(this.xP[0], this.yP[0], radius);
/* 731: 783 */ addShape(shape);
/* 732: */
/* 733: 785 */ this.pCount = 0;
/* 734: 786 */ this.mode = 1;
/* 735: 787 */ this.drawingContext.setChanged(true);
/* 736: 788 */ return;
/* 737: */ }
/* 738: 793 */ if ((this.shapeType == 5) &&
/* 739: 794 */ (this.pCount > 0)) {
/* 740: 795 */ for (int i = 0; i < this.pCount; i++) {
/* 741: 796 */ DrawingUtils.drawStarngeLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 742: */ }
/* 743: */ }
/* 744: 801 */ if ((this.shapeType == 2) &&
/* 745: 802 */ (this.pCount > 0)) {
/* 746: 803 */ for (int i = 0; i < this.pCount; i++) {
/* 747: 804 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 748: */ }
/* 749: */ }
/* 750: 809 */ if ((this.shapeType == 1) &&
/* 751: 810 */ (this.pCount > 0)) {
/* 752: 811 */ for (int i = 0; i < this.pCount; i++) {
/* 753: 812 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 754: */ }
/* 755: */ }
/* 756: 817 */ if ((this.shapeType == 4) &&
/* 757: 818 */ (this.pCount > 0)) {
/* 758: 819 */ for (int i = 0; i < this.pCount; i++) {
/* 759: 820 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 760: */ }
/* 761: */ }
/* 762: 825 */ this.x_clicked_old = x;
/* 763: 826 */ this.y_clicked_old = y;
/* 764: */
/* 765: 828 */ this.pCount += 1;
/* 766: */ }
/* 767: 831 */ if ((this.mode == 1) && (this.pCount == 0) && (this.mouseButton == 1))
/* 768: */ {
/* 769: 836 */ Iterator iter1 = this.document.getLayers().iterator();
/* 770: 837 */ while (iter1.hasNext())
/* 771: */ {
/* 772: 838 */ Layer layer = (Layer)iter1.next();
/* 773: 839 */ if ((layer.getVisible()) && (layer.getEnable()))
/* 774: */ {
/* 775: 841 */ Iterator iter = layer.getShapes().iterator();
/* 776: 842 */ while (iter.hasNext())
/* 777: */ {
/* 778: 843 */ Shape shape = (Shape)iter.next();
/* 779: */
/* 780: 845 */ double dis = this.drawingContext.distanseToLogical(2.0D);
/* 781: 847 */ if (shape.containsPoint(x, y, dis))
/* 782: */ {
/* 783: 849 */ this.selectedShapeList.add(shape);
/* 784: */
/* 785: 851 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 786: 852 */ this.drawingContext.setChanged(true);
/* 787: 853 */ return;
/* 788: */ }
/* 789: */ }
/* 790: */ }
/* 791: */ }
/* 792: 859 */ DrawingUtils.drawRectangleXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 793: 860 */ this.xP[this.pCount] = x;
/* 794: 861 */ this.yP[this.pCount] = y;
/* 795: 862 */ this.pCount += 1;
/* 796: */ }
/* 797: */ }
/* 798: */
/* 799: */ protected void continousAction(MouseEvent evt)
/* 800: */ {
/* 801: 870 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 802: 871 */ double x = p2d.x;
/* 803: 872 */ double y = p2d.y;
/* 804: */
/* 805: */
/* 806: */
/* 807: */
/* 808: */
/* 809: 878 */ Graphics2D big = this.drawingContext.getGraphics();
/* 810: 880 */ if ((this.action != 1) && (this.mouseButton == 1))
/* 811: */ {
/* 812: 883 */ if (this.currentSnapPoint != null)
/* 813: */ {
/* 814: 884 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 815: */
/* 816: 886 */ this.currentSnapPoint = null;
/* 817: */ }
/* 818: 888 */ int minlen = 2147483647;
/* 819: 889 */ for (int i = 0; i < this.snapList.size(); i++)
/* 820: */ {
/* 821: 890 */ SnapPoint sp = (SnapPoint)this.snapList.get(i);
/* 822: 891 */ Point2D_ p = sp.getPoint();
/* 823: 892 */ double len = GeometryUtils.length(p.x, p.y, x, y);
/* 824: 893 */ int ilen = this.drawingContext.distanseToScreen(len);
/* 825: 894 */ if ((ilen < this.snapSensitiveLength) && (minlen > ilen))
/* 826: */ {
/* 827: 895 */ minlen = ilen;
/* 828: 896 */ this.currentSnapPoint = sp;
/* 829: */ }
/* 830: */ }
/* 831: 899 */ if (this.currentSnapPoint != null) {
/* 832: 900 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 833: */ }
/* 834: 905 */ if (this.action != 5) {
/* 835: 906 */ for (int i = 0; i < this.actionShapeList.size(); i++)
/* 836: */ {
/* 837: 908 */ Shape shape_tmp = (Shape)this.actionShapeList.get(i);
/* 838: 910 */ if (this.action == 2)
/* 839: */ {
/* 840: 911 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 841: 912 */ actionMoveCopy(shape_tmp, x, y, this.x_clicked, this.y_clicked);
/* 842: */ }
/* 843: 915 */ if (this.action == 3)
/* 844: */ {
/* 845: 916 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 846: 917 */ actionMoveCopy(shape_tmp, x, y, this.x_clicked, this.y_clicked);
/* 847: */ }
/* 848: 920 */ if (this.action == 4)
/* 849: */ {
/* 850: 921 */ actionRotate(shape_tmp, this.x_clicked, this.y_clicked, this.x_clicked_old, this.y_clicked_old);
/* 851: 922 */ actionRotate(shape_tmp, this.x_clicked, this.y_clicked, x, y);
/* 852: */ }
/* 853: */ }
/* 854: */ }
/* 855: 927 */ if ((this.action == 5) && (this.actionShape != null))
/* 856: */ {
/* 857: 929 */ this.actionShape.moveActionPoint(this, this.context, this.x_clicked_old, this.y_clicked_old);
/* 858: 930 */ this.actionShape.moveActionPoint(this, this.context, x, y);
/* 859: */ }
/* 860: 934 */ this.x_clicked_old = x;
/* 861: 935 */ this.y_clicked_old = y;
/* 862: 936 */ return;
/* 863: */ }
/* 864: 939 */ if (this.mode == 3)
/* 865: */ {
/* 866: 942 */ if (this.currentSnapPoint != null) {
/* 867: 943 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 868: */ }
/* 869: 945 */ this.currentSnapPoint = null;
/* 870: */
/* 871: */
/* 872: 948 */ int minlen = 2147483647;
/* 873: 949 */ for (int i = 0; i < this.snapList.size(); i++)
/* 874: */ {
/* 875: 950 */ SnapPoint sp = (SnapPoint)this.snapList.get(i);
/* 876: 951 */ Point2D_ p = sp.getPoint();
/* 877: */
/* 878: 953 */ double len = GeometryUtils.length(p.x, p.y, x, y);
/* 879: 954 */ int ilen = this.drawingContext.distanseToScreen(len);
/* 880: 956 */ if ((ilen < this.snapSensitiveLength) && (minlen > ilen))
/* 881: */ {
/* 882: 957 */ minlen = ilen;
/* 883: 958 */ this.currentSnapPoint = sp;
/* 884: */ }
/* 885: */ }
/* 886: 961 */ if (this.currentSnapPoint != null) {
/* 887: 962 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 888: */ }
/* 889: 966 */ int tmp = this.pCount - 1;
/* 890: 968 */ if (this.pCount > 0)
/* 891: */ {
/* 892: 970 */ if ((this.shapeType == 3) &&
/* 893: 971 */ (this.pCount == 1))
/* 894: */ {
/* 895: 972 */ double r = GeometryUtils.length(this.xP[0], this.yP[0], this.x_clicked_old, this.y_clicked_old);
/* 896: 973 */ DrawingUtils.drawOvalXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[0], this.yP[0], r);
/* 897: 974 */ r = GeometryUtils.length(this.xP[0], this.yP[0], x, y);
/* 898: 975 */ DrawingUtils.drawOvalXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[0], this.yP[0], r);
/* 899: */ }
/* 900: 979 */ if (this.shapeType == 5)
/* 901: */ {
/* 902: 980 */ DrawingUtils.drawStarngeLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[tmp], this.yP[tmp]);
/* 903: 981 */ DrawingUtils.drawStarngeLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, x, y, this.xP[tmp], this.yP[tmp]);
/* 904: */ }
/* 905: 984 */ if (this.shapeType == 4)
/* 906: */ {
/* 907: 985 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[tmp], this.yP[tmp]);
/* 908: 986 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, x, y, this.xP[tmp], this.yP[tmp]);
/* 909: */ }
/* 910: 989 */ if (this.shapeType == 1)
/* 911: */ {
/* 912: 990 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[tmp], this.yP[tmp]);
/* 913: 991 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, x, y, this.xP[tmp], this.yP[tmp]);
/* 914: */ }
/* 915: */ }
/* 916: 995 */ this.x_clicked_old = x;
/* 917: 996 */ this.y_clicked_old = y;
/* 918: */
/* 919: 998 */ return;
/* 920: */ }
/* 921:1002 */ if ((this.mode == 1) && (this.pCount == 1) && (this.mouseButton == 1))
/* 922: */ {
/* 923:1006 */ DrawingUtils.drawRectangleXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 924:1007 */ DrawingUtils.drawRectangleXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, x, y, this.x_clicked, this.y_clicked);
/* 925: */
/* 926:1009 */ this.x_clicked_old = x;
/* 927:1010 */ this.y_clicked_old = y;
/* 928:1011 */ return;
/* 929: */ }
/* 930: */ }
/* 931: */
/* 932: */ protected void endAction(MouseEvent evt)
/* 933: */ {
/* 934:1017 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 935:1018 */ double x = p2d.x;
/* 936:1019 */ double y = p2d.y;
/* 937: */
/* 938:1021 */ Graphics2D big = this.drawingContext.getGraphics();
/* 939:1023 */ if ((this.action != 1) && (this.mouseButton == 1))
/* 940: */ {
/* 941:1026 */ if (this.currentSnapPoint != null)
/* 942: */ {
/* 943:1027 */ Point2D_ p = this.currentSnapPoint.getPoint();
/* 944:1028 */ x = p.x;
/* 945:1029 */ y = p.y;
/* 946:1030 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 947: */
/* 948:1032 */ this.currentSnapPoint = null;
/* 949: */ }
/* 950:1035 */ if (this.action != 5) {
/* 951:1037 */ if (this.actionShapeList.size() > 0)
/* 952: */ {
/* 953:1040 */ MacroCommand cmd = new MacroCommand();
/* 954:1042 */ for (int i = 0; i < this.actionShapeList.size(); i++)
/* 955: */ {
/* 956:1044 */ Shape shape_tmp = (Shape)this.actionShapeList.get(i);
/* 957:1046 */ if (this.action == 2)
/* 958: */ {
/* 959:1047 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 960:1048 */ cmd.addCommand(moveShapeAll(shape_tmp, x - this.xP[0], y - this.yP[0]));
/* 961:1049 */ this.selectedShapeList.clear();
/* 962: */ }
/* 963:1052 */ if (this.action == 3)
/* 964: */ {
/* 965:1053 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 966: */
/* 967:1055 */ Shape sh = (Shape)shape_tmp.clone();
/* 968:1056 */ sh.move(x - this.xP[0], y - this.yP[0]);
/* 969: */
/* 970:1058 */ cmd.addCommand(copyShapeAll(this.document.getCurrentLayer(), sh));
/* 971: */
/* 972:1060 */ addStaticSnapPoint((CadShape)sh);
/* 973:1061 */ this.selectedShapeList.clear();
/* 974: */ }
/* 975:1064 */ if (this.action == 4)
/* 976: */ {
/* 977:1065 */ actionRotate(shape_tmp, this.x_clicked, this.y_clicked, this.x_clicked_old, this.y_clicked_old);
/* 978:1066 */ double A = GeometryUtils.fingAngele(this.xP[0], this.yP[0], x, y);
/* 979: */
/* 980:1068 */ cmd.addCommand(rotateShapeAll(shape_tmp, this.xP[0], this.yP[0], A));
/* 981: */
/* 982:1070 */ this.selectedShapeList.clear();
/* 983: */ }
/* 984: */ }
/* 985:1074 */ if (cmd.getCommandCount() > 0)
/* 986: */ {
/* 987:1075 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 988:1076 */ cmd.execute();
/* 989: */
/* 990:1078 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 991: */ }
/* 992: */ }
/* 993: */ }
/* 994:1083 */ if ((this.action == 5) && (this.actionShape != null)) {
/* 995:1084 */ this.actionShape.postActionPoint(this, x, y);
/* 996: */ }
/* 997:1087 */ this.action = 1;
/* 998:1088 */ this.actionShapeList.clear();
/* 999:1089 */ this.actionShape = null;
/* 1000: */
/* 1001:1091 */ this.drawingContext.setChanged(true);
/* 1002: */
/* 1003:1093 */ this.pCount = 0;
/* 1004:1094 */ return;
/* 1005: */ }
/* 1006:1098 */ if ((this.mode == 3) && (this.mouseButton == 1))
/* 1007: */ {
/* 1008:1100 */ if (this.currentSnapPoint != null)
/* 1009: */ {
/* 1010:1101 */ Point2D_ p = this.currentSnapPoint.getPoint();
/* 1011:1102 */ x = p.x;
/* 1012:1103 */ y = p.y;
/* 1013:1104 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 1014: */
/* 1015:1106 */ this.currentSnapPoint = null;
/* 1016: */ }
/* 1017:1110 */ this.xP[this.pCount] = x;
/* 1018:1111 */ this.yP[this.pCount] = y;
/* 1019:1114 */ if ((this.shapeType == 3) &&
/* 1020:1115 */ (this.pCount == 1))
/* 1021: */ {
/* 1022:1116 */ double radius = Math.sqrt((this.xP[0] - this.xP[1]) * (this.xP[0] - this.xP[1]) + (this.yP[0] - this.yP[1]) * (this.yP[0] - this.yP[1]));
/* 1023:1117 */ Shape shape = new CadCircle(this.xP[0], this.yP[0], radius);
/* 1024:1118 */ addShape(shape);
/* 1025: */
/* 1026:1120 */ this.selectedShapeList.clear();
/* 1027:1121 */ this.pCount = 0;
/* 1028:1122 */ this.mode = 1;
/* 1029:1123 */ this.drawingContext.setChanged(true);
/* 1030:1124 */ return;
/* 1031: */ }
/* 1032:1129 */ if ((this.shapeType == 5) &&
/* 1033:1130 */ (this.pCount > 0))
/* 1034: */ {
/* 1035:1132 */ Shape shape = new CadLine(this.xP[0], this.yP[0], this.xP[1], this.yP[1], this.context);
/* 1036:1133 */ addShape(shape);
/* 1037: */
/* 1038:1135 */ this.selectedShapeList.clear();
/* 1039: */
/* 1040:1137 */ this.pCount = 0;
/* 1041:1138 */ this.mode = 1;
/* 1042:1139 */ this.drawingContext.setChanged(true);
/* 1043:1140 */ return;
/* 1044: */ }
/* 1045:1144 */ if ((this.shapeType == 4) &&
/* 1046:1145 */ (this.pCount > 0))
/* 1047: */ {
/* 1048:1146 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[(this.pCount - 1)], this.yP[(this.pCount - 1)]);
/* 1049:1147 */ for (int i = 0; i < this.pCount; i++) {
/* 1050:1148 */ DrawingUtils.drawLine(this.drawingContext, this.foregroundColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 1051: */ }
/* 1052: */ }
/* 1053:1153 */ if ((this.shapeType == 1) &&
/* 1054:1154 */ (this.pCount > 0))
/* 1055: */ {
/* 1056:1155 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[(this.pCount - 1)], this.yP[(this.pCount - 1)]);
/* 1057:1156 */ for (int i = 0; i < this.pCount; i++) {
/* 1058:1157 */ DrawingUtils.drawLine(this.drawingContext, this.foregroundColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 1059: */ }
/* 1060: */ }
/* 1061:1162 */ this.x_clicked_old = x;
/* 1062:1163 */ this.y_clicked_old = y;
/* 1063: */
/* 1064:1165 */ this.pCount += 1;
/* 1065:1166 */ return;
/* 1066: */ }
/* 1067:1170 */ if ((this.mode == 1) && (this.mouseButton == 1))
/* 1068: */ {
/* 1069:1174 */ double x_tmp = Math.min(this.xP[0], x);
/* 1070:1175 */ double y_tmp = Math.max(this.yP[0], y);
/* 1071:1176 */ double width_tmp = Math.abs(this.xP[0] - x);
/* 1072:1177 */ double height_tmp = Math.abs(this.yP[0] - y);
/* 1073:1178 */ Rectangle2D_ rect_tmp = new Rectangle2D_(x_tmp, y_tmp, width_tmp, height_tmp);
/* 1074: */
/* 1075:1180 */ Iterator iter1 = this.document.getLayers().iterator();
/* 1076:1181 */ while (iter1.hasNext())
/* 1077: */ {
/* 1078:1182 */ Layer layer = (Layer)iter1.next();
/* 1079:1183 */ if ((layer.getVisible()) && (layer.getEnable()))
/* 1080: */ {
/* 1081:1184 */ Iterator iter = layer.getShapes().iterator();
/* 1082:1185 */ while (iter.hasNext())
/* 1083: */ {
/* 1084:1186 */ Shape shape = (Shape)iter.next();
/* 1085:1187 */ Rectangle2D_ rect = shape.getBounds();
/* 1086:1189 */ if (containsBounds(rect_tmp, rect)) {
/* 1087:1190 */ this.selectedShapeList.add(shape);
/* 1088: */ }
/* 1089: */ }
/* 1090: */ }
/* 1091: */ }
/* 1092:1196 */ DrawingUtils.drawRectangleXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 1093: */
/* 1094:1198 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 1095: */
/* 1096:1200 */ this.drawingContext.setChanged(true);
/* 1097:1201 */ this.pCount = 0;
/* 1098:1202 */ return;
/* 1099: */ }
/* 1100: */ }
/* 1101: */
/* 1102: */ protected boolean containsBounds(Rectangle2D_ r1, Rectangle2D_ r2)
/* 1103: */ {
/* 1104:1207 */ if ((r1.x <= r2.x) && (r1.y >= r2.y) && (r1.x + r1.width >= r2.x + r2.width) && (r1.y - r1.height <= r2.y - r2.height)) {
/* 1105:1211 */ return true;
/* 1106: */ }
/* 1107:1212 */ return false;
/* 1108: */ }
/* 1109: */
/* 1110: */ public void mouseWheelMoved(MouseWheelEvent evt)
/* 1111: */ {
/* 1112:1216 */ Graphics2D big = this.drawingContext.getGraphics();
/* 1113: */
/* 1114:1218 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 1115:1219 */ double x = p2d.x;
/* 1116:1220 */ double y = p2d.y;
/* 1117: */
/* 1118:1222 */ this.x_clicked_old = this.x_clicked;
/* 1119:1223 */ this.y_clicked_old = this.y_clicked;
/* 1120:1225 */ if ((this.mode == 1) && (this.pCount == 1) && (this.mouseButton == 1)) {
/* 1121:1229 */ DrawingUtils.drawRectangleXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, x, y, this.x_clicked, this.y_clicked);
/* 1122: */ }
/* 1123:1232 */ this.drawingContext.changeScaleTo(evt.getWheelRotation());
/* 1124: */
/* 1125:1234 */ this.propertyChangeSupport.firePropertyChange("scale", Double.valueOf(0.0D), Double.valueOf(this.drawingContext.getScale()));
/* 1126: */ }
/* 1127: */
/* 1128: */ public void keyPressed(KeyEvent evt)
/* 1129: */ {
/* 1130:1239 */ Graphics2D big = this.drawingContext.getGraphics();
/* 1131:1241 */ if (this.mode == 1)
/* 1132: */ {
/* 1133:1242 */ if ((evt.getKeyCode() == 127) &&
/* 1134:1243 */ (this.selectedShapeList.size() > 0))
/* 1135: */ {
/* 1136:1244 */ deleteSelectedShape();
/* 1137:1245 */ this.drawingContext.setChanged(true);
/* 1138:1246 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 1139:1247 */ return;
/* 1140: */ }
/* 1141:1251 */ if (evt.getKeyCode() == 27)
/* 1142: */ {
/* 1143:1252 */ if (this.selectedShapeList.size() > 0)
/* 1144: */ {
/* 1145:1253 */ this.selectedShapeList.clear();
/* 1146:1254 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 1147: */ }
/* 1148:1257 */ this.drawingContext.setChanged(true);
/* 1149:1258 */ this.pCount = 0;
/* 1150: */ }
/* 1151: */ }
/* 1152:1263 */ if ((this.mode == 3) &&
/* 1153:1264 */ (evt.getKeyCode() == 27))
/* 1154: */ {
/* 1155:1265 */ int count = this.pCount - 1;
/* 1156: */
/* 1157: */
/* 1158:1268 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[count], this.yP[count]);
/* 1159: */
/* 1160: */
/* 1161: */
/* 1162:1272 */ Shape shape = null;
/* 1163:1274 */ if (this.shapeType == 4)
/* 1164: */ {
/* 1165:1275 */ MacroCommand cmd = new MacroCommand();
/* 1166:1276 */ for (int i = 0; i < this.pCount - 1; i++)
/* 1167: */ {
/* 1168:1277 */ shape = new CadSegment(this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 1169:1278 */ cmd.addCommand(addShapeAll(shape));
/* 1170: */ }
/* 1171:1280 */ if (cmd.getCommandCount() > 0)
/* 1172: */ {
/* 1173:1281 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 1174:1282 */ cmd.execute();
/* 1175: */
/* 1176:1284 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 1177: */ }
/* 1178: */ }
/* 1179:1288 */ if (this.shapeType == 1)
/* 1180: */ {
/* 1181:1289 */ shape = new CadPolyline(this.xP, this.yP, this.pCount);
/* 1182:1290 */ addShape(shape);
/* 1183: */ }
/* 1184:1293 */ this.selectedShapeList.clear();
/* 1185: */
/* 1186: */
/* 1187:1296 */ this.pCount = 0;
/* 1188:1297 */ this.mode = 1;
/* 1189:1298 */ this.drawingContext.setChanged(true);
/* 1190: */ }
/* 1191: */ }
/* 1192: */ }
/* Location: C:\Users\kul_mut\Downloads\CADBox.2D-1.0.0\CADBox.2D\CADBox.2D.jar
* Qualified Name: org.cadbox.j2d.scale.CadDrawingEngine
* JD-Core Version: 0.7.0.1
*/ | UTF-8 | Java | 60,413 | java | CadDrawingEngine.java | Java | [
{
"context": "2: */ }\r\n\r\n\r\r\n/* Location: C:\\Users\\kul_mut\\Downloads\\CADBox.2D-1.0.0\\CADBox.2D\\CADBox.2D.jar",
"end": 60261,
"score": 0.9993135929107666,
"start": 60254,
"tag": "USERNAME",
"value": "kul_mut"
}
]
| null | []
| /* 1: */ package org.cadbox.j2d.scale;
/* 2: */
/* 3: */ import java.awt.BasicStroke;
/* 4: */ import java.awt.Color;
/* 5: */ import java.awt.Graphics2D;
/* 6: */ import java.awt.Stroke;
/* 7: */ import java.awt.event.KeyEvent;
/* 8: */ import java.awt.event.MouseEvent;
/* 9: */ import java.awt.event.MouseWheelEvent;
/* 10: */ import java.awt.image.BufferedImage;
/* 11: */ import java.beans.PropertyChangeSupport;
/* 12: */ import java.util.ArrayList;
/* 13: */ import java.util.Collection;
/* 14: */ import java.util.HashSet;
/* 15: */ import java.util.Iterator;
/* 16: */ import java.util.List;
/* 17: */ import java.util.Set;
/* 18: */ import org.cadbox.MacroCommand;
/* 19: */ import org.cadbox.SimpleURManager;
/* 20: */ import org.cadbox.UREngine;
/* 21: */ import org.cadbox.URManager;
/* 22: */ import org.cadbox.UndoableCommand;
/* 23: */ import org.cadbox.j2d.CadDocument;
/* 24: */ import org.cadbox.j2d.scale.command.AddShapeCommand;
/* 25: */ import org.cadbox.j2d.scale.command.CopyShapeCommand;
/* 26: */ import org.cadbox.j2d.scale.command.DeleteShapeCommand;
/* 27: */ import org.cadbox.j2d.scale.command.ModifyShapeCommand;
/* 28: */ import org.cadbox.j2d.scale.command.MoveShapeCommand;
/* 29: */ import org.cadbox.j2d.scale.command.RotateShapeCommand;
/* 30: */ import org.cadbox.j2d.scale.core.Circle;
/* 31: */ import org.cadbox.j2d.scale.core.Context;
/* 32: */ import org.cadbox.j2d.scale.core.DrawingContext;
/* 33: */ import org.cadbox.j2d.scale.core.DrawingEngine;
/* 34: */ import org.cadbox.j2d.scale.core.GeometryUtils;
/* 35: */ import org.cadbox.j2d.scale.core.Group;
/* 36: */ import org.cadbox.j2d.scale.core.Layer;
/* 37: */ import org.cadbox.j2d.scale.core.Layout;
/* 38: */ import org.cadbox.j2d.scale.core.LineType;
/* 39: */ import org.cadbox.j2d.scale.core.LineWeight;
/* 40: */ import org.cadbox.j2d.scale.core.PropertyContext;
/* 41: */ import org.cadbox.j2d.scale.core.Shape;
/* 42: */ import org.cadbox.j2d.scale.core.geom.Point2D_;
/* 43: */ import org.cadbox.j2d.scale.core.geom.Point2I;
/* 44: */ import org.cadbox.j2d.scale.core.geom.Rectangle2D_;
/* 45: */ import org.cadbox.j2d.scale.core.unit.MmUnit;
/* 46: */ import org.cadbox.j2d.scale.core.unit.UnitTranslator;
/* 47: */
/* 48: */ public class CadDrawingEngine
/* 49: */ extends DrawingEngine
/* 50: */ {
/* 51: 72 */ CadDocument document = null;
/* 52: */ PropertyChangeSupport propertyChangeSupport;
/* 53: */ private double x_clicked;
/* 54: */ private double y_clicked;
/* 55: */ private int mouseButton;
/* 56: */ private double x_clicked_old;
/* 57: */ private double y_clicked_old;
/* 58: 82 */ private Set selectedShapeList = new HashSet();
/* 59: 85 */ private Color snapPointColor = Color.red;
/* 60: 86 */ private BasicStroke snapPointStroke = new BasicStroke(3.0F);
/* 61: 88 */ private Color shapeDrawingColor = Color.black;
/* 62: 89 */ private BasicStroke shapeDrawingStroke = new BasicStroke(1.0F);
/* 63: 92 */ private Stroke selectedShapeStroke = new BasicStroke(1.0F, 0, 0, 1.0F, new float[] { 5.0F }, 0.0F);
/* 64: 95 */ private Color backgroundColor = Color.white;
/* 65: 96 */ private Color foregroundColor = Color.black;
/* 66: */ public static final int SELECTION_MODE = 1;
/* 67: */ public static final int MOTION_MODE = 2;
/* 68: */ public static final int CREATION_MODE = 3;
/* 69: */ public static final int ZOOM_IN_MODE = 4;
/* 70: */ public static final int ZOOM_OUT_MODE = 5;
/* 71: 104 */ private int mode = 1;
/* 72: */ public static final int SHAPE_NONE = 0;
/* 73: */ public static final int SHAPE_POLYLINE = 1;
/* 74: */ public static final int SHAPE_POLYGONE = 2;
/* 75: */ public static final int SHAPE_CIRCLE = 3;
/* 76: */ public static final int SHAPE_SEGMENT = 4;
/* 77: */ public static final int SHAPE_LINE = 5;
/* 78: 113 */ public int shapeType = 0;
/* 79: 115 */ private int pCount = 0;
/* 80: 117 */ private int snapSensitiveLength = 10;
/* 81: 119 */ private double[] xP = new double[2000];
/* 82: 120 */ private double[] yP = new double[2000];
/* 83: */ public static final int NONE_ACTION = 1;
/* 84: */ public static final int MOVE_ACTION = 2;
/* 85: */ public static final int COPY_ACTION = 3;
/* 86: */ public static final int ROTATE_ACTION = 4;
/* 87: */ public static final int EDIT_ACTION = 5;
/* 88: 128 */ private int action = 1;
/* 89: 130 */ private List actionShapeList = new ArrayList();
/* 90: */ private CadShape actionShape;
/* 91: */ Context context;
/* 92: */ DrawingContext drawingContext;
/* 93: */ PropertyContext propertyContext;
/* 94: 138 */ private List snapList = new ArrayList();
/* 95: */ private SnapPoint currentSnapPoint;
/* 96: */
/* 97: */ public CadDrawingEngine(CadDocument document, PropertyChangeSupport propertyChangeSupport)
/* 98: */ {
/* 99: 143 */ this.document = document;
/* 100: 144 */ this.propertyChangeSupport = propertyChangeSupport;
/* 101: */
/* 102: 146 */ this.context = document.getContext();
/* 103: 147 */ this.drawingContext = this.context.getDrawingContext();
/* 104: 148 */ this.propertyContext = this.context.getPropertyContext();
/* 105: */ }
/* 106: */
/* 107: */ public void reset()
/* 108: */ {
/* 109: 152 */ this.selectedShapeList.clear();
/* 110: 153 */ this.actionShape = null;
/* 111: 154 */ this.actionShapeList.clear();
/* 112: 155 */ this.pCount = 0;
/* 113: */ }
/* 114: */
/* 115: */ public void setMode(int mode)
/* 116: */ {
/* 117: 159 */ this.mode = mode;
/* 118: 160 */ this.selectedShapeList.clear();
/* 119: */ }
/* 120: */
/* 121: */ public int getMode()
/* 122: */ {
/* 123: 164 */ return this.mode;
/* 124: */ }
/* 125: */
/* 126: */ public void setShapeType(int shapeType)
/* 127: */ {
/* 128: 168 */ this.shapeType = shapeType;
/* 129: 169 */ this.selectedShapeList.clear();
/* 130: */ }
/* 131: */
/* 132: */ public int getShapeType()
/* 133: */ {
/* 134: 173 */ return this.shapeType;
/* 135: */ }
/* 136: */
/* 137: */ public void setAction(int action)
/* 138: */ {
/* 139: 178 */ this.action = action;
/* 140: */ }
/* 141: */
/* 142: */ public int getAction()
/* 143: */ {
/* 144: 182 */ return this.action;
/* 145: */ }
/* 146: */
/* 147: */ public void clearSelectedShapes()
/* 148: */ {
/* 149: 186 */ this.selectedShapeList.clear();
/* 150: */ }
/* 151: */
/* 152: */ public Color getSnapPointColor()
/* 153: */ {
/* 154: 190 */ return this.snapPointColor;
/* 155: */ }
/* 156: */
/* 157: */ public void setSnapPointColor(Color snapPointColor)
/* 158: */ {
/* 159: 194 */ this.snapPointColor = snapPointColor;
/* 160: */ }
/* 161: */
/* 162: */ public BasicStroke getSnapPointStroke()
/* 163: */ {
/* 164: 198 */ return this.snapPointStroke;
/* 165: */ }
/* 166: */
/* 167: */ public void setSnapPointStroke(BasicStroke snapPointStroke)
/* 168: */ {
/* 169: 202 */ this.snapPointStroke = snapPointStroke;
/* 170: */ }
/* 171: */
/* 172: */ public Color getShapeDrawingColor()
/* 173: */ {
/* 174: 206 */ return this.shapeDrawingColor;
/* 175: */ }
/* 176: */
/* 177: */ public void setShapeDrawingColor(Color shapeDrawingColor)
/* 178: */ {
/* 179: 210 */ this.shapeDrawingColor = shapeDrawingColor;
/* 180: */ }
/* 181: */
/* 182: */ public BasicStroke getShapeDrawingStroke()
/* 183: */ {
/* 184: 214 */ return this.shapeDrawingStroke;
/* 185: */ }
/* 186: */
/* 187: */ public void setShapeDrawingStroke(BasicStroke shapeDrawingStroke)
/* 188: */ {
/* 189: 218 */ this.shapeDrawingStroke = shapeDrawingStroke;
/* 190: */ }
/* 191: */
/* 192: */ public Collection getSelectedShapeList()
/* 193: */ {
/* 194: 222 */ return this.selectedShapeList;
/* 195: */ }
/* 196: */
/* 197: */ public Stroke getSelectedShapeStroke()
/* 198: */ {
/* 199: 233 */ return this.selectedShapeStroke;
/* 200: */ }
/* 201: */
/* 202: */ public void setSelectedShapeStroke(Stroke selectedShapeStroke)
/* 203: */ {
/* 204: 237 */ this.selectedShapeStroke = selectedShapeStroke;
/* 205: */ }
/* 206: */
/* 207: */ public BufferedImage getImage()
/* 208: */ {
/* 209: 241 */ draw();
/* 210: 242 */ return this.drawingContext.getImage();
/* 211: */ }
/* 212: */
/* 213: */ private synchronized void draw()
/* 214: */ {
/* 215: 246 */ if (this.drawingContext.isChanged())
/* 216: */ {
/* 217: 247 */ paint();
/* 218: 248 */ this.drawingContext.setChanged(false);
/* 219: */ }
/* 220: */ }
/* 221: */
/* 222: */ private void paint()
/* 223: */ {
/* 224: 254 */ Graphics2D big = this.drawingContext.getGraphics();
/* 225: */
/* 226: 256 */ Layout layout = this.document.getLayout();
/* 227: 257 */ if ((layout != null) && (layout.getLayoutType() == 0)) {
/* 228: 258 */ preDraw();
/* 229: */ } else {
/* 230: 260 */ preDraw1();
/* 231: */ }
/* 232: 264 */ Iterator iter1 = this.document.getLayers().iterator();
/* 233: 265 */ while (iter1.hasNext())
/* 234: */ {
/* 235: 266 */ Layer layer = (Layer)iter1.next();
/* 236: 267 */ if (layer.getVisible() == true)
/* 237: */ {
/* 238: 268 */ Iterator iter = layer.getShapes().iterator();
/* 239: 269 */ while (iter.hasNext())
/* 240: */ {
/* 241: 270 */ Shape shape = (Shape)iter.next();
/* 242: */
/* 243: 272 */ big.setColor(shape.getColor());
/* 244: */
/* 245: 274 */ double width = UnitTranslator.lengthUnitToPixel(shape.getLineWeight().getLineWeightValue());
/* 246: 275 */ float w = this.drawingContext.distanseToScreen(width);
/* 247: */
/* 248: 277 */ float[] t = shape.getLineType().getLineTypeValue();
/* 249: 278 */ for (int i = 0; i < t.length; i++) {
/* 250: 279 */ t[i] = this.drawingContext.distanseToScreen(t[i] * 10.0F);
/* 251: */ }
/* 252: 283 */ BasicStroke bs = new BasicStroke(w, 1, 1);
/* 253: 284 */ big.setStroke(bs);
/* 254: 286 */ if ((!this.selectedShapeList.contains(shape)) &&
/* 255: 287 */ (inWindowBounds(shape))) {
/* 256: 288 */ shape.draw(this.context);
/* 257: */ }
/* 258: */ }
/* 259: */ }
/* 260: */ }
/* 261: 297 */ if (this.selectedShapeList.size() > 0)
/* 262: */ {
/* 263: 298 */ big.setStroke(this.selectedShapeStroke);
/* 264: 299 */ Iterator iter = this.selectedShapeList.iterator();
/* 265: 300 */ while (iter.hasNext())
/* 266: */ {
/* 267: 301 */ Shape shape_tmp = (Shape)iter.next();
/* 268: 304 */ if (inWindowBounds(shape_tmp))
/* 269: */ {
/* 270: 310 */ big.setColor(shape_tmp.getColor());
/* 271: 311 */ shape_tmp.drawOptimized(this.context);
/* 272: */
/* 273: 313 */ big.setColor(Color.blue);
/* 274: 314 */ Iterator iter2 = ((CadShape)shape_tmp).getActionPoints().iterator();
/* 275: 315 */ while (iter2.hasNext())
/* 276: */ {
/* 277: 316 */ Point2D_ p = ((ActionPoint)iter2.next()).getPoint();
/* 278: 317 */ Point2I p1 = this.drawingContext.translateToScreen(p.x, p.y);
/* 279: 318 */ big.fillRect(p1.x - 5, p1.y - 5, 10, 10);
/* 280: */ }
/* 281: */ }
/* 282: */ }
/* 283: */ }
/* 284: */ }
/* 285: */
/* 286: */ private boolean inWindowBounds(Shape shape)
/* 287: */ {
/* 288: 327 */ return true;
/* 289: */ }
/* 290: */
/* 291: */ private void preDraw()
/* 292: */ {
/* 293: 332 */ Graphics2D big = this.drawingContext.getGraphics();
/* 294: */
/* 295: 334 */ big.setColor(this.backgroundColor);
/* 296: 335 */ big.setStroke(new BasicStroke(1.0F));
/* 297: */
/* 298: 337 */ big.fillRect(0, 0, this.drawingContext.getWidth(), this.drawingContext.getHeight());
/* 299: */
/* 300: 339 */ Point2I p1 = this.drawingContext.translateToScreen(new Point2D_(this.drawingContext.getLogicalLeft(), this.drawingContext.getLogicalTop()));
/* 301: 340 */ Point2I p2 = this.drawingContext.translateToScreen(new Point2D_(this.drawingContext.getLogicalRight(), this.drawingContext.getLogicalBottom()));
/* 302: */
/* 303: */
/* 304: 343 */ big.setColor(Color.black);
/* 305: 344 */ big.drawRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
/* 306: */
/* 307: */
/* 308: */
/* 309: */
/* 310: */
/* 311: */
/* 312: */
/* 313: */
/* 314: */
/* 315: */
/* 316: */
/* 317: */
/* 318: */
/* 319: */
/* 320: */
/* 321: */
/* 322: */
/* 323: */
/* 324: */
/* 325: */
/* 326: */
/* 327: 366 */ big.setColor(Color.lightGray);
/* 328: 367 */ p1 = this.drawingContext.translateToScreen(new Point2D_(250.0D, 0.0D));
/* 329: 368 */ p2 = this.drawingContext.translateToScreen(new Point2D_(0.0D, 0.0D));
/* 330: 369 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 331: */
/* 332: 371 */ p1 = this.drawingContext.translateToScreen(new Point2D_(250.0D, 0.0D));
/* 333: 372 */ p2 = this.drawingContext.translateToScreen(new Point2D_(240.0D, 5.0D));
/* 334: 373 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 335: 374 */ p1 = this.drawingContext.translateToScreen(new Point2D_(250.0D, 0.0D));
/* 336: 375 */ p2 = this.drawingContext.translateToScreen(new Point2D_(240.0D, -5.0D));
/* 337: 376 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 338: */
/* 339: */
/* 340: 379 */ p1 = this.drawingContext.translateToScreen(new Point2D_(0.0D, 250.0D));
/* 341: 380 */ p2 = this.drawingContext.translateToScreen(new Point2D_(0.0D, 0.0D));
/* 342: 381 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 343: */
/* 344: 383 */ p1 = this.drawingContext.translateToScreen(new Point2D_(0.0D, 250.0D));
/* 345: 384 */ p2 = this.drawingContext.translateToScreen(new Point2D_(5.0D, 240.0D));
/* 346: 385 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 347: */
/* 348: 387 */ p1 = this.drawingContext.translateToScreen(new Point2D_(0.0D, 250.0D));
/* 349: 388 */ p2 = this.drawingContext.translateToScreen(new Point2D_(-5.0D, 240.0D));
/* 350: 389 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 351: */ }
/* 352: */
/* 353: */ private void preDraw1()
/* 354: */ {
/* 355: 397 */ Graphics2D big = this.drawingContext.getGraphics();
/* 356: */
/* 357: */
/* 358: 400 */ big.setColor(Color.gray);
/* 359: 401 */ big.setStroke(new BasicStroke(1.0F));
/* 360: */
/* 361: 403 */ big.fillRect(0, 0, this.drawingContext.getWidth(), this.drawingContext.getHeight());
/* 362: */
/* 363: 405 */ Point2I p1 = this.drawingContext.translateToScreen(new Point2D_(this.drawingContext.getLogicalLeft(), this.drawingContext.getLogicalTop()));
/* 364: 406 */ Point2I p2 = this.drawingContext.translateToScreen(new Point2D_(this.drawingContext.getLogicalRight(), this.drawingContext.getLogicalBottom()));
/* 365: */
/* 366: */
/* 367: 409 */ big.setColor(Color.black);
/* 368: 410 */ big.fillRect(p1.x + 5, p1.y + 5, p2.x - p1.x, p2.y - p1.y);
/* 369: */
/* 370: 412 */ big.setColor(Color.white);
/* 371: 413 */ big.fillRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
/* 372: */
/* 373: 415 */ big.setColor(Color.black);
/* 374: 416 */ big.drawRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
/* 375: */ }
/* 376: */
/* 377: */ protected void actionMoveCopy(Shape shape, double x1, double y1, double x2, double y2)
/* 378: */ {
/* 379: 421 */ Graphics2D big = this.drawingContext.getGraphics();
/* 380: */
/* 381: 423 */ big.setXORMode(Color.white);
/* 382: */
/* 383: 425 */ Point2I p1 = this.drawingContext.translateToScreen(new Point2D_(x1, y1));
/* 384: 426 */ Point2I p2 = this.drawingContext.translateToScreen(new Point2D_(x2, y2));
/* 385: 427 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 386: */
/* 387: 429 */ shape.move(x1 - x2, y1 - y2);
/* 388: 430 */ shape.draw(this.context);
/* 389: 431 */ shape.move(-(x1 - x2), -(y1 - y2));
/* 390: 432 */ big.setPaintMode();
/* 391: */ }
/* 392: */
/* 393: */ protected void actionRotate(Shape shape, double x1, double y1, double x2, double y2)
/* 394: */ {
/* 395: 439 */ Graphics2D big = this.drawingContext.getGraphics();
/* 396: */
/* 397: 441 */ big.setXORMode(Color.white);
/* 398: */
/* 399: 443 */ Point2I p1 = this.drawingContext.translateToScreen(new Point2D_(x1, y1));
/* 400: 444 */ Point2I p2 = this.drawingContext.translateToScreen(new Point2D_(x2, y2));
/* 401: 445 */ big.drawLine(p1.x, p1.y, p2.x, p2.y);
/* 402: */
/* 403: 447 */ double A = GeometryUtils.fingAngele(x1, y1, x2, y2);
/* 404: */
/* 405: 449 */ shape.rotate(x1, y1, A);
/* 406: 450 */ shape.draw(this.context);
/* 407: 451 */ shape.rotate(x1, y1, -A);
/* 408: 452 */ big.setPaintMode();
/* 409: */ }
/* 410: */
/* 411: */ public void addShape(Shape shape)
/* 412: */ {
/* 413: 458 */ PropertyContext pContext = this.context.getPropertyContext();
/* 414: */
/* 415: 460 */ UndoableCommand cmd = addShapeAll(shape);
/* 416: 461 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 417: 462 */ cmd.execute();
/* 418: */
/* 419: 464 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 420: */ }
/* 421: */
/* 422: */ public void deleteSelectedShape()
/* 423: */ {
/* 424: 468 */ if (this.selectedShapeList.size() > 0)
/* 425: */ {
/* 426: 469 */ MacroCommand cmd = new MacroCommand();
/* 427: 470 */ Iterator iter = this.selectedShapeList.iterator();
/* 428: 471 */ while (iter.hasNext())
/* 429: */ {
/* 430: 472 */ Shape shape_tmp = (Shape)iter.next();
/* 431: 473 */ Group g = shape_tmp.getParent();
/* 432: 474 */ if (g != null)
/* 433: */ {
/* 434: 476 */ removeStaticSnapPoint((CadShape)shape_tmp);
/* 435: */
/* 436: */
/* 437: */
/* 438: 480 */ DeleteShapeCommand dc = new DeleteShapeCommand(g, shape_tmp);
/* 439: 481 */ cmd.addCommand(dc);
/* 440: */ }
/* 441: */ }
/* 442: 484 */ if (cmd.getCommandCount() > 0)
/* 443: */ {
/* 444: 485 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 445: 486 */ cmd.execute();
/* 446: */ }
/* 447: 488 */ this.selectedShapeList.clear();
/* 448: 489 */ this.document.setModified(true);
/* 449: 490 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 450: */ }
/* 451: */ }
/* 452: */
/* 453: */ public void modifyShape(Shape oldShape, Shape newShape)
/* 454: */ {
/* 455: 496 */ ModifyShapeCommand cmd = new ModifyShapeCommand(oldShape, newShape);
/* 456: 497 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 457: */
/* 458: 499 */ removeStaticSnapPoint((CadShape)oldShape);
/* 459: 500 */ cmd.execute();
/* 460: 501 */ addStaticSnapPoint((CadShape)newShape);
/* 461: */
/* 462: 503 */ this.selectedShapeList.remove(oldShape);
/* 463: 504 */ this.selectedShapeList.add(newShape);
/* 464: 505 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 465: */ }
/* 466: */
/* 467: */ public void moveShape(Shape shape, double vX, double vY)
/* 468: */ {
/* 469: 509 */ UndoableCommand cmd = moveShapeAll(shape, vX, vY);
/* 470: 510 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 471: */
/* 472: 512 */ removeStaticSnapPoint((CadShape)shape);
/* 473: 513 */ cmd.execute();
/* 474: 514 */ addStaticSnapPoint((CadShape)shape);
/* 475: */
/* 476: 516 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 477: */ }
/* 478: */
/* 479: */ public void copyShape(Layer layer, Shape shape)
/* 480: */ {
/* 481: 520 */ UndoableCommand cmd = copyShapeAll(layer, shape);
/* 482: 521 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 483: */
/* 484: */
/* 485: 524 */ cmd.execute();
/* 486: 525 */ addStaticSnapPoint((CadShape)shape);
/* 487: */
/* 488: 527 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 489: */ }
/* 490: */
/* 491: */ public void rotateShape(Shape shape, double x, double y, double angle)
/* 492: */ {
/* 493: 531 */ UndoableCommand cmd = rotateShapeAll(shape, x, y, angle);
/* 494: 532 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 495: */
/* 496: 534 */ removeStaticSnapPoint((CadShape)shape);
/* 497: 535 */ cmd.execute();
/* 498: 536 */ addStaticSnapPoint((CadShape)shape);
/* 499: */
/* 500: 538 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 501: */ }
/* 502: */
/* 503: */ public UndoableCommand addShapeAll(Shape shape)
/* 504: */ {
/* 505: 542 */ PropertyContext pContext = this.context.getPropertyContext();
/* 506: */
/* 507: 544 */ shape.setColor(pContext.getColor());
/* 508: 545 */ shape.setLineWeight(pContext.getLineWeight());
/* 509: 546 */ shape.setLineType(pContext.getLineType());
/* 510: */
/* 511: 548 */ addStaticSnapPoint((CadShape)shape);
/* 512: */
/* 513: 550 */ AddShapeCommand cmd = new AddShapeCommand(shape, this.document.getCurrentLayer());
/* 514: 551 */ return cmd;
/* 515: */ }
/* 516: */
/* 517: */ public UndoableCommand moveShapeAll(Shape shape, double vX, double vY)
/* 518: */ {
/* 519: 555 */ MoveShapeCommand cmd = new MoveShapeCommand(shape, vX, vY);
/* 520: 556 */ return cmd;
/* 521: */ }
/* 522: */
/* 523: */ public UndoableCommand copyShapeAll(Layer layer, Shape shape)
/* 524: */ {
/* 525: 560 */ CopyShapeCommand cmd = new CopyShapeCommand(layer, shape);
/* 526: 561 */ return cmd;
/* 527: */ }
/* 528: */
/* 529: */ public UndoableCommand rotateShapeAll(Shape shape, double x, double y, double angle)
/* 530: */ {
/* 531: 565 */ RotateShapeCommand cmd = new RotateShapeCommand(shape, x, y, angle);
/* 532: 566 */ return cmd;
/* 533: */ }
/* 534: */
/* 535: */ private void addStaticSnapPoint(CadShape shape)
/* 536: */ {
/* 537: 570 */ Collection c = shape.getSnapPoints();
/* 538: 571 */ Iterator iter = c.iterator();
/* 539: 572 */ while (iter.hasNext())
/* 540: */ {
/* 541: 573 */ SnapPoint sp = (SnapPoint)iter.next();
/* 542: 574 */ if (!this.snapList.contains(sp)) {
/* 543: 575 */ this.snapList.add(sp);
/* 544: */ }
/* 545: */ }
/* 546: */ }
/* 547: */
/* 548: */ private void removeStaticSnapPoint(CadShape shape)
/* 549: */ {
/* 550: 580 */ Collection c = shape.getSnapPoints();
/* 551: 581 */ this.snapList.removeAll(c);
/* 552: */ }
/* 553: */
/* 554: */ public void mousePressed(MouseEvent evt)
/* 555: */ {
/* 556: 587 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 557: */
/* 558: 589 */ double x = p2d.x;
/* 559: 590 */ double y = p2d.y;
/* 560: */
/* 561: 592 */ this.x_clicked = (this.x_clicked_old = x);
/* 562: 593 */ this.y_clicked = (this.y_clicked_old = y);
/* 563: */
/* 564: 595 */ this.mouseButton = evt.getButton();
/* 565: 597 */ if ((this.mode == 4) && (this.mouseButton == 1))
/* 566: */ {
/* 567: 599 */ this.drawingContext.changeScaleTo(-1);
/* 568: 600 */ this.document.setModified(true);
/* 569: */ }
/* 570: 603 */ if ((this.mode == 5) && (this.mouseButton == 1))
/* 571: */ {
/* 572: 605 */ this.drawingContext.changeScaleTo(1);
/* 573: 606 */ this.document.setModified(true);
/* 574: */ }
/* 575: 609 */ if (this.pCount == 0)
/* 576: */ {
/* 577: 610 */ startAction(evt);
/* 578: 611 */ return;
/* 579: */ }
/* 580: 614 */ if ((this.pCount > 0) &&
/* 581: 615 */ (this.xP[(this.pCount - 1)] != x) && (this.yP[(this.pCount - 1)] != y)) {
/* 582: 616 */ endAction(evt);
/* 583: */ }
/* 584: 620 */ this.document.setModified(true);
/* 585: */ }
/* 586: */
/* 587: */ public void mouseDragged(MouseEvent evt)
/* 588: */ {
/* 589: 627 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 590: 628 */ double x = p2d.x;
/* 591: 629 */ double y = p2d.y;
/* 592: 631 */ if ((this.mode == 2) || (this.mouseButton == 3))
/* 593: */ {
/* 594: 634 */ boolean redraw = true;
/* 595: */
/* 596: 636 */ double lenX = this.x_clicked - x;
/* 597: 637 */ double lenY = this.y_clicked - y;
/* 598: */
/* 599: */
/* 600: 640 */ this.drawingContext.moveTo(lenX, lenY);
/* 601: */
/* 602: 642 */ this.pCount = 0;
/* 603: 644 */ if (redraw) {
/* 604: 645 */ this.drawingContext.setChanged(true);
/* 605: */ }
/* 606: 646 */ return;
/* 607: */ }
/* 608: 649 */ if (this.pCount == 1) {
/* 609: 650 */ continousAction(evt);
/* 610: */ }
/* 611: */ }
/* 612: */
/* 613: */ public void mouseMoved(MouseEvent evt)
/* 614: */ {
/* 615: 656 */ Graphics2D big = this.drawingContext.getGraphics();
/* 616: */
/* 617: 658 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 618: 659 */ double x = p2d.x;
/* 619: 660 */ double y = p2d.y;
/* 620: */
/* 621: 662 */ this.propertyChangeSupport.firePropertyChange("mouseCoordinateX", Double.valueOf(0.0D), Double.valueOf(UnitTranslator.pixelToMilemetor(p2d.x).getValue()));
/* 622: 663 */ this.propertyChangeSupport.firePropertyChange("mouseCoordinateY", Double.valueOf(0.0D), Double.valueOf(UnitTranslator.pixelToMilemetor(p2d.y).getValue()));
/* 623: */
/* 624: 665 */ this.propertyChangeSupport.firePropertyChange("scale", Double.valueOf(0.0D), Double.valueOf(this.drawingContext.getScale()));
/* 625: 667 */ if (this.pCount > 0) {
/* 626: 668 */ continousAction(evt);
/* 627: */ }
/* 628: 671 */ if (this.mode == 3)
/* 629: */ {
/* 630: 673 */ if (this.currentSnapPoint != null) {
/* 631: 674 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 632: */ }
/* 633: 676 */ this.currentSnapPoint = null;
/* 634: */
/* 635: */
/* 636: 679 */ int minlen = 2147483647;
/* 637: 680 */ for (int i = 0; i < this.snapList.size(); i++)
/* 638: */ {
/* 639: 681 */ SnapPoint sp = (SnapPoint)this.snapList.get(i);
/* 640: 682 */ Point2D_ p = sp.getPoint();
/* 641: */
/* 642: 684 */ double len = GeometryUtils.length(p.x, p.y, x, y);
/* 643: 685 */ int ilen = this.drawingContext.distanseToScreen(len);
/* 644: 687 */ if ((ilen < this.snapSensitiveLength) && (minlen > ilen))
/* 645: */ {
/* 646: 688 */ minlen = ilen;
/* 647: 689 */ this.currentSnapPoint = sp;
/* 648: */ }
/* 649: */ }
/* 650: 692 */ if (this.currentSnapPoint != null) {
/* 651: 693 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 652: */ }
/* 653: */ }
/* 654: */ }
/* 655: */
/* 656: */ protected void startAction(MouseEvent evt)
/* 657: */ {
/* 658: 701 */ Graphics2D big = this.drawingContext.getGraphics();
/* 659: */
/* 660: 703 */ double x = this.x_clicked;
/* 661: 704 */ double y = this.y_clicked;
/* 662: 706 */ if ((this.selectedShapeList.size() > 0) && (this.action == 1))
/* 663: */ {
/* 664: 707 */ Iterator iter = this.selectedShapeList.iterator();
/* 665: 708 */ while (iter.hasNext())
/* 666: */ {
/* 667: 709 */ CadShape shape_tmp = (CadShape)iter.next();
/* 668: */
/* 669: 711 */ Iterator iter1 = shape_tmp.getActionPoints().iterator();
/* 670: 712 */ while (iter1.hasNext())
/* 671: */ {
/* 672: 713 */ ActionPoint ap = (ActionPoint)iter1.next();
/* 673: 714 */ Point2D_ p = ap.getPoint();
/* 674: */
/* 675: 716 */ double dis = this.drawingContext.distanseToLogical(5.0D);
/* 676: 718 */ if ((x >= p.x - dis) && (x <= p.x + dis) && (y >= p.y - dis) && (y <= p.y + dis))
/* 677: */ {
/* 678: 719 */ this.action = 5;
/* 679: 720 */ shape_tmp.setActionPoint(ap);
/* 680: 721 */ this.actionShape = shape_tmp;
/* 681: 722 */ break;
/* 682: */ }
/* 683: */ }
/* 684: */ }
/* 685: */ }
/* 686: 728 */ if ((this.action != 1) && (this.selectedShapeList.size() > 0) && (this.mouseButton == 1))
/* 687: */ {
/* 688: 731 */ this.xP[this.pCount] = this.x_clicked;
/* 689: 732 */ this.yP[this.pCount] = this.y_clicked;
/* 690: 734 */ if (this.action != 5)
/* 691: */ {
/* 692: 735 */ Iterator iter = this.selectedShapeList.iterator();
/* 693: 736 */ while (iter.hasNext())
/* 694: */ {
/* 695: 737 */ Shape shape_tmp = (Shape)iter.next();
/* 696: */
/* 697: 739 */ this.actionShapeList.add(shape_tmp);
/* 698: 742 */ if (this.action == 2) {
/* 699: 743 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 700: */ }
/* 701: 746 */ if (this.action == 3) {
/* 702: 747 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 703: */ }
/* 704: 750 */ if (this.action == 4) {
/* 705: 751 */ actionRotate(shape_tmp, this.x_clicked, this.y_clicked, this.x_clicked_old, this.y_clicked_old);
/* 706: */ }
/* 707: */ }
/* 708: */ }
/* 709: 756 */ if ((this.action == 5) && (this.actionShape != null)) {
/* 710: 758 */ this.actionShape.moveActionPoint(this, this.context, x, y);
/* 711: */ }
/* 712: 761 */ this.pCount += 1;
/* 713: 762 */ return;
/* 714: */ }
/* 715: 764 */ this.action = 1;
/* 716: 767 */ if ((this.mode == 3) && (this.mouseButton == 1))
/* 717: */ {
/* 718: 769 */ if (this.currentSnapPoint != null)
/* 719: */ {
/* 720: 770 */ Point2D_ p = this.currentSnapPoint.getPoint();
/* 721: 771 */ x = p.x;
/* 722: 772 */ y = p.y;
/* 723: */ }
/* 724: 775 */ this.xP[this.pCount] = x;
/* 725: 776 */ this.yP[this.pCount] = y;
/* 726: 779 */ if ((this.shapeType == 3) &&
/* 727: 780 */ (this.pCount == 1))
/* 728: */ {
/* 729: 781 */ double radius = Math.sqrt((this.xP[0] - this.xP[1]) * (this.xP[0] - this.xP[1]) + (this.yP[0] - this.yP[1]) * (this.yP[0] - this.yP[1]));
/* 730: 782 */ Shape shape = new Circle(this.xP[0], this.yP[0], radius);
/* 731: 783 */ addShape(shape);
/* 732: */
/* 733: 785 */ this.pCount = 0;
/* 734: 786 */ this.mode = 1;
/* 735: 787 */ this.drawingContext.setChanged(true);
/* 736: 788 */ return;
/* 737: */ }
/* 738: 793 */ if ((this.shapeType == 5) &&
/* 739: 794 */ (this.pCount > 0)) {
/* 740: 795 */ for (int i = 0; i < this.pCount; i++) {
/* 741: 796 */ DrawingUtils.drawStarngeLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 742: */ }
/* 743: */ }
/* 744: 801 */ if ((this.shapeType == 2) &&
/* 745: 802 */ (this.pCount > 0)) {
/* 746: 803 */ for (int i = 0; i < this.pCount; i++) {
/* 747: 804 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 748: */ }
/* 749: */ }
/* 750: 809 */ if ((this.shapeType == 1) &&
/* 751: 810 */ (this.pCount > 0)) {
/* 752: 811 */ for (int i = 0; i < this.pCount; i++) {
/* 753: 812 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 754: */ }
/* 755: */ }
/* 756: 817 */ if ((this.shapeType == 4) &&
/* 757: 818 */ (this.pCount > 0)) {
/* 758: 819 */ for (int i = 0; i < this.pCount; i++) {
/* 759: 820 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 760: */ }
/* 761: */ }
/* 762: 825 */ this.x_clicked_old = x;
/* 763: 826 */ this.y_clicked_old = y;
/* 764: */
/* 765: 828 */ this.pCount += 1;
/* 766: */ }
/* 767: 831 */ if ((this.mode == 1) && (this.pCount == 0) && (this.mouseButton == 1))
/* 768: */ {
/* 769: 836 */ Iterator iter1 = this.document.getLayers().iterator();
/* 770: 837 */ while (iter1.hasNext())
/* 771: */ {
/* 772: 838 */ Layer layer = (Layer)iter1.next();
/* 773: 839 */ if ((layer.getVisible()) && (layer.getEnable()))
/* 774: */ {
/* 775: 841 */ Iterator iter = layer.getShapes().iterator();
/* 776: 842 */ while (iter.hasNext())
/* 777: */ {
/* 778: 843 */ Shape shape = (Shape)iter.next();
/* 779: */
/* 780: 845 */ double dis = this.drawingContext.distanseToLogical(2.0D);
/* 781: 847 */ if (shape.containsPoint(x, y, dis))
/* 782: */ {
/* 783: 849 */ this.selectedShapeList.add(shape);
/* 784: */
/* 785: 851 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 786: 852 */ this.drawingContext.setChanged(true);
/* 787: 853 */ return;
/* 788: */ }
/* 789: */ }
/* 790: */ }
/* 791: */ }
/* 792: 859 */ DrawingUtils.drawRectangleXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 793: 860 */ this.xP[this.pCount] = x;
/* 794: 861 */ this.yP[this.pCount] = y;
/* 795: 862 */ this.pCount += 1;
/* 796: */ }
/* 797: */ }
/* 798: */
/* 799: */ protected void continousAction(MouseEvent evt)
/* 800: */ {
/* 801: 870 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 802: 871 */ double x = p2d.x;
/* 803: 872 */ double y = p2d.y;
/* 804: */
/* 805: */
/* 806: */
/* 807: */
/* 808: */
/* 809: 878 */ Graphics2D big = this.drawingContext.getGraphics();
/* 810: 880 */ if ((this.action != 1) && (this.mouseButton == 1))
/* 811: */ {
/* 812: 883 */ if (this.currentSnapPoint != null)
/* 813: */ {
/* 814: 884 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 815: */
/* 816: 886 */ this.currentSnapPoint = null;
/* 817: */ }
/* 818: 888 */ int minlen = 2147483647;
/* 819: 889 */ for (int i = 0; i < this.snapList.size(); i++)
/* 820: */ {
/* 821: 890 */ SnapPoint sp = (SnapPoint)this.snapList.get(i);
/* 822: 891 */ Point2D_ p = sp.getPoint();
/* 823: 892 */ double len = GeometryUtils.length(p.x, p.y, x, y);
/* 824: 893 */ int ilen = this.drawingContext.distanseToScreen(len);
/* 825: 894 */ if ((ilen < this.snapSensitiveLength) && (minlen > ilen))
/* 826: */ {
/* 827: 895 */ minlen = ilen;
/* 828: 896 */ this.currentSnapPoint = sp;
/* 829: */ }
/* 830: */ }
/* 831: 899 */ if (this.currentSnapPoint != null) {
/* 832: 900 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 833: */ }
/* 834: 905 */ if (this.action != 5) {
/* 835: 906 */ for (int i = 0; i < this.actionShapeList.size(); i++)
/* 836: */ {
/* 837: 908 */ Shape shape_tmp = (Shape)this.actionShapeList.get(i);
/* 838: 910 */ if (this.action == 2)
/* 839: */ {
/* 840: 911 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 841: 912 */ actionMoveCopy(shape_tmp, x, y, this.x_clicked, this.y_clicked);
/* 842: */ }
/* 843: 915 */ if (this.action == 3)
/* 844: */ {
/* 845: 916 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 846: 917 */ actionMoveCopy(shape_tmp, x, y, this.x_clicked, this.y_clicked);
/* 847: */ }
/* 848: 920 */ if (this.action == 4)
/* 849: */ {
/* 850: 921 */ actionRotate(shape_tmp, this.x_clicked, this.y_clicked, this.x_clicked_old, this.y_clicked_old);
/* 851: 922 */ actionRotate(shape_tmp, this.x_clicked, this.y_clicked, x, y);
/* 852: */ }
/* 853: */ }
/* 854: */ }
/* 855: 927 */ if ((this.action == 5) && (this.actionShape != null))
/* 856: */ {
/* 857: 929 */ this.actionShape.moveActionPoint(this, this.context, this.x_clicked_old, this.y_clicked_old);
/* 858: 930 */ this.actionShape.moveActionPoint(this, this.context, x, y);
/* 859: */ }
/* 860: 934 */ this.x_clicked_old = x;
/* 861: 935 */ this.y_clicked_old = y;
/* 862: 936 */ return;
/* 863: */ }
/* 864: 939 */ if (this.mode == 3)
/* 865: */ {
/* 866: 942 */ if (this.currentSnapPoint != null) {
/* 867: 943 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 868: */ }
/* 869: 945 */ this.currentSnapPoint = null;
/* 870: */
/* 871: */
/* 872: 948 */ int minlen = 2147483647;
/* 873: 949 */ for (int i = 0; i < this.snapList.size(); i++)
/* 874: */ {
/* 875: 950 */ SnapPoint sp = (SnapPoint)this.snapList.get(i);
/* 876: 951 */ Point2D_ p = sp.getPoint();
/* 877: */
/* 878: 953 */ double len = GeometryUtils.length(p.x, p.y, x, y);
/* 879: 954 */ int ilen = this.drawingContext.distanseToScreen(len);
/* 880: 956 */ if ((ilen < this.snapSensitiveLength) && (minlen > ilen))
/* 881: */ {
/* 882: 957 */ minlen = ilen;
/* 883: 958 */ this.currentSnapPoint = sp;
/* 884: */ }
/* 885: */ }
/* 886: 961 */ if (this.currentSnapPoint != null) {
/* 887: 962 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 888: */ }
/* 889: 966 */ int tmp = this.pCount - 1;
/* 890: 968 */ if (this.pCount > 0)
/* 891: */ {
/* 892: 970 */ if ((this.shapeType == 3) &&
/* 893: 971 */ (this.pCount == 1))
/* 894: */ {
/* 895: 972 */ double r = GeometryUtils.length(this.xP[0], this.yP[0], this.x_clicked_old, this.y_clicked_old);
/* 896: 973 */ DrawingUtils.drawOvalXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[0], this.yP[0], r);
/* 897: 974 */ r = GeometryUtils.length(this.xP[0], this.yP[0], x, y);
/* 898: 975 */ DrawingUtils.drawOvalXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.xP[0], this.yP[0], r);
/* 899: */ }
/* 900: 979 */ if (this.shapeType == 5)
/* 901: */ {
/* 902: 980 */ DrawingUtils.drawStarngeLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[tmp], this.yP[tmp]);
/* 903: 981 */ DrawingUtils.drawStarngeLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, x, y, this.xP[tmp], this.yP[tmp]);
/* 904: */ }
/* 905: 984 */ if (this.shapeType == 4)
/* 906: */ {
/* 907: 985 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[tmp], this.yP[tmp]);
/* 908: 986 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, x, y, this.xP[tmp], this.yP[tmp]);
/* 909: */ }
/* 910: 989 */ if (this.shapeType == 1)
/* 911: */ {
/* 912: 990 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[tmp], this.yP[tmp]);
/* 913: 991 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, x, y, this.xP[tmp], this.yP[tmp]);
/* 914: */ }
/* 915: */ }
/* 916: 995 */ this.x_clicked_old = x;
/* 917: 996 */ this.y_clicked_old = y;
/* 918: */
/* 919: 998 */ return;
/* 920: */ }
/* 921:1002 */ if ((this.mode == 1) && (this.pCount == 1) && (this.mouseButton == 1))
/* 922: */ {
/* 923:1006 */ DrawingUtils.drawRectangleXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 924:1007 */ DrawingUtils.drawRectangleXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, x, y, this.x_clicked, this.y_clicked);
/* 925: */
/* 926:1009 */ this.x_clicked_old = x;
/* 927:1010 */ this.y_clicked_old = y;
/* 928:1011 */ return;
/* 929: */ }
/* 930: */ }
/* 931: */
/* 932: */ protected void endAction(MouseEvent evt)
/* 933: */ {
/* 934:1017 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 935:1018 */ double x = p2d.x;
/* 936:1019 */ double y = p2d.y;
/* 937: */
/* 938:1021 */ Graphics2D big = this.drawingContext.getGraphics();
/* 939:1023 */ if ((this.action != 1) && (this.mouseButton == 1))
/* 940: */ {
/* 941:1026 */ if (this.currentSnapPoint != null)
/* 942: */ {
/* 943:1027 */ Point2D_ p = this.currentSnapPoint.getPoint();
/* 944:1028 */ x = p.x;
/* 945:1029 */ y = p.y;
/* 946:1030 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 947: */
/* 948:1032 */ this.currentSnapPoint = null;
/* 949: */ }
/* 950:1035 */ if (this.action != 5) {
/* 951:1037 */ if (this.actionShapeList.size() > 0)
/* 952: */ {
/* 953:1040 */ MacroCommand cmd = new MacroCommand();
/* 954:1042 */ for (int i = 0; i < this.actionShapeList.size(); i++)
/* 955: */ {
/* 956:1044 */ Shape shape_tmp = (Shape)this.actionShapeList.get(i);
/* 957:1046 */ if (this.action == 2)
/* 958: */ {
/* 959:1047 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 960:1048 */ cmd.addCommand(moveShapeAll(shape_tmp, x - this.xP[0], y - this.yP[0]));
/* 961:1049 */ this.selectedShapeList.clear();
/* 962: */ }
/* 963:1052 */ if (this.action == 3)
/* 964: */ {
/* 965:1053 */ actionMoveCopy(shape_tmp, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 966: */
/* 967:1055 */ Shape sh = (Shape)shape_tmp.clone();
/* 968:1056 */ sh.move(x - this.xP[0], y - this.yP[0]);
/* 969: */
/* 970:1058 */ cmd.addCommand(copyShapeAll(this.document.getCurrentLayer(), sh));
/* 971: */
/* 972:1060 */ addStaticSnapPoint((CadShape)sh);
/* 973:1061 */ this.selectedShapeList.clear();
/* 974: */ }
/* 975:1064 */ if (this.action == 4)
/* 976: */ {
/* 977:1065 */ actionRotate(shape_tmp, this.x_clicked, this.y_clicked, this.x_clicked_old, this.y_clicked_old);
/* 978:1066 */ double A = GeometryUtils.fingAngele(this.xP[0], this.yP[0], x, y);
/* 979: */
/* 980:1068 */ cmd.addCommand(rotateShapeAll(shape_tmp, this.xP[0], this.yP[0], A));
/* 981: */
/* 982:1070 */ this.selectedShapeList.clear();
/* 983: */ }
/* 984: */ }
/* 985:1074 */ if (cmd.getCommandCount() > 0)
/* 986: */ {
/* 987:1075 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 988:1076 */ cmd.execute();
/* 989: */
/* 990:1078 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 991: */ }
/* 992: */ }
/* 993: */ }
/* 994:1083 */ if ((this.action == 5) && (this.actionShape != null)) {
/* 995:1084 */ this.actionShape.postActionPoint(this, x, y);
/* 996: */ }
/* 997:1087 */ this.action = 1;
/* 998:1088 */ this.actionShapeList.clear();
/* 999:1089 */ this.actionShape = null;
/* 1000: */
/* 1001:1091 */ this.drawingContext.setChanged(true);
/* 1002: */
/* 1003:1093 */ this.pCount = 0;
/* 1004:1094 */ return;
/* 1005: */ }
/* 1006:1098 */ if ((this.mode == 3) && (this.mouseButton == 1))
/* 1007: */ {
/* 1008:1100 */ if (this.currentSnapPoint != null)
/* 1009: */ {
/* 1010:1101 */ Point2D_ p = this.currentSnapPoint.getPoint();
/* 1011:1102 */ x = p.x;
/* 1012:1103 */ y = p.y;
/* 1013:1104 */ DrawingUtils.drawSnapPointXor(this.drawingContext, this.snapPointColor, this.snapPointStroke, this.currentSnapPoint);
/* 1014: */
/* 1015:1106 */ this.currentSnapPoint = null;
/* 1016: */ }
/* 1017:1110 */ this.xP[this.pCount] = x;
/* 1018:1111 */ this.yP[this.pCount] = y;
/* 1019:1114 */ if ((this.shapeType == 3) &&
/* 1020:1115 */ (this.pCount == 1))
/* 1021: */ {
/* 1022:1116 */ double radius = Math.sqrt((this.xP[0] - this.xP[1]) * (this.xP[0] - this.xP[1]) + (this.yP[0] - this.yP[1]) * (this.yP[0] - this.yP[1]));
/* 1023:1117 */ Shape shape = new CadCircle(this.xP[0], this.yP[0], radius);
/* 1024:1118 */ addShape(shape);
/* 1025: */
/* 1026:1120 */ this.selectedShapeList.clear();
/* 1027:1121 */ this.pCount = 0;
/* 1028:1122 */ this.mode = 1;
/* 1029:1123 */ this.drawingContext.setChanged(true);
/* 1030:1124 */ return;
/* 1031: */ }
/* 1032:1129 */ if ((this.shapeType == 5) &&
/* 1033:1130 */ (this.pCount > 0))
/* 1034: */ {
/* 1035:1132 */ Shape shape = new CadLine(this.xP[0], this.yP[0], this.xP[1], this.yP[1], this.context);
/* 1036:1133 */ addShape(shape);
/* 1037: */
/* 1038:1135 */ this.selectedShapeList.clear();
/* 1039: */
/* 1040:1137 */ this.pCount = 0;
/* 1041:1138 */ this.mode = 1;
/* 1042:1139 */ this.drawingContext.setChanged(true);
/* 1043:1140 */ return;
/* 1044: */ }
/* 1045:1144 */ if ((this.shapeType == 4) &&
/* 1046:1145 */ (this.pCount > 0))
/* 1047: */ {
/* 1048:1146 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[(this.pCount - 1)], this.yP[(this.pCount - 1)]);
/* 1049:1147 */ for (int i = 0; i < this.pCount; i++) {
/* 1050:1148 */ DrawingUtils.drawLine(this.drawingContext, this.foregroundColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 1051: */ }
/* 1052: */ }
/* 1053:1153 */ if ((this.shapeType == 1) &&
/* 1054:1154 */ (this.pCount > 0))
/* 1055: */ {
/* 1056:1155 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[(this.pCount - 1)], this.yP[(this.pCount - 1)]);
/* 1057:1156 */ for (int i = 0; i < this.pCount; i++) {
/* 1058:1157 */ DrawingUtils.drawLine(this.drawingContext, this.foregroundColor, this.shapeDrawingStroke, this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 1059: */ }
/* 1060: */ }
/* 1061:1162 */ this.x_clicked_old = x;
/* 1062:1163 */ this.y_clicked_old = y;
/* 1063: */
/* 1064:1165 */ this.pCount += 1;
/* 1065:1166 */ return;
/* 1066: */ }
/* 1067:1170 */ if ((this.mode == 1) && (this.mouseButton == 1))
/* 1068: */ {
/* 1069:1174 */ double x_tmp = Math.min(this.xP[0], x);
/* 1070:1175 */ double y_tmp = Math.max(this.yP[0], y);
/* 1071:1176 */ double width_tmp = Math.abs(this.xP[0] - x);
/* 1072:1177 */ double height_tmp = Math.abs(this.yP[0] - y);
/* 1073:1178 */ Rectangle2D_ rect_tmp = new Rectangle2D_(x_tmp, y_tmp, width_tmp, height_tmp);
/* 1074: */
/* 1075:1180 */ Iterator iter1 = this.document.getLayers().iterator();
/* 1076:1181 */ while (iter1.hasNext())
/* 1077: */ {
/* 1078:1182 */ Layer layer = (Layer)iter1.next();
/* 1079:1183 */ if ((layer.getVisible()) && (layer.getEnable()))
/* 1080: */ {
/* 1081:1184 */ Iterator iter = layer.getShapes().iterator();
/* 1082:1185 */ while (iter.hasNext())
/* 1083: */ {
/* 1084:1186 */ Shape shape = (Shape)iter.next();
/* 1085:1187 */ Rectangle2D_ rect = shape.getBounds();
/* 1086:1189 */ if (containsBounds(rect_tmp, rect)) {
/* 1087:1190 */ this.selectedShapeList.add(shape);
/* 1088: */ }
/* 1089: */ }
/* 1090: */ }
/* 1091: */ }
/* 1092:1196 */ DrawingUtils.drawRectangleXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.x_clicked, this.y_clicked);
/* 1093: */
/* 1094:1198 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 1095: */
/* 1096:1200 */ this.drawingContext.setChanged(true);
/* 1097:1201 */ this.pCount = 0;
/* 1098:1202 */ return;
/* 1099: */ }
/* 1100: */ }
/* 1101: */
/* 1102: */ protected boolean containsBounds(Rectangle2D_ r1, Rectangle2D_ r2)
/* 1103: */ {
/* 1104:1207 */ if ((r1.x <= r2.x) && (r1.y >= r2.y) && (r1.x + r1.width >= r2.x + r2.width) && (r1.y - r1.height <= r2.y - r2.height)) {
/* 1105:1211 */ return true;
/* 1106: */ }
/* 1107:1212 */ return false;
/* 1108: */ }
/* 1109: */
/* 1110: */ public void mouseWheelMoved(MouseWheelEvent evt)
/* 1111: */ {
/* 1112:1216 */ Graphics2D big = this.drawingContext.getGraphics();
/* 1113: */
/* 1114:1218 */ Point2D_ p2d = this.drawingContext.translateToLogical(evt.getX(), evt.getY());
/* 1115:1219 */ double x = p2d.x;
/* 1116:1220 */ double y = p2d.y;
/* 1117: */
/* 1118:1222 */ this.x_clicked_old = this.x_clicked;
/* 1119:1223 */ this.y_clicked_old = this.y_clicked;
/* 1120:1225 */ if ((this.mode == 1) && (this.pCount == 1) && (this.mouseButton == 1)) {
/* 1121:1229 */ DrawingUtils.drawRectangleXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, x, y, this.x_clicked, this.y_clicked);
/* 1122: */ }
/* 1123:1232 */ this.drawingContext.changeScaleTo(evt.getWheelRotation());
/* 1124: */
/* 1125:1234 */ this.propertyChangeSupport.firePropertyChange("scale", Double.valueOf(0.0D), Double.valueOf(this.drawingContext.getScale()));
/* 1126: */ }
/* 1127: */
/* 1128: */ public void keyPressed(KeyEvent evt)
/* 1129: */ {
/* 1130:1239 */ Graphics2D big = this.drawingContext.getGraphics();
/* 1131:1241 */ if (this.mode == 1)
/* 1132: */ {
/* 1133:1242 */ if ((evt.getKeyCode() == 127) &&
/* 1134:1243 */ (this.selectedShapeList.size() > 0))
/* 1135: */ {
/* 1136:1244 */ deleteSelectedShape();
/* 1137:1245 */ this.drawingContext.setChanged(true);
/* 1138:1246 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 1139:1247 */ return;
/* 1140: */ }
/* 1141:1251 */ if (evt.getKeyCode() == 27)
/* 1142: */ {
/* 1143:1252 */ if (this.selectedShapeList.size() > 0)
/* 1144: */ {
/* 1145:1253 */ this.selectedShapeList.clear();
/* 1146:1254 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 1147: */ }
/* 1148:1257 */ this.drawingContext.setChanged(true);
/* 1149:1258 */ this.pCount = 0;
/* 1150: */ }
/* 1151: */ }
/* 1152:1263 */ if ((this.mode == 3) &&
/* 1153:1264 */ (evt.getKeyCode() == 27))
/* 1154: */ {
/* 1155:1265 */ int count = this.pCount - 1;
/* 1156: */
/* 1157: */
/* 1158:1268 */ DrawingUtils.drawLineXor(this.drawingContext, this.shapeDrawingColor, this.shapeDrawingStroke, this.x_clicked_old, this.y_clicked_old, this.xP[count], this.yP[count]);
/* 1159: */
/* 1160: */
/* 1161: */
/* 1162:1272 */ Shape shape = null;
/* 1163:1274 */ if (this.shapeType == 4)
/* 1164: */ {
/* 1165:1275 */ MacroCommand cmd = new MacroCommand();
/* 1166:1276 */ for (int i = 0; i < this.pCount - 1; i++)
/* 1167: */ {
/* 1168:1277 */ shape = new CadSegment(this.xP[i], this.yP[i], this.xP[(i + 1)], this.yP[(i + 1)]);
/* 1169:1278 */ cmd.addCommand(addShapeAll(shape));
/* 1170: */ }
/* 1171:1280 */ if (cmd.getCommandCount() > 0)
/* 1172: */ {
/* 1173:1281 */ SimpleURManager.getInstance().getUREngine(this.document).addCommand(cmd);
/* 1174:1282 */ cmd.execute();
/* 1175: */
/* 1176:1284 */ this.propertyChangeSupport.firePropertyChange("redraw", Double.valueOf(1.0D), Double.valueOf(2.0D));
/* 1177: */ }
/* 1178: */ }
/* 1179:1288 */ if (this.shapeType == 1)
/* 1180: */ {
/* 1181:1289 */ shape = new CadPolyline(this.xP, this.yP, this.pCount);
/* 1182:1290 */ addShape(shape);
/* 1183: */ }
/* 1184:1293 */ this.selectedShapeList.clear();
/* 1185: */
/* 1186: */
/* 1187:1296 */ this.pCount = 0;
/* 1188:1297 */ this.mode = 1;
/* 1189:1298 */ this.drawingContext.setChanged(true);
/* 1190: */ }
/* 1191: */ }
/* 1192: */ }
/* Location: C:\Users\kul_mut\Downloads\CADBox.2D-1.0.0\CADBox.2D\CADBox.2D.jar
* Qualified Name: org.cadbox.j2d.scale.CadDrawingEngine
* JD-Core Version: 0.7.0.1
*/ | 60,413 | 0.505438 | 0.401553 | 1,202 | 48.265392 | 33.716549 | 215 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.819468 | false | false | 15 |
71f34d4e4cb882473baf3b101fed99e7bb3f5422 | 31,447,750,591,931 | cf08c0b1e0c1dac9d752b91493c15b8336cb731e | /TranskribusDictionaries/src/main/java/eu/transkribus/languageresources/util/SimpleDictFileHandler.java | 6ee7c0fc6e58dc832e518cb7299c5a62b008ba21 | []
| no_license | Transkribus/TranskribusLanguageResources | https://github.com/Transkribus/TranskribusLanguageResources | fd79af74f989486c3c7c326a665143117ae4d10e | dfd3bac075f610e77189203dad06fedf44c3fc94 | refs/heads/master | 2021-01-20T20:39:22.630000 | 2020-02-11T10:29:16 | 2020-02-11T10:29:16 | 61,701,487 | 1 | 2 | null | false | 2020-10-13T06:40:35 | 2016-06-22T08:17:34 | 2020-02-11T10:29:22 | 2020-10-13T06:40:34 | 37,476 | 1 | 2 | 3 | Java | false | false | /*
* 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 eu.transkribus.languageresources.util;
import eu.transkribus.interfaces.IEntry;
import eu.transkribus.languageresources.dictionaries.Dictionary;
import eu.transkribus.languageresources.exceptions.ARPAParseException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
*
* @author max
*/
public class SimpleDictFileHandler
{
public static Dictionary readAsDictionary(String file) throws IOException
{
Map<String, Integer> entries = read(new File(file));
Dictionary dict = new Dictionary();
for (Map.Entry<String, Integer> entry : entries.entrySet())
{
dict.addEntry(entry.getKey(), entry.getValue());
}
return dict;
}
public static Map<String, Integer> read(String file) throws IOException
{
return read(new File(file));
}
public static Map<String, Integer> read(File file) throws FileNotFoundException, IOException
{
Map<String, Integer> dict = new HashMap<>();
Reader reader = new BufferedReader(new FileReader(file));
while (true)
{
String line = ((BufferedReader) reader).readLine();
if (line == null)
{
break;
}
try
{
String[] parts = line.split(",");
if (parts.length == 3)
{
dict.put(parts[0], new Integer(parts[2]));
} else
{
dict.put(parts[0], new Integer(parts[1]));
}
} catch (NumberFormatException nfe)
{
System.out.println("Warning, had problems reading line: " + line);
}
}
reader.close();
return dict;
}
public static void write(File file, Collection<IEntry> entries) throws IOException
{
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ROOT);
numberFormat.setMinimumFractionDigits(0);
numberFormat.setMaximumFractionDigits(0);
numberFormat.setGroupingUsed(false);
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file))))
{
List<IEntry> entriesList = new ArrayList<>(entries);
entriesList.sort((IEntry o1, IEntry o2) -> -new Integer(o1.getFrequency()).compareTo(o2.getFrequency()));
for (IEntry entry : entriesList)
{
writer.println(String.format("%s,%d", entry.getKey(), entry.getFrequency()));
}
}
}
public static void write(String stazhdict, Collection<IEntry> entries)
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| UTF-8 | Java | 3,391 | java | SimpleDictFileHandler.java | Java | [
{
"context": "l.Locale;\nimport java.util.Map;\n\n/**\n *\n * @author max\n */\npublic class SimpleDictFileHandler\n{\n\n pub",
"end": 899,
"score": 0.5490244030952454,
"start": 896,
"tag": "NAME",
"value": "max"
}
]
| 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 eu.transkribus.languageresources.util;
import eu.transkribus.interfaces.IEntry;
import eu.transkribus.languageresources.dictionaries.Dictionary;
import eu.transkribus.languageresources.exceptions.ARPAParseException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
*
* @author max
*/
public class SimpleDictFileHandler
{
public static Dictionary readAsDictionary(String file) throws IOException
{
Map<String, Integer> entries = read(new File(file));
Dictionary dict = new Dictionary();
for (Map.Entry<String, Integer> entry : entries.entrySet())
{
dict.addEntry(entry.getKey(), entry.getValue());
}
return dict;
}
public static Map<String, Integer> read(String file) throws IOException
{
return read(new File(file));
}
public static Map<String, Integer> read(File file) throws FileNotFoundException, IOException
{
Map<String, Integer> dict = new HashMap<>();
Reader reader = new BufferedReader(new FileReader(file));
while (true)
{
String line = ((BufferedReader) reader).readLine();
if (line == null)
{
break;
}
try
{
String[] parts = line.split(",");
if (parts.length == 3)
{
dict.put(parts[0], new Integer(parts[2]));
} else
{
dict.put(parts[0], new Integer(parts[1]));
}
} catch (NumberFormatException nfe)
{
System.out.println("Warning, had problems reading line: " + line);
}
}
reader.close();
return dict;
}
public static void write(File file, Collection<IEntry> entries) throws IOException
{
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ROOT);
numberFormat.setMinimumFractionDigits(0);
numberFormat.setMaximumFractionDigits(0);
numberFormat.setGroupingUsed(false);
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file))))
{
List<IEntry> entriesList = new ArrayList<>(entries);
entriesList.sort((IEntry o1, IEntry o2) -> -new Integer(o1.getFrequency()).compareTo(o2.getFrequency()));
for (IEntry entry : entriesList)
{
writer.println(String.format("%s,%d", entry.getKey(), entry.getFrequency()));
}
}
}
public static void write(String stazhdict, Collection<IEntry> entries)
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| 3,391 | 0.628428 | 0.625184 | 111 | 29.549549 | 29.106434 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594595 | false | false | 15 |
9ec5192dd62cbf6038bb456e1fedcba936fe7217 | 17,566,416,279,598 | de066f4cf88407feac9d2bd1fd487e589b7b02cc | /resrfullTest/src/main/java/core/controller/TestController.java | 5bda381981a2963effb7a33cb40e79fd1c137d0b | []
| no_license | Tumama/SpringBoot-Mybatis-Mysql-Seed-Project | https://github.com/Tumama/SpringBoot-Mybatis-Mysql-Seed-Project | 035b11303ef6ffcf8a396d40ca2998ea4baf8dba | 8c2d07675df6c6d22ceadee13f68e95ec408418d | refs/heads/master | 2021-05-07T18:54:04.654000 | 2017-11-03T07:14:34 | 2017-11-03T07:14:34 | 108,813,390 | 0 | 1 | null | false | 2017-10-30T09:40:11 | 2017-10-30T06:56:32 | 2017-10-30T07:01:16 | 2017-10-30T09:40:11 | 12,715 | 0 | 1 | 0 | HTML | false | null | package core.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/v1/test")
public class TestController {
// @RequestMapping
// @RequestMapping("/find")
// @RequestMapping(method=RequestMethod.GET)
// @RequestMapping(value="/hello", headers = {"apiVersion=2.0"})
@RequestMapping(method=RequestMethod.GET ,params = "name")
// @RequestMapping(value="", method=RequestMethod.GET)
public String test() {
return "0";
}
@RequestMapping(method=RequestMethod.GET ,params = {"name","test"})
public String test1(@RequestParam(value="name", defaultValue="") String name ,@RequestParam(value="test", defaultValue="") String test ) {
return "1"+name+test;
}
@RequestMapping(value="/" , method=RequestMethod.GET ,params = {"name"})
public String test2(@RequestParam("name") String name ,@RequestParam("test") String test ) {
return "2"+name+test;
}
}
| UTF-8 | Java | 1,135 | java | TestController.java | Java | []
| null | []
| package core.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/v1/test")
public class TestController {
// @RequestMapping
// @RequestMapping("/find")
// @RequestMapping(method=RequestMethod.GET)
// @RequestMapping(value="/hello", headers = {"apiVersion=2.0"})
@RequestMapping(method=RequestMethod.GET ,params = "name")
// @RequestMapping(value="", method=RequestMethod.GET)
public String test() {
return "0";
}
@RequestMapping(method=RequestMethod.GET ,params = {"name","test"})
public String test1(@RequestParam(value="name", defaultValue="") String name ,@RequestParam(value="test", defaultValue="") String test ) {
return "1"+name+test;
}
@RequestMapping(value="/" , method=RequestMethod.GET ,params = {"name"})
public String test2(@RequestParam("name") String name ,@RequestParam("test") String test ) {
return "2"+name+test;
}
}
| 1,135 | 0.723348 | 0.7163 | 34 | 32.382355 | 32.92506 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 15 |
13e1a8cb287a769b7bd3850f4b9cb9de0e657279 | 2,491,081,055,643 | 283178c39268e0c723d91f00a6a63ec89534778c | /current/load/src/main/java/org/regendb/load/experiment/model/RnaSegmentSample.java | c329f328163196389777d9b0a3ebec404fb0d4b2 | []
| no_license | mdibl/regendb_loader | https://github.com/mdibl/regendb_loader | 332774d93299f6de6547bbf8a3923eec9e5ffcd6 | 96ec5de2d792a76de49779eb3a3a455830d421ba | refs/heads/master | 2019-08-30T21:49:21.842000 | 2018-12-17T22:05:53 | 2018-12-17T22:05:53 | 97,877,321 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright MDI Biological Laboratory
*/
package org.regendb.load.experiment.model;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.regendb.load.acc.model.Acc;
import java.math.BigDecimal;
/**
* A relationship between a Sample and an RNASegment.
*
* @author Michael C Rosenstein
* @version $Id: RnaSegmentSample.java 712 2014-06-27 14:55:05Z mcr $
*/
public final class RnaSegmentSample {
/**
* The code of the Sample.
*/
private final String sampleCode;
/**
* The ID of the Sample.
*/
private Long sampleId;
/**
* The Acc of the RNASegment expressed.
*/
private final Acc rnaSegmentAcc;
/**
* The ID of the RNASegment expressed.
*/
private Long rnaSegmentId;
/**
* The normalized expression level.
*/
private final BigDecimal exnLevelNorm;
/**
* Constructor.
*
* @param sampleCode the code of the Sample
* @param rnaSegmentAcc the Acc of the RnaSegment
* @param exnLevelNorm the normalized expression level of the RnaSegment in the Sample
*/
public RnaSegmentSample(final String sampleCode, final Acc rnaSegmentAcc, final BigDecimal exnLevelNorm) {
this.sampleCode = sampleCode;
this.rnaSegmentAcc = rnaSegmentAcc;
this.exnLevelNorm = exnLevelNorm;
}
public final String getSampleCode() {
return sampleCode;
}
public final Long getSampleId() {
return sampleId;
}
public final void setSampleId(final Long sampleId) {
this.sampleId = sampleId;
}
public final Acc getRnaSegmentAcc() {
return rnaSegmentAcc;
}
public final Long getRnaSegmentId() {
return rnaSegmentId;
}
public final void setRnaSegmentId(final Long rnaSegmentId) {
this.rnaSegmentId = rnaSegmentId;
}
public final BigDecimal getExnLevelNorm() {
return exnLevelNorm;
}
@Override
public final String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("sampleCode", sampleCode)
.append("sampleId", sampleId)
.append("rnaSegmentAcc", rnaSegmentAcc)
.append("rnaSegmentId", rnaSegmentId)
.append("exnLevelNorm", exnLevelNorm)
.toString();
}
@Override
public final boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
final RnaSegmentSample rhs = (RnaSegmentSample) obj;
return new EqualsBuilder()
.append(this.sampleCode, rhs.sampleCode)
.append(this.rnaSegmentAcc, rhs.rnaSegmentAcc)
.append(this.exnLevelNorm, rhs.exnLevelNorm)
.append(this.sampleId, rhs.sampleId)
.append(this.rnaSegmentId, rhs.rnaSegmentId)
.isEquals();
}
@Override
public final int hashCode() {
return new HashCodeBuilder(17, 71)
.append(sampleCode)
.append(rnaSegmentAcc)
.append(exnLevelNorm)
.append(sampleId)
.append(rnaSegmentId)
.toHashCode();
}
}
| UTF-8 | Java | 3,545 | java | RnaSegmentSample.java | Java | [
{
"context": " between a Sample and an RNASegment.\n *\n * @author Michael C Rosenstein\n * @version $Id: RnaSegmentSample.java 712 2014-0",
"end": 477,
"score": 0.9995545148849487,
"start": 457,
"tag": "NAME",
"value": "Michael C Rosenstein"
}
]
| null | []
| /*
* Copyright MDI Biological Laboratory
*/
package org.regendb.load.experiment.model;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.regendb.load.acc.model.Acc;
import java.math.BigDecimal;
/**
* A relationship between a Sample and an RNASegment.
*
* @author <NAME>
* @version $Id: RnaSegmentSample.java 712 2014-06-27 14:55:05Z mcr $
*/
public final class RnaSegmentSample {
/**
* The code of the Sample.
*/
private final String sampleCode;
/**
* The ID of the Sample.
*/
private Long sampleId;
/**
* The Acc of the RNASegment expressed.
*/
private final Acc rnaSegmentAcc;
/**
* The ID of the RNASegment expressed.
*/
private Long rnaSegmentId;
/**
* The normalized expression level.
*/
private final BigDecimal exnLevelNorm;
/**
* Constructor.
*
* @param sampleCode the code of the Sample
* @param rnaSegmentAcc the Acc of the RnaSegment
* @param exnLevelNorm the normalized expression level of the RnaSegment in the Sample
*/
public RnaSegmentSample(final String sampleCode, final Acc rnaSegmentAcc, final BigDecimal exnLevelNorm) {
this.sampleCode = sampleCode;
this.rnaSegmentAcc = rnaSegmentAcc;
this.exnLevelNorm = exnLevelNorm;
}
public final String getSampleCode() {
return sampleCode;
}
public final Long getSampleId() {
return sampleId;
}
public final void setSampleId(final Long sampleId) {
this.sampleId = sampleId;
}
public final Acc getRnaSegmentAcc() {
return rnaSegmentAcc;
}
public final Long getRnaSegmentId() {
return rnaSegmentId;
}
public final void setRnaSegmentId(final Long rnaSegmentId) {
this.rnaSegmentId = rnaSegmentId;
}
public final BigDecimal getExnLevelNorm() {
return exnLevelNorm;
}
@Override
public final String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("sampleCode", sampleCode)
.append("sampleId", sampleId)
.append("rnaSegmentAcc", rnaSegmentAcc)
.append("rnaSegmentId", rnaSegmentId)
.append("exnLevelNorm", exnLevelNorm)
.toString();
}
@Override
public final boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
final RnaSegmentSample rhs = (RnaSegmentSample) obj;
return new EqualsBuilder()
.append(this.sampleCode, rhs.sampleCode)
.append(this.rnaSegmentAcc, rhs.rnaSegmentAcc)
.append(this.exnLevelNorm, rhs.exnLevelNorm)
.append(this.sampleId, rhs.sampleId)
.append(this.rnaSegmentId, rhs.rnaSegmentId)
.isEquals();
}
@Override
public final int hashCode() {
return new HashCodeBuilder(17, 71)
.append(sampleCode)
.append(rnaSegmentAcc)
.append(exnLevelNorm)
.append(sampleId)
.append(rnaSegmentId)
.toHashCode();
}
}
| 3,531 | 0.612976 | 0.605924 | 128 | 26.695313 | 22.402761 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.335938 | false | false | 15 |
c53d036f4a5137d5ea0fddb983076fd286cbec8b | 22,574,348,144,580 | 26e3ac3ccf64b914b751e66993af69a0a7037b56 | /app/src/main/java/com/example/android/popularmovies2/ux/FavoritesCursorAdapter.java | 5001c439ad98214cf0093fd6164052d5d61a76ee | [
"MIT"
]
| permissive | emanuele78/android-tmdb-client | https://github.com/emanuele78/android-tmdb-client | eeb37716319ca97efd9130023bec06d724480c37 | 0cffbff7bb916e8a506f0213d222059f2997e40e | refs/heads/master | 2021-04-06T17:56:17.028000 | 2019-05-16T10:02:49 | 2019-05-16T10:02:49 | 125,377,004 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android.popularmovies2.ux;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.popularmovies2.R;
import com.example.android.popularmovies2.data.PopularMoviesContract;
import com.example.android.popularmovies2.network.NetworkUtils;
/**
* Created by Emanuele on 13/03/2018.
*/
public class FavoritesCursorAdapter extends
RecyclerView.Adapter<FavoritesCursorAdapter.RecyclerViewHolder> {
private Cursor cursor;
private ListItemClickListener listener;
public FavoritesCursorAdapter(ListItemClickListener listener) {
this.listener = listener;
}
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
int layoutIdForListItem = R.layout.item_preferred;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layoutIdForListItem, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
// Indices for the _id, description, and priority columns
int pictureIndex = cursor.getColumnIndex(PopularMoviesContract.ItemEntry.COLUMN_POSTER);
int titleIndex = cursor.getColumnIndex(PopularMoviesContract.ItemEntry.COLUMN_TITLE);
int typeIndex = cursor.getColumnIndex(PopularMoviesContract.ItemEntry.COLUMN_ITEM_TYPE);
cursor.moveToPosition(position);
// Determine the values of the wanted data
String picture = cursor.getString(pictureIndex);
String title = cursor.getString(titleIndex);
int type = cursor.getInt(typeIndex);
if (type == PopularMoviesContract.ItemEntry.MOVIE_MEDIA_TYPE) {
holder.typeImageView.setImageResource(R.drawable.ic_movie_s);
} else {
holder.typeImageView.setImageResource(R.drawable.ic_tv_s);
}
holder.titleTextView.setText(title);
NetworkUtils.loadImage(holder.posterImageView, picture,
R.drawable.ic_video_camera, R.drawable.ic_video_camera);
}
@Override
public int getItemCount() {
if (cursor != null) {
return cursor.getCount();
}
return 0;
}
public void setData(Cursor cursor) {
this.cursor = cursor;
if (cursor != null) {
notifyDataSetChanged();
}
}
class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView titleTextView;
ImageView posterImageView;
ImageView typeImageView;
public RecyclerViewHolder(View view) {
super(view);
titleTextView = view.findViewById(R.id.info_tv);
posterImageView = view.findViewById(R.id.poster_iv);
typeImageView = view.findViewById(R.id.type_iv);
view.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
cursor.moveToPosition(position);
int itemIdIndex =
cursor.getColumnIndex(PopularMoviesContract.ItemEntry.COLUMN_ITEM_ID);
int itemTypeIndex =
cursor.getColumnIndex(PopularMoviesContract.ItemEntry.COLUMN_ITEM_TYPE);
int recordIndex =
cursor.getColumnIndex(PopularMoviesContract.ItemEntry._ID);
int itemType = cursor.getInt(itemTypeIndex);
int itemId = cursor.getInt(itemIdIndex);
long record = cursor.getLong(recordIndex);
listener.onListItemClick(itemId, itemType, record);
}
}
}
public interface ListItemClickListener {
void onListItemClick(int itemId, int itemType, long recordId);
}
}
| UTF-8 | Java | 4,152 | java | FavoritesCursorAdapter.java | Java | [
{
"context": "armovies2.network.NetworkUtils;\n\n/**\n * Created by Emanuele on 13/03/2018.\n */\npublic class FavoritesCursorAd",
"end": 524,
"score": 0.8871496319770813,
"start": 516,
"tag": "USERNAME",
"value": "Emanuele"
}
]
| null | []
| package com.example.android.popularmovies2.ux;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.popularmovies2.R;
import com.example.android.popularmovies2.data.PopularMoviesContract;
import com.example.android.popularmovies2.network.NetworkUtils;
/**
* Created by Emanuele on 13/03/2018.
*/
public class FavoritesCursorAdapter extends
RecyclerView.Adapter<FavoritesCursorAdapter.RecyclerViewHolder> {
private Cursor cursor;
private ListItemClickListener listener;
public FavoritesCursorAdapter(ListItemClickListener listener) {
this.listener = listener;
}
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
int layoutIdForListItem = R.layout.item_preferred;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layoutIdForListItem, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
// Indices for the _id, description, and priority columns
int pictureIndex = cursor.getColumnIndex(PopularMoviesContract.ItemEntry.COLUMN_POSTER);
int titleIndex = cursor.getColumnIndex(PopularMoviesContract.ItemEntry.COLUMN_TITLE);
int typeIndex = cursor.getColumnIndex(PopularMoviesContract.ItemEntry.COLUMN_ITEM_TYPE);
cursor.moveToPosition(position);
// Determine the values of the wanted data
String picture = cursor.getString(pictureIndex);
String title = cursor.getString(titleIndex);
int type = cursor.getInt(typeIndex);
if (type == PopularMoviesContract.ItemEntry.MOVIE_MEDIA_TYPE) {
holder.typeImageView.setImageResource(R.drawable.ic_movie_s);
} else {
holder.typeImageView.setImageResource(R.drawable.ic_tv_s);
}
holder.titleTextView.setText(title);
NetworkUtils.loadImage(holder.posterImageView, picture,
R.drawable.ic_video_camera, R.drawable.ic_video_camera);
}
@Override
public int getItemCount() {
if (cursor != null) {
return cursor.getCount();
}
return 0;
}
public void setData(Cursor cursor) {
this.cursor = cursor;
if (cursor != null) {
notifyDataSetChanged();
}
}
class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView titleTextView;
ImageView posterImageView;
ImageView typeImageView;
public RecyclerViewHolder(View view) {
super(view);
titleTextView = view.findViewById(R.id.info_tv);
posterImageView = view.findViewById(R.id.poster_iv);
typeImageView = view.findViewById(R.id.type_iv);
view.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
cursor.moveToPosition(position);
int itemIdIndex =
cursor.getColumnIndex(PopularMoviesContract.ItemEntry.COLUMN_ITEM_ID);
int itemTypeIndex =
cursor.getColumnIndex(PopularMoviesContract.ItemEntry.COLUMN_ITEM_TYPE);
int recordIndex =
cursor.getColumnIndex(PopularMoviesContract.ItemEntry._ID);
int itemType = cursor.getInt(itemTypeIndex);
int itemId = cursor.getInt(itemIdIndex);
long record = cursor.getLong(recordIndex);
listener.onListItemClick(itemId, itemType, record);
}
}
}
public interface ListItemClickListener {
void onListItemClick(int itemId, int itemType, long recordId);
}
}
| 4,152 | 0.669557 | 0.666185 | 111 | 36.405407 | 27.641977 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594595 | false | false | 15 |
c6ca60836db0bc71f0e360f24cad5d941a752dd3 | 19,224,273,639,327 | 9d7a8345845e53843958263c75b618eef83327f1 | /MetaDataManagement/REST-Scheduler/src/main/java/edu/kit/dama/rest/scheduler/service/impl/SchedulerRestService.java | 92e7a30afc9e385b75a9c8119bf7681c031dafd2 | [
"Apache-2.0"
]
| permissive | kit-data-manager/base | https://github.com/kit-data-manager/base | 39f543b2b7824ebc2cd92f46366f7d4b82e44895 | 3420af44035768f5111ea9f279b285ac0e22633a | refs/heads/master | 2021-07-18T07:40:27.960000 | 2020-06-16T05:30:20 | 2020-06-16T05:30:20 | 41,793,596 | 3 | 4 | Apache-2.0 | false | 2020-07-01T20:55:08 | 2015-09-02T09:52:14 | 2020-06-16T05:30:23 | 2020-07-01T20:55:07 | 21,701 | 3 | 2 | 5 | Java | false | false | /*
* Copyright 2015 Karlsruhe Institute of Technology.
*
* 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 edu.kit.dama.rest.scheduler.service.impl;
import com.sun.jersey.api.core.HttpContext;
import edu.kit.dama.authorization.entities.GroupId;
import edu.kit.dama.authorization.entities.IAuthorizationContext;
import edu.kit.dama.authorization.exceptions.UnauthorizedAccessAttemptException;
import edu.kit.dama.rest.scheduler.services.interfaces.ISchedulerRestService;
import edu.kit.dama.rest.scheduler.types.ScheduleWrapper;
import edu.kit.dama.rest.scheduler.types.TriggerWrapper;
import edu.kit.dama.rest.util.RestUtils;
import edu.kit.dama.scheduler.api.schedule.SimpleSchedule;
import edu.kit.dama.scheduler.api.trigger.*;
import edu.kit.dama.scheduler.manager.SecureSchedulerManager;
import edu.kit.dama.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
*
* @author wq7203
*/
@Path("/")
public final class SchedulerRestService implements ISchedulerRestService {
private static final Logger LOGGER = LoggerFactory.getLogger(SchedulerRestService.class);
private static final String[] DATE_FORMATS = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"};
@Override
public Response checkService() {
return Response.ok().build();
}
@Override
public StreamingOutput getAllSchedules(HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
List<SimpleSchedule> schedules;
try {
schedules = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getAllSchedules();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(ScheduleWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new ScheduleWrapper(schedules));
}
@Override
public StreamingOutput getScheduleById(String id, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
SimpleSchedule schedule;
try {
schedule = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getScheduleById(id);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
if (schedule == null) {
throw new WebApplicationException(new Exception("Schedule for id " + id + " not found"), Response.Status.NOT_FOUND);
}
return RestUtils.createObjectGraphStream(ScheduleWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new ScheduleWrapper(schedule));
}
@Override
public StreamingOutput getAllTriggers(HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
List<JobTrigger> triggers;
try {
triggers = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getAllTriggers();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(triggers));
}
@Override
public StreamingOutput getTriggerById(String id, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
JobTrigger trigger;
try {
trigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getTriggerById(id);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
if (trigger == null) {
throw new WebApplicationException(new Exception("Trigger for id " + id + " not found"), Response.Status.NOT_FOUND);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(trigger));
}
@Override
public StreamingOutput getCurrentlyExecutingJobs(HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
List<SimpleSchedule> schedules;
try {
schedules = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getCurrentlyExecutingJobs();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(ScheduleWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new ScheduleWrapper(schedules));
}
@Override
public StreamingOutput getTriggersByScheduleId(String id, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
List<JobTrigger> triggers;
try {
triggers = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getTriggersByScheduleId(id);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(triggers));
}
@Override
public StreamingOutput addSchedule(String name, String group, String description, String jobClass, String jobParameters, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
SimpleSchedule schedule;
try {
schedule = SecureSchedulerManager.factorySecureSchedulerManager(ctx).createSchedule();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
schedule.setName(name);
schedule.setScheduleGroup(group);
schedule.setDescription(description);
schedule.setJobClass(jobClass);
schedule.setJobParameters(jobParameters);
SimpleSchedule result;
try {
result = SecureSchedulerManager.factorySecureSchedulerManager(ctx).addSchedule(schedule);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(ScheduleWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new ScheduleWrapper(result));
}
@Override
public StreamingOutput addExpressionTrigger(String id, String name, String group, Integer priority, String description, String startDate, String endDate, String expression, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
ExpressionTrigger trigger;
try {
trigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).createExpressionTrigger();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
trigger.setName(name);
trigger.setTriggerGroup(group);
trigger.setPriority(priority);
trigger.setDescription(description);
trigger.setStartDate(this.parseDate(startDate));
trigger.setEndDate(this.parseDate(endDate));
trigger.setExpression(expression);
JobTrigger addedTrigger;
try {
addedTrigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).addTrigger(id, trigger);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(addedTrigger));
}
@Override
public StreamingOutput addIntervallTrigger(String id, String name, String group, Integer priority, String description, String startDate, String endDate, Integer times, Long period, Long initialDelay, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
IntervalTrigger trigger;
try {
trigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).createIntervalTrigger();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
trigger.setName(name);
trigger.setTriggerGroup(group);
trigger.setPriority(priority);
trigger.setDescription(description);
trigger.setStartDate(this.parseDate(startDate));
trigger.setEndDate(this.parseDate(endDate));
trigger.setTimes(times);
trigger.setPeriod(period);
trigger.setInitialDelay(initialDelay);
JobTrigger addedTrigger;
try {
addedTrigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).addTrigger(id, trigger);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(addedTrigger));
}
@Override
public StreamingOutput addDelayTrigger(String id, String name, String group, Integer priority, String description, String startDate, String endDate, Integer times, Long delay, Long initialDelay, HttpContext hc) {
LOGGER.warn("Adding delay triggers is currently not supported.");
throw new WebApplicationException(405);
}
@Override
public StreamingOutput addNowTrigger(String id, String name, String group, Integer priority, String description, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
NowTrigger trigger;
try {
trigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).createNowTrigger();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
trigger.setName(name);
trigger.setTriggerGroup(group);
trigger.setPriority(priority);
trigger.setDescription(description);
JobTrigger addedTrigger;
try {
addedTrigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).addTrigger(id, trigger);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(addedTrigger));
}
@Override
public StreamingOutput addAtTrigger(String id, String name, String group, Integer priority, String description, String startDate, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
AtTrigger trigger;
try {
trigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).createAtTrigger();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
trigger.setName(name);
trigger.setTriggerGroup(group);
trigger.setPriority(priority);
trigger.setDescription(description);
trigger.setStartDate(this.parseDate(startDate));
JobTrigger addedTrigger;
try {
addedTrigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).addTrigger(id, trigger);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(addedTrigger));
}
@Override
public Response deleteScheduleById(String id, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
boolean removed;
try {
removed = SecureSchedulerManager.factorySecureSchedulerManager(ctx).removeSchedule(id);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
Response response;
if (removed) {
response = Response.ok().build();
} else {
response = Response.status(Response.Status.NOT_FOUND).build();
}
return response;
}
@Override
public Response deleteTriggerById(String id, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
boolean removed;
try {
removed = SecureSchedulerManager.factorySecureSchedulerManager(ctx).removeTrigger(id);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
Response response;
if (removed) {
response = Response.ok().build();
} else {
response = Response.status(Response.Status.NOT_FOUND).build();
}
return response;
}
private Date parseDate(String date) {
if (date == null) {
return null;
}
try {
return new Date(Long.parseLong(date));
} catch (NumberFormatException ex) {
}
for (String pattern : DATE_FORMATS) {
try {
return (new SimpleDateFormat(pattern)).parse(date);
} catch (ParseException ex) {
}
}
throw new WebApplicationException(new Exception("Date parameter " + date + "is malformed, expected formats are " + Arrays.toString(DATE_FORMATS) + "."), Response.Status.BAD_REQUEST);
}
}
| UTF-8 | Java | 15,095 | java | SchedulerRestService.java | Java | [
{
"context": "il.Date;\nimport java.util.List;\n\n/**\n *\n * @author wq7203\n */\n@Path(\"/\")\npublic final class SchedulerRestSe",
"end": 1715,
"score": 0.9995827078819275,
"start": 1709,
"tag": "USERNAME",
"value": "wq7203"
},
{
"context": "UNAUTHORIZED);\n }\n\n trigger.setName(name);\n trigger.setTriggerGroup(group);\n ",
"end": 9516,
"score": 0.8661437630653381,
"start": 9512,
"tag": "NAME",
"value": "name"
}
]
| null | []
| /*
* Copyright 2015 Karlsruhe Institute of Technology.
*
* 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 edu.kit.dama.rest.scheduler.service.impl;
import com.sun.jersey.api.core.HttpContext;
import edu.kit.dama.authorization.entities.GroupId;
import edu.kit.dama.authorization.entities.IAuthorizationContext;
import edu.kit.dama.authorization.exceptions.UnauthorizedAccessAttemptException;
import edu.kit.dama.rest.scheduler.services.interfaces.ISchedulerRestService;
import edu.kit.dama.rest.scheduler.types.ScheduleWrapper;
import edu.kit.dama.rest.scheduler.types.TriggerWrapper;
import edu.kit.dama.rest.util.RestUtils;
import edu.kit.dama.scheduler.api.schedule.SimpleSchedule;
import edu.kit.dama.scheduler.api.trigger.*;
import edu.kit.dama.scheduler.manager.SecureSchedulerManager;
import edu.kit.dama.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
*
* @author wq7203
*/
@Path("/")
public final class SchedulerRestService implements ISchedulerRestService {
private static final Logger LOGGER = LoggerFactory.getLogger(SchedulerRestService.class);
private static final String[] DATE_FORMATS = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"};
@Override
public Response checkService() {
return Response.ok().build();
}
@Override
public StreamingOutput getAllSchedules(HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
List<SimpleSchedule> schedules;
try {
schedules = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getAllSchedules();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(ScheduleWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new ScheduleWrapper(schedules));
}
@Override
public StreamingOutput getScheduleById(String id, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
SimpleSchedule schedule;
try {
schedule = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getScheduleById(id);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
if (schedule == null) {
throw new WebApplicationException(new Exception("Schedule for id " + id + " not found"), Response.Status.NOT_FOUND);
}
return RestUtils.createObjectGraphStream(ScheduleWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new ScheduleWrapper(schedule));
}
@Override
public StreamingOutput getAllTriggers(HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
List<JobTrigger> triggers;
try {
triggers = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getAllTriggers();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(triggers));
}
@Override
public StreamingOutput getTriggerById(String id, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
JobTrigger trigger;
try {
trigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getTriggerById(id);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
if (trigger == null) {
throw new WebApplicationException(new Exception("Trigger for id " + id + " not found"), Response.Status.NOT_FOUND);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(trigger));
}
@Override
public StreamingOutput getCurrentlyExecutingJobs(HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
List<SimpleSchedule> schedules;
try {
schedules = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getCurrentlyExecutingJobs();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(ScheduleWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new ScheduleWrapper(schedules));
}
@Override
public StreamingOutput getTriggersByScheduleId(String id, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
List<JobTrigger> triggers;
try {
triggers = SecureSchedulerManager.factorySecureSchedulerManager(ctx).getTriggersByScheduleId(id);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(triggers));
}
@Override
public StreamingOutput addSchedule(String name, String group, String description, String jobClass, String jobParameters, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
SimpleSchedule schedule;
try {
schedule = SecureSchedulerManager.factorySecureSchedulerManager(ctx).createSchedule();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
schedule.setName(name);
schedule.setScheduleGroup(group);
schedule.setDescription(description);
schedule.setJobClass(jobClass);
schedule.setJobParameters(jobParameters);
SimpleSchedule result;
try {
result = SecureSchedulerManager.factorySecureSchedulerManager(ctx).addSchedule(schedule);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(ScheduleWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new ScheduleWrapper(result));
}
@Override
public StreamingOutput addExpressionTrigger(String id, String name, String group, Integer priority, String description, String startDate, String endDate, String expression, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
ExpressionTrigger trigger;
try {
trigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).createExpressionTrigger();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
trigger.setName(name);
trigger.setTriggerGroup(group);
trigger.setPriority(priority);
trigger.setDescription(description);
trigger.setStartDate(this.parseDate(startDate));
trigger.setEndDate(this.parseDate(endDate));
trigger.setExpression(expression);
JobTrigger addedTrigger;
try {
addedTrigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).addTrigger(id, trigger);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(addedTrigger));
}
@Override
public StreamingOutput addIntervallTrigger(String id, String name, String group, Integer priority, String description, String startDate, String endDate, Integer times, Long period, Long initialDelay, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
IntervalTrigger trigger;
try {
trigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).createIntervalTrigger();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
trigger.setName(name);
trigger.setTriggerGroup(group);
trigger.setPriority(priority);
trigger.setDescription(description);
trigger.setStartDate(this.parseDate(startDate));
trigger.setEndDate(this.parseDate(endDate));
trigger.setTimes(times);
trigger.setPeriod(period);
trigger.setInitialDelay(initialDelay);
JobTrigger addedTrigger;
try {
addedTrigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).addTrigger(id, trigger);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(addedTrigger));
}
@Override
public StreamingOutput addDelayTrigger(String id, String name, String group, Integer priority, String description, String startDate, String endDate, Integer times, Long delay, Long initialDelay, HttpContext hc) {
LOGGER.warn("Adding delay triggers is currently not supported.");
throw new WebApplicationException(405);
}
@Override
public StreamingOutput addNowTrigger(String id, String name, String group, Integer priority, String description, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
NowTrigger trigger;
try {
trigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).createNowTrigger();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
trigger.setName(name);
trigger.setTriggerGroup(group);
trigger.setPriority(priority);
trigger.setDescription(description);
JobTrigger addedTrigger;
try {
addedTrigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).addTrigger(id, trigger);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(addedTrigger));
}
@Override
public StreamingOutput addAtTrigger(String id, String name, String group, Integer priority, String description, String startDate, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
AtTrigger trigger;
try {
trigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).createAtTrigger();
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
trigger.setName(name);
trigger.setTriggerGroup(group);
trigger.setPriority(priority);
trigger.setDescription(description);
trigger.setStartDate(this.parseDate(startDate));
JobTrigger addedTrigger;
try {
addedTrigger = SecureSchedulerManager.factorySecureSchedulerManager(ctx).addTrigger(id, trigger);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
return RestUtils.createObjectGraphStream(TriggerWrapper.class, Constants.REST_DEFAULT_OBJECT_GRAPH, new TriggerWrapper(addedTrigger));
}
@Override
public Response deleteScheduleById(String id, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
boolean removed;
try {
removed = SecureSchedulerManager.factorySecureSchedulerManager(ctx).removeSchedule(id);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
Response response;
if (removed) {
response = Response.ok().build();
} else {
response = Response.status(Response.Status.NOT_FOUND).build();
}
return response;
}
@Override
public Response deleteTriggerById(String id, HttpContext hc) {
IAuthorizationContext ctx = RestUtils.authorize(hc, new GroupId(Constants.USERS_GROUP_ID));
boolean removed;
try {
removed = SecureSchedulerManager.factorySecureSchedulerManager(ctx).removeTrigger(id);
} catch (UnauthorizedAccessAttemptException ex) {
throw new WebApplicationException(ex, Response.Status.UNAUTHORIZED);
}
Response response;
if (removed) {
response = Response.ok().build();
} else {
response = Response.status(Response.Status.NOT_FOUND).build();
}
return response;
}
private Date parseDate(String date) {
if (date == null) {
return null;
}
try {
return new Date(Long.parseLong(date));
} catch (NumberFormatException ex) {
}
for (String pattern : DATE_FORMATS) {
try {
return (new SimpleDateFormat(pattern)).parse(date);
} catch (ParseException ex) {
}
}
throw new WebApplicationException(new Exception("Date parameter " + date + "is malformed, expected formats are " + Arrays.toString(DATE_FORMATS) + "."), Response.Status.BAD_REQUEST);
}
}
| 15,095 | 0.708314 | 0.707188 | 362 | 40.698895 | 42.349121 | 221 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.737569 | false | false | 15 |
1ad753dd15b0a42af9955c54c9ab349fd678a0f2 | 32,057,635,921,270 | b11c78cde3fc597229e9815cf35fb63628af01ea | /allopathy-app-User-Management/src/main/java/com/allopathy/management/data/model/MaterialMedica.java | 4a3c17db6174033eefc780f2f29cfb3e824783c9 | []
| no_license | RahulSurana123/Project-allopathy-app | https://github.com/RahulSurana123/Project-allopathy-app | 7d26eec12f1350e6387ab05fc1b39ed872f69198 | d4b84fc93f421356ebdc960d937ea88e3f7f1c6d | refs/heads/master | 2023-06-26T16:18:47.674000 | 2021-07-24T02:05:18 | 2021-07-24T02:05:18 | 387,650,731 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.allopathy.management.data.model;
import java.util.UUID;
import com.allopathy.management.constant.ClassIdConstants;
import lombok.Data;
@Data
public class MaterialMedica {
public MaterialMedica() {
super();
}
public MaterialMedica(String id, String medicalId, Repertory mind,
Repertory head, Repertory eyes, Repertory ears, Repertory nose,
Repertory face, Repertory mouth, Repertory tongue, Repertory taste,
Repertory gums, Repertory teeth, Repertory throat,
Repertory stomach, Repertory abdomen, Repertory urinary,
Repertory male, Repertory female, Repertory respiratory,
Repertory circulatory, Repertory locomotor, Repertory nervous,
Repertory fever, Repertory skin, Repertory generalities,
Repertory modalities, String extraField1, String extraField2,
String extraField3, String extraField4, String extraField5,
String classId) {
super();
this.id = id;
this.medicalId = medicalId;
this.mind = mind;
this.head = head;
this.eyes = eyes;
this.ears = ears;
this.nose = nose;
this.face = face;
this.mouth = mouth;
this.tongue = tongue;
this.taste = taste;
this.gums = gums;
this.teeth = teeth;
this.throat = throat;
this.stomach = stomach;
this.abdomen = abdomen;
this.urinary = urinary;
this.male = male;
this.female = female;
this.respiratory = respiratory;
this.circulatory = circulatory;
this.locomotor = locomotor;
this.nervous = nervous;
this.fever = fever;
this.skin = skin;
this.generalities = generalities;
this.modalities = modalities;
this.extraField1 = extraField1;
this.extraField2 = extraField2;
this.extraField3 = extraField3;
this.extraField4 = extraField4;
this.extraField5 = extraField5;
this.classId = classId;
}
String id;
String medicalId;
Repertory mind;
Repertory head;
Repertory eyes;
Repertory ears;
Repertory nose;
Repertory face;
Repertory mouth;
Repertory tongue;
Repertory taste;
Repertory gums;
Repertory teeth;
Repertory throat;
Repertory stomach;
Repertory abdomen;
Repertory urinary;
Repertory male;
Repertory female;
Repertory respiratory;
Repertory circulatory;
Repertory locomotor;
Repertory nervous;
Repertory fever;
Repertory skin;
Repertory generalities;
Repertory modalities;
String extraField1;
String extraField2;
String extraField3;
String extraField4;
String extraField5;
String classId = ClassIdConstants.MaterialMedica_Doc;
public void setId() {
this.id = UUID.randomUUID().toString().replace("-", "");
}
}
| UTF-8 | Java | 2,582 | java | MaterialMedica.java | Java | []
| null | []
| package com.allopathy.management.data.model;
import java.util.UUID;
import com.allopathy.management.constant.ClassIdConstants;
import lombok.Data;
@Data
public class MaterialMedica {
public MaterialMedica() {
super();
}
public MaterialMedica(String id, String medicalId, Repertory mind,
Repertory head, Repertory eyes, Repertory ears, Repertory nose,
Repertory face, Repertory mouth, Repertory tongue, Repertory taste,
Repertory gums, Repertory teeth, Repertory throat,
Repertory stomach, Repertory abdomen, Repertory urinary,
Repertory male, Repertory female, Repertory respiratory,
Repertory circulatory, Repertory locomotor, Repertory nervous,
Repertory fever, Repertory skin, Repertory generalities,
Repertory modalities, String extraField1, String extraField2,
String extraField3, String extraField4, String extraField5,
String classId) {
super();
this.id = id;
this.medicalId = medicalId;
this.mind = mind;
this.head = head;
this.eyes = eyes;
this.ears = ears;
this.nose = nose;
this.face = face;
this.mouth = mouth;
this.tongue = tongue;
this.taste = taste;
this.gums = gums;
this.teeth = teeth;
this.throat = throat;
this.stomach = stomach;
this.abdomen = abdomen;
this.urinary = urinary;
this.male = male;
this.female = female;
this.respiratory = respiratory;
this.circulatory = circulatory;
this.locomotor = locomotor;
this.nervous = nervous;
this.fever = fever;
this.skin = skin;
this.generalities = generalities;
this.modalities = modalities;
this.extraField1 = extraField1;
this.extraField2 = extraField2;
this.extraField3 = extraField3;
this.extraField4 = extraField4;
this.extraField5 = extraField5;
this.classId = classId;
}
String id;
String medicalId;
Repertory mind;
Repertory head;
Repertory eyes;
Repertory ears;
Repertory nose;
Repertory face;
Repertory mouth;
Repertory tongue;
Repertory taste;
Repertory gums;
Repertory teeth;
Repertory throat;
Repertory stomach;
Repertory abdomen;
Repertory urinary;
Repertory male;
Repertory female;
Repertory respiratory;
Repertory circulatory;
Repertory locomotor;
Repertory nervous;
Repertory fever;
Repertory skin;
Repertory generalities;
Repertory modalities;
String extraField1;
String extraField2;
String extraField3;
String extraField4;
String extraField5;
String classId = ClassIdConstants.MaterialMedica_Doc;
public void setId() {
this.id = UUID.randomUUID().toString().replace("-", "");
}
}
| 2,582 | 0.726569 | 0.718823 | 133 | 18.413534 | 17.695473 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.112782 | false | false | 15 |
730c94c077cca0d666662fa440cf9b78c98690f3 | 29,265,907,180,738 | c17017451a432059cb337cd909e8138e44db3c02 | /Task_0424/김예슬/BOJ_G3_16637_괄호추가하기.java | fe9583873007d1f2df71f6c60ac424b43e036858 | []
| no_license | AlgoStudy14/task | https://github.com/AlgoStudy14/task | 0ccc26d28cd539d22c0e88fa107ce0d92ec0e290 | e93ac6e2625233e2e92c89384d32ce5e67f3f3ff | refs/heads/main | 2023-08-29T09:38:32.459000 | 2021-10-02T00:16:12 | 2021-10-02T00:16:12 | 337,013,584 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package algo0417;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/***
* <문제 요약>
* 구해야 하는 것 : 괄호를 적절히 추가해 만들 수 있는 식의 결과의 최댓값 출력
* 제약 사항: 중첩괄호 사용 불가, 괄호 안에는 연산자 하나만!
* 문제 유형 : subset, dfs 사용
* <풀이법 요약>
* 0. numbers: 피연산자, op: 연산자
* 1. 괄호 사용O, 괄호 사용X 나눠서 dfs
* 1-1. depth는 연산자의 인덱스라 생각
* 1-2. 괄호 O: 현재까지의 결과에 (현재 + 1) 피연산자와 (현재 + 2) 피연산자의 연산의 결과를 연산
* 1-3. 괄호 X: 현재까지의 결과에 바로 뒤 피연산자까지 계산
*/
public class BOJ_G3_16637_괄호추가하기 {
static int N, max;
static int[] numbers;
static char[] op;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
numbers = new int[N / 2 + 1];
op = new char[N / 2];
String s = br.readLine();
for (int i = 0; i < N; i++) {
if (i % 2 == 0) numbers[i / 2] = s.charAt(i) - '0';
else op[i / 2] = s.charAt(i);
}
max = Integer.MIN_VALUE;
subset(0, numbers[0]);
System.out.println(max);
}
static void subset(int depth, int sum) {
if (depth == N / 2) {
max = Math.max(max, sum);
return;
}
// 괄호O
if (depth + 2 <= N / 2) {
int tmp = calc(numbers[depth + 1], numbers[depth + 2], op[depth + 1]);
subset(depth + 2, calc(sum, tmp, op[depth]));
}
// 괄호X
subset(depth + 1, calc(sum, numbers[depth + 1], op[depth]));
}
// +, -, x
static int calc(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
}
return -1;
}
}
| UTF-8 | Java | 1,993 | java | BOJ_G3_16637_괄호추가하기.java | Java | []
| null | []
| package algo0417;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/***
* <문제 요약>
* 구해야 하는 것 : 괄호를 적절히 추가해 만들 수 있는 식의 결과의 최댓값 출력
* 제약 사항: 중첩괄호 사용 불가, 괄호 안에는 연산자 하나만!
* 문제 유형 : subset, dfs 사용
* <풀이법 요약>
* 0. numbers: 피연산자, op: 연산자
* 1. 괄호 사용O, 괄호 사용X 나눠서 dfs
* 1-1. depth는 연산자의 인덱스라 생각
* 1-2. 괄호 O: 현재까지의 결과에 (현재 + 1) 피연산자와 (현재 + 2) 피연산자의 연산의 결과를 연산
* 1-3. 괄호 X: 현재까지의 결과에 바로 뒤 피연산자까지 계산
*/
public class BOJ_G3_16637_괄호추가하기 {
static int N, max;
static int[] numbers;
static char[] op;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
numbers = new int[N / 2 + 1];
op = new char[N / 2];
String s = br.readLine();
for (int i = 0; i < N; i++) {
if (i % 2 == 0) numbers[i / 2] = s.charAt(i) - '0';
else op[i / 2] = s.charAt(i);
}
max = Integer.MIN_VALUE;
subset(0, numbers[0]);
System.out.println(max);
}
static void subset(int depth, int sum) {
if (depth == N / 2) {
max = Math.max(max, sum);
return;
}
// 괄호O
if (depth + 2 <= N / 2) {
int tmp = calc(numbers[depth + 1], numbers[depth + 2], op[depth + 1]);
subset(depth + 2, calc(sum, tmp, op[depth]));
}
// 괄호X
subset(depth + 1, calc(sum, numbers[depth + 1], op[depth]));
}
// +, -, x
static int calc(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
}
return -1;
}
}
| 1,993 | 0.522415 | 0.497908 | 71 | 21.563381 | 18.766716 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.774648 | false | false | 15 |
0f56238333d7799969f13cf8df41261b9966da19 | 31,275,951,873,293 | adf6d273ade3c8971133b3a4c2d4bdca7d8fda13 | /Mystatus_change.java | 432c0a63fb471914f250a38626a23b5ed136d11a | []
| no_license | Kimura-san/racook | https://github.com/Kimura-san/racook | 87ab74d607a92cf8eea63599d135b10951346041 | cb20e854d94a77b1a6031ab9b50824f378734ff7 | refs/heads/main | 2023-05-04T18:37:10.650000 | 2021-05-24T06:34:02 | 2021-05-24T06:34:02 | 370,245,684 | 0 | 0 | null | false | 2021-05-24T06:14:30 | 2021-05-24T06:06:47 | 2021-05-24T06:11:55 | 2021-05-24T06:14:29 | 0 | 0 | 0 | 0 | Java | false | false | package com.sample.racook;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Mystatus_change extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mystatus_change);
Button button = findViewById(R.id.button7);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("user").child("user1").child("プロフィール").child("favorite").setValue("和食");
// ボタンを押すとアンケート結果をFirebaseに記入しマイページに戻る
Intent intent = new Intent(Mystatus_change.this,Main_mainActivity.class);
startActivity(intent);
}
});
Button button2 = findViewById(R.id.button1);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("user").child("user1").child("プロフィール").child("favorite").setValue("洋食");
// ボタンを押すとアンケート結果をFirebaseに記入しマイページに戻る
Intent intent = new Intent(Mystatus_change.this,Main_mainActivity.class);
startActivity(intent);
}
});
Button button3 = findViewById(R.id.button2);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("user").child("user1").child("プロフィール").child("favorite").setValue("中華");
// ボタンを押すとアンケート結果をFirebaseに記入しマイページに戻る
Intent intent = new Intent(Mystatus_change.this,Main_mainActivity.class);
startActivity(intent);
}
});
Button button4 = findViewById(R.id.button3);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("user").child("user1").child("プロフィール").child("favorite").setValue("デザート");
// ボタンを押すとアンケート結果をFirebaseに記入しマイページに戻る
Intent intent = new Intent(Mystatus_change.this,Main_mainActivity.class);
startActivity(intent);
}
});
}
} | UTF-8 | Java | 3,218 | java | Mystatus_change.java | Java | []
| null | []
| package com.sample.racook;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Mystatus_change extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mystatus_change);
Button button = findViewById(R.id.button7);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("user").child("user1").child("プロフィール").child("favorite").setValue("和食");
// ボタンを押すとアンケート結果をFirebaseに記入しマイページに戻る
Intent intent = new Intent(Mystatus_change.this,Main_mainActivity.class);
startActivity(intent);
}
});
Button button2 = findViewById(R.id.button1);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("user").child("user1").child("プロフィール").child("favorite").setValue("洋食");
// ボタンを押すとアンケート結果をFirebaseに記入しマイページに戻る
Intent intent = new Intent(Mystatus_change.this,Main_mainActivity.class);
startActivity(intent);
}
});
Button button3 = findViewById(R.id.button2);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("user").child("user1").child("プロフィール").child("favorite").setValue("中華");
// ボタンを押すとアンケート結果をFirebaseに記入しマイページに戻る
Intent intent = new Intent(Mystatus_change.this,Main_mainActivity.class);
startActivity(intent);
}
});
Button button4 = findViewById(R.id.button3);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("user").child("user1").child("プロフィール").child("favorite").setValue("デザート");
// ボタンを押すとアンケート結果をFirebaseに記入しマイページに戻る
Intent intent = new Intent(Mystatus_change.this,Main_mainActivity.class);
startActivity(intent);
}
});
}
} | 3,218 | 0.64149 | 0.636705 | 81 | 34.148148 | 32.633812 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.506173 | false | false | 15 |
e77d3d11bd04b1b6a4871ea70f2e7dc77bc8d0d5 | 11,115,375,394,480 | b8abcb055c899387ab2751a284719da710c57611 | /msrc/core/com/collabrr/adk/api/annonymous/impl/ShareApplicationToAnonymousCollabrrUserJobHandler.java | 96d8e5b1407fe63022d2dc4481a655f77df9bddd | []
| no_license | ganeshdevp/PW | https://github.com/ganeshdevp/PW | bf92d2434e15eb1e6596c9cdf1154569e0462801 | d7065b36d095e7ca9d2679aa9a96db3dc9b8260f | refs/heads/master | 2021-01-01T06:56:02.239000 | 2017-07-18T03:44:46 | 2017-07-18T03:44:46 | 97,549,729 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.collabrr.adk.api.annonymous.impl;
import org.apache.commons.lang.exception.ExceptionUtils;
import com.collabrr.adk.spi.annonymous.CollabrrAnnonymousConstants.Permission;
import com.vg.pw.exceptions.DocExException;
import com.vg.pw.hbase.store.entity.urrolecontext.URRoleContext;
import com.vg.pw.hbase.util.ResourceAccessPermission;
import com.vg.pw.logger.DocexLogger;
import com.vg.pw.services.central.JobHandler;
import com.vg.pw.xmlprocessor.Element;
import com.vg.pw.xmlprocessor.Node;
public class ShareApplicationToAnonymousCollabrrUserJobHandler extends JobHandler {
/**
* @param jobId
*/
public ShareApplicationToAnonymousCollabrrUserJobHandler(String jobId) {
super(jobId);
}
private static final DocexLogger LOGGER = new DocexLogger(ShareApplicationToAnonymousCollabrrUserJobHandler.class);
public Element process(Element jobInfo) throws DocExException {
LOGGER.logInfo("Entering process ...");
try {
String resourceId = Node.getDataElement(jobInfo, "ApplicationId");
String annonymousUser = Node.getDataElement(jobInfo, "AnnonymousUserId");
String resourceAccessPermission = Node.getDataElement(jobInfo, "Permission");
String type = Node.getDataElement(jobInfo, "ResourceType");
String appRoleList = Node.getDataElement(jobInfo, "AppRoles");
//String discussionThread = Node.getDataElement(jobInfo, "DiscussionThread");
String annonymousUserGeneratorId = Node.getDataElement(jobInfo, "uid");
if(resourceId == null || resourceId.trim().equals("")) {
throw new DocExException(new IllegalArgumentException("Resource Id is empty and hence cannot proceed further with resource share."));
}
if(type == null || type.trim().equals("")) {
throw new DocExException(new IllegalArgumentException("Resource Type is empty and hence cannot proceed further with resource share."));
}
if(annonymousUser == null || annonymousUser.trim().equals("")) {
throw new DocExException(new IllegalArgumentException("Annonymous user id is empty and hence cannot proceed further with resource share."));
}
if(annonymousUserGeneratorId == null || annonymousUserGeneratorId.trim().equals("")) {
throw new DocExException(new IllegalArgumentException("Job Creator User Id is empty and hence cannot proceed further with resource share."));
}
if(resourceAccessPermission == null || resourceAccessPermission.trim().equals("")) {
resourceAccessPermission = String.valueOf(ResourceAccessPermission.READ_ONLY);
}
Permission permission = Permission.getPermissionByName(resourceAccessPermission);
URRoleContext urRoleContext = new URRoleContext();
urRoleContext.setResid(resourceId);
urRoleContext.setRoles(appRoleList);
urRoleContext.setRestype(type);
urRoleContext.addURRoleContext(annonymousUser, null, annonymousUser);
return null;
}
catch(DocExException e) {
LOGGER.logError(new StringBuilder("An error occured while trying to share the application with the anonymous user. ").append(ExceptionUtils.getFullStackTrace(e)).toString());
throw e;
}
finally {
LOGGER.logInfo("Leaving process ...");
}
}
}
| UTF-8 | Java | 3,191 | java | ShareApplicationToAnonymousCollabrrUserJobHandler.java | Java | []
| null | []
| package com.collabrr.adk.api.annonymous.impl;
import org.apache.commons.lang.exception.ExceptionUtils;
import com.collabrr.adk.spi.annonymous.CollabrrAnnonymousConstants.Permission;
import com.vg.pw.exceptions.DocExException;
import com.vg.pw.hbase.store.entity.urrolecontext.URRoleContext;
import com.vg.pw.hbase.util.ResourceAccessPermission;
import com.vg.pw.logger.DocexLogger;
import com.vg.pw.services.central.JobHandler;
import com.vg.pw.xmlprocessor.Element;
import com.vg.pw.xmlprocessor.Node;
public class ShareApplicationToAnonymousCollabrrUserJobHandler extends JobHandler {
/**
* @param jobId
*/
public ShareApplicationToAnonymousCollabrrUserJobHandler(String jobId) {
super(jobId);
}
private static final DocexLogger LOGGER = new DocexLogger(ShareApplicationToAnonymousCollabrrUserJobHandler.class);
public Element process(Element jobInfo) throws DocExException {
LOGGER.logInfo("Entering process ...");
try {
String resourceId = Node.getDataElement(jobInfo, "ApplicationId");
String annonymousUser = Node.getDataElement(jobInfo, "AnnonymousUserId");
String resourceAccessPermission = Node.getDataElement(jobInfo, "Permission");
String type = Node.getDataElement(jobInfo, "ResourceType");
String appRoleList = Node.getDataElement(jobInfo, "AppRoles");
//String discussionThread = Node.getDataElement(jobInfo, "DiscussionThread");
String annonymousUserGeneratorId = Node.getDataElement(jobInfo, "uid");
if(resourceId == null || resourceId.trim().equals("")) {
throw new DocExException(new IllegalArgumentException("Resource Id is empty and hence cannot proceed further with resource share."));
}
if(type == null || type.trim().equals("")) {
throw new DocExException(new IllegalArgumentException("Resource Type is empty and hence cannot proceed further with resource share."));
}
if(annonymousUser == null || annonymousUser.trim().equals("")) {
throw new DocExException(new IllegalArgumentException("Annonymous user id is empty and hence cannot proceed further with resource share."));
}
if(annonymousUserGeneratorId == null || annonymousUserGeneratorId.trim().equals("")) {
throw new DocExException(new IllegalArgumentException("Job Creator User Id is empty and hence cannot proceed further with resource share."));
}
if(resourceAccessPermission == null || resourceAccessPermission.trim().equals("")) {
resourceAccessPermission = String.valueOf(ResourceAccessPermission.READ_ONLY);
}
Permission permission = Permission.getPermissionByName(resourceAccessPermission);
URRoleContext urRoleContext = new URRoleContext();
urRoleContext.setResid(resourceId);
urRoleContext.setRoles(appRoleList);
urRoleContext.setRestype(type);
urRoleContext.addURRoleContext(annonymousUser, null, annonymousUser);
return null;
}
catch(DocExException e) {
LOGGER.logError(new StringBuilder("An error occured while trying to share the application with the anonymous user. ").append(ExceptionUtils.getFullStackTrace(e)).toString());
throw e;
}
finally {
LOGGER.logInfo("Leaving process ...");
}
}
}
| 3,191 | 0.756189 | 0.756189 | 83 | 37.445782 | 41.711647 | 177 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.807229 | false | false | 15 |
7fd346837eb39033a64455ee09857df4c4220c21 | 26,242,250,237,474 | f8ea01347f28b0059ad0446a72bd1cdb6fab2f45 | /src/main/java/com/pochka15/funfics/services/funfics/FunficRatingService.java | e1125a0f780b06ebf8d5108d06cdef60875ac354 | []
| no_license | pochka15/funfics | https://github.com/pochka15/funfics | 2bf64d69a116cafadd4d61a1d802fc2d9f04ad6d | b6e3273ef787e870501a871a655b06b0f8e2846b | refs/heads/master | 2023-04-03T14:35:39.549000 | 2021-04-24T18:13:49 | 2021-04-24T18:13:49 | 342,191,179 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pochka15.funfics.services.funfics;
import com.pochka15.funfics.dto.form.RateFunficForm;
import com.pochka15.funfics.dto.funfic.FunficWithRatingDto;
import com.pochka15.funfics.exceptions.UserCannotRateFunfic;
import com.pochka15.funfics.exceptions.UserNotFound;
import java.util.List;
public interface FunficRatingService {
/**
* @param funficId id if the funfic
* @param username username which gave the
* @return <b>true</b> if there is no rating given by the 'username' for the funfic with the id funficId
*/
boolean checkIfUserCanRateFunfic(long funficId, String username);
/**
* @param rateFunficForm just input data
* @param username name of the user who rated the funfic
*/
void rateFunfic(RateFunficForm rateFunficForm, String username) throws UserNotFound, UserCannotRateFunfic;
float averageRating(long funficId);
/**
* @return a list of funfic data structures that don't contain the content of funfics
*/
List<FunficWithRatingDto> fetchAllFunfics();
}
| UTF-8 | Java | 1,060 | java | FunficRatingService.java | Java | [
{
"context": "m funficId id if the funfic\n * @param username username which gave the\n * @return <b>true</b> if there is n",
"end": 424,
"score": 0.9742553234100342,
"start": 410,
"tag": "USERNAME",
"value": "username which"
}
]
| null | []
| package com.pochka15.funfics.services.funfics;
import com.pochka15.funfics.dto.form.RateFunficForm;
import com.pochka15.funfics.dto.funfic.FunficWithRatingDto;
import com.pochka15.funfics.exceptions.UserCannotRateFunfic;
import com.pochka15.funfics.exceptions.UserNotFound;
import java.util.List;
public interface FunficRatingService {
/**
* @param funficId id if the funfic
* @param username username which gave the
* @return <b>true</b> if there is no rating given by the 'username' for the funfic with the id funficId
*/
boolean checkIfUserCanRateFunfic(long funficId, String username);
/**
* @param rateFunficForm just input data
* @param username name of the user who rated the funfic
*/
void rateFunfic(RateFunficForm rateFunficForm, String username) throws UserNotFound, UserCannotRateFunfic;
float averageRating(long funficId);
/**
* @return a list of funfic data structures that don't contain the content of funfics
*/
List<FunficWithRatingDto> fetchAllFunfics();
}
| 1,060 | 0.740566 | 0.731132 | 30 | 34.333332 | 32.488289 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.433333 | false | false | 15 |
24a1cdaa9d30ed077f2d8d631e59cb895d8023d0 | 24,352,464,597,368 | e12b0eae81e7dbaeebd80d749f0764830ce29827 | /Test.java | d987469bbc75e8cce2ef0cbe41e3d8105889f2e2 | []
| no_license | LenguajesRestrepoUN/Proyecto | https://github.com/LenguajesRestrepoUN/Proyecto | 3dca4f1fa14b6a49bd92762fa769b586f4f3cd43 | 5faa76602453869cc062d942bb0ff7513266ceb8 | refs/heads/master | 2021-01-01T04:04:59.834000 | 2016-06-01T19:39:41 | 2016-06-01T19:39:41 | 58,587,433 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javax.swing.*;
import java.awt.*;
public class Test {
public JFrame frame;
public JFrame frame2;
public JFrame frame3;
public Test(){
frame = new JFrame("Console");
frame.setSize(800, 800);
//frame2 = new JFrame("Console 2");
//frame2.setSize(600, 500);
JTabbedPane pestañas0 = new JTabbedPane();
JTextArea intel = new JTextArea(15, 40);
intel.setLineWrap(true);
intel.setWrapStyleWord(true);
intel.setEditable(false);
JScrollPane scroller = new JScrollPane(intel);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
JPanel panel = new JPanel();
panel.add(scroller);
JButton nextB = new JButton("Next");
pestañas0.addTab("Cosonle", panel);
//frame2.add(BorderLayout.SOUTH, nextB);
//frame2.add(panel);
//frame2.setVisible(true);
//Creamos el conjunto de pestañas
JTabbedPane pestañas=new JTabbedPane();
//Creamos el panel y lo añadimos a las pestañas
JPanel panel1=new JPanel();
//Componentes del panel1
JTextArea intel2 = new JTextArea(15, 40);
intel2.setLineWrap(true);
intel2.setWrapStyleWord(true);
intel2.setEditable(false);
JScrollPane scroller2 = new JScrollPane(intel2);
scroller2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
panel1.add(scroller2);
//panel1.add(et_p1);
//Añadimos un nombre de la pestaña y el panel
pestañas.addTab("Scopes 1", panel1);
//Realizamos lo mismo con el resto
JPanel panel2=new JPanel();
//Componentes del panel2
JTextArea intel3 = new JTextArea(15, 40);
intel3.setLineWrap(true);
intel3.setWrapStyleWord(true);
intel3.setEditable(false);
JScrollPane scroller3 = new JScrollPane(intel3);
scroller3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
panel2.add(scroller3);
pestañas.addTab("Scopes 2", panel2);
//-------------------------------------------
JTabbedPane pestañas2=new JTabbedPane();
JPanel panel12=new JPanel();
JTextArea intel4 = new JTextArea(15, 40);
intel4.setLineWrap(true);
intel4.setWrapStyleWord(true);
intel4.setEditable(false);
JScrollPane scroller4 = new JScrollPane(intel4);
scroller4.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller4.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
panel12.add(scroller4);
pestañas2.addTab("Cola 1", panel12);
JPanel panel22=new JPanel();
pestañas2.addTab("Panel 2", panel22);
JLabel et_p22=new JLabel("Estas en el panel 22");
panel22.add(et_p22);
Box box = new Box(BoxLayout.Y_AXIS);
Box box2 = new Box(BoxLayout.X_AXIS);
box2.add(pestañas0);
box2.add(pestañas);
box.add(box2);
box.add(pestañas2);
frame.add(box);
frame.add(BorderLayout.SOUTH, nextB);
frame.setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}
| UTF-8 | Java | 3,612 | java | Test.java | Java | []
| null | []
| import javax.swing.*;
import java.awt.*;
public class Test {
public JFrame frame;
public JFrame frame2;
public JFrame frame3;
public Test(){
frame = new JFrame("Console");
frame.setSize(800, 800);
//frame2 = new JFrame("Console 2");
//frame2.setSize(600, 500);
JTabbedPane pestañas0 = new JTabbedPane();
JTextArea intel = new JTextArea(15, 40);
intel.setLineWrap(true);
intel.setWrapStyleWord(true);
intel.setEditable(false);
JScrollPane scroller = new JScrollPane(intel);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
JPanel panel = new JPanel();
panel.add(scroller);
JButton nextB = new JButton("Next");
pestañas0.addTab("Cosonle", panel);
//frame2.add(BorderLayout.SOUTH, nextB);
//frame2.add(panel);
//frame2.setVisible(true);
//Creamos el conjunto de pestañas
JTabbedPane pestañas=new JTabbedPane();
//Creamos el panel y lo añadimos a las pestañas
JPanel panel1=new JPanel();
//Componentes del panel1
JTextArea intel2 = new JTextArea(15, 40);
intel2.setLineWrap(true);
intel2.setWrapStyleWord(true);
intel2.setEditable(false);
JScrollPane scroller2 = new JScrollPane(intel2);
scroller2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
panel1.add(scroller2);
//panel1.add(et_p1);
//Añadimos un nombre de la pestaña y el panel
pestañas.addTab("Scopes 1", panel1);
//Realizamos lo mismo con el resto
JPanel panel2=new JPanel();
//Componentes del panel2
JTextArea intel3 = new JTextArea(15, 40);
intel3.setLineWrap(true);
intel3.setWrapStyleWord(true);
intel3.setEditable(false);
JScrollPane scroller3 = new JScrollPane(intel3);
scroller3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
panel2.add(scroller3);
pestañas.addTab("Scopes 2", panel2);
//-------------------------------------------
JTabbedPane pestañas2=new JTabbedPane();
JPanel panel12=new JPanel();
JTextArea intel4 = new JTextArea(15, 40);
intel4.setLineWrap(true);
intel4.setWrapStyleWord(true);
intel4.setEditable(false);
JScrollPane scroller4 = new JScrollPane(intel4);
scroller4.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller4.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
panel12.add(scroller4);
pestañas2.addTab("Cola 1", panel12);
JPanel panel22=new JPanel();
pestañas2.addTab("Panel 2", panel22);
JLabel et_p22=new JLabel("Estas en el panel 22");
panel22.add(et_p22);
Box box = new Box(BoxLayout.Y_AXIS);
Box box2 = new Box(BoxLayout.X_AXIS);
box2.add(pestañas0);
box2.add(pestañas);
box.add(box2);
box.add(pestañas2);
frame.add(box);
frame.add(BorderLayout.SOUTH, nextB);
frame.setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}
| 3,612 | 0.643215 | 0.613737 | 110 | 31.690908 | 25.121431 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.763636 | false | false | 15 |
b43b43dba6493870fb1e9418e4163fccbed969e7 | 8,486,855,417,476 | a78b9aadc6374f5f76b4739a968295982d1622e1 | /app/src/main/java/in/dc297/mqttclpro/MessageActivity.java | cb62aca0f53d8d01886fcdaf16673a5150d02b92 | [
"MIT"
]
| permissive | mathisdt/mqttclpro | https://github.com/mathisdt/mqttclpro | 33d6dfb6e7773aa8aab25a8dae2d82176f0713c6 | a4519e77e5865d5a23f7deee1e69177fb712e7a4 | refs/heads/master | 2021-01-26T07:48:40.190000 | 2017-11-10T19:50:03 | 2017-11-10T19:50:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package in.dc297.mqttclpro;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MessageActivity extends AppCompatActivity {
private String topic = null;
private ListView messagesLV = null;
private MessagesListAdapter messagesListAdapter = null;
DBHelper db = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
db = new DBHelper(getApplicationContext());
/*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent topicIntent = getIntent();
topic = topicIntent.getStringExtra("in.dc297.mqttclpro.topic");
if(topic==null || topic.equals("")){
Toast.makeText(this,"No messages received",Toast.LENGTH_SHORT).show();
finish();
}
((TextView)toolbar.findViewById(R.id.toolbar_title)).setText("Received messages for "+topic);
messagesLV = (ListView) findViewById(R.id.messages_lv);
db.setMessagesRead(topic,0);
String[] from = new String[] { "message", "timestamp","display_topic"};
int[] to = new int[]{R.id.mmessage_tv,R.id.mtimestamp_tv,R.id.mtopic_tv};
messagesListAdapter = new MessagesListAdapter(this,R.layout.messages_list_item,db.getMessages(topic,0),from,to,0);
messagesLV.setAdapter(messagesListAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_message_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_delete) {
db.deleteMessages(topic,0);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| UTF-8 | Java | 3,073 | java | MessageActivity.java | Java | []
| null | []
| package in.dc297.mqttclpro;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MessageActivity extends AppCompatActivity {
private String topic = null;
private ListView messagesLV = null;
private MessagesListAdapter messagesListAdapter = null;
DBHelper db = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
db = new DBHelper(getApplicationContext());
/*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent topicIntent = getIntent();
topic = topicIntent.getStringExtra("in.dc297.mqttclpro.topic");
if(topic==null || topic.equals("")){
Toast.makeText(this,"No messages received",Toast.LENGTH_SHORT).show();
finish();
}
((TextView)toolbar.findViewById(R.id.toolbar_title)).setText("Received messages for "+topic);
messagesLV = (ListView) findViewById(R.id.messages_lv);
db.setMessagesRead(topic,0);
String[] from = new String[] { "message", "timestamp","display_topic"};
int[] to = new int[]{R.id.mmessage_tv,R.id.mtimestamp_tv,R.id.mtopic_tv};
messagesListAdapter = new MessagesListAdapter(this,R.layout.messages_list_item,db.getMessages(topic,0),from,to,0);
messagesLV.setAdapter(messagesListAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_message_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_delete) {
db.deleteMessages(topic,0);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 3,073 | 0.672958 | 0.669053 | 81 | 36.938271 | 27.785486 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.814815 | false | false | 15 |
dd358bac987d3604f952d82c444915628de02076 | 32,856,499,832,664 | 23c73165b9067f74cf3b08f9b030643f7e636a36 | /src/evolution/multi/NSGA2Selector.java | 9f00b71c687df45ae7f8ca9d8d4746431a071acf | [
"MIT"
]
| permissive | supovic1/evaTeaching | https://github.com/supovic1/evaTeaching | f12e17ee8ed0019a99c395052bfb5abe0baa006d | 417c845a06f9f0aa4042039d9b8aff9ee75fa851 | refs/heads/master | 2020-05-15T12:38:54.834000 | 2019-04-22T08:21:55 | 2019-04-22T08:21:55 | 182,272,614 | 0 | 0 | MIT | false | 2019-04-19T21:32:54 | 2019-04-19T13:56:49 | 2019-04-19T14:02:39 | 2019-04-19T21:32:53 | 252 | 0 | 0 | 0 | Java | false | false | package evolution.multi;
import evolution.Population;
import evolution.individuals.Individual;
import evolution.individuals.MultiRealIndividual;
import evolution.selectors.Selector;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Implementation of the NSGA-II selection.
*/
public class NSGA2Selector implements Selector {
@Override
public void select(int howMany, Population from, Population to) {
MultiObjectiveUtils.assignFrontAndSsc(from);
ArrayList<Individual> inds = new ArrayList<Individual>();
for(int i = 0; i < from.getPopulationSize(); i++) {
inds.add(from.get(i));
}
Collections.sort(inds, new NSGA2Comparator());
for (int i = 0; i < howMany; i++) {
to.add(inds.get(i));
}
}
/**
* Compares the individuals based on the front number (lower is better) and the crowding distance (larger is better).
*/
class NSGA2Comparator implements Comparator<Individual> {
@Override
public int compare(Individual o1, Individual o2) {
MultiRealIndividual mri1 = (MultiRealIndividual)o1;
MultiRealIndividual mri2 = (MultiRealIndividual)o2;
if (mri1.getFront() < mri2.getFront()) {
return -1;
}
if (mri1.getFront() > mri2.getFront()) {
return 1;
}
if (mri1.getSsc() > mri2.getSsc()) {
return -1;
}
if (mri1.getSsc() < mri2.getSsc()) {
return 1;
}
return 0;
}
}
}
| UTF-8 | Java | 1,651 | java | NSGA2Selector.java | Java | []
| null | []
| package evolution.multi;
import evolution.Population;
import evolution.individuals.Individual;
import evolution.individuals.MultiRealIndividual;
import evolution.selectors.Selector;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Implementation of the NSGA-II selection.
*/
public class NSGA2Selector implements Selector {
@Override
public void select(int howMany, Population from, Population to) {
MultiObjectiveUtils.assignFrontAndSsc(from);
ArrayList<Individual> inds = new ArrayList<Individual>();
for(int i = 0; i < from.getPopulationSize(); i++) {
inds.add(from.get(i));
}
Collections.sort(inds, new NSGA2Comparator());
for (int i = 0; i < howMany; i++) {
to.add(inds.get(i));
}
}
/**
* Compares the individuals based on the front number (lower is better) and the crowding distance (larger is better).
*/
class NSGA2Comparator implements Comparator<Individual> {
@Override
public int compare(Individual o1, Individual o2) {
MultiRealIndividual mri1 = (MultiRealIndividual)o1;
MultiRealIndividual mri2 = (MultiRealIndividual)o2;
if (mri1.getFront() < mri2.getFront()) {
return -1;
}
if (mri1.getFront() > mri2.getFront()) {
return 1;
}
if (mri1.getSsc() > mri2.getSsc()) {
return -1;
}
if (mri1.getSsc() < mri2.getSsc()) {
return 1;
}
return 0;
}
}
}
| 1,651 | 0.589945 | 0.575409 | 62 | 25.629032 | 25.023365 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.451613 | false | false | 15 |
96a3d93662a1a3a9a80ea276313f1d37687dd4d1 | 8,040,178,796,226 | 889f5fb3650d22a03799c915f92603f90d0b1827 | /app/src/main/java/com/brunaLopes/appchat/servidor/MensagemListener.java | 9d6faa9d269f94c2e804fca4560b875ad373051a | []
| no_license | brunalopesd/android-AppChat | https://github.com/brunalopesd/android-AppChat | 00c6b0bb79375ded0276b6800ae628080b09ab8e | 4c9050db8c20c3a36f1457a49f9f35801ca9bb84 | refs/heads/master | 2023-04-04T01:19:56.837000 | 2021-04-12T00:07:39 | 2021-04-12T00:07:39 | 357,007,938 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.brunaLopes.appchat.servidor;
import java.util.List;
public interface MensagemListener {
void onListaDeUsuariosChegando(List<String> usuarios);
void onMensagemChegando(String remetente, String texto);
void onMensagemDeErroChegando(String motivo);
} | UTF-8 | Java | 275 | java | MensagemListener.java | Java | []
| null | []
| package com.brunaLopes.appchat.servidor;
import java.util.List;
public interface MensagemListener {
void onListaDeUsuariosChegando(List<String> usuarios);
void onMensagemChegando(String remetente, String texto);
void onMensagemDeErroChegando(String motivo);
} | 275 | 0.796364 | 0.796364 | 11 | 24.09091 | 23.914448 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 15 |
cdb795ae9900aa919303f03bd8a1935f25f97121 | 29,394,756,177,697 | 5bed415d089c063a4bd9861f88fec7a39574553c | /app/src/main/java/mobile/bts/com/viefund/Entities/PlanInfo.java | fb7cd9d63a3d8a7135fe19d10f0b0ee43ad5c2ba | []
| no_license | NDTChan/VIEFUND | https://github.com/NDTChan/VIEFUND | 56d12103db73415359f1e49bc68c6cd8feeca623 | fb8ada518227ae85300229aac5434e1eef0798e0 | refs/heads/master | 2020-04-13T12:04:58.019000 | 2018-12-26T15:21:42 | 2018-12-26T15:21:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mobile.bts.com.viefund.Entities;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.table.DatabaseTable;
import java.util.List;
/**
* BT Company
* Created by Administrator on 3/12/2018.
*/
@DatabaseTable
public class PlanInfo {
public static final String ID_FIELD_NAME = "ID";
public static final String PlanID_FIELD_NAME = "PlanID";
public static final String InfoLabel_FIELD_NAME = "InfoLabel";
public static final String InfoContent_FIELD_NAME = "InfoContent";
@DatabaseField(id = true, canBeNull = false, columnName = ID_FIELD_NAME)
private String ID;
@DatabaseField(columnName = PlanID_FIELD_NAME)
private String PlanID;
@DatabaseField(columnName = InfoLabel_FIELD_NAME)
private String InfoLabel;
@DatabaseField(columnName = InfoContent_FIELD_NAME)
private String InfoContent;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getPlanID() {
return PlanID;
}
public void setPlanID(String planID) {
PlanID = planID;
}
public String getInfoLabel() {
return InfoLabel;
}
public void setInfoLabel(String infoLabel) {
InfoLabel = infoLabel;
}
public String getInfoContent() {
return InfoContent;
}
public void setInfoContent(String infoContent) {
InfoContent = infoContent;
}
public PlanInfo() {
}
public PlanInfo(String ID, String planID, String infoLabel, String infoContent) {
this.ID = ID;
PlanID = planID;
InfoLabel = infoLabel;
InfoContent = infoContent;
}
private static List<PlanInfo> _DATA_Plan_Info = null;
public static List<PlanInfo> Load_PlanInfo_By_PlanID(Dao<PlanInfo,String> _planInfo, String PlanID){
try {
QueryBuilder<PlanInfo, String> queryBuilder = _planInfo.queryBuilder();
queryBuilder.where().eq(PlantAccount.PlanID_FIELD_NAME,PlanID);
PreparedQuery<PlanInfo> preparedQuery = queryBuilder.prepare();
_DATA_Plan_Info = _planInfo.query(preparedQuery);
}catch (Exception ex){
_DATA_Plan_Info = null;
ex.printStackTrace();
}
return _DATA_Plan_Info;
}
}
| UTF-8 | Java | 2,430 | java | PlanInfo.java | Java | []
| null | []
| package mobile.bts.com.viefund.Entities;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.table.DatabaseTable;
import java.util.List;
/**
* BT Company
* Created by Administrator on 3/12/2018.
*/
@DatabaseTable
public class PlanInfo {
public static final String ID_FIELD_NAME = "ID";
public static final String PlanID_FIELD_NAME = "PlanID";
public static final String InfoLabel_FIELD_NAME = "InfoLabel";
public static final String InfoContent_FIELD_NAME = "InfoContent";
@DatabaseField(id = true, canBeNull = false, columnName = ID_FIELD_NAME)
private String ID;
@DatabaseField(columnName = PlanID_FIELD_NAME)
private String PlanID;
@DatabaseField(columnName = InfoLabel_FIELD_NAME)
private String InfoLabel;
@DatabaseField(columnName = InfoContent_FIELD_NAME)
private String InfoContent;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getPlanID() {
return PlanID;
}
public void setPlanID(String planID) {
PlanID = planID;
}
public String getInfoLabel() {
return InfoLabel;
}
public void setInfoLabel(String infoLabel) {
InfoLabel = infoLabel;
}
public String getInfoContent() {
return InfoContent;
}
public void setInfoContent(String infoContent) {
InfoContent = infoContent;
}
public PlanInfo() {
}
public PlanInfo(String ID, String planID, String infoLabel, String infoContent) {
this.ID = ID;
PlanID = planID;
InfoLabel = infoLabel;
InfoContent = infoContent;
}
private static List<PlanInfo> _DATA_Plan_Info = null;
public static List<PlanInfo> Load_PlanInfo_By_PlanID(Dao<PlanInfo,String> _planInfo, String PlanID){
try {
QueryBuilder<PlanInfo, String> queryBuilder = _planInfo.queryBuilder();
queryBuilder.where().eq(PlantAccount.PlanID_FIELD_NAME,PlanID);
PreparedQuery<PlanInfo> preparedQuery = queryBuilder.prepare();
_DATA_Plan_Info = _planInfo.query(preparedQuery);
}catch (Exception ex){
_DATA_Plan_Info = null;
ex.printStackTrace();
}
return _DATA_Plan_Info;
}
}
| 2,430 | 0.660082 | 0.651029 | 92 | 25.413044 | 24.486088 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 15 |
cfdbb72e31093cefde707ac79bfdedcca74b258b | 4,681,514,373,680 | bb03ec07e1e9d2db61cbf149443181623ad9eee2 | /fuse-dv/fuse-dv-core/src/main/java/com/yangdb/fuse/executor/opensearch/logging/LoggingActionListener.java | 8891e5abf279517d7d6cc621b35e1da7c56268bb | [
"Apache-2.0"
]
| permissive | YANG-DB/yang-db | https://github.com/YANG-DB/yang-db | 9d00c7749f4b6c78eca28976e2325951c7b08808 | e662ca6c4c6aff46c556b44604e02503dacca843 | refs/heads/dev-opensearch | 2023-08-12T01:56:51.539000 | 2023-08-01T03:45:21 | 2023-08-01T03:45:21 | 177,745,239 | 108 | 5 | Apache-2.0 | false | 2023-07-12T18:08:02 | 2019-03-26T08:29:02 | 2023-05-26T02:41:24 | 2023-07-12T18:08:01 | 183,803 | 98 | 5 | 28 | Java | false | false | package com.yangdb.fuse.executor.opensearch.logging;
/*-
* #%L
* fuse-dv-core
* %%
* Copyright (C) 2016 - 2019 The YangDb Graph Database Project
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.codahale.metrics.Meter;
import com.yangdb.fuse.dispatcher.logging.LogMessage;
import org.opensearch.action.ActionListener;
import java.io.Closeable;
import java.io.IOException;
import java.util.Optional;
import java.util.function.Function;
/**
* Created by roman.margolis on 14/12/2017.
*/
public class LoggingActionListener<TResponse> implements ActionListener<TResponse> {
//region Constructors
public LoggingActionListener(
Function<TResponse, LogMessage> successMessage,
Function<Exception, LogMessage> failureMessage,
Closeable timerContext,
Meter successMeter,
Meter failureMeter) {
this.successMessage = successMessage;
this.failureMessage = failureMessage;
this.innerActionListener = Optional.empty();
this.innerFailureMessage = Optional.empty();
this.timerContext = timerContext;
this.successMeter = successMeter;
this.failureMeter = failureMeter;
}
public LoggingActionListener(
ActionListener<TResponse> innerActionListener,
Function<TResponse, LogMessage> successMessage,
Function<Exception, LogMessage> failureMessage,
Function<Exception, LogMessage> innerFailureMessage,
Closeable timerContext,
Meter successMeter,
Meter failureMeter) {
this(successMessage, failureMessage, timerContext, successMeter, failureMeter);
this.innerActionListener = Optional.ofNullable(innerActionListener);
this.innerFailureMessage = Optional.ofNullable(innerFailureMessage);
}
//endregion
//region ActionListsner Implementation
@Override
public void onResponse(TResponse tResponse) {
try {
this.timerContext.close();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
innerActionListener.ifPresent(tResponseActionListener -> tResponseActionListener.onResponse(tResponse));
} catch (Exception ex) {
innerFailureMessage.ifPresent(logMessage -> logMessage.apply(ex).log());
} finally {
this.successMessage.apply(tResponse).log();
this.successMeter.mark();
}
}
@Override
public void onFailure(Exception e) {
try {
this.timerContext.close();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
innerActionListener.ifPresent(tResponseActionListener -> tResponseActionListener.onFailure(e));
} catch (Exception ex) {
innerFailureMessage.ifPresent(logMessage -> logMessage.apply(ex).log());
} finally {
this.failureMessage.apply(e).log();
this.failureMeter.mark();
}
}
//endregion
//region Fields
private Function<TResponse, LogMessage> successMessage;
private Function<Exception, LogMessage> failureMessage;
private Closeable timerContext;
private Meter successMeter;
private Meter failureMeter;
private Optional<ActionListener<TResponse>> innerActionListener;
private Optional<Function<Exception, LogMessage>> innerFailureMessage;
//endregion
}
| UTF-8 | Java | 3,962 | java | LoggingActionListener.java | Java | [
{
"context": "rt java.util.function.Function;\n\n/**\n * Created by roman.margolis on 14/12/2017.\n */\npublic class LoggingActionList",
"end": 1011,
"score": 0.9710593223571777,
"start": 997,
"tag": "NAME",
"value": "roman.margolis"
}
]
| null | []
| package com.yangdb.fuse.executor.opensearch.logging;
/*-
* #%L
* fuse-dv-core
* %%
* Copyright (C) 2016 - 2019 The YangDb Graph Database Project
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.codahale.metrics.Meter;
import com.yangdb.fuse.dispatcher.logging.LogMessage;
import org.opensearch.action.ActionListener;
import java.io.Closeable;
import java.io.IOException;
import java.util.Optional;
import java.util.function.Function;
/**
* Created by roman.margolis on 14/12/2017.
*/
public class LoggingActionListener<TResponse> implements ActionListener<TResponse> {
//region Constructors
public LoggingActionListener(
Function<TResponse, LogMessage> successMessage,
Function<Exception, LogMessage> failureMessage,
Closeable timerContext,
Meter successMeter,
Meter failureMeter) {
this.successMessage = successMessage;
this.failureMessage = failureMessage;
this.innerActionListener = Optional.empty();
this.innerFailureMessage = Optional.empty();
this.timerContext = timerContext;
this.successMeter = successMeter;
this.failureMeter = failureMeter;
}
public LoggingActionListener(
ActionListener<TResponse> innerActionListener,
Function<TResponse, LogMessage> successMessage,
Function<Exception, LogMessage> failureMessage,
Function<Exception, LogMessage> innerFailureMessage,
Closeable timerContext,
Meter successMeter,
Meter failureMeter) {
this(successMessage, failureMessage, timerContext, successMeter, failureMeter);
this.innerActionListener = Optional.ofNullable(innerActionListener);
this.innerFailureMessage = Optional.ofNullable(innerFailureMessage);
}
//endregion
//region ActionListsner Implementation
@Override
public void onResponse(TResponse tResponse) {
try {
this.timerContext.close();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
innerActionListener.ifPresent(tResponseActionListener -> tResponseActionListener.onResponse(tResponse));
} catch (Exception ex) {
innerFailureMessage.ifPresent(logMessage -> logMessage.apply(ex).log());
} finally {
this.successMessage.apply(tResponse).log();
this.successMeter.mark();
}
}
@Override
public void onFailure(Exception e) {
try {
this.timerContext.close();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
innerActionListener.ifPresent(tResponseActionListener -> tResponseActionListener.onFailure(e));
} catch (Exception ex) {
innerFailureMessage.ifPresent(logMessage -> logMessage.apply(ex).log());
} finally {
this.failureMessage.apply(e).log();
this.failureMeter.mark();
}
}
//endregion
//region Fields
private Function<TResponse, LogMessage> successMessage;
private Function<Exception, LogMessage> failureMessage;
private Closeable timerContext;
private Meter successMeter;
private Meter failureMeter;
private Optional<ActionListener<TResponse>> innerActionListener;
private Optional<Function<Exception, LogMessage>> innerFailureMessage;
//endregion
}
| 3,962 | 0.678698 | 0.67365 | 113 | 34.061947 | 26.26963 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.566372 | false | false | 15 |
093c96675ff54932ca053898bbdd16065b5526b2 | 11,802,570,144,506 | 41e476124ab9d766d9b5cba5b1c1a789bd681bab | /src/com/company/Rectangle.java | 6a3ab1771dc76e8b853c5b5315afa03d77711f95 | []
| no_license | adaubenspeck/Pair_Programming | https://github.com/adaubenspeck/Pair_Programming | a655302d94d6e860448bffd3e071da2ceced9fce | 737555766a6723f6433697a8b4589f23a0dd3941 | refs/heads/master | 2021-01-11T03:49:15.770000 | 2016-10-19T18:24:06 | 2016-10-19T18:24:06 | 71,386,853 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
/**
* Created by ad110 on 10/19/16.
*/
public class Rectangle {
public double length;
public double width;
public double area;
public double perimeter;
public Rectangle(double x ,double y){
length = x;
width = y;
}
public double Area(){
area = length * width;
return area;
}
public double Per(){
perimeter = 2 * length + 2 * width;
return perimeter;
}
}
| UTF-8 | Java | 467 | java | Rectangle.java | Java | [
{
"context": "package com.company;\n\n/**\n * Created by ad110 on 10/19/16.\n */\npublic class Rectangle {\n pub",
"end": 45,
"score": 0.99950110912323,
"start": 40,
"tag": "USERNAME",
"value": "ad110"
}
]
| null | []
| package com.company;
/**
* Created by ad110 on 10/19/16.
*/
public class Rectangle {
public double length;
public double width;
public double area;
public double perimeter;
public Rectangle(double x ,double y){
length = x;
width = y;
}
public double Area(){
area = length * width;
return area;
}
public double Per(){
perimeter = 2 * length + 2 * width;
return perimeter;
}
}
| 467 | 0.569593 | 0.546039 | 25 | 17.68 | 12.767835 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false | 15 |
61a0755beb7925e0e3958d5d4fa41589c4dfad85 | 12,953,621,380,518 | 758ed734445b946d5f468fae90753cb89487c2b4 | /src/test/java/driver/com/repositoryTests/SponsorCRUDTest.java | 71b4ebe5e04bc3771f684729a883c0a67288c257 | []
| no_license | EdddieSims/DriverStandings | https://github.com/EdddieSims/DriverStandings | 38f03ca7bac37a231dc494baed28f7c974f6ac0c | 8d9892b9e9de539ee1bd2794f0a1b922315e4360 | refs/heads/master | 2020-12-08T01:37:25.621000 | 2016-09-02T16:40:49 | 2016-09-02T16:40:49 | 66,271,429 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package driver.com.repositoryTests;
import driver.com.App;
import driver.com.conf.factory.SponsorFactory;
import driver.com.domain.Sponsor;
import driver.com.repositories.SponsorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.testng.annotations.Test;
/**
* Created by Edmund.Simons on 2016/08/10.
*/
@SpringApplicationConfiguration(classes= App.class)
@WebAppConfiguration
public class SponsorCRUDTest extends AbstractTestNGSpringContextTests
{
private Long id;
@Autowired
private SponsorRepository repository;
Sponsor sponsor;
Sponsor readSponsor;
Sponsor updateSponsor;
@Test
public void create() throws Exception
{
sponsor = SponsorFactory.createSponsor("Petron", "Marine Blue");
this.repository.save(sponsor);
this.id = sponsor.getId();
System.out.println(this.id);
}
@Test
public void read() throws Exception
{
readSponsor = this.repository.findOne(1L);
System.out.println(readSponsor.getName());
}
@Test
public void update() throws Exception
{
sponsor = this.repository.findOne(1L);
updateSponsor = new Sponsor.Builder(sponsor.getName()).copy(sponsor).name("Petronas").logoColour("Petrol Green").build();
this.repository.save(updateSponsor);
System.out.println(updateSponsor.getName());
}
@Test
public void delete() throws Exception
{
sponsor = this.repository.findOne(1L);
this.repository.delete(sponsor);
}
}
| UTF-8 | Java | 1,765 | java | SponsorCRUDTest.java | Java | [
{
"context": "rt org.testng.annotations.Test;\n\n/**\n * Created by Edmund.Simons on 2016/08/10.\n */\n@SpringApplicationConfiguratio",
"end": 537,
"score": 0.9996805787086487,
"start": 524,
"tag": "NAME",
"value": "Edmund.Simons"
},
{
"context": "{\n sponsor = SponsorFactory.createSponsor(\"Petron\", \"Marine Blue\");\n this.repository.save(sp",
"end": 968,
"score": 0.9539487361907959,
"start": 962,
"tag": "NAME",
"value": "Petron"
},
{
"context": "sponsor = SponsorFactory.createSponsor(\"Petron\", \"Marine Blue\");\n this.repository.save(sponsor);\n ",
"end": 983,
"score": 0.9990983009338379,
"start": 972,
"tag": "NAME",
"value": "Marine Blue"
},
{
"context": "or.Builder(sponsor.getName()).copy(sponsor).name(\"Petronas\").logoColour(\"Petrol Green\").build();\n thi",
"end": 1466,
"score": 0.9988924860954285,
"start": 1458,
"tag": "NAME",
"value": "Petronas"
}
]
| null | []
| package driver.com.repositoryTests;
import driver.com.App;
import driver.com.conf.factory.SponsorFactory;
import driver.com.domain.Sponsor;
import driver.com.repositories.SponsorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.testng.annotations.Test;
/**
* Created by Edmund.Simons on 2016/08/10.
*/
@SpringApplicationConfiguration(classes= App.class)
@WebAppConfiguration
public class SponsorCRUDTest extends AbstractTestNGSpringContextTests
{
private Long id;
@Autowired
private SponsorRepository repository;
Sponsor sponsor;
Sponsor readSponsor;
Sponsor updateSponsor;
@Test
public void create() throws Exception
{
sponsor = SponsorFactory.createSponsor("Petron", "<NAME>");
this.repository.save(sponsor);
this.id = sponsor.getId();
System.out.println(this.id);
}
@Test
public void read() throws Exception
{
readSponsor = this.repository.findOne(1L);
System.out.println(readSponsor.getName());
}
@Test
public void update() throws Exception
{
sponsor = this.repository.findOne(1L);
updateSponsor = new Sponsor.Builder(sponsor.getName()).copy(sponsor).name("Petronas").logoColour("Petrol Green").build();
this.repository.save(updateSponsor);
System.out.println(updateSponsor.getName());
}
@Test
public void delete() throws Exception
{
sponsor = this.repository.findOne(1L);
this.repository.delete(sponsor);
}
}
| 1,760 | 0.721813 | 0.715581 | 61 | 27.934425 | 26.133245 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459016 | false | false | 15 |
eee97c13793fecbf0b3824fe8ea4231075c7f6d4 | 12,833,362,293,346 | b31062d3f0d0098b39f82223d348f00314283de5 | /src/main/java/com/example/excelProj/Repository/JobPaginationRepository.java | adf7df1c4f3fa10b5479e7853a2d059ebc02b0e6 | []
| no_license | ibushah/Job-Portal-Backend | https://github.com/ibushah/Job-Portal-Backend | a596e0d263cd11a32e525e4a7a064f39b8acac46 | 5dc1369ee53ed93e6b215c187cb115fb354d27e3 | refs/heads/master | 2022-07-01T02:22:54.542000 | 2020-11-06T17:35:10 | 2020-11-06T17:35:10 | 247,836,760 | 0 | 1 | null | false | 2022-05-25T23:23:37 | 2020-03-16T23:30:05 | 2020-11-06T17:36:24 | 2022-05-25T23:23:36 | 43,825 | 0 | 1 | 3 | JavaScript | false | false | package com.example.excelProj.Repository;
import com.example.excelProj.Model.Job;
//import jdk.nashorn.internal.scripts.JO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
/**
* Created by Rehan on 3/22/2020.
*/
@Repository
public interface JobPaginationRepository extends PagingAndSortingRepository<Job,Long>{
}
| UTF-8 | Java | 683 | java | JobPaginationRepository.java | Java | [
{
"context": "riable;\n\nimport java.util.List;\n\n/**\n * Created by Rehan on 3/22/2020.\n */\n@Repository\npublic interface J",
"end": 559,
"score": 0.8269046545028687,
"start": 554,
"tag": "USERNAME",
"value": "Rehan"
}
]
| null | []
| package com.example.excelProj.Repository;
import com.example.excelProj.Model.Job;
//import jdk.nashorn.internal.scripts.JO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
/**
* Created by Rehan on 3/22/2020.
*/
@Repository
public interface JobPaginationRepository extends PagingAndSortingRepository<Job,Long>{
}
| 683 | 0.828697 | 0.818448 | 23 | 28.695652 | 26.540264 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false | 15 |
28ee040a1c88001e11785524121b78e49d819045 | 4,853,313,049,920 | d6cfec44c1f3dadade1ebf63fa74d9ed5aef3c3b | /employeRestWS/src/main/java/com/demo/emp/controller/EmployeeController.java | efb82ab862b8664f6b4225676ffef3b76f5d99ca | []
| no_license | Taher1985/employeRestWS | https://github.com/Taher1985/employeRestWS | 542f087eab0aa59046a45cd2e0aaea2d0b06cade | 62920f91c915b92656fa030613933efb8c784b88 | refs/heads/master | 2020-04-22T00:13:06.408000 | 2019-02-10T14:04:43 | 2019-02-10T14:04:43 | 169,971,512 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.emp.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.demo.emp.model.Employee;
import com.demo.emp.model.EmployeeErrorResponse;
import com.demo.emp.service.EmployeeService;
@RestController
@RequestMapping("employee")
public class EmployeeController {
private static final Logger LOG = LoggerFactory.getLogger(EmployeeController.class);
private static final Integer ERORR_CODE = 1;
@Autowired
private EmployeeService employeeService;
@RequestMapping(value = "/getEmployeeList", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<Employee> getEmployeeList() throws Exception {
LOG.info("In getEmployeeList()");
Employee employee = new Employee();
List<Employee> employeesList = employeeService.getEmployeeList();
employee.setEmployeeList(employeesList);
return new ResponseEntity<Employee>(employee, HttpStatus.OK);
}
@RequestMapping(value = "/getEmployee/{employeeId}", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<Employee> getEmployee(@PathVariable String employeeId) throws Exception {
LOG.info("In getEmployee()");
Employee employee = employeeService.getEmployee(employeeId);
return new ResponseEntity<Employee>(employee, HttpStatus.OK);
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public ResponseEntity<EmployeeErrorResponse> addEmployee(@RequestBody Employee employee) throws Exception {
LOG.info("In addEmployee()");
EmployeeErrorResponse response = new EmployeeErrorResponse();
employee = employeeService.addEmployee(employee);
response.setMessage("Employee ID " + employee.getEmployeeId() + " added");
return new ResponseEntity<EmployeeErrorResponse>(response, HttpStatus.OK);
}
@RequestMapping(value = "/updateEmployee", method = RequestMethod.PUT)
public ResponseEntity<EmployeeErrorResponse> updateEmployee(@RequestBody Employee employee) throws Exception {
LOG.info("In updateEmployee()");
EmployeeErrorResponse response = new EmployeeErrorResponse();
employeeService.updateEmployee(employee);
response.setMessage("Employee ID " + employee.getEmployeeId() + " updated");
return new ResponseEntity<EmployeeErrorResponse>(response, HttpStatus.OK);
}
@RequestMapping(value = "/deleteEmployee/{employeeId}", method = RequestMethod.DELETE)
public ResponseEntity<EmployeeErrorResponse> deleteEmployee(@PathVariable String employeeId) throws Exception {
LOG.info("In deleteEmployee()");
EmployeeErrorResponse response = new EmployeeErrorResponse();
employeeService.deleteEmployee(employeeId);
response.setMessage("Employee ID " + employeeId + " deleted");
return new ResponseEntity<EmployeeErrorResponse>(response, HttpStatus.OK);
}
}
| UTF-8 | Java | 3,315 | java | EmployeeController.java | Java | []
| null | []
| package com.demo.emp.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.demo.emp.model.Employee;
import com.demo.emp.model.EmployeeErrorResponse;
import com.demo.emp.service.EmployeeService;
@RestController
@RequestMapping("employee")
public class EmployeeController {
private static final Logger LOG = LoggerFactory.getLogger(EmployeeController.class);
private static final Integer ERORR_CODE = 1;
@Autowired
private EmployeeService employeeService;
@RequestMapping(value = "/getEmployeeList", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<Employee> getEmployeeList() throws Exception {
LOG.info("In getEmployeeList()");
Employee employee = new Employee();
List<Employee> employeesList = employeeService.getEmployeeList();
employee.setEmployeeList(employeesList);
return new ResponseEntity<Employee>(employee, HttpStatus.OK);
}
@RequestMapping(value = "/getEmployee/{employeeId}", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<Employee> getEmployee(@PathVariable String employeeId) throws Exception {
LOG.info("In getEmployee()");
Employee employee = employeeService.getEmployee(employeeId);
return new ResponseEntity<Employee>(employee, HttpStatus.OK);
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public ResponseEntity<EmployeeErrorResponse> addEmployee(@RequestBody Employee employee) throws Exception {
LOG.info("In addEmployee()");
EmployeeErrorResponse response = new EmployeeErrorResponse();
employee = employeeService.addEmployee(employee);
response.setMessage("Employee ID " + employee.getEmployeeId() + " added");
return new ResponseEntity<EmployeeErrorResponse>(response, HttpStatus.OK);
}
@RequestMapping(value = "/updateEmployee", method = RequestMethod.PUT)
public ResponseEntity<EmployeeErrorResponse> updateEmployee(@RequestBody Employee employee) throws Exception {
LOG.info("In updateEmployee()");
EmployeeErrorResponse response = new EmployeeErrorResponse();
employeeService.updateEmployee(employee);
response.setMessage("Employee ID " + employee.getEmployeeId() + " updated");
return new ResponseEntity<EmployeeErrorResponse>(response, HttpStatus.OK);
}
@RequestMapping(value = "/deleteEmployee/{employeeId}", method = RequestMethod.DELETE)
public ResponseEntity<EmployeeErrorResponse> deleteEmployee(@PathVariable String employeeId) throws Exception {
LOG.info("In deleteEmployee()");
EmployeeErrorResponse response = new EmployeeErrorResponse();
employeeService.deleteEmployee(employeeId);
response.setMessage("Employee ID " + employeeId + " deleted");
return new ResponseEntity<EmployeeErrorResponse>(response, HttpStatus.OK);
}
}
| 3,315 | 0.78371 | 0.782805 | 72 | 44.041668 | 32.472397 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.638889 | false | false | 1 |
a254a941688bf759c00260ba24aa1a189ed8d9c3 | 5,119,601,024,570 | a6c1654f36486efc91989ccd09d9ef5088200667 | /server-learning/src/main/java/com/server/learning/security/SecurityFilter.java | 41e96944b6ff0c0cf198d649e4b542b07ffeb5f5 | []
| no_license | yosuawilly/latihanTapestry | https://github.com/yosuawilly/latihanTapestry | 521f69fc807bc7a35b31ae5dd4ec692e4ac7e8a5 | c1723917d1c6ec5bf1681135bf2758347f3dce99 | refs/heads/master | 2020-05-04T21:53:05.790000 | 2014-07-04T10:07:11 | 2014-07-04T10:07:11 | 19,565,301 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.server.learning.security;
import java.io.IOException;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.runtime.Component;
import org.apache.tapestry5.services.ComponentEventRequestParameters;
import org.apache.tapestry5.services.ComponentRequestFilter;
import org.apache.tapestry5.services.ComponentRequestHandler;
import org.apache.tapestry5.services.ComponentSource;
import org.apache.tapestry5.services.PageRenderLinkSource;
import org.apache.tapestry5.services.PageRenderRequestParameters;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestGlobals;
import org.apache.tapestry5.services.Response;
import com.server.learning.annotations.PublicPage;
import com.server.learning.pages.Home;
import com.server.learning.pages.Index;
import com.server.learning.pages.Login;
import com.server.learning.services.Authenticator;
public class SecurityFilter implements ComponentRequestFilter{
private final PageRenderLinkSource renderLinkSource;
private final ComponentSource componentSource;
private final Response response;
private final Request request;
private final RequestGlobals requestGlobals;
private final Authenticator authenticator;
private String homePage = Home.class.getSimpleName();
private String loginPage = Login.class.getSimpleName();
public SecurityFilter(PageRenderLinkSource renderLinkSource, ComponentSource componentSource,
Response response, Request request, RequestGlobals requestGlobals, Authenticator authenticator) {
this.renderLinkSource = renderLinkSource;
this.componentSource = componentSource;
this.response = response;
this.request = request;
this.requestGlobals = requestGlobals;
this.authenticator = authenticator;
}
@Override
public void handleComponentEvent(
ComponentEventRequestParameters parameters,
ComponentRequestHandler handler) throws IOException {
if(dispatchedToLoginPage(parameters.getActivePageName())) return;
handler.handleComponentEvent(parameters);
}
@Override
public void handlePageRender(PageRenderRequestParameters parameters,
ComponentRequestHandler handler) throws IOException {
if(dispatchedToLoginPage(parameters.getLogicalPageName())) return;
handler.handlePageRender(parameters);
}
private boolean dispatchedToLoginPage(String pageName) throws IOException{
if(authenticator.isLoggedIn()){
if(pageName.equalsIgnoreCase(loginPage) || pageName.equalsIgnoreCase(Index.class.getSimpleName())){
Link link = renderLinkSource.createPageRenderLink(homePage);
response.sendRedirect(link);
return true;
}
return false;
}
Component page = componentSource.getPage(pageName);
if(page.getClass().isAnnotationPresent(PublicPage.class)) return false;
Link link = renderLinkSource.createPageRenderLink("Login");
response.sendRedirect(link);
return true;
}
}
| UTF-8 | Java | 2,967 | java | SecurityFilter.java | Java | []
| null | []
| package com.server.learning.security;
import java.io.IOException;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.runtime.Component;
import org.apache.tapestry5.services.ComponentEventRequestParameters;
import org.apache.tapestry5.services.ComponentRequestFilter;
import org.apache.tapestry5.services.ComponentRequestHandler;
import org.apache.tapestry5.services.ComponentSource;
import org.apache.tapestry5.services.PageRenderLinkSource;
import org.apache.tapestry5.services.PageRenderRequestParameters;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestGlobals;
import org.apache.tapestry5.services.Response;
import com.server.learning.annotations.PublicPage;
import com.server.learning.pages.Home;
import com.server.learning.pages.Index;
import com.server.learning.pages.Login;
import com.server.learning.services.Authenticator;
public class SecurityFilter implements ComponentRequestFilter{
private final PageRenderLinkSource renderLinkSource;
private final ComponentSource componentSource;
private final Response response;
private final Request request;
private final RequestGlobals requestGlobals;
private final Authenticator authenticator;
private String homePage = Home.class.getSimpleName();
private String loginPage = Login.class.getSimpleName();
public SecurityFilter(PageRenderLinkSource renderLinkSource, ComponentSource componentSource,
Response response, Request request, RequestGlobals requestGlobals, Authenticator authenticator) {
this.renderLinkSource = renderLinkSource;
this.componentSource = componentSource;
this.response = response;
this.request = request;
this.requestGlobals = requestGlobals;
this.authenticator = authenticator;
}
@Override
public void handleComponentEvent(
ComponentEventRequestParameters parameters,
ComponentRequestHandler handler) throws IOException {
if(dispatchedToLoginPage(parameters.getActivePageName())) return;
handler.handleComponentEvent(parameters);
}
@Override
public void handlePageRender(PageRenderRequestParameters parameters,
ComponentRequestHandler handler) throws IOException {
if(dispatchedToLoginPage(parameters.getLogicalPageName())) return;
handler.handlePageRender(parameters);
}
private boolean dispatchedToLoginPage(String pageName) throws IOException{
if(authenticator.isLoggedIn()){
if(pageName.equalsIgnoreCase(loginPage) || pageName.equalsIgnoreCase(Index.class.getSimpleName())){
Link link = renderLinkSource.createPageRenderLink(homePage);
response.sendRedirect(link);
return true;
}
return false;
}
Component page = componentSource.getPage(pageName);
if(page.getClass().isAnnotationPresent(PublicPage.class)) return false;
Link link = renderLinkSource.createPageRenderLink("Login");
response.sendRedirect(link);
return true;
}
}
| 2,967 | 0.793057 | 0.789349 | 82 | 34.182926 | 26.903227 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.865854 | false | false | 1 |
0b7a376f4eab0d9f59fc659903ab14adde7ee716 | 8,246,337,213,183 | efe7b37995773f0e6821a796d66e9c60c6ba1a28 | /家庭记账本系统/webfinalexam后台/webfinalexam/src/test/java/com/finalexam/webfinalexam/dao/FamilyMemberDaoTest.java | ddfe5cca918cd4bb1cbc00a47353aef300bff72d | []
| no_license | HuirongZhang/JavaWeb | https://github.com/HuirongZhang/JavaWeb | 5fd87f2cb5df06edc24ae9b8eabb373f301a230b | 80cf49b73769b845a4a3f3c86ab2aece6a5e3fb5 | refs/heads/master | 2020-03-11T12:40:29.506000 | 2019-09-25T01:54:03 | 2019-09-25T01:54:03 | 130,003,841 | 0 | 0 | null | false | 2020-04-02T04:11:30 | 2018-04-18T04:29:41 | 2019-09-25T01:54:06 | 2020-04-02T04:11:30 | 24,588 | 0 | 0 | 0 | Java | false | false | package com.finalexam.webfinalexam.dao;
import com.finalexam.webfinalexam.entity.FamilyMember;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class FamilyMemberDaoTest {
@Autowired
private FamilyMemberDao familyMemberDao;
@Test
@Ignore
public void queryFamilyMember() {
List<FamilyMember> familyMemberList=familyMemberDao.queryFamilyMember(2);
assertEquals(1,familyMemberList.size());
}
@Test
@Ignore
public void queryFamilyMemberById() {
FamilyMember familyMember=familyMemberDao.queryFamilyMemberById(2,1);
assertEquals("小明",familyMember.getMemberName());
}
@Test
@Ignore
public void insertFamilyMember() {
FamilyMember familyMember=new FamilyMember();
familyMember.setFamilyId(2);
familyMember.setMemberName("大白");
familyMember.setMemberSex("男");
familyMember.setMemberJob("教师");
familyMember.setMemberWages("7000");
int effectedNum=familyMemberDao.insertFamilyMember(familyMember);
assertEquals(1,effectedNum);
}
@Test
@Ignore
public void updateFamilyMember() {
FamilyMember familyMember=new FamilyMember();
familyMember.setFamilyId(2);
familyMember.setMemberId(1);
familyMember.setMemberWages("15000");
int effectedNum=familyMemberDao.updateFamilyMember(familyMember);
assertEquals(1,effectedNum);
}
@Test
@Ignore
public void deleteFamilyMember() {
int effectedNum=familyMemberDao.deleteFamilyMember(2,2);
assertEquals(1,effectedNum);
}
} | UTF-8 | Java | 1,942 | java | FamilyMemberDaoTest.java | Java | [
{
"context": "queryFamilyMemberById(2,1);\n assertEquals(\"小明\",familyMember.getMemberName());\n }\n\n @Test\n",
"end": 927,
"score": 0.9980377554893494,
"start": 925,
"tag": "NAME",
"value": "小明"
},
{
"context": "tFamilyId(2);\n familyMember.setMemberName(\"大白\");\n familyMember.setMemberSex(\"男\");\n ",
"end": 1157,
"score": 0.9988532662391663,
"start": 1155,
"tag": "NAME",
"value": "大白"
}
]
| null | []
| package com.finalexam.webfinalexam.dao;
import com.finalexam.webfinalexam.entity.FamilyMember;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class FamilyMemberDaoTest {
@Autowired
private FamilyMemberDao familyMemberDao;
@Test
@Ignore
public void queryFamilyMember() {
List<FamilyMember> familyMemberList=familyMemberDao.queryFamilyMember(2);
assertEquals(1,familyMemberList.size());
}
@Test
@Ignore
public void queryFamilyMemberById() {
FamilyMember familyMember=familyMemberDao.queryFamilyMemberById(2,1);
assertEquals("小明",familyMember.getMemberName());
}
@Test
@Ignore
public void insertFamilyMember() {
FamilyMember familyMember=new FamilyMember();
familyMember.setFamilyId(2);
familyMember.setMemberName("大白");
familyMember.setMemberSex("男");
familyMember.setMemberJob("教师");
familyMember.setMemberWages("7000");
int effectedNum=familyMemberDao.insertFamilyMember(familyMember);
assertEquals(1,effectedNum);
}
@Test
@Ignore
public void updateFamilyMember() {
FamilyMember familyMember=new FamilyMember();
familyMember.setFamilyId(2);
familyMember.setMemberId(1);
familyMember.setMemberWages("15000");
int effectedNum=familyMemberDao.updateFamilyMember(familyMember);
assertEquals(1,effectedNum);
}
@Test
@Ignore
public void deleteFamilyMember() {
int effectedNum=familyMemberDao.deleteFamilyMember(2,2);
assertEquals(1,effectedNum);
}
} | 1,942 | 0.718361 | 0.70695 | 65 | 28.676924 | 22.647879 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584615 | false | false | 1 |
46fbeae7cafb51278ee0e56223e59dc68a0bc2d9 | 14,955,076,130,596 | 99bf31f4c9d5c2f483eb0af074d7afb5f61f90f0 | /src/main/java/VerPublicacionesUI.java | ad4b091339fb5fba035ab4d0cf5ca6a2ad4a2f7c | []
| no_license | Neury0102/clientefinalweb | https://github.com/Neury0102/clientefinalweb | f45fd0ee4a3889a326785dad9ff3ddd0f1fc2f91 | a35f5c1f290f9e138b728fa8ef9f4aeefc57137f | refs/heads/master | 2021-01-19T04:13:41.431000 | 2016-07-21T19:05:06 | 2016-07-21T19:05:06 | 63,811,994 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Created by saleta on 7/21/2016.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
public class VerPublicacionesUI extends JFrame {
Cliente c = new Cliente();
Cliente.PublicacionInfo[] publicaciones = c.getPublicaciones();
JList publicacionesList;
public VerPublicacionesUI() throws IOException {
setSize(new Dimension(414, 344));
getContentPane().setLayout(null);
DefaultListModel<Cliente.PublicacionInfo> model = new DefaultListModel<>();
publicacionesList = new JList(model);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(112, 44, 146, 159);
getContentPane().add(scrollPane);
scrollPane.setViewportView(publicacionesList);
for (Cliente.PublicacionInfo p : publicaciones){
model.addElement(p);
}
JButton btnVerPublicacion = new JButton("Ver Publicaci\u00F3n");
btnVerPublicacion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Cliente.PublicacionInfo p = (Cliente.PublicacionInfo)publicacionesList.getSelectedValue();
DetallePublicacionUI dp = null;
try {
dp = new DetallePublicacionUI(p);
} catch (IOException e) {
e.printStackTrace();
}
dp.setVisible(true);
}
});
btnVerPublicacion.setBounds(102, 247, 173, 25);
getContentPane().add(btnVerPublicacion);
JLabel lblPublicacionesDisponibles = new JLabel("Publicaciones Disponibles");
lblPublicacionesDisponibles.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPublicacionesDisponibles.setBounds(102, 15, 237, 16);
getContentPane().add(lblPublicacionesDisponibles);
}
}
| UTF-8 | Java | 1,931 | java | VerPublicacionesUI.java | Java | [
{
"context": "/**\n * Created by saleta on 7/21/2016.\n */\nimport javax.swing.*;\nimport ja",
"end": 24,
"score": 0.9871827363967896,
"start": 18,
"tag": "USERNAME",
"value": "saleta"
}
]
| null | []
| /**
* Created by saleta on 7/21/2016.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
public class VerPublicacionesUI extends JFrame {
Cliente c = new Cliente();
Cliente.PublicacionInfo[] publicaciones = c.getPublicaciones();
JList publicacionesList;
public VerPublicacionesUI() throws IOException {
setSize(new Dimension(414, 344));
getContentPane().setLayout(null);
DefaultListModel<Cliente.PublicacionInfo> model = new DefaultListModel<>();
publicacionesList = new JList(model);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(112, 44, 146, 159);
getContentPane().add(scrollPane);
scrollPane.setViewportView(publicacionesList);
for (Cliente.PublicacionInfo p : publicaciones){
model.addElement(p);
}
JButton btnVerPublicacion = new JButton("Ver Publicaci\u00F3n");
btnVerPublicacion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Cliente.PublicacionInfo p = (Cliente.PublicacionInfo)publicacionesList.getSelectedValue();
DetallePublicacionUI dp = null;
try {
dp = new DetallePublicacionUI(p);
} catch (IOException e) {
e.printStackTrace();
}
dp.setVisible(true);
}
});
btnVerPublicacion.setBounds(102, 247, 173, 25);
getContentPane().add(btnVerPublicacion);
JLabel lblPublicacionesDisponibles = new JLabel("Publicaciones Disponibles");
lblPublicacionesDisponibles.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPublicacionesDisponibles.setBounds(102, 15, 237, 16);
getContentPane().add(lblPublicacionesDisponibles);
}
}
| 1,931 | 0.649922 | 0.623511 | 50 | 37.619999 | 25.667793 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.84 | false | false | 1 |
7e5358e377ef228d6d78cdcbdd02daabf1978301 | 32,126,355,381,065 | 73f69976ebead45996c2e12436466052f761adfb | /login/src/main/java/com/gongw/login/LoginService.java | 4266a0c069f67eaba66e8eb033012f57890c65bf | []
| no_license | GSIL-Monitor/WMail | https://github.com/GSIL-Monitor/WMail | 6fb39d40c16fa600a20a87eed203d5b4799e7378 | da4db85672e9f8072346a077b4fc7e69ac282a13 | refs/heads/master | 2020-04-19T08:23:36.036000 | 2018-10-16T14:07:47 | 2018-10-16T14:07:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gongw.login;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gongw.router.provider.ILoginProvider;
/**
* Created by gongw on 2018/7/10.
*/
@Route(path = ILoginProvider.ROUTER_PATH_TO_LOGIN_SERVICE, name = "login")
public class LoginService implements ILoginProvider {
@Override
public void init(Context context) {}
@Override
public void goToLogin(Activity activity) {
Intent intent = new Intent(activity, LoginActivity.class);
activity.startActivity(intent);
}
}
| UTF-8 | Java | 636 | java | LoginService.java | Java | [
{
"context": "router.provider.ILoginProvider;\n\n/**\n * Created by gongw on 2018/7/10.\n */\n\n@Route(path = ILoginProvider.R",
"end": 252,
"score": 0.999683141708374,
"start": 247,
"tag": "USERNAME",
"value": "gongw"
}
]
| null | []
| package com.gongw.login;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gongw.router.provider.ILoginProvider;
/**
* Created by gongw on 2018/7/10.
*/
@Route(path = ILoginProvider.ROUTER_PATH_TO_LOGIN_SERVICE, name = "login")
public class LoginService implements ILoginProvider {
@Override
public void init(Context context) {}
@Override
public void goToLogin(Activity activity) {
Intent intent = new Intent(activity, LoginActivity.class);
activity.startActivity(intent);
}
}
| 636 | 0.737421 | 0.726415 | 27 | 22.555555 | 23.268694 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37037 | false | false | 1 |
df8e26ef83f40a0f6097718de014210b1e46aedb | 10,943,576,683,651 | 29aa17ddb82b55f940018906147de21471d0faf7 | /jwd-task01-template/src/main/java/by/tc/task02/service/client/AddingClientService.java | 1bd79eafe164faf678005609f489c752b53a06a6 | []
| no_license | MikhailNavitski/Task2 | https://github.com/MikhailNavitski/Task2 | c4bd6df2814d3c7ebf865582224b7af0a0ef9479 | 1048e59f02d5956b490ae8bed0fb383d04f83d5c | refs/heads/master | 2021-09-06T09:10:25.583000 | 2018-02-04T20:30:10 | 2018-02-04T20:30:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.tc.task02.service.client;
import by.tc.task02.entity.Renter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class AddingClientService {
public static Renter createRenter() throws IOException {
Renter renter = new Renter();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Введите ваше имя");
String name = reader.readLine();
renter.setName(name);
renter.setAvailableItems(3);
return renter;
}
}
| UTF-8 | Java | 590 | java | AddingClientService.java | Java | []
| null | []
| package by.tc.task02.service.client;
import by.tc.task02.entity.Renter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class AddingClientService {
public static Renter createRenter() throws IOException {
Renter renter = new Renter();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Введите ваше имя");
String name = reader.readLine();
renter.setName(name);
renter.setAvailableItems(3);
return renter;
}
}
| 590 | 0.704861 | 0.696181 | 20 | 27.799999 | 21.816507 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 1 |
d543c9e05be8ac23ff9f7c03f9d8f6c0ec07a73d | 26,096,221,303,558 | 30ad19c2eaab9f595f9977f22135934a98f0e270 | /src/main/java/dataStructures/sets/WeightedIntervalScheduling.java | b55a2baa7783d460f1fa5b2aaf7381564a81cfb5 | []
| no_license | pedrohfsd/dataStructures | https://github.com/pedrohfsd/dataStructures | 256cd6c5cedd618df89b5e01f1846b34ca1c9a29 | c5fef267d1d08426719a28bc6c8dacd997a7ac43 | refs/heads/master | 2016-06-04T23:39:21.695000 | 2015-10-19T19:16:33 | 2015-10-19T19:16:33 | 43,705,984 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dataStructures.sets;
public class WeightedIntervalScheduling {
public static double findMaximumCost(SchedulableFacade facade){
double[] cache = WeightedIntervalScheduling.buildCache(facade.getMinStartTime(), facade.getMaxEndTime());
return doFindMaximumCost(cache, facade, facade.getMaxEndTime());
}
private static double doFindMaximumCost(double[] cache, SchedulableFacade facade, int currTime){
if(facade.getMinStartTime()>currTime) return 0;
if(cache[currTime-facade.getMinStartTime()] != -1) return cache[currTime-facade.getMinStartTime()];
SchedulableInterval[] intervals = facade.getNextEndingAt(currTime);
double max = -1;
for(SchedulableInterval interval : intervals){
double ret = interval.getCost()+doFindMaximumCost(cache, facade, currTime-interval.getDuration());
if(max<ret)max = ret;
}
double ret = doFindMaximumCost(cache, facade, currTime-1);
if(max<ret)max = ret;
cache[currTime-facade.getMinStartTime()] = max;
return max;
}
public static double[] buildCache(int minStartTime, int maxEndTime){
double[] cache = new double[maxEndTime-minStartTime+1];
for (int i = 0; i < cache.length; i++) {
cache[i] = -1;
}
return cache;
}
public static interface SchedulableInterval{
public int getDuration();
public int getCost();
// public SchedulableInterval[] getNextValid();
}
public static interface SchedulableFacade{
public int getMinStartTime();
public int getMaxEndTime();
public SchedulableInterval[] getNextEndingAt(int time);
}
}
| UTF-8 | Java | 1,573 | java | WeightedIntervalScheduling.java | Java | []
| null | []
| package dataStructures.sets;
public class WeightedIntervalScheduling {
public static double findMaximumCost(SchedulableFacade facade){
double[] cache = WeightedIntervalScheduling.buildCache(facade.getMinStartTime(), facade.getMaxEndTime());
return doFindMaximumCost(cache, facade, facade.getMaxEndTime());
}
private static double doFindMaximumCost(double[] cache, SchedulableFacade facade, int currTime){
if(facade.getMinStartTime()>currTime) return 0;
if(cache[currTime-facade.getMinStartTime()] != -1) return cache[currTime-facade.getMinStartTime()];
SchedulableInterval[] intervals = facade.getNextEndingAt(currTime);
double max = -1;
for(SchedulableInterval interval : intervals){
double ret = interval.getCost()+doFindMaximumCost(cache, facade, currTime-interval.getDuration());
if(max<ret)max = ret;
}
double ret = doFindMaximumCost(cache, facade, currTime-1);
if(max<ret)max = ret;
cache[currTime-facade.getMinStartTime()] = max;
return max;
}
public static double[] buildCache(int minStartTime, int maxEndTime){
double[] cache = new double[maxEndTime-minStartTime+1];
for (int i = 0; i < cache.length; i++) {
cache[i] = -1;
}
return cache;
}
public static interface SchedulableInterval{
public int getDuration();
public int getCost();
// public SchedulableInterval[] getNextValid();
}
public static interface SchedulableFacade{
public int getMinStartTime();
public int getMaxEndTime();
public SchedulableInterval[] getNextEndingAt(int time);
}
}
| 1,573 | 0.725366 | 0.720915 | 45 | 32.955555 | 30.97953 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.266667 | false | false | 1 |
848205056a05fd7e125e751ff2e3a4d276352687 | 14,525,579,411,741 | 1c4baa143d3022c14f436b3dfca38fd7d299d4d3 | /src/main/java/jp/co/flect/heroku/platformapi/model/AccountFeature.java | 743b35a80cbb691ee0c546ec8de490b5bad572bf | [
"MIT"
]
| permissive | mateusz-fiolka/heroku-platform-api | https://github.com/mateusz-fiolka/heroku-platform-api | 8a402f0ee277dcb35843a220d767c4e1f68e7200 | 8188f855f60f966ab331224ee3e9f19a1681dd79 | refs/heads/master | 2018-05-13T02:28:26.845000 | 2015-12-17T13:34:04 | 2015-12-17T13:34:04 | 48,161,545 | 0 | 1 | null | true | 2015-12-17T08:18:01 | 2015-12-17T08:17:58 | 2015-12-17T08:17:59 | 2014-03-26T02:25:47 | 336 | 0 | 0 | 0 | Java | null | null | package jp.co.flect.heroku.platformapi.model;
import java.util.Map;
public class AccountFeature extends Feature {
public AccountFeature() {
super();
}
public AccountFeature(Map<String, Object> map) {
super(map);
}
}
| UTF-8 | Java | 232 | java | AccountFeature.java | Java | []
| null | []
| package jp.co.flect.heroku.platformapi.model;
import java.util.Map;
public class AccountFeature extends Feature {
public AccountFeature() {
super();
}
public AccountFeature(Map<String, Object> map) {
super(map);
}
}
| 232 | 0.711207 | 0.711207 | 15 | 14.466666 | 17.719543 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.066667 | false | false | 1 |
c371e2a88b42c2958c22b7694501cd93a4ee84dd | 28,793,460,765,277 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/23/23_c66fd1fb132d6eea4cb8245282adc4862467b9a7/GenericElectric/23_c66fd1fb132d6eea4cb8245282adc4862467b9a7_GenericElectric_s.java | b8f4d04ceba872d6a7a99f5cdcd0e88a4671ce59 | []
| no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | package assets.tacotek.Items;
import ic2.api.item.ElectricItem;
import ic2.api.item.IElectricItem;
import java.util.List;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import assets.tacotek.common.tacotek;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public abstract class GenericElectric extends Item implements IElectricItem {
private boolean canGiveEnergy = false;
private int maxCharge = 1337;
private int tier = 1;
private int transferLimit;
public GenericElectric(int id) {
this(id, 10000, 2, 100);
}
public GenericElectric(int id, int max, int teir, int transferMax) {
super(id);
this.setCreativeTab(tacotek.tacotekTab);
this.maxCharge = max;
this.tier = teir;
this.transferLimit = transferMax;
this.setMaxStackSize(1);
this.setMaxDamage(100);
this.canRepair = false;
}
/**
* @param stack the itemStack which is being used.
* @param i the amount of power which is to be used.
* @return returns true if the item has enough power, as specified.
*/
protected boolean canTakeDamage(ItemStack stack, int i) {
return ElectricItem.manager.discharge(stack, i, 0x7fffffff, true, true) == i;
}
/**
* @param stack the itemStack which was used.
* @param i the amount of power to use.
* @param player the player which is using the item.
*/
protected void damage(ItemStack stack, int i, EntityPlayer player) {
ElectricItem.manager.use(stack, i, player);
}
@SideOnly(Side.CLIENT)
public void getSubItems(int var1, CreativeTabs var2, List var3) {
ItemStack tCharged = new ItemStack(this, 1), tUncharged = new ItemStack(this, 1, getMaxDamage());
ElectricItem.manager.charge(tCharged, Integer.MAX_VALUE, Integer.MAX_VALUE, true, false);
var3.add(tCharged);
var3.add(tUncharged);
}
@Override
public boolean canProvideEnergy(ItemStack itemStack) {
return this.canGiveEnergy;
}
@Override
public int getChargedItemId(ItemStack itemStack) {
return this.itemID;
}
@Override
public int getEmptyItemId(ItemStack itemStack) {
return this.itemID;
}
@Override
public int getMaxCharge(ItemStack itemStack) {
return this.maxCharge;
}
@Override
public int getTier(ItemStack itemStack) {
return this.tier;
}
@Override
public int getTransferLimit(ItemStack itemStack) {
return this.transferLimit;
}
}
| UTF-8 | Java | 2,588 | java | 23_c66fd1fb132d6eea4cb8245282adc4862467b9a7_GenericElectric_s.java | Java | []
| null | []
| package assets.tacotek.Items;
import ic2.api.item.ElectricItem;
import ic2.api.item.IElectricItem;
import java.util.List;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import assets.tacotek.common.tacotek;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public abstract class GenericElectric extends Item implements IElectricItem {
private boolean canGiveEnergy = false;
private int maxCharge = 1337;
private int tier = 1;
private int transferLimit;
public GenericElectric(int id) {
this(id, 10000, 2, 100);
}
public GenericElectric(int id, int max, int teir, int transferMax) {
super(id);
this.setCreativeTab(tacotek.tacotekTab);
this.maxCharge = max;
this.tier = teir;
this.transferLimit = transferMax;
this.setMaxStackSize(1);
this.setMaxDamage(100);
this.canRepair = false;
}
/**
* @param stack the itemStack which is being used.
* @param i the amount of power which is to be used.
* @return returns true if the item has enough power, as specified.
*/
protected boolean canTakeDamage(ItemStack stack, int i) {
return ElectricItem.manager.discharge(stack, i, 0x7fffffff, true, true) == i;
}
/**
* @param stack the itemStack which was used.
* @param i the amount of power to use.
* @param player the player which is using the item.
*/
protected void damage(ItemStack stack, int i, EntityPlayer player) {
ElectricItem.manager.use(stack, i, player);
}
@SideOnly(Side.CLIENT)
public void getSubItems(int var1, CreativeTabs var2, List var3) {
ItemStack tCharged = new ItemStack(this, 1), tUncharged = new ItemStack(this, 1, getMaxDamage());
ElectricItem.manager.charge(tCharged, Integer.MAX_VALUE, Integer.MAX_VALUE, true, false);
var3.add(tCharged);
var3.add(tUncharged);
}
@Override
public boolean canProvideEnergy(ItemStack itemStack) {
return this.canGiveEnergy;
}
@Override
public int getChargedItemId(ItemStack itemStack) {
return this.itemID;
}
@Override
public int getEmptyItemId(ItemStack itemStack) {
return this.itemID;
}
@Override
public int getMaxCharge(ItemStack itemStack) {
return this.maxCharge;
}
@Override
public int getTier(ItemStack itemStack) {
return this.tier;
}
@Override
public int getTransferLimit(ItemStack itemStack) {
return this.transferLimit;
}
}
| 2,588 | 0.703246 | 0.69204 | 95 | 26.231579 | 24.395191 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.473684 | false | false | 1 |
8b4322b615b518537ce6c4f36191d9a4a2e8bdf6 | 24,902,220,398,814 | 36eb8971247ddc846c650400f5499d8f06e70ca4 | /domain/src/main/java/com/example/android/domain/entity/company/Company.java | ad138076e473305641b02800e2339487ea009479 | []
| no_license | RomanNikonovich/sudries_2 | https://github.com/RomanNikonovich/sudries_2 | 490c7ccb01e00b35d76f22a7f04b4fb7f7c8b664 | 87c036a5cddee5c0441a83b9f6e7b3a935d72400 | refs/heads/master | 2020-03-14T11:49:22.412000 | 2018-04-30T13:17:41 | 2018-04-30T13:17:41 | 131,597,761 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android.domain.entity.company;
import java.util.ArrayList;
import java.util.List;
public class Company {
private String name = null, location = null;
private int baseSalary = 0;
private List<Employee> employees = new ArrayList<>();
@Override
public String toString() {
return "Company{" +
"name='" + name + '\'' +
", location='" + location + '\'' +
", baseSalary=" + baseSalary +
", employees=" + employees +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Company company = (Company) o;
if (name != null ? !name.equals(company.name) : company.name != null) return false;
return location != null ? location.equals(company.location) : company.location == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (location != null ? location.hashCode() : 0);
return result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getBaseSalary() {
return baseSalary;
}
public void setBaseSalary(int baseSalary) {
this.baseSalary = baseSalary;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
} | UTF-8 | Java | 1,769 | java | Company.java | Java | []
| null | []
| package com.example.android.domain.entity.company;
import java.util.ArrayList;
import java.util.List;
public class Company {
private String name = null, location = null;
private int baseSalary = 0;
private List<Employee> employees = new ArrayList<>();
@Override
public String toString() {
return "Company{" +
"name='" + name + '\'' +
", location='" + location + '\'' +
", baseSalary=" + baseSalary +
", employees=" + employees +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Company company = (Company) o;
if (name != null ? !name.equals(company.name) : company.name != null) return false;
return location != null ? location.equals(company.location) : company.location == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (location != null ? location.hashCode() : 0);
return result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getBaseSalary() {
return baseSalary;
}
public void setBaseSalary(int baseSalary) {
this.baseSalary = baseSalary;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
} | 1,769 | 0.569813 | 0.566987 | 70 | 24.285715 | 22.810488 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.414286 | false | false | 1 |
749af290104648a8a769cffcf96d8028a527d511 | 24,850,680,795,521 | 6ceab086aae653e1bc1651ec18230e7a846804a5 | /src/main/java/net/ftlines/css/scoper/wicket/WicketPanelMarkupTransformer.java | 5b4880109aa2365855310b4b0f8d724d378996a9 | []
| no_license | 42Lines/wicket-css-scope | https://github.com/42Lines/wicket-css-scope | 57b868742dd01f6dcd1674c4d3ae5eb57ba138ae | 9465a259844de7c8de295642009ab6aa3f8411eb | refs/heads/master | 2023-09-04T20:01:52.059000 | 2022-09-02T10:48:24 | 2022-09-02T10:48:24 | 236,817,477 | 2 | 0 | null | false | 2023-08-15T17:43:36 | 2020-01-28T19:09:31 | 2022-09-02T10:48:27 | 2022-09-02T10:48:32 | 110 | 2 | 0 | 1 | Java | false | false | package net.ftlines.css.scoper.wicket;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import net.ftlines.css.scoper.PanelizedMarkupTransformer;
import net.ftlines.css.scoper.ScopedFragmentResult;
public class WicketPanelMarkupTransformer implements PanelizedMarkupTransformer {
private String sourceInput;
public WicketPanelMarkupTransformer(String sourceInput) {
this.sourceInput = sourceInput;
}
public String getSourceInput() {
return sourceInput;
}
@Override
public String apply(ScopedFragmentResult compiledFragments) {
return "<html xmlns:wicket>\n" //
+ composeHead(compiledFragments) //
+ composeBody(compiledFragments) //
+ "</html>"; //
}
protected String getWicketTag() {
return "wicket:panel";
}
protected String composeBody(ScopedFragmentResult compiledFragments) {
StringBuffer buffer = new StringBuffer();
buffer.append("<"+getWicketTag()+">").append("\n");
buffer.append(compiledFragments.getScopedMarkup()).append("\n");
buffer.append("</"+getWicketTag()+">").append("\n");
return buffer.toString();
}
protected String composeHead(ScopedFragmentResult compiledFragments) {
String head = composeStyle(compiledFragments).strip() + getOtherNonStyleHeadElements().strip();
if(head.length() > 0) {
return "<wicket:head>" + head + "</wicket:head>";
}
return "";
}
protected String composeStyle(ScopedFragmentResult compiledFragments) {
StringBuffer buffer = new StringBuffer();
buffer.append("<style compiled=\"true\">").append("\n");
buffer.append(compiledFragments.getScopedCss()).append("\n");
buffer.append("</style>").append("\n\n");
return buffer.toString();
}
protected String getOtherNonStyleHeadElements() {
if(!sourceInput.toLowerCase().contains("wicket:head"))
return "";
Document doc = Jsoup.parseBodyFragment(sourceInput);
Elements headTags = doc.getElementsByTag("wicket:head");
headTags.select("style:not([ignore_compile])").remove();
return headTags.get(0).html();
}
}
| UTF-8 | Java | 2,049 | java | WicketPanelMarkupTransformer.java | Java | []
| null | []
| package net.ftlines.css.scoper.wicket;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import net.ftlines.css.scoper.PanelizedMarkupTransformer;
import net.ftlines.css.scoper.ScopedFragmentResult;
public class WicketPanelMarkupTransformer implements PanelizedMarkupTransformer {
private String sourceInput;
public WicketPanelMarkupTransformer(String sourceInput) {
this.sourceInput = sourceInput;
}
public String getSourceInput() {
return sourceInput;
}
@Override
public String apply(ScopedFragmentResult compiledFragments) {
return "<html xmlns:wicket>\n" //
+ composeHead(compiledFragments) //
+ composeBody(compiledFragments) //
+ "</html>"; //
}
protected String getWicketTag() {
return "wicket:panel";
}
protected String composeBody(ScopedFragmentResult compiledFragments) {
StringBuffer buffer = new StringBuffer();
buffer.append("<"+getWicketTag()+">").append("\n");
buffer.append(compiledFragments.getScopedMarkup()).append("\n");
buffer.append("</"+getWicketTag()+">").append("\n");
return buffer.toString();
}
protected String composeHead(ScopedFragmentResult compiledFragments) {
String head = composeStyle(compiledFragments).strip() + getOtherNonStyleHeadElements().strip();
if(head.length() > 0) {
return "<wicket:head>" + head + "</wicket:head>";
}
return "";
}
protected String composeStyle(ScopedFragmentResult compiledFragments) {
StringBuffer buffer = new StringBuffer();
buffer.append("<style compiled=\"true\">").append("\n");
buffer.append(compiledFragments.getScopedCss()).append("\n");
buffer.append("</style>").append("\n\n");
return buffer.toString();
}
protected String getOtherNonStyleHeadElements() {
if(!sourceInput.toLowerCase().contains("wicket:head"))
return "";
Document doc = Jsoup.parseBodyFragment(sourceInput);
Elements headTags = doc.getElementsByTag("wicket:head");
headTags.select("style:not([ignore_compile])").remove();
return headTags.get(0).html();
}
}
| 2,049 | 0.730112 | 0.729136 | 70 | 28.271429 | 25.843441 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.7 | false | false | 1 |
8355658ad4cadd3802cf776239246786f8283a16 | 38,671,885,547,359 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/13/13_5f82f80a6f263030b313e9e0991c5aba2decccd8/XmlDatabase/13_5f82f80a6f263030b313e9e0991c5aba2decccd8_XmlDatabase_t.java | 0191da7112b3c6f4b77cf1b3d70b5f9431cb3b9f | []
| no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | package net.canarymod.database.xml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import net.canarymod.database.Column;
import net.canarymod.database.Column.DataType;
import net.canarymod.database.DataAccess;
import net.canarymod.database.Database;
import net.canarymod.database.exceptions.DatabaseAccessException;
import net.canarymod.database.exceptions.DatabaseReadException;
import net.canarymod.database.exceptions.DatabaseTableInconsistencyException;
import net.canarymod.database.exceptions.DatabaseWriteException;
import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class XmlDatabase extends Database {
private XmlDatabase() {
File path = new File("db/");
if (!path.exists()) {
path.mkdirs();
}
}
private static XmlDatabase instance;
public static XmlDatabase getInstance() {
if (instance == null) {
instance = new XmlDatabase();
}
return instance;
}
/** Used to serialize the XML data into a bytestream */
private XMLOutputter xmlSerializer = new XMLOutputter(Format.getPrettyFormat().setExpandEmptyElements(true).setOmitDeclaration(true).setOmitEncoding(true).setLineSeparator("\n"));
private SAXBuilder fileBuilder = new SAXBuilder();
@Override
public void insert(DataAccess data) throws DatabaseWriteException {
File file = new File("db/" + data.getName() + ".xml");
if (!file.exists()) {
try {
file.createNewFile();
initFile(file, data.getName());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
Document dbTable = null;
try {
FileInputStream in = new FileInputStream(file);
dbTable = fileBuilder.build(in);
in.close();
insertData(file, data, dbTable);
} catch (JDOMException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
@Override
public void load(DataAccess data, String[] fieldNames, Object[] fieldValues) throws DatabaseReadException {
File file = new File("db/" + data.getName() + ".xml");
if (!file.exists()) {
throw new DatabaseReadException("Table " + data.getName() + " does not exist!");
}
if (fieldNames.length != fieldValues.length) {
throw new DatabaseReadException("Field and Value field lenghts are inconsistent!");
}
try {
FileInputStream in = new FileInputStream(file);
Document table = fileBuilder.build(in);
in.close();
loadData(data, table, fieldNames, fieldValues);
} catch (JDOMException e) {
throw new DatabaseReadException(e.getMessage());
} catch (IOException e) {
throw new DatabaseReadException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseReadException(e.getMessage());
} catch (DatabaseAccessException e) {
throw new DatabaseReadException(e.getMessage());
}
}
@Override
public void loadAll(DataAccess typeTemplate, List<DataAccess> datasets, String[] fieldNames, Object[] fieldValues) throws DatabaseReadException {
File file = new File("db/" + typeTemplate.getName() + ".xml");
if (!file.exists()) {
throw new DatabaseReadException("Table " + typeTemplate.getName() + " does not exist!");
}
if (fieldNames.length != fieldValues.length) {
throw new DatabaseReadException("Field and Value field lenghts are inconsistent!");
}
try {
FileInputStream in = new FileInputStream(file);
Document table = fileBuilder.build(in);
in.close();
loadAllData(typeTemplate.getClass().asSubclass(DataAccess.class), datasets, table, fieldNames, fieldValues);
} catch (JDOMException e) {
throw new DatabaseReadException(e.getMessage());
} catch (IOException e) {
throw new DatabaseReadException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseReadException(e.getMessage());
} catch (DatabaseAccessException e) {
throw new DatabaseReadException(e.getMessage());
} catch (InstantiationException e) {
throw new DatabaseReadException(e.getMessage());
} catch (IllegalAccessException e) {
throw new DatabaseReadException(e.getMessage());
}
}
@Override
public void update(DataAccess data, String[] fieldNames, Object[] fieldValues) throws DatabaseWriteException {
File file = new File("db/" + data.getName() + ".xml");
if (!file.exists()) {
throw new DatabaseWriteException("Table " + data.getName() + " does not exist!");
}
if (fieldNames.length != fieldValues.length) {
throw new DatabaseWriteException("Field and Value field lenghts are inconsistent!");
}
try {
FileInputStream in = new FileInputStream(file);
Document table = fileBuilder.build(in);
in.close();
updateData(file, table, data, fieldNames, fieldValues);
} catch (JDOMException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
@Override
public void remove(String tableName, String[] fieldNames, Object[] fieldValues) throws DatabaseWriteException {
File file = new File("db/" + tableName + ".xml");
if (!file.exists()) {
throw new DatabaseWriteException("Table " + tableName + " does not exist!");
}
if (fieldNames.length != fieldValues.length) {
throw new DatabaseWriteException("Field and Value field lenghts are inconsistent!");
}
try {
FileInputStream in = new FileInputStream(file);
Document table = fileBuilder.build(in);
in.close();
removeData(file, table, fieldNames, fieldValues);
} catch (JDOMException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
@Override
public void updateSchema(DataAccess data) throws DatabaseWriteException {
File file = new File("db/" + data.getName() + ".xml");
if (!file.exists()) {
try {
file.createNewFile();
initFile(file, data.getName());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
try {
FileInputStream in = new FileInputStream(file);
Document table = fileBuilder.build(in);
in.close();
HashSet<Column> tableLayout = data.getTableLayout();
for (Element element : table.getRootElement().getChildren()) {
addFields(element, tableLayout);
removeFields(element, tableLayout);
}
write(file.getPath(), table);
} catch (JDOMException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
private void initFile(File file, String rootName) throws IOException {
Document doc = new Document();
doc.setRootElement(new Element(rootName));
write(file.getPath(), doc);
}
/**
* Adds new fields to the Element, according to the given layout set.
* @param element
* @param layout
*/
private void addFields(Element element, HashSet<Column> layout) {
for (Column column : layout) {
boolean found = false;
for (Element child : element.getChildren()) {
if (child.getName().equals(column.columnName())) {
found = true;
}
}
if (!found) {
Element col = new Element(column.columnName());
col.setAttribute("auto-increment", String.valueOf(column.autoIncrement()));
col.setAttribute("data-type", column.dataType().name());
col.setAttribute("column-type", column.columnType().name());
col.setAttribute("is-list", String.valueOf(column.isList()));
element.addContent(col);
}
}
}
/**
* Removes fields from the given element that are not contained in the given layout
* @param element
* @param layout
*/
private void removeFields(Element element, HashSet<Column> layout) {
for (Element child : element.getChildren()) {
boolean found = false;
for (Column column : layout) {
if (child.getName().equals(column.columnName())) {
found = true;
}
}
if (!found) {
child.detach();
}
}
}
/**
* Inserts data into the XML file. This does NOT update data.
* It will create a new entry if there isn't the exact same already present
* @param file
* @param data
* @param dbTable
* @throws IOException
* @throws DatabaseTableInconsistencyException
*/
private void insertData(File file, DataAccess data, Document dbTable) throws IOException, DatabaseTableInconsistencyException {
HashMap<Column, Object> entry = data.toDatabaseEntryList();
if (data.isInconsistent()) {
// Just an extra precaution
throw new DatabaseTableInconsistencyException("DataAccess is marked inconsistent!");
}
Element set = new Element("entry");
for (Column column : entry.keySet()) {
Element col = new Element(column.columnName());
col.setAttribute("auto-increment", String.valueOf(column.autoIncrement()));
col.setAttribute("data-type", column.dataType().name());
col.setAttribute("column-type", column.columnType().name());
col.setAttribute("is-list", String.valueOf(column.isList()));
addToElement(dbTable, col, entry.get(column), column);
set.addContent(col);
boolean foundDupe = false;
for (Element c : dbTable.getRootElement().getChildren()) {
if (elementEquals(set, c)) {
foundDupe = true;
}
}
if (!foundDupe) {}
}
dbTable.getRootElement().addContent(set);
write(file.getPath(), dbTable);
}
/**
* Updates an already existing element in the document.
* IMPORTANT: the lengths of fields and content array must have been checked before this method is called!
* @param file
* @param table
* @param fields
* @param values
* @throws IOException
* @throws DatabaseTableInconsistencyException
* @throws DatabaseWriteException
*/
private void updateData(File file, Document table, DataAccess data, String[] fields, Object[] values) throws IOException, DatabaseTableInconsistencyException, DatabaseWriteException {
boolean hasUpdated = false;
for (Element element : table.getRootElement().getChildren()) {
int equalFields = 0;
for (int i = 0; i < fields.length; ++i) {
Element child = element.getChild(fields[i]);
if (child != null) {
if (child.getText().equals(String.valueOf(values[i]))) {
equalFields++;
}
}
}
if (equalFields != fields.length) {
continue; // Not the entry we're looking for
}
if (data.isInconsistent()) {
// Just an extra precaution
throw new DatabaseTableInconsistencyException("DataAccess is marked inconsistent!");
}
HashMap<Column, Object> dataSet = data.toDatabaseEntryList();
for (Column column : dataSet.keySet()) {
Element child = element.getChild(column.columnName());
if (child == null) {
throw new DatabaseTableInconsistencyException("Column " + column.columnName() + " does not exist. Update table schema or fix DataAccess!");
}
// Do not change auto-increment fields
if (column.autoIncrement()) {
continue;
}
addToElement(table, child, dataSet.get(column), column);
hasUpdated = true;
}
}
if(hasUpdated) {
write(file.getPath(), table);
}
else {
//No fields found, that means it is a new entry
insert(data);
}
}
private void removeData(File file, Document table, String[] fields, Object[] values) throws IOException, DatabaseTableInconsistencyException {
ArrayList<Element> toremove = new ArrayList<Element>();
for (Element element : table.getRootElement().getChildren()) {
int equalFields = 0;
for (int i = 0; i < fields.length; ++i) {
Element child = element.getChild(fields[i]);
if (child != null) {
if (child.getText().equals(String.valueOf(values[i]))) {
equalFields++;
}
}
}
if (equalFields != fields.length) {
continue; // Not the entry we're looking for
}
// table.getRootElement().removeContent(element);
toremove.add(element);
}
for(Element e : toremove) {
e.detach();
}
write(file.getPath(), table);
}
private void loadData(DataAccess data, Document table, String[] fields, Object[] values) throws IOException, DatabaseTableInconsistencyException, DatabaseAccessException {
for (Element element : table.getRootElement().getChildren()) {
int equalFields = 0;
for (int i = 0; i < fields.length; ++i) {
Element child = element.getChild(fields[i]);
if (child != null) {
if (child.getText().equals(String.valueOf(values[i]))) {
equalFields++;
}
}
}
if (equalFields != fields.length) {
continue; // Not the entry we're looking for
}
HashMap<String, Object> dataSet = new HashMap<String, Object>();
for (Element child : element.getChildren()) {
DataType type = DataType.fromString(child.getAttributeValue("data-type"));
addTypeToMap(child, dataSet, type);
}
data.load(dataSet);
return;
}
}
private void loadAllData(Class<? extends DataAccess> template, List<DataAccess> datasets, Document table, String[] fields, Object[] values) throws IOException, DatabaseTableInconsistencyException, DatabaseAccessException, InstantiationException, IllegalAccessException {
for (Element element : table.getRootElement().getChildren()) {
int equalFields = 0;
for (int i = 0; i < fields.length; ++i) {
Element child = element.getChild(fields[i]);
if (child != null) {
if (child.getText().equals(String.valueOf(values[i]))) {
equalFields++;
}
}
}
if (equalFields != fields.length) {
continue; // Not the entry we're looking for
}
HashMap<String, Object> dataSet = new HashMap<String, Object>();
for (Element child : element.getChildren()) {
DataType type = DataType.fromString(child.getAttributeValue("data-type"));
addTypeToMap(child, dataSet, type);
}
DataAccess da = template.newInstance();
da.load(dataSet);
datasets.add(da);
}
}
/**
* Performs a field-by-field comparison for the two given Contents.
* First they must be of type Element and then the fields are checked against each other.
* If the number of equal fields does not match the number of child elements ot Content a,
* this method will return false, true otherwise
* @param a
* @param b
* @return
*/
private boolean elementEquals(Content a, Content b) {
if (!(b instanceof Element)) {
return false;
}
if (!(a instanceof Element)) {
return false;
}
if (a == b) {
return true;
}
Element elB = (Element) b;
Element elA = (Element) a;
if (elA.getContentSize() != elB.getContentSize()) {
return false;
}
int equalHits = 0;
for (Element el : elA.getChildren()) {
for (Element other : elB.getChildren()) {
if (el.getName().equals(other.getName())) {
if (el.getText().equalsIgnoreCase(other.getText())) {
equalHits++;
}
}
}
}
return equalHits == elA.getChildren().size();
}
/**
* Generates the next auto-increment ID for this table
* @param doc
* @param col
* @return
* @throws DatabaseTableInconsistencyException
*/
private int getIncrementId(Document doc, Column col) throws DatabaseTableInconsistencyException {
// Search from last to first content entry for a valid element
int id = 0;
int index = doc.getRootElement().getChildren().size() - 1;
if (index < 0) {
// No data in this document yet, start at 1
return 1;
}
Element c = doc.getRootElement().getChildren().get(index);
try {
String num = c.getChildText(col.columnName());
if (num != null) {
id = Integer.valueOf(num);
id++;
return id;
} else {
// That means there is no data;
return 1;
}
} catch (NumberFormatException e) {
throw new DatabaseTableInconsistencyException(col.columnName() + "is not an incrementable field. Fix your DataAccess!");
}
}
/**
* Add data to a data set from the given xml element and type
* @param child
* @param dataSet
* @param type
*/
private void addTypeToMap(Element child, HashMap<String, Object> dataSet, DataType type) {
switch (type) {
case BYTE:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Byte> byteList = new ArrayList<Byte>();
for (Element el : child.getChildren()) {
byteList.add(Byte.parseByte(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Byte.parseByte(child.getText()));
}
break;
case DOUBLE:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Double> byteList = new ArrayList<Double>();
for (Element el : child.getChildren()) {
byteList.add(Double.parseDouble(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Double.parseDouble(child.getText()));
}
break;
case FLOAT:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Float> byteList = new ArrayList<Float>();
for (Element el : child.getChildren()) {
byteList.add(Float.parseFloat(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Float.parseFloat(child.getText()));
}
break;
case INTEGER:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Integer> byteList = new ArrayList<Integer>();
for (Element el : child.getChildren()) {
byteList.add(Integer.parseInt(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Integer.parseInt(child.getText()));
}
break;
case LONG:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Long> byteList = new ArrayList<Long>();
for (Element el : child.getChildren()) {
byteList.add(Long.parseLong(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Long.parseLong(child.getText()));
}
break;
case SHORT:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Short> byteList = new ArrayList<Short>();
for (Element el : child.getChildren()) {
byteList.add(Short.parseShort(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Short.parseShort(child.getText()));
}
break;
case STRING:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<String> byteList = new ArrayList<String>();
for (Element el : child.getChildren()) {
byteList.add(el.getText());
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), child.getText());
}
break;
case BOOLEAN:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Boolean> byteList = new ArrayList<Boolean>();
for (Element el : child.getChildren()) {
byteList.add(Boolean.valueOf(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Boolean.valueOf(child.getText()));
}
break;
default:
break;
}
}
/**
* Adds data to an element
* @param element
* @param obj
* @throws DatabaseTableInconsistencyException
*/
private void addToElement(Document doc, Element element, Object obj, Column col) throws DatabaseTableInconsistencyException {
if (col.autoIncrement()) {
element.setText(String.valueOf(getIncrementId(doc, col)));
}
else if (col.isList()) {
List<?> entries = (List<?>) obj;
// First detach everything so there won't be dupes
for (Element el : element.getChildren()) {
el.detach();
}
if(obj == null) {
return;
}
// Add fresh data
for (Object entry : entries) {
element.addContent(new Element("list-element").setText(String.valueOf(entry)));
}
}
else {
element.setText(String.valueOf(obj));
}
}
private void write(String path, Document doc) throws IOException {
File file = new File(path);
RandomAccessFile f = new RandomAccessFile(file.getPath(), "rw");
f.getChannel().lock();
f.setLength(0);
f.write(xmlSerializer.outputString(doc).getBytes(Charset.defaultCharset()));
f.close();
}
}
| UTF-8 | Java | 26,318 | java | 13_5f82f80a6f263030b313e9e0991c5aba2decccd8_XmlDatabase_t.java | Java | []
| null | []
| package net.canarymod.database.xml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import net.canarymod.database.Column;
import net.canarymod.database.Column.DataType;
import net.canarymod.database.DataAccess;
import net.canarymod.database.Database;
import net.canarymod.database.exceptions.DatabaseAccessException;
import net.canarymod.database.exceptions.DatabaseReadException;
import net.canarymod.database.exceptions.DatabaseTableInconsistencyException;
import net.canarymod.database.exceptions.DatabaseWriteException;
import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class XmlDatabase extends Database {
private XmlDatabase() {
File path = new File("db/");
if (!path.exists()) {
path.mkdirs();
}
}
private static XmlDatabase instance;
public static XmlDatabase getInstance() {
if (instance == null) {
instance = new XmlDatabase();
}
return instance;
}
/** Used to serialize the XML data into a bytestream */
private XMLOutputter xmlSerializer = new XMLOutputter(Format.getPrettyFormat().setExpandEmptyElements(true).setOmitDeclaration(true).setOmitEncoding(true).setLineSeparator("\n"));
private SAXBuilder fileBuilder = new SAXBuilder();
@Override
public void insert(DataAccess data) throws DatabaseWriteException {
File file = new File("db/" + data.getName() + ".xml");
if (!file.exists()) {
try {
file.createNewFile();
initFile(file, data.getName());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
Document dbTable = null;
try {
FileInputStream in = new FileInputStream(file);
dbTable = fileBuilder.build(in);
in.close();
insertData(file, data, dbTable);
} catch (JDOMException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
@Override
public void load(DataAccess data, String[] fieldNames, Object[] fieldValues) throws DatabaseReadException {
File file = new File("db/" + data.getName() + ".xml");
if (!file.exists()) {
throw new DatabaseReadException("Table " + data.getName() + " does not exist!");
}
if (fieldNames.length != fieldValues.length) {
throw new DatabaseReadException("Field and Value field lenghts are inconsistent!");
}
try {
FileInputStream in = new FileInputStream(file);
Document table = fileBuilder.build(in);
in.close();
loadData(data, table, fieldNames, fieldValues);
} catch (JDOMException e) {
throw new DatabaseReadException(e.getMessage());
} catch (IOException e) {
throw new DatabaseReadException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseReadException(e.getMessage());
} catch (DatabaseAccessException e) {
throw new DatabaseReadException(e.getMessage());
}
}
@Override
public void loadAll(DataAccess typeTemplate, List<DataAccess> datasets, String[] fieldNames, Object[] fieldValues) throws DatabaseReadException {
File file = new File("db/" + typeTemplate.getName() + ".xml");
if (!file.exists()) {
throw new DatabaseReadException("Table " + typeTemplate.getName() + " does not exist!");
}
if (fieldNames.length != fieldValues.length) {
throw new DatabaseReadException("Field and Value field lenghts are inconsistent!");
}
try {
FileInputStream in = new FileInputStream(file);
Document table = fileBuilder.build(in);
in.close();
loadAllData(typeTemplate.getClass().asSubclass(DataAccess.class), datasets, table, fieldNames, fieldValues);
} catch (JDOMException e) {
throw new DatabaseReadException(e.getMessage());
} catch (IOException e) {
throw new DatabaseReadException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseReadException(e.getMessage());
} catch (DatabaseAccessException e) {
throw new DatabaseReadException(e.getMessage());
} catch (InstantiationException e) {
throw new DatabaseReadException(e.getMessage());
} catch (IllegalAccessException e) {
throw new DatabaseReadException(e.getMessage());
}
}
@Override
public void update(DataAccess data, String[] fieldNames, Object[] fieldValues) throws DatabaseWriteException {
File file = new File("db/" + data.getName() + ".xml");
if (!file.exists()) {
throw new DatabaseWriteException("Table " + data.getName() + " does not exist!");
}
if (fieldNames.length != fieldValues.length) {
throw new DatabaseWriteException("Field and Value field lenghts are inconsistent!");
}
try {
FileInputStream in = new FileInputStream(file);
Document table = fileBuilder.build(in);
in.close();
updateData(file, table, data, fieldNames, fieldValues);
} catch (JDOMException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
@Override
public void remove(String tableName, String[] fieldNames, Object[] fieldValues) throws DatabaseWriteException {
File file = new File("db/" + tableName + ".xml");
if (!file.exists()) {
throw new DatabaseWriteException("Table " + tableName + " does not exist!");
}
if (fieldNames.length != fieldValues.length) {
throw new DatabaseWriteException("Field and Value field lenghts are inconsistent!");
}
try {
FileInputStream in = new FileInputStream(file);
Document table = fileBuilder.build(in);
in.close();
removeData(file, table, fieldNames, fieldValues);
} catch (JDOMException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
@Override
public void updateSchema(DataAccess data) throws DatabaseWriteException {
File file = new File("db/" + data.getName() + ".xml");
if (!file.exists()) {
try {
file.createNewFile();
initFile(file, data.getName());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
try {
FileInputStream in = new FileInputStream(file);
Document table = fileBuilder.build(in);
in.close();
HashSet<Column> tableLayout = data.getTableLayout();
for (Element element : table.getRootElement().getChildren()) {
addFields(element, tableLayout);
removeFields(element, tableLayout);
}
write(file.getPath(), table);
} catch (JDOMException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (IOException e) {
throw new DatabaseWriteException(e.getMessage());
} catch (DatabaseTableInconsistencyException e) {
throw new DatabaseWriteException(e.getMessage());
}
}
private void initFile(File file, String rootName) throws IOException {
Document doc = new Document();
doc.setRootElement(new Element(rootName));
write(file.getPath(), doc);
}
/**
* Adds new fields to the Element, according to the given layout set.
* @param element
* @param layout
*/
private void addFields(Element element, HashSet<Column> layout) {
for (Column column : layout) {
boolean found = false;
for (Element child : element.getChildren()) {
if (child.getName().equals(column.columnName())) {
found = true;
}
}
if (!found) {
Element col = new Element(column.columnName());
col.setAttribute("auto-increment", String.valueOf(column.autoIncrement()));
col.setAttribute("data-type", column.dataType().name());
col.setAttribute("column-type", column.columnType().name());
col.setAttribute("is-list", String.valueOf(column.isList()));
element.addContent(col);
}
}
}
/**
* Removes fields from the given element that are not contained in the given layout
* @param element
* @param layout
*/
private void removeFields(Element element, HashSet<Column> layout) {
for (Element child : element.getChildren()) {
boolean found = false;
for (Column column : layout) {
if (child.getName().equals(column.columnName())) {
found = true;
}
}
if (!found) {
child.detach();
}
}
}
/**
* Inserts data into the XML file. This does NOT update data.
* It will create a new entry if there isn't the exact same already present
* @param file
* @param data
* @param dbTable
* @throws IOException
* @throws DatabaseTableInconsistencyException
*/
private void insertData(File file, DataAccess data, Document dbTable) throws IOException, DatabaseTableInconsistencyException {
HashMap<Column, Object> entry = data.toDatabaseEntryList();
if (data.isInconsistent()) {
// Just an extra precaution
throw new DatabaseTableInconsistencyException("DataAccess is marked inconsistent!");
}
Element set = new Element("entry");
for (Column column : entry.keySet()) {
Element col = new Element(column.columnName());
col.setAttribute("auto-increment", String.valueOf(column.autoIncrement()));
col.setAttribute("data-type", column.dataType().name());
col.setAttribute("column-type", column.columnType().name());
col.setAttribute("is-list", String.valueOf(column.isList()));
addToElement(dbTable, col, entry.get(column), column);
set.addContent(col);
boolean foundDupe = false;
for (Element c : dbTable.getRootElement().getChildren()) {
if (elementEquals(set, c)) {
foundDupe = true;
}
}
if (!foundDupe) {}
}
dbTable.getRootElement().addContent(set);
write(file.getPath(), dbTable);
}
/**
* Updates an already existing element in the document.
* IMPORTANT: the lengths of fields and content array must have been checked before this method is called!
* @param file
* @param table
* @param fields
* @param values
* @throws IOException
* @throws DatabaseTableInconsistencyException
* @throws DatabaseWriteException
*/
private void updateData(File file, Document table, DataAccess data, String[] fields, Object[] values) throws IOException, DatabaseTableInconsistencyException, DatabaseWriteException {
boolean hasUpdated = false;
for (Element element : table.getRootElement().getChildren()) {
int equalFields = 0;
for (int i = 0; i < fields.length; ++i) {
Element child = element.getChild(fields[i]);
if (child != null) {
if (child.getText().equals(String.valueOf(values[i]))) {
equalFields++;
}
}
}
if (equalFields != fields.length) {
continue; // Not the entry we're looking for
}
if (data.isInconsistent()) {
// Just an extra precaution
throw new DatabaseTableInconsistencyException("DataAccess is marked inconsistent!");
}
HashMap<Column, Object> dataSet = data.toDatabaseEntryList();
for (Column column : dataSet.keySet()) {
Element child = element.getChild(column.columnName());
if (child == null) {
throw new DatabaseTableInconsistencyException("Column " + column.columnName() + " does not exist. Update table schema or fix DataAccess!");
}
// Do not change auto-increment fields
if (column.autoIncrement()) {
continue;
}
addToElement(table, child, dataSet.get(column), column);
hasUpdated = true;
}
}
if(hasUpdated) {
write(file.getPath(), table);
}
else {
//No fields found, that means it is a new entry
insert(data);
}
}
private void removeData(File file, Document table, String[] fields, Object[] values) throws IOException, DatabaseTableInconsistencyException {
ArrayList<Element> toremove = new ArrayList<Element>();
for (Element element : table.getRootElement().getChildren()) {
int equalFields = 0;
for (int i = 0; i < fields.length; ++i) {
Element child = element.getChild(fields[i]);
if (child != null) {
if (child.getText().equals(String.valueOf(values[i]))) {
equalFields++;
}
}
}
if (equalFields != fields.length) {
continue; // Not the entry we're looking for
}
// table.getRootElement().removeContent(element);
toremove.add(element);
}
for(Element e : toremove) {
e.detach();
}
write(file.getPath(), table);
}
private void loadData(DataAccess data, Document table, String[] fields, Object[] values) throws IOException, DatabaseTableInconsistencyException, DatabaseAccessException {
for (Element element : table.getRootElement().getChildren()) {
int equalFields = 0;
for (int i = 0; i < fields.length; ++i) {
Element child = element.getChild(fields[i]);
if (child != null) {
if (child.getText().equals(String.valueOf(values[i]))) {
equalFields++;
}
}
}
if (equalFields != fields.length) {
continue; // Not the entry we're looking for
}
HashMap<String, Object> dataSet = new HashMap<String, Object>();
for (Element child : element.getChildren()) {
DataType type = DataType.fromString(child.getAttributeValue("data-type"));
addTypeToMap(child, dataSet, type);
}
data.load(dataSet);
return;
}
}
private void loadAllData(Class<? extends DataAccess> template, List<DataAccess> datasets, Document table, String[] fields, Object[] values) throws IOException, DatabaseTableInconsistencyException, DatabaseAccessException, InstantiationException, IllegalAccessException {
for (Element element : table.getRootElement().getChildren()) {
int equalFields = 0;
for (int i = 0; i < fields.length; ++i) {
Element child = element.getChild(fields[i]);
if (child != null) {
if (child.getText().equals(String.valueOf(values[i]))) {
equalFields++;
}
}
}
if (equalFields != fields.length) {
continue; // Not the entry we're looking for
}
HashMap<String, Object> dataSet = new HashMap<String, Object>();
for (Element child : element.getChildren()) {
DataType type = DataType.fromString(child.getAttributeValue("data-type"));
addTypeToMap(child, dataSet, type);
}
DataAccess da = template.newInstance();
da.load(dataSet);
datasets.add(da);
}
}
/**
* Performs a field-by-field comparison for the two given Contents.
* First they must be of type Element and then the fields are checked against each other.
* If the number of equal fields does not match the number of child elements ot Content a,
* this method will return false, true otherwise
* @param a
* @param b
* @return
*/
private boolean elementEquals(Content a, Content b) {
if (!(b instanceof Element)) {
return false;
}
if (!(a instanceof Element)) {
return false;
}
if (a == b) {
return true;
}
Element elB = (Element) b;
Element elA = (Element) a;
if (elA.getContentSize() != elB.getContentSize()) {
return false;
}
int equalHits = 0;
for (Element el : elA.getChildren()) {
for (Element other : elB.getChildren()) {
if (el.getName().equals(other.getName())) {
if (el.getText().equalsIgnoreCase(other.getText())) {
equalHits++;
}
}
}
}
return equalHits == elA.getChildren().size();
}
/**
* Generates the next auto-increment ID for this table
* @param doc
* @param col
* @return
* @throws DatabaseTableInconsistencyException
*/
private int getIncrementId(Document doc, Column col) throws DatabaseTableInconsistencyException {
// Search from last to first content entry for a valid element
int id = 0;
int index = doc.getRootElement().getChildren().size() - 1;
if (index < 0) {
// No data in this document yet, start at 1
return 1;
}
Element c = doc.getRootElement().getChildren().get(index);
try {
String num = c.getChildText(col.columnName());
if (num != null) {
id = Integer.valueOf(num);
id++;
return id;
} else {
// That means there is no data;
return 1;
}
} catch (NumberFormatException e) {
throw new DatabaseTableInconsistencyException(col.columnName() + "is not an incrementable field. Fix your DataAccess!");
}
}
/**
* Add data to a data set from the given xml element and type
* @param child
* @param dataSet
* @param type
*/
private void addTypeToMap(Element child, HashMap<String, Object> dataSet, DataType type) {
switch (type) {
case BYTE:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Byte> byteList = new ArrayList<Byte>();
for (Element el : child.getChildren()) {
byteList.add(Byte.parseByte(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Byte.parseByte(child.getText()));
}
break;
case DOUBLE:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Double> byteList = new ArrayList<Double>();
for (Element el : child.getChildren()) {
byteList.add(Double.parseDouble(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Double.parseDouble(child.getText()));
}
break;
case FLOAT:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Float> byteList = new ArrayList<Float>();
for (Element el : child.getChildren()) {
byteList.add(Float.parseFloat(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Float.parseFloat(child.getText()));
}
break;
case INTEGER:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Integer> byteList = new ArrayList<Integer>();
for (Element el : child.getChildren()) {
byteList.add(Integer.parseInt(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Integer.parseInt(child.getText()));
}
break;
case LONG:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Long> byteList = new ArrayList<Long>();
for (Element el : child.getChildren()) {
byteList.add(Long.parseLong(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Long.parseLong(child.getText()));
}
break;
case SHORT:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Short> byteList = new ArrayList<Short>();
for (Element el : child.getChildren()) {
byteList.add(Short.parseShort(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Short.parseShort(child.getText()));
}
break;
case STRING:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<String> byteList = new ArrayList<String>();
for (Element el : child.getChildren()) {
byteList.add(el.getText());
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), child.getText());
}
break;
case BOOLEAN:
if (Boolean.valueOf(child.getAttributeValue("is-list"))) {
ArrayList<Boolean> byteList = new ArrayList<Boolean>();
for (Element el : child.getChildren()) {
byteList.add(Boolean.valueOf(el.getText()));
}
dataSet.put(child.getName(), byteList);
} else {
dataSet.put(child.getName(), Boolean.valueOf(child.getText()));
}
break;
default:
break;
}
}
/**
* Adds data to an element
* @param element
* @param obj
* @throws DatabaseTableInconsistencyException
*/
private void addToElement(Document doc, Element element, Object obj, Column col) throws DatabaseTableInconsistencyException {
if (col.autoIncrement()) {
element.setText(String.valueOf(getIncrementId(doc, col)));
}
else if (col.isList()) {
List<?> entries = (List<?>) obj;
// First detach everything so there won't be dupes
for (Element el : element.getChildren()) {
el.detach();
}
if(obj == null) {
return;
}
// Add fresh data
for (Object entry : entries) {
element.addContent(new Element("list-element").setText(String.valueOf(entry)));
}
}
else {
element.setText(String.valueOf(obj));
}
}
private void write(String path, Document doc) throws IOException {
File file = new File(path);
RandomAccessFile f = new RandomAccessFile(file.getPath(), "rw");
f.getChannel().lock();
f.setLength(0);
f.write(xmlSerializer.outputString(doc).getBytes(Charset.defaultCharset()));
f.close();
}
}
| 26,318 | 0.540163 | 0.539289 | 692 | 37.030346 | 31.532127 | 275 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.539017 | false | false | 1 |
f95a40e0194ab65c500d1d36c9a99f8279e49f1f | 28,149,215,681,516 | 754549de022bb11d4f68a958ac3c55040a406c09 | /com.bcs.core/src/main/java/com/bcs/core/db/repository/UserTraceLogRepository.java | 710cf7153e8d2015e4b219d534cbd53aecd19a29 | []
| no_license | michaelchou-XtremeApp/TaishinRose | https://github.com/michaelchou-XtremeApp/TaishinRose | 10ab5d32ebe96ea63504942c94d283d2f5f1df9c | af6fa0bd354576b0b9ed7b47ffa8b0e2cd2308f4 | refs/heads/develop-LDAP | 2020-07-28T15:38:13.930000 | 2019-09-19T03:15:12 | 2019-09-19T03:15:12 | 209,452,564 | 0 | 0 | null | false | 2019-11-13T12:10:55 | 2019-09-19T03:14:18 | 2019-09-19T03:17:19 | 2019-11-13T12:10:54 | 13,935 | 0 | 0 | 1 | Java | false | false | package com.bcs.core.db.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import com.bcs.core.db.entity.UserTraceLog;
import com.bcs.core.db.persistence.EntityRepository;
public interface UserTraceLogRepository extends EntityRepository<UserTraceLog, Long>, UserTraceLogRepositoryCustom{
@Transactional(readOnly = true, timeout = 30)
public Page<UserTraceLog> findByTargetAndAction(String target, String action, Pageable pageable);
@Transactional(readOnly = true, timeout = 30)
public Page<UserTraceLog> findByReferenceId(String referenceId, Pageable pageable);
@Transactional(readOnly = true, timeout = 30)
public Page<UserTraceLog> findByLevel(String level, Pageable pageable);
@Transactional(readOnly = true, timeout = 30)
public Page<UserTraceLog> findByModifyUser(String modifyUser, Pageable pageable);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT(DISTINCT MID) "
+ "FROM BCS_USER_TRACE_LOG, BCS_LINE_USER "
+ "WHERE ACTION = 'Binded2Block' AND MID = MODIFY_USER AND STATUS = 'BLOCK'", nativeQuery = true)
public Long countBinded2Block();
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT(DISTINCT MID) "
+ "FROM BCS_USER_TRACE_LOG, BCS_LINE_USER "
+ "WHERE ACTION = 'Binded2Block' AND MID = MODIFY_USER AND STATUS = 'BLOCK' AND BCS_LINE_USER.MODIFY_TIME >= ?1 AND BCS_LINE_USER.MODIFY_TIME < ?2", nativeQuery = true)
public Long countBinded2Block(String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT('x') "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE LEVEL = ?1 AND MODIFY_DAY >= ?2 AND MODIFY_DAY < ?3", nativeQuery = true)
public Long countByLevel(String level, String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT('x') "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE TARGET = ?1 AND ACTION = ?2 AND MODIFY_DAY >= ?3 AND MODIFY_DAY < ?4", nativeQuery = true)
public Long countByTargetAndAction(String target, String action, String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT('x') "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE MODIFY_DAY >= ?1 AND MODIFY_DAY < ?2", nativeQuery = true)
public Long countAll(String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT('x') AS allCount, COUNT(distinct BCS_USER_TRACE_LOG.MODIFY_USER) AS allDistinctCount "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE TARGET = ?1 AND ACTION = ?2 AND REFERENCE_ID = ?3 AND BCS_USER_TRACE_LOG.MODIFY_DAY >= ?4 AND BCS_USER_TRACE_LOG.MODIFY_DAY < ?5 ", nativeQuery = true)
public List<Object[]> countByReferenceIdAndTime(String target, String action, String referenceId, String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT DISTINCT MODIFY_USER "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE REFERENCE_ID = ?1", nativeQuery = true)
public List<String> findMidByReferenceId(String referenceId);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT DISTINCT MODIFY_USER "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE REFERENCE_ID = ?1 AND BCS_USER_TRACE_LOG.MODIFY_DAY >= ?2", nativeQuery = true)
public List<String> findMidByReferenceId(String referenceId, String start);
@Transactional(readOnly = true, timeout = 30)
@Query(value="SELECT * FROM BCS_USER_TRACE_LOG WHERE MODIFY_USER= ?1 AND ACTION= ?2 ORDER BY MODIFY_TIME DESC", nativeQuery = true)
public List<UserTraceLog> findByModifyUserAndAction(String modifyUser, String action);
@Transactional(readOnly = true, timeout = 30)
@Query(value="SELECT * FROM BCS_USER_TRACE_LOG WHERE TARGET= ?1 AND ACTION= ?2 AND MODIFY_DAY >= ?3 AND MODIFY_DAY < ?4", nativeQuery = true)
public List<UserTraceLog> findByTargetAndAction(String target, String action, String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT(DISTINCT MID) "
+ "FROM BCS_USER_TRACE_LOG, BCS_LINE_USER "
+ "WHERE ACTION = 'Block' AND MID = MODIFY_USER AND STATUS = 'BLOCK' AND BCS_USER_TRACE_LOG.MODIFY_TIME >= ?1 AND BCS_USER_TRACE_LOG.MODIFY_TIME < ?2", nativeQuery = true)
public Long countBlock(String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT(DISTINCT MID) "
+ "FROM BCS_USER_TRACE_LOG, BCS_LINE_USER "
+ "WHERE ACTION = 'Binded2Block' AND MID = MODIFY_USER AND STATUS = 'BLOCK' AND BCS_USER_TRACE_LOG.MODIFY_TIME >= ?1 AND BCS_USER_TRACE_LOG.MODIFY_TIME < ?2", nativeQuery = true)
public Long countBinded2Block2(String start, String end);
}
| UTF-8 | Java | 4,885 | java | UserTraceLogRepository.java | Java | []
| null | []
| package com.bcs.core.db.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import com.bcs.core.db.entity.UserTraceLog;
import com.bcs.core.db.persistence.EntityRepository;
public interface UserTraceLogRepository extends EntityRepository<UserTraceLog, Long>, UserTraceLogRepositoryCustom{
@Transactional(readOnly = true, timeout = 30)
public Page<UserTraceLog> findByTargetAndAction(String target, String action, Pageable pageable);
@Transactional(readOnly = true, timeout = 30)
public Page<UserTraceLog> findByReferenceId(String referenceId, Pageable pageable);
@Transactional(readOnly = true, timeout = 30)
public Page<UserTraceLog> findByLevel(String level, Pageable pageable);
@Transactional(readOnly = true, timeout = 30)
public Page<UserTraceLog> findByModifyUser(String modifyUser, Pageable pageable);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT(DISTINCT MID) "
+ "FROM BCS_USER_TRACE_LOG, BCS_LINE_USER "
+ "WHERE ACTION = 'Binded2Block' AND MID = MODIFY_USER AND STATUS = 'BLOCK'", nativeQuery = true)
public Long countBinded2Block();
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT(DISTINCT MID) "
+ "FROM BCS_USER_TRACE_LOG, BCS_LINE_USER "
+ "WHERE ACTION = 'Binded2Block' AND MID = MODIFY_USER AND STATUS = 'BLOCK' AND BCS_LINE_USER.MODIFY_TIME >= ?1 AND BCS_LINE_USER.MODIFY_TIME < ?2", nativeQuery = true)
public Long countBinded2Block(String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT('x') "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE LEVEL = ?1 AND MODIFY_DAY >= ?2 AND MODIFY_DAY < ?3", nativeQuery = true)
public Long countByLevel(String level, String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT('x') "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE TARGET = ?1 AND ACTION = ?2 AND MODIFY_DAY >= ?3 AND MODIFY_DAY < ?4", nativeQuery = true)
public Long countByTargetAndAction(String target, String action, String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT('x') "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE MODIFY_DAY >= ?1 AND MODIFY_DAY < ?2", nativeQuery = true)
public Long countAll(String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT('x') AS allCount, COUNT(distinct BCS_USER_TRACE_LOG.MODIFY_USER) AS allDistinctCount "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE TARGET = ?1 AND ACTION = ?2 AND REFERENCE_ID = ?3 AND BCS_USER_TRACE_LOG.MODIFY_DAY >= ?4 AND BCS_USER_TRACE_LOG.MODIFY_DAY < ?5 ", nativeQuery = true)
public List<Object[]> countByReferenceIdAndTime(String target, String action, String referenceId, String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT DISTINCT MODIFY_USER "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE REFERENCE_ID = ?1", nativeQuery = true)
public List<String> findMidByReferenceId(String referenceId);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT DISTINCT MODIFY_USER "
+ "FROM BCS_USER_TRACE_LOG "
+ "WHERE REFERENCE_ID = ?1 AND BCS_USER_TRACE_LOG.MODIFY_DAY >= ?2", nativeQuery = true)
public List<String> findMidByReferenceId(String referenceId, String start);
@Transactional(readOnly = true, timeout = 30)
@Query(value="SELECT * FROM BCS_USER_TRACE_LOG WHERE MODIFY_USER= ?1 AND ACTION= ?2 ORDER BY MODIFY_TIME DESC", nativeQuery = true)
public List<UserTraceLog> findByModifyUserAndAction(String modifyUser, String action);
@Transactional(readOnly = true, timeout = 30)
@Query(value="SELECT * FROM BCS_USER_TRACE_LOG WHERE TARGET= ?1 AND ACTION= ?2 AND MODIFY_DAY >= ?3 AND MODIFY_DAY < ?4", nativeQuery = true)
public List<UserTraceLog> findByTargetAndAction(String target, String action, String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT(DISTINCT MID) "
+ "FROM BCS_USER_TRACE_LOG, BCS_LINE_USER "
+ "WHERE ACTION = 'Block' AND MID = MODIFY_USER AND STATUS = 'BLOCK' AND BCS_USER_TRACE_LOG.MODIFY_TIME >= ?1 AND BCS_USER_TRACE_LOG.MODIFY_TIME < ?2", nativeQuery = true)
public Long countBlock(String start, String end);
@Transactional(readOnly = true, timeout = 30)
@Query(value = "SELECT COUNT(DISTINCT MID) "
+ "FROM BCS_USER_TRACE_LOG, BCS_LINE_USER "
+ "WHERE ACTION = 'Binded2Block' AND MID = MODIFY_USER AND STATUS = 'BLOCK' AND BCS_USER_TRACE_LOG.MODIFY_TIME >= ?1 AND BCS_USER_TRACE_LOG.MODIFY_TIME < ?2", nativeQuery = true)
public Long countBinded2Block2(String start, String end);
}
| 4,885 | 0.721187 | 0.707267 | 94 | 50.968086 | 42.819378 | 190 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.829787 | false | false | 1 |
36ab9b1fa866016efb8dba8bf03d118e2cd6d303 | 22,746,146,819,672 | 2df43674e622051bb5d0e75e235c79f9cf0303eb | /app/src/main/java/tk/andrekunde/catalogoprodutos/MainActivity.java | f967961a8e1d5b282421214b4f213582ddb8037a | []
| no_license | alkunde/catalogo_produtos | https://github.com/alkunde/catalogo_produtos | 0cb47807bbaaff31b10c9d19107fb23b37bbaed4 | 2c3a3ebc0520e22117000c1d06f16cf9a70ac44c | refs/heads/master | 2018-12-31T08:37:19.003000 | 2016-08-04T01:03:49 | 2016-08-04T01:03:49 | 64,433,262 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tk.andrekunde.catalogoprodutos;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.facebook.drawee.backends.pipeline.Fresco;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import tk.andrekunde.catalogoprodutos.adapter.ProdutoAdapter;
import tk.andrekunde.catalogoprodutos.database.DatabaseHelper;
import tk.andrekunde.catalogoprodutos.domain.Produto;
import tk.andrekunde.catalogoprodutos.interfaces.RecyclerViewOnClickListenerHack;
public class MainActivity extends AppCompatActivity implements RecyclerViewOnClickListenerHack {
private DatabaseHelper dbHelper;
//private Toolbar mToolbar;
private SwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerView mRecyclerView;
private ProgressDialog mProgressDialog;
private List<Produto> mList = new ArrayList<>();
private ProdutoAdapter mAdapter;
private static final int SELECAO_PRODUTO = 1;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fresco.initialize(this);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
if (toolbar != null) {
toolbar.setTitle("");
setSupportActionBar(toolbar);
}
dbHelper = new DatabaseHelper(this);
mRecyclerView = (RecyclerView) findViewById(R.id.rv_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addOnItemTouchListener(new RecyclerViewTouchListener(this, mRecyclerView, this));
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(llm);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srl_swipe);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override public void onRefresh() {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
carregarLista();
} else {
mSwipeRefreshLayout.setRefreshing(false);
Snackbar.make(mRecyclerView, "Falha na conexão com a internet.", Snackbar.LENGTH_LONG)
.setAction("Ok", new View.OnClickListener() {
@Override public void onClick(View view) {
Intent i = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivity(i);
}
})
.setActionTextColor(getApplicationContext().getResources().getColor(R.color.colorLink))
.show();
}
}
});
carregarLista();
mAdapter = new ProdutoAdapter(this, mList);
mRecyclerView.setAdapter(mAdapter);
}
@Override public void onClickListener(View view, int position) {
Intent i = new Intent(MainActivity.this, DetalheProdutoActivity.class);
Bundle params = new Bundle();
params.putParcelable("produto", mList.get(position));
i.putExtras(params);
startActivityForResult(i, SELECAO_PRODUTO);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Produto prod = data.getParcelableExtra("produto");
for (int i = 0; i < mList.size(); i++) {
if (prod.getName().equals(mList.get(i).getName())) {
mList.get(i).setFavorite(prod.getFavoriteBool());
mAdapter.notifyDataSetChanged();
break;
}
}
}
public class RecyclerViewTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private RecyclerViewOnClickListenerHack mRecyclerViewOnClickListenerHack;
public RecyclerViewTouchListener(Context c, final RecyclerView rv, RecyclerViewOnClickListenerHack rvoclh) {
mRecyclerViewOnClickListenerHack = rvoclh;
mGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
View cv = rv.findChildViewUnder(e.getX(), e.getY());
if (cv != null && mRecyclerViewOnClickListenerHack != null)
mRecyclerViewOnClickListenerHack.onClickListener(cv, rv.getChildPosition(cv));
return true;
}
});
}
@Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
mGestureDetector.onTouchEvent(e);
return false;
}
@Override public void onTouchEvent(RecyclerView rv, MotionEvent e) {}
@Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {}
}
public void carregarLista() {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Buscando produtos...");
mProgressDialog.show();
String url = "https://gist.githubusercontent.com/ronanrodrigo/b95b75cfddc6b1cb601d7f806859e1dc/raw/dc973df65664f6997eeba30158d838c4b716204c/products.json";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override public void onResponse(JSONArray response) {
carregarListagem(response);
}
}, new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) {
carregarListagemOffline();
}
});
MyApplication.getInstance().addToReqQueue(jsonArrayRequest);
}
public void carregarListagemOffline() {
mList = dbHelper.buscarProdutos();
mProgressDialog.dismiss();
mAdapter = new ProdutoAdapter(this, mList);
mRecyclerView.setAdapter(mAdapter);
Snackbar.make(mRecyclerView, "Problemas de conexão. Carregamento offline apenas dos favoritos.", Snackbar.LENGTH_LONG).show();
}
public void carregarListagem(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Produto p = new Produto();
p.setName(obj.getString("name"));
p.setDescription(obj.getString("description"));
p.setPhoto(obj.getString("photo"));
p.setPrice(obj.getDouble("price"));
p.setCategoryId(obj.getLong("category_id"));
Produto prod = dbHelper.verificaProdutoPorNome(p.getName());
if (prod != null) p.setFavorite(prod.getFavorite());
mList.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
mProgressDialog.dismiss();
mSwipeRefreshLayout.setRefreshing(false);
mAdapter.notifyDataSetChanged();
}
} | UTF-8 | Java | 8,176 | java | MainActivity.java | Java | [
{
"context": " String url = \"https://gist.githubusercontent.com/ronanrodrigo/b95b75cfddc6b1cb601d7f806859e1dc/raw/dc973df65664",
"end": 6257,
"score": 0.9997227787971497,
"start": 6245,
"tag": "USERNAME",
"value": "ronanrodrigo"
}
]
| null | []
| package tk.andrekunde.catalogoprodutos;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.facebook.drawee.backends.pipeline.Fresco;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import tk.andrekunde.catalogoprodutos.adapter.ProdutoAdapter;
import tk.andrekunde.catalogoprodutos.database.DatabaseHelper;
import tk.andrekunde.catalogoprodutos.domain.Produto;
import tk.andrekunde.catalogoprodutos.interfaces.RecyclerViewOnClickListenerHack;
public class MainActivity extends AppCompatActivity implements RecyclerViewOnClickListenerHack {
private DatabaseHelper dbHelper;
//private Toolbar mToolbar;
private SwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerView mRecyclerView;
private ProgressDialog mProgressDialog;
private List<Produto> mList = new ArrayList<>();
private ProdutoAdapter mAdapter;
private static final int SELECAO_PRODUTO = 1;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fresco.initialize(this);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
if (toolbar != null) {
toolbar.setTitle("");
setSupportActionBar(toolbar);
}
dbHelper = new DatabaseHelper(this);
mRecyclerView = (RecyclerView) findViewById(R.id.rv_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addOnItemTouchListener(new RecyclerViewTouchListener(this, mRecyclerView, this));
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(llm);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srl_swipe);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override public void onRefresh() {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
carregarLista();
} else {
mSwipeRefreshLayout.setRefreshing(false);
Snackbar.make(mRecyclerView, "Falha na conexão com a internet.", Snackbar.LENGTH_LONG)
.setAction("Ok", new View.OnClickListener() {
@Override public void onClick(View view) {
Intent i = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivity(i);
}
})
.setActionTextColor(getApplicationContext().getResources().getColor(R.color.colorLink))
.show();
}
}
});
carregarLista();
mAdapter = new ProdutoAdapter(this, mList);
mRecyclerView.setAdapter(mAdapter);
}
@Override public void onClickListener(View view, int position) {
Intent i = new Intent(MainActivity.this, DetalheProdutoActivity.class);
Bundle params = new Bundle();
params.putParcelable("produto", mList.get(position));
i.putExtras(params);
startActivityForResult(i, SELECAO_PRODUTO);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Produto prod = data.getParcelableExtra("produto");
for (int i = 0; i < mList.size(); i++) {
if (prod.getName().equals(mList.get(i).getName())) {
mList.get(i).setFavorite(prod.getFavoriteBool());
mAdapter.notifyDataSetChanged();
break;
}
}
}
public class RecyclerViewTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private RecyclerViewOnClickListenerHack mRecyclerViewOnClickListenerHack;
public RecyclerViewTouchListener(Context c, final RecyclerView rv, RecyclerViewOnClickListenerHack rvoclh) {
mRecyclerViewOnClickListenerHack = rvoclh;
mGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
View cv = rv.findChildViewUnder(e.getX(), e.getY());
if (cv != null && mRecyclerViewOnClickListenerHack != null)
mRecyclerViewOnClickListenerHack.onClickListener(cv, rv.getChildPosition(cv));
return true;
}
});
}
@Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
mGestureDetector.onTouchEvent(e);
return false;
}
@Override public void onTouchEvent(RecyclerView rv, MotionEvent e) {}
@Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {}
}
public void carregarLista() {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Buscando produtos...");
mProgressDialog.show();
String url = "https://gist.githubusercontent.com/ronanrodrigo/b95b75cfddc6b1cb601d7f806859e1dc/raw/dc973df65664f6997eeba30158d838c4b716204c/products.json";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override public void onResponse(JSONArray response) {
carregarListagem(response);
}
}, new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) {
carregarListagemOffline();
}
});
MyApplication.getInstance().addToReqQueue(jsonArrayRequest);
}
public void carregarListagemOffline() {
mList = dbHelper.buscarProdutos();
mProgressDialog.dismiss();
mAdapter = new ProdutoAdapter(this, mList);
mRecyclerView.setAdapter(mAdapter);
Snackbar.make(mRecyclerView, "Problemas de conexão. Carregamento offline apenas dos favoritos.", Snackbar.LENGTH_LONG).show();
}
public void carregarListagem(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Produto p = new Produto();
p.setName(obj.getString("name"));
p.setDescription(obj.getString("description"));
p.setPhoto(obj.getString("photo"));
p.setPrice(obj.getDouble("price"));
p.setCategoryId(obj.getLong("category_id"));
Produto prod = dbHelper.verificaProdutoPorNome(p.getName());
if (prod != null) p.setFavorite(prod.getFavorite());
mList.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
mProgressDialog.dismiss();
mSwipeRefreshLayout.setRefreshing(false);
mAdapter.notifyDataSetChanged();
}
} | 8,176 | 0.656105 | 0.649743 | 199 | 40.080402 | 31.375559 | 163 | false | false | 0 | 0 | 0 | 0 | 103 | 0.012601 | 0.688442 | false | false | 1 |
5a8f8cdee6d94af74543e24da933929ce9254483 | 25,907,242,749,883 | 71384ec058397e1e5837883aae6b7853710560c4 | /src/eu/detuks/iden/results/RetMethodIdent.java | b2bdb27ece85e7f0e445893d5323dfe84e86be5c | []
| no_license | detuks/DeIdentifier | https://github.com/detuks/DeIdentifier | bf887c6ac036797ea74dd4dc300025b8476627c0 | 17819861e38f0796ff82d954578566fcf8de05a3 | refs/heads/master | 2020-12-24T16:49:19.405000 | 2013-04-28T09:24:58 | 2013-04-28T09:24:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package eu.detuks.iden.results;
import java.util.ArrayList;
public class RetMethodIdent {
public String name;
public String equals;
public int proc;
public ArrayList<RetFieldIdent> fields = new ArrayList<RetFieldIdent>();
public RetMethodIdent(String name,
String equals,
int proc,
ArrayList<RetFieldIdent> fields) {
this.name = name;
this.equals = equals;
this.proc = proc;
this.fields = fields;
}
}
| UTF-8 | Java | 422 | java | RetMethodIdent.java | Java | []
| null | []
| package eu.detuks.iden.results;
import java.util.ArrayList;
public class RetMethodIdent {
public String name;
public String equals;
public int proc;
public ArrayList<RetFieldIdent> fields = new ArrayList<RetFieldIdent>();
public RetMethodIdent(String name,
String equals,
int proc,
ArrayList<RetFieldIdent> fields) {
this.name = name;
this.equals = equals;
this.proc = proc;
this.fields = fields;
}
}
| 422 | 0.741706 | 0.741706 | 20 | 20.1 | 16.603914 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.55 | false | false | 1 |
9d7d1ef9a2f6b68843363fdbbb1b445022f47289 | 10,539,849,770,993 | 591b4d757aeafca8316aa297bd7e33c1589a9263 | /core/core-services-impl/src/main/java/com/sflpro/notifier/services/notification/impl/email/EmailNotificationServiceImpl.java | 8ddf2ac498a5dc397d3a397ffe2ad8c80ce2f131 | [
"Apache-2.0"
]
| permissive | Syuziko/notifier | https://github.com/Syuziko/notifier | 10f1c75ee82ea41379a80e740def3b3f097857be | 748d1c90103d47993e7cc9df264b9c447604ec4d | refs/heads/master | 2020-05-17T02:08:41.584000 | 2018-04-25T14:41:38 | 2018-04-25T14:41:38 | 183,443,096 | 0 | 0 | null | true | 2019-04-25T13:45:25 | 2019-04-25T13:45:24 | 2018-11-26T11:18:46 | 2019-04-24T12:31:05 | 1,274 | 0 | 0 | 0 | null | false | false | package com.sflpro.notifier.services.notification.impl.email;
import com.sflpro.notifier.db.entities.notification.email.EmailNotification;
import com.sflpro.notifier.db.repositories.repositories.notification.AbstractNotificationRepository;
import com.sflpro.notifier.db.repositories.repositories.notification.email.EmailNotificationRepository;
import com.sflpro.notifier.services.notification.dto.email.EmailNotificationDto;
import com.sflpro.notifier.services.notification.email.EmailNotificationService;
import com.sflpro.notifier.services.notification.impl.AbstractNotificationServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import javax.annotation.Nonnull;
/**
* User: Ruben Dilanyan
* Company: SFL LLC
* Date: 3/21/15
* Time: 8:07 PM
*/
@Service
public class EmailNotificationServiceImpl extends AbstractNotificationServiceImpl<EmailNotification> implements EmailNotificationService {
private static final Logger LOGGER = LoggerFactory.getLogger(EmailNotificationServiceImpl.class);
/* Dependencies */
@Autowired
private EmailNotificationRepository emailNotificationRepository;
/* Constructors */
public EmailNotificationServiceImpl() {
LOGGER.debug("Initializing email notification service");
}
@Transactional
@Nonnull
@Override
public EmailNotification createEmailNotification(@Nonnull final EmailNotificationDto emailNotificationDto) {
assertEmailNotificationDto(emailNotificationDto);
LOGGER.debug("Creating email notification for DTO - {}", emailNotificationDto);
EmailNotification emailNotification = new EmailNotification(true);
emailNotificationDto.updateDomainEntityProperties(emailNotification);
// Persist notification
emailNotification = emailNotificationRepository.save(emailNotification);
LOGGER.debug("Successfully created email notification with id - {}, email notification - {}", emailNotification.getId(), emailNotification);
return emailNotification;
}
/* Utility methods */
@Override
protected AbstractNotificationRepository<EmailNotification> getRepository() {
return emailNotificationRepository;
}
@Override
protected Class<EmailNotification> getInstanceClass() {
return EmailNotification.class;
}
private void assertEmailNotificationDto(final EmailNotificationDto notificationDto) {
assertNotificationDto(notificationDto);
Assert.notNull(notificationDto.getProviderType(), "ProviderType in notification DTO should not be null");
Assert.notNull(notificationDto.getRecipientEmail(), "Recipient email in notification DTO should not be null");
Assert.notNull(notificationDto.getSenderEmail(), "Sender email in notification DTO should not be null");
}
/* Properties getters and setters */
public EmailNotificationRepository getEmailNotificationRepository() {
return emailNotificationRepository;
}
public void setEmailNotificationRepository(final EmailNotificationRepository emailNotificationRepository) {
this.emailNotificationRepository = emailNotificationRepository;
}
}
| UTF-8 | Java | 3,389 | java | EmailNotificationServiceImpl.java | Java | [
{
"context": "t;\n\nimport javax.annotation.Nonnull;\n\n/**\n * User: Ruben Dilanyan\n * Company: SFL LLC\n * Date: 3/21/15\n * Time: 8:0",
"end": 928,
"score": 0.9998853802680969,
"start": 914,
"tag": "NAME",
"value": "Ruben Dilanyan"
}
]
| null | []
| package com.sflpro.notifier.services.notification.impl.email;
import com.sflpro.notifier.db.entities.notification.email.EmailNotification;
import com.sflpro.notifier.db.repositories.repositories.notification.AbstractNotificationRepository;
import com.sflpro.notifier.db.repositories.repositories.notification.email.EmailNotificationRepository;
import com.sflpro.notifier.services.notification.dto.email.EmailNotificationDto;
import com.sflpro.notifier.services.notification.email.EmailNotificationService;
import com.sflpro.notifier.services.notification.impl.AbstractNotificationServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import javax.annotation.Nonnull;
/**
* User: <NAME>
* Company: SFL LLC
* Date: 3/21/15
* Time: 8:07 PM
*/
@Service
public class EmailNotificationServiceImpl extends AbstractNotificationServiceImpl<EmailNotification> implements EmailNotificationService {
private static final Logger LOGGER = LoggerFactory.getLogger(EmailNotificationServiceImpl.class);
/* Dependencies */
@Autowired
private EmailNotificationRepository emailNotificationRepository;
/* Constructors */
public EmailNotificationServiceImpl() {
LOGGER.debug("Initializing email notification service");
}
@Transactional
@Nonnull
@Override
public EmailNotification createEmailNotification(@Nonnull final EmailNotificationDto emailNotificationDto) {
assertEmailNotificationDto(emailNotificationDto);
LOGGER.debug("Creating email notification for DTO - {}", emailNotificationDto);
EmailNotification emailNotification = new EmailNotification(true);
emailNotificationDto.updateDomainEntityProperties(emailNotification);
// Persist notification
emailNotification = emailNotificationRepository.save(emailNotification);
LOGGER.debug("Successfully created email notification with id - {}, email notification - {}", emailNotification.getId(), emailNotification);
return emailNotification;
}
/* Utility methods */
@Override
protected AbstractNotificationRepository<EmailNotification> getRepository() {
return emailNotificationRepository;
}
@Override
protected Class<EmailNotification> getInstanceClass() {
return EmailNotification.class;
}
private void assertEmailNotificationDto(final EmailNotificationDto notificationDto) {
assertNotificationDto(notificationDto);
Assert.notNull(notificationDto.getProviderType(), "ProviderType in notification DTO should not be null");
Assert.notNull(notificationDto.getRecipientEmail(), "Recipient email in notification DTO should not be null");
Assert.notNull(notificationDto.getSenderEmail(), "Sender email in notification DTO should not be null");
}
/* Properties getters and setters */
public EmailNotificationRepository getEmailNotificationRepository() {
return emailNotificationRepository;
}
public void setEmailNotificationRepository(final EmailNotificationRepository emailNotificationRepository) {
this.emailNotificationRepository = emailNotificationRepository;
}
}
| 3,381 | 0.786958 | 0.784007 | 77 | 43.012985 | 39.51968 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.506494 | false | false | 1 |
27e73bff0d3152dda271e9f71fddb630b3c96d2c | 11,493,332,499,000 | 7f62dbaf32e33c916f67800a0eab2e33ef9e10d3 | /Java Class/Workspace/chap06/src/chap06/Calculator2Main.java | 530371879e28c07de4992c3843f9d5d4b2a8c8ed | []
| no_license | SeojunHwang/Busan_Study | https://github.com/SeojunHwang/Busan_Study | a1f1a86fef6a28d474e5ac65ee41a85941e78e69 | f1d6db8682434c4d818886b6ca1de600b3b1cab7 | refs/heads/master | 2023-07-07T23:29:24.453000 | 2021-07-28T23:48:17 | 2021-07-28T23:48:17 | 355,062,223 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chap06;
public class Calculator2Main {
public static void main(String[] args) {
// 사칙 연산을 하는 프로그램을 작성
// +, -, *, /
int a;
int b;
int result;
a = 10;
b = 20;
// result = a + b;
// System.out.println("a + b = " + result);
//
// result = a + b;
// System.out.println("a + b = " + result);
//
// result = a + b;
// System.out.println("a + b = " + result);
//
// result = a - b;
// System.out.println("a - b = " + result);
//
// result = a - b;
// System.out.println("a - b = " + result);
//
// result = a - b;
// System.out.println("a - b = " + result);
//
//
//
// result = a * b;
// System.out.println("a * b = " + result);
//
// a = 30;
// b = 5;
// result = a / b;
// System.out.println("a / b = " + result);
add(a, b);
add(10, 30);
minus(a, b);
multi(a, b);
divide(30, 5);
}
// 자바의 메서드 생성
// 자바스크립트와는 달리 접근 제한자와 반환 타입 입력해야 함
// 매개 변수 입력 시 매개변수의 데이터 타입을 입력해야 함
// 메서드는 이러한 중복 실행되는 부분을 따로 모아서 소스코드를 간단하게 표기하기 위해 사용
// 자바스크립트에서의 4가지 함수 형식과 동일함
public static void add(int x, int y) {
int result = x + y;
System.out.println("두 수의 합은 : " + result);
}
public static void minus(int x, int y) {
int result = x - y;
System.out.println("두 수의 차는 : " + result);
}
public static void multi(int x, int y) {
int result = x * y;
System.out.println("두 수의 곱은 : " + result);
}
public static void divide(int x, int y) {
double result = (double)x / (double)y;
System.out.println("두 수의 나눗셈은 : " + result);
}
}
| UTF-8 | Java | 1,805 | java | Calculator2Main.java | Java | []
| null | []
| package chap06;
public class Calculator2Main {
public static void main(String[] args) {
// 사칙 연산을 하는 프로그램을 작성
// +, -, *, /
int a;
int b;
int result;
a = 10;
b = 20;
// result = a + b;
// System.out.println("a + b = " + result);
//
// result = a + b;
// System.out.println("a + b = " + result);
//
// result = a + b;
// System.out.println("a + b = " + result);
//
// result = a - b;
// System.out.println("a - b = " + result);
//
// result = a - b;
// System.out.println("a - b = " + result);
//
// result = a - b;
// System.out.println("a - b = " + result);
//
//
//
// result = a * b;
// System.out.println("a * b = " + result);
//
// a = 30;
// b = 5;
// result = a / b;
// System.out.println("a / b = " + result);
add(a, b);
add(10, 30);
minus(a, b);
multi(a, b);
divide(30, 5);
}
// 자바의 메서드 생성
// 자바스크립트와는 달리 접근 제한자와 반환 타입 입력해야 함
// 매개 변수 입력 시 매개변수의 데이터 타입을 입력해야 함
// 메서드는 이러한 중복 실행되는 부분을 따로 모아서 소스코드를 간단하게 표기하기 위해 사용
// 자바스크립트에서의 4가지 함수 형식과 동일함
public static void add(int x, int y) {
int result = x + y;
System.out.println("두 수의 합은 : " + result);
}
public static void minus(int x, int y) {
int result = x - y;
System.out.println("두 수의 차는 : " + result);
}
public static void multi(int x, int y) {
int result = x * y;
System.out.println("두 수의 곱은 : " + result);
}
public static void divide(int x, int y) {
double result = (double)x / (double)y;
System.out.println("두 수의 나눗셈은 : " + result);
}
}
| 1,805 | 0.530856 | 0.518912 | 75 | 19.026667 | 16.345415 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.253333 | false | false | 1 |
186b5471127009c1c2f44ed00e14469858ccd9b9 | 9,947,144,290,664 | a4a51084cfb715c7076c810520542af38a854868 | /src/main/java/com/tencent/qalsdk/sdk/b.java | 85491d11f70561e13d3b9023dc00d2a4e2aff447 | []
| no_license | BharathPalanivelu/repotest | https://github.com/BharathPalanivelu/repotest | ddaf56a94eb52867408e0e769f35bef2d815da72 | f78ae38738d2ba6c9b9b4049f3092188fabb5b59 | refs/heads/master | 2020-09-30T18:55:04.802000 | 2019-12-02T10:52:08 | 2019-12-02T10:52:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.qalsdk.sdk;
import com.tencent.qalsdk.base.remote.ToServiceMsg;
import java.util.concurrent.ConcurrentHashMap;
public final class b {
/* renamed from: a reason: collision with root package name */
private static ConcurrentHashMap<String, x> f32230a = new ConcurrentHashMap<>();
public static int a(ToServiceMsg toServiceMsg) {
if (toServiceMsg == null) {
return -1;
}
if (toServiceMsg.getServiceName().equals(v.a().b())) {
return v.a().a(toServiceMsg);
}
if (!f32230a.containsKey(toServiceMsg.getServiceName())) {
f32230a.putIfAbsent(toServiceMsg.getServiceName(), new x(toServiceMsg.getServiceName()));
}
return f32230a.get(toServiceMsg.getServiceName()).b(toServiceMsg);
}
}
| UTF-8 | Java | 810 | java | b.java | Java | []
| null | []
| package com.tencent.qalsdk.sdk;
import com.tencent.qalsdk.base.remote.ToServiceMsg;
import java.util.concurrent.ConcurrentHashMap;
public final class b {
/* renamed from: a reason: collision with root package name */
private static ConcurrentHashMap<String, x> f32230a = new ConcurrentHashMap<>();
public static int a(ToServiceMsg toServiceMsg) {
if (toServiceMsg == null) {
return -1;
}
if (toServiceMsg.getServiceName().equals(v.a().b())) {
return v.a().a(toServiceMsg);
}
if (!f32230a.containsKey(toServiceMsg.getServiceName())) {
f32230a.putIfAbsent(toServiceMsg.getServiceName(), new x(toServiceMsg.getServiceName()));
}
return f32230a.get(toServiceMsg.getServiceName()).b(toServiceMsg);
}
}
| 810 | 0.661728 | 0.635802 | 23 | 34.217392 | 30.229494 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 1 |
ddabb01f3cb093710520b15ccb57e9b1add3a2d7 | 35,940,286,367,878 | 4a698321e6b1ab1337cfe52ab3ea38a1134f8894 | /mall-b2c/src/main/java/com/cplatform/b2c/model/LotteryBean.java | d7b5652fd196a08a256435e262bb0f954951f55a | []
| no_license | bellmit/ws | https://github.com/bellmit/ws | c823419a6a335c424a19bfcdcc00f052f20ec65c | 6d3cd146ab82e06097a4eb94c4c3061ce000328c | refs/heads/master | 2022-03-22T22:47:10.514000 | 2015-10-10T10:39:54 | 2015-10-10T10:39:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cplatform.b2c.model;
// "AMOUNT":4.0,"COUNT":2,"DATE":"20130802095707","GOOD_ID":"D3",
// "GOOD_NAME":"福彩3D","ISSUE_NO":"2013207","ORDER_ID":"13754086274568282","PRICE":2.0,"STATUS":"3"},
public class LotteryBean {
private double AMOUNT;
private int COUNT;
private String DATE;
private String GOOD_ID;
private String GOOD_NAME;
private String ISSUE_NO;
private String ORDER_ID;
private double PRICE;
private String STATUS;
public double getAMOUNT() {
return AMOUNT;
}
public void setAMOUNT(double aMOUNT) {
AMOUNT = aMOUNT;
}
public int getCOUNT() {
return COUNT;
}
public void setCOUNT(int cOUNT) {
COUNT = cOUNT;
}
public String getDATE() {
return DATE;
}
public void setDATE(String dATE) {
DATE = dATE;
}
public String getGOOD_ID() {
return GOOD_ID;
}
public void setGOOD_ID(String gOODID) {
GOOD_ID = gOODID;
}
public String getGOOD_NAME() {
return GOOD_NAME;
}
public void setGOOD_NAME(String gOODNAME) {
GOOD_NAME = gOODNAME;
}
public String getISSUE_NO() {
return ISSUE_NO;
}
public void setISSUE_NO(String iSSUENO) {
ISSUE_NO = iSSUENO;
}
public String getORDER_ID() {
return ORDER_ID;
}
public void setORDER_ID(String oRDERID) {
ORDER_ID = oRDERID;
}
public double getPRICE() {
return PRICE;
}
public void setPRICE(double pRICE) {
PRICE = pRICE;
}
public String getSTATUS() {
return STATUS;
}
public void setSTATUS(String sTATUS) {
STATUS = sTATUS;
}
}
| UTF-8 | Java | 1,685 | java | LotteryBean.java | Java | [
{
"context": ":\"20130802095707\",\"GOOD_ID\":\"D3\",\n// \"GOOD_NAME\":\"福彩3D\",\"ISSUE_NO\":\"2013207\",\"ORDER_ID\":\"137540862745682",
"end": 120,
"score": 0.7590063810348511,
"start": 116,
"tag": "NAME",
"value": "福彩3D"
}
]
| null | []
| package com.cplatform.b2c.model;
// "AMOUNT":4.0,"COUNT":2,"DATE":"20130802095707","GOOD_ID":"D3",
// "GOOD_NAME":"福彩3D","ISSUE_NO":"2013207","ORDER_ID":"13754086274568282","PRICE":2.0,"STATUS":"3"},
public class LotteryBean {
private double AMOUNT;
private int COUNT;
private String DATE;
private String GOOD_ID;
private String GOOD_NAME;
private String ISSUE_NO;
private String ORDER_ID;
private double PRICE;
private String STATUS;
public double getAMOUNT() {
return AMOUNT;
}
public void setAMOUNT(double aMOUNT) {
AMOUNT = aMOUNT;
}
public int getCOUNT() {
return COUNT;
}
public void setCOUNT(int cOUNT) {
COUNT = cOUNT;
}
public String getDATE() {
return DATE;
}
public void setDATE(String dATE) {
DATE = dATE;
}
public String getGOOD_ID() {
return GOOD_ID;
}
public void setGOOD_ID(String gOODID) {
GOOD_ID = gOODID;
}
public String getGOOD_NAME() {
return GOOD_NAME;
}
public void setGOOD_NAME(String gOODNAME) {
GOOD_NAME = gOODNAME;
}
public String getISSUE_NO() {
return ISSUE_NO;
}
public void setISSUE_NO(String iSSUENO) {
ISSUE_NO = iSSUENO;
}
public String getORDER_ID() {
return ORDER_ID;
}
public void setORDER_ID(String oRDERID) {
ORDER_ID = oRDERID;
}
public double getPRICE() {
return PRICE;
}
public void setPRICE(double pRICE) {
PRICE = pRICE;
}
public String getSTATUS() {
return STATUS;
}
public void setSTATUS(String sTATUS) {
STATUS = sTATUS;
}
}
| 1,685 | 0.594289 | 0.56633 | 114 | 13.745614 | 16.788055 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.719298 | false | false | 1 |
1eeddfc6f0aeb0dd2ed61da883342955b3024011 | 3,461,743,664,952 | 3440c66c07e5c97304144c1dcd78fc122ed078b2 | /app/src/main/java/com/example/ts/safetyguard/adapter/WifiAdapter.java | 6ce8edd854ff979305a85687e8609b03e5e6d0a0 | []
| no_license | guohaodongpu/SafetyGuard | https://github.com/guohaodongpu/SafetyGuard | 657640de5dd67db48bf84c0a43b8589295462e1f | 3d4b470a1e3e3259093773979a79f4d0b049a4e7 | refs/heads/master | 2020-05-09T20:08:32.928000 | 2019-05-05T09:31:23 | 2019-05-05T09:31:23 | 181,395,878 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.ts.safetyguard.adapter;
import android.content.Context;
import android.net.wifi.ScanResult;
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.example.ts.safetyguard.R;
import java.util.List;
public class WifiAdapter extends BaseAdapter {
private List<ScanResult> mWifiList;
private Context mContext;
public WifiAdapter (Context context,List<ScanResult> list) {
this.mWifiList = list;
this.mContext = context;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public int getCount() {
return mWifiList.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_wifi_list,parent,false);
ScanResult scanResult = mWifiList.get(position);
TextView textView = view.findViewById(R.id.wifi_text_view);
textView.setText(scanResult.SSID);
ImageView imageView = view.findViewById(R.id.wifi_image_view);
if (Math.abs(scanResult.level) > 80) {
imageView.setImageDrawable(imageView.getResources().getDrawable(R.drawable.wifi_low));
} else if (Math.abs(scanResult.level) > 60 ) {
imageView.setImageDrawable(imageView.getResources().getDrawable(R.drawable.wifi_middle));
} else {
imageView.setImageDrawable(imageView.getResources().getDrawable(R.drawable.wifi_high));
}
return view;
}
}
| UTF-8 | Java | 1,752 | java | WifiAdapter.java | Java | []
| null | []
| package com.example.ts.safetyguard.adapter;
import android.content.Context;
import android.net.wifi.ScanResult;
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.example.ts.safetyguard.R;
import java.util.List;
public class WifiAdapter extends BaseAdapter {
private List<ScanResult> mWifiList;
private Context mContext;
public WifiAdapter (Context context,List<ScanResult> list) {
this.mWifiList = list;
this.mContext = context;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public int getCount() {
return mWifiList.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_wifi_list,parent,false);
ScanResult scanResult = mWifiList.get(position);
TextView textView = view.findViewById(R.id.wifi_text_view);
textView.setText(scanResult.SSID);
ImageView imageView = view.findViewById(R.id.wifi_image_view);
if (Math.abs(scanResult.level) > 80) {
imageView.setImageDrawable(imageView.getResources().getDrawable(R.drawable.wifi_low));
} else if (Math.abs(scanResult.level) > 60 ) {
imageView.setImageDrawable(imageView.getResources().getDrawable(R.drawable.wifi_middle));
} else {
imageView.setImageDrawable(imageView.getResources().getDrawable(R.drawable.wifi_high));
}
return view;
}
}
| 1,752 | 0.704338 | 0.702055 | 55 | 30.854546 | 27.684862 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581818 | false | false | 1 |
d93af74504e0c67036a2195f3161dc4998e6949a | 20,839,181,357,112 | 4b13c1b4877bd9ced4352ab58b4aa890a06c2d60 | /docs/src/test/samples/com/webcohesion/enunciate/samples/docs/PropertyTypeActual.java | fe5234c4b351b7a099b4da1f4a1c1dcac9310b4c | [
"Apache-2.0"
]
| permissive | stoicflame/enunciate | https://github.com/stoicflame/enunciate | e1866a8be2e634d8c98adee853179b81df80a20e | 446c86328a4eb6b7d1453fec7436c45552418d41 | refs/heads/master | 2023-09-04T19:24:44.788000 | 2023-04-28T00:36:40 | 2023-04-28T02:51:03 | 1,707,059 | 464 | 206 | NOASSERTION | false | 2023-08-15T17:40:53 | 2011-05-05T15:54:15 | 2023-07-19T11:21:42 | 2023-08-15T17:40:52 | 36,340 | 474 | 207 | 63 | Java | false | false | package com.webcohesion.enunciate.samples.docs;
public class PropertyTypeActual {
}
| UTF-8 | Java | 85 | java | PropertyTypeActual.java | Java | []
| null | []
| package com.webcohesion.enunciate.samples.docs;
public class PropertyTypeActual {
}
| 85 | 0.823529 | 0.823529 | 4 | 20.25 | 20.363878 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 1 |
4056b9ee52049f42b35390d5872648a61b11727f | 24,026,047,083,246 | ee6b20ba46f5142501540c67645e8d5951f56e27 | /funkeyDataServer/src/main/java/funkey/dao/CommandsDao.java | 911bcd3217d84802401856081c3119f0e2d50ef0 | []
| no_license | odedns/projects | https://github.com/odedns/projects | 15dd121af9571f4be5eb68f9088161530e4d524e | 35727b3bfb5682e05978fdf06a14255734775ccc | refs/heads/master | 2022-11-13T08:46:24.317000 | 2020-07-08T17:37:48 | 2020-07-08T17:37:48 | 252,156,219 | 0 | 0 | null | false | 2022-10-05T19:45:29 | 2020-04-01T11:31:51 | 2020-07-08T17:37:59 | 2022-10-05T19:45:26 | 191,983 | 0 | 0 | 7 | HTML | false | false | package funkey.dao;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class CommandsDao {
private static final String TABLE_NAME = "commands";
@Autowired
private DynamoDB dynamoDB;
private static final Logger log = Logger.getLogger(CommandsDao.class);
public CommandsDao()
{
}
public void addCommand(Command cmd) throws JsonProcessingException
{
ObjectMapper om = new ObjectMapper();
String json = om.writeValueAsString(cmd);
log.debug("addCommand json = " + json);
Table cmdTable = dynamoDB.getTable(TABLE_NAME);
Item item = Item.fromJSON(json);
cmdTable.putItem(item);
}
public void deleteCommand(long cmdId)
{
Table cmdTable = dynamoDB.getTable(TABLE_NAME);
cmdTable.deleteItem("commandId", cmdId);
}
public void updateCommand(long cmdId, Command cmd)
{
}
public Command findById(long id)
{
return(null);
}
public List<Command> findAll()
{
return(null);
}
public DynamoDB getDynamoDB() {
return dynamoDB;
}
public void setDynamoDB(DynamoDB dynamoDB) {
this.dynamoDB = dynamoDB;
}
}
| UTF-8 | Java | 1,556 | java | CommandsDao.java | Java | []
| null | []
| package funkey.dao;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class CommandsDao {
private static final String TABLE_NAME = "commands";
@Autowired
private DynamoDB dynamoDB;
private static final Logger log = Logger.getLogger(CommandsDao.class);
public CommandsDao()
{
}
public void addCommand(Command cmd) throws JsonProcessingException
{
ObjectMapper om = new ObjectMapper();
String json = om.writeValueAsString(cmd);
log.debug("addCommand json = " + json);
Table cmdTable = dynamoDB.getTable(TABLE_NAME);
Item item = Item.fromJSON(json);
cmdTable.putItem(item);
}
public void deleteCommand(long cmdId)
{
Table cmdTable = dynamoDB.getTable(TABLE_NAME);
cmdTable.deleteItem("commandId", cmdId);
}
public void updateCommand(long cmdId, Command cmd)
{
}
public Command findById(long id)
{
return(null);
}
public List<Command> findAll()
{
return(null);
}
public DynamoDB getDynamoDB() {
return dynamoDB;
}
public void setDynamoDB(DynamoDB dynamoDB) {
this.dynamoDB = dynamoDB;
}
}
| 1,556 | 0.718509 | 0.715938 | 71 | 19.915493 | 21.832104 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.267606 | false | false | 1 |
704428dc43feb1b6b4c57a813e71252aeb7f3cff | 33,251,636,830,657 | b9a9e21759cf11deea7f9d3a28a468d7bfd5a1cf | /src/main/java/com/qxb/leetcode/_37/Solution.java | bfe0e2c95cd02ac23ef9d72330931e309c85a069 | []
| no_license | qixubin/MyLeetcode | https://github.com/qixubin/MyLeetcode | f66e00f0ef12033e6e33113a1a222935772ee35b | 7f77cadf3c0cb75e63ccba5ea39ab578e53437e5 | refs/heads/master | 2020-06-18T01:59:09.324000 | 2016-12-08T08:33:06 | 2016-12-08T08:33:06 | 74,959,157 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qxb.leetcode._37;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by qixubin on 2016/5/25.
* <p>
* Write a program to solve a Sudoku puzzle by filling the empty cells.
* <p>
* Empty cells are indicated by the character '.'.
* <p>
* You may assume that there will be only one unique solution.
*/
public class Solution {
public void solveSudoku(char[][] board) {
char[][] init = new char[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
init[i][j] = board[i][j];
}
}
int n =-1;
boolean backward = false;
while (true){
if (backward) {
int i = n / 9;
int j = n % 9;
char c = board[i][j];
int num = char2int(c);
if (init[i][j] != '.'){
n--;
}else{
ArrayList<Integer> pv = findPossible(board,i,j);
if (pv.size() == 1) {
board[i][j] ='.';
n--;
backward = true;
}else{
if (num == pv.get(pv.size() - 1)) {
board[i][j] = '.';
n--;
backward = true;
}else{
board[i][j] = int2char(pv.get(pv.indexOf(num) + 1));
backward =false;
}
}
}
} else {
if (n ==80)
return;
int x = (n + 1) / 9;
int y = (n + 1) % 9;
char next_c = board[x][y];
if (next_c == '.') {
ArrayList<Integer> next_pv = findPossible(board,x,y);
if (next_pv.size() ==0){
backward = true;
}else{
board[x][y] = int2char(next_pv.get(0));
n++;
backward = false;
}
} else {
n++;
backward = false;
}
}
}
}
public Integer char2int(char c) {
return Integer.parseInt(new Character(c).toString());
}
public char int2char(int i) {
return new Integer(i).toString().charAt(0);
}
public ArrayList<Integer> findPossible(char[][] board, int i, int j) {
ArrayList<Integer> arr = new ArrayList<Integer>(Arrays.asList(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9}));
for (int k = 0; k < 9; k++) {
if (k==i)
continue;
char c = board[k][j];
if (c != '.') {
arr.remove(char2int(c));
}
}
for (int m = 0; m < 9; m++) {
if (m==j)
continue;
char c = board[i][m];
if (c != '.') {
arr.remove(char2int(c));
}
}
int x = i / 3;
int y = j / 3;
for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
if((x * 3 + m ==i) && (y * 3 + n ==j)){
continue;
}
char c = board[x * 3 + m][y * 3 + n];
if (c != '.') {
arr.remove(char2int(c));
}
}
}
return arr;
}
public static void main(String[] argv) {
Solution s1 = new Solution();
// System.out.println(Math.pow(2,4));
// System.out.println(s1.isPower(0));
//
// ArrayList<Integer> arr = new ArrayList<Integer>(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9}));
// arr.remove(new Integer(2));
// arr.remove(new Integer(2));
// System.out.println("11");
char[][] nums = new char[9][9];
nums[0] = new char[]{'5', '3', '.', '.', '7', '.', '.', '.', '.'};
nums[1] = new char[]{'6', '.', '.', '1', '9', '5', '.', '.', '.'};
nums[2] = new char[]{'.', '9', '8', '.', '.', '.', '.', '6', '.'};
nums[3] = new char[]{'8', '.', '.', '.', '6', '.', '.', '.', '3'};
nums[4] = new char[]{'4', '.', '.', '8', '.', '3', '.', '.', '1'};
nums[5] = new char[]{'7', '.', '.', '.', '2', '.', '.', '.', '6'};
nums[6] = new char[]{'.', '6', '.', '.', '.', '.', '2', '8', '.'};
nums[7] = new char[]{'.', '.', '.', '4', '1', '9', '.', '.', '5'};
nums[8] = new char[]{'.', '.', '.', '.', '8', '.', '.', '7', '9'};
// ArrayList al = s1.findPossible(nums, 1,0);
// System.out.println(al);
s1.solveSudoku(nums);
for (int i =0; i <9 ; i++){
for (int j =0; j < 9; j ++){
System.out.print(nums[i][j]+" ");
}
System.out.println();
}
// System.out.println(80/9);
// System.out.println(80%9);
//
// String[] a = new String[2];
// //int[] b = new int[2];
// ArrayList[][] c = new ArrayList[9][8];
// System.out.println(a.getClass());
// System.out.println(c.getClass());
}
}
| UTF-8 | Java | 5,259 | java | Solution.java | Java | [
{
"context": "yList;\nimport java.util.Arrays;\n\n/**\n * Created by qixubin on 2016/5/25.\n * <p>\n * Write a program to solve ",
"end": 110,
"score": 0.9996035695075989,
"start": 103,
"tag": "USERNAME",
"value": "qixubin"
}
]
| null | []
| package com.qxb.leetcode._37;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by qixubin on 2016/5/25.
* <p>
* Write a program to solve a Sudoku puzzle by filling the empty cells.
* <p>
* Empty cells are indicated by the character '.'.
* <p>
* You may assume that there will be only one unique solution.
*/
public class Solution {
public void solveSudoku(char[][] board) {
char[][] init = new char[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
init[i][j] = board[i][j];
}
}
int n =-1;
boolean backward = false;
while (true){
if (backward) {
int i = n / 9;
int j = n % 9;
char c = board[i][j];
int num = char2int(c);
if (init[i][j] != '.'){
n--;
}else{
ArrayList<Integer> pv = findPossible(board,i,j);
if (pv.size() == 1) {
board[i][j] ='.';
n--;
backward = true;
}else{
if (num == pv.get(pv.size() - 1)) {
board[i][j] = '.';
n--;
backward = true;
}else{
board[i][j] = int2char(pv.get(pv.indexOf(num) + 1));
backward =false;
}
}
}
} else {
if (n ==80)
return;
int x = (n + 1) / 9;
int y = (n + 1) % 9;
char next_c = board[x][y];
if (next_c == '.') {
ArrayList<Integer> next_pv = findPossible(board,x,y);
if (next_pv.size() ==0){
backward = true;
}else{
board[x][y] = int2char(next_pv.get(0));
n++;
backward = false;
}
} else {
n++;
backward = false;
}
}
}
}
public Integer char2int(char c) {
return Integer.parseInt(new Character(c).toString());
}
public char int2char(int i) {
return new Integer(i).toString().charAt(0);
}
public ArrayList<Integer> findPossible(char[][] board, int i, int j) {
ArrayList<Integer> arr = new ArrayList<Integer>(Arrays.asList(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9}));
for (int k = 0; k < 9; k++) {
if (k==i)
continue;
char c = board[k][j];
if (c != '.') {
arr.remove(char2int(c));
}
}
for (int m = 0; m < 9; m++) {
if (m==j)
continue;
char c = board[i][m];
if (c != '.') {
arr.remove(char2int(c));
}
}
int x = i / 3;
int y = j / 3;
for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
if((x * 3 + m ==i) && (y * 3 + n ==j)){
continue;
}
char c = board[x * 3 + m][y * 3 + n];
if (c != '.') {
arr.remove(char2int(c));
}
}
}
return arr;
}
public static void main(String[] argv) {
Solution s1 = new Solution();
// System.out.println(Math.pow(2,4));
// System.out.println(s1.isPower(0));
//
// ArrayList<Integer> arr = new ArrayList<Integer>(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9}));
// arr.remove(new Integer(2));
// arr.remove(new Integer(2));
// System.out.println("11");
char[][] nums = new char[9][9];
nums[0] = new char[]{'5', '3', '.', '.', '7', '.', '.', '.', '.'};
nums[1] = new char[]{'6', '.', '.', '1', '9', '5', '.', '.', '.'};
nums[2] = new char[]{'.', '9', '8', '.', '.', '.', '.', '6', '.'};
nums[3] = new char[]{'8', '.', '.', '.', '6', '.', '.', '.', '3'};
nums[4] = new char[]{'4', '.', '.', '8', '.', '3', '.', '.', '1'};
nums[5] = new char[]{'7', '.', '.', '.', '2', '.', '.', '.', '6'};
nums[6] = new char[]{'.', '6', '.', '.', '.', '.', '2', '8', '.'};
nums[7] = new char[]{'.', '.', '.', '4', '1', '9', '.', '.', '5'};
nums[8] = new char[]{'.', '.', '.', '.', '8', '.', '.', '7', '9'};
// ArrayList al = s1.findPossible(nums, 1,0);
// System.out.println(al);
s1.solveSudoku(nums);
for (int i =0; i <9 ; i++){
for (int j =0; j < 9; j ++){
System.out.print(nums[i][j]+" ");
}
System.out.println();
}
// System.out.println(80/9);
// System.out.println(80%9);
//
// String[] a = new String[2];
// //int[] b = new int[2];
// ArrayList[][] c = new ArrayList[9][8];
// System.out.println(a.getClass());
// System.out.println(c.getClass());
}
}
| 5,259 | 0.35482 | 0.32858 | 166 | 30.680723 | 22.563175 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.138554 | false | false | 1 |
1ad31dac4b8d1b67ee9f61561b3c6336a8a4512b | 7,464,653,184,650 | 515fc6a4c7dcd24b034e68f711fa18d0de4112c8 | /templates/server/src/main/resources/archetype-resources/api/src/main/java/__packageInPathFormat__/general/common/api/exception/NoActiveUserException.java | 4b6e5f5f5c1c4a7ba6bff053638f5b3c9b4e0fe3 | [
"Apache-2.0"
]
| permissive | oasp/oasp4j | https://github.com/oasp/oasp4j | 186af233cd7bfef2fd135dfd6dadc43a27799309 | 4ff7e9eb9900455befc40e1375efb64005205de9 | refs/heads/develop | 2021-11-26T22:24:21.246000 | 2021-05-22T14:43:20 | 2021-05-22T14:43:20 | 20,517,345 | 80 | 215 | Apache-2.0 | false | 2021-05-22T14:43:21 | 2014-06-05T08:20:28 | 2021-03-17T18:54:50 | 2021-05-22T14:43:20 | 10,498 | 63 | 311 | 60 | Java | false | false | package ${package}.general.common.api.exception;
import ${package}.general.common.api.NlsBundleApplicationRoot;
/**
* Thrown when an operation is requested that requires a user to be logged in, but no such user exists.
*/
public class NoActiveUserException extends ApplicationBusinessException {
/** UID for serialization. */
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public NoActiveUserException() {
this(null);
}
/**
* The constructor.
*
* @param cause The root cause of this exception.
*/
public NoActiveUserException(Throwable cause) {
super(cause, createBundle(NlsBundleApplicationRoot.class).errorNoActiveUser());
}
}
| UTF-8 | Java | 709 | java | NoActiveUserException.java | Java | []
| null | []
| package ${package}.general.common.api.exception;
import ${package}.general.common.api.NlsBundleApplicationRoot;
/**
* Thrown when an operation is requested that requires a user to be logged in, but no such user exists.
*/
public class NoActiveUserException extends ApplicationBusinessException {
/** UID for serialization. */
private static final long serialVersionUID = 1L;
/**
* The constructor.
*/
public NoActiveUserException() {
this(null);
}
/**
* The constructor.
*
* @param cause The root cause of this exception.
*/
public NoActiveUserException(Throwable cause) {
super(cause, createBundle(NlsBundleApplicationRoot.class).errorNoActiveUser());
}
}
| 709 | 0.715092 | 0.713681 | 31 | 21.870968 | 28.412561 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.225806 | false | false | 1 |
c98693f221b9ab452e16985a979d938caaa10e06 | 16,844,861,762,085 | deacdfb67fc54d97e411267a71fc7d1bbcc17bcf | /src/main/java/com/bulletphysics/linearmath/DebugModesType.java | f6812ba1b14810d235c13f7aa493beb9d4d187f6 | [
"Apache-2.0"
]
| permissive | recaifurkan/java-bullet-gwt | https://github.com/recaifurkan/java-bullet-gwt | 0226fbc1fcce8fdf75252b141d365b6a44dfd1df | 0534692c2b83941ac0669662362731137f76a5dc | refs/heads/master | 2020-06-25T03:36:52.538000 | 2019-08-01T20:00:54 | 2019-08-01T20:00:54 | 199,186,590 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bulletphysics.linearmath;
public enum DebugModesType{
NO_DEBUG(0),
DRAW_WIREFRAME (1),
DRAW_AABB(2),
DRAW_FEATURES_TEXT(4),
DRAW_CONTACT_POINTS(8),
NO_DEACTIVATION(16),
NO_HELP_TEXT(32),
DRAW_TEXT(64),
PROFILE_TIMINGS(128),
ENABLE_SAT_COMPARISON(256),
DISABLE_BULLET_LCP(512),
ENABLE_CCD(1024),
MAX_DEBUG_DRAW_MODE(1025),
DrawConstraints((1 << 11)),
DrawConstraintLimits((1 << 12));
private int deger;
DebugModesType(int deger) {
this.deger = deger;
}
public int getDeger() {
return this.deger;
}
public static String getName(int value) {
for (DebugModesType type : DebugModesType.values()) {
if(type.getDeger() == value) {
return type.name();
}
}
return null;
}
}
| UTF-8 | Java | 739 | java | DebugModesType.java | Java | []
| null | []
| package com.bulletphysics.linearmath;
public enum DebugModesType{
NO_DEBUG(0),
DRAW_WIREFRAME (1),
DRAW_AABB(2),
DRAW_FEATURES_TEXT(4),
DRAW_CONTACT_POINTS(8),
NO_DEACTIVATION(16),
NO_HELP_TEXT(32),
DRAW_TEXT(64),
PROFILE_TIMINGS(128),
ENABLE_SAT_COMPARISON(256),
DISABLE_BULLET_LCP(512),
ENABLE_CCD(1024),
MAX_DEBUG_DRAW_MODE(1025),
DrawConstraints((1 << 11)),
DrawConstraintLimits((1 << 12));
private int deger;
DebugModesType(int deger) {
this.deger = deger;
}
public int getDeger() {
return this.deger;
}
public static String getName(int value) {
for (DebugModesType type : DebugModesType.values()) {
if(type.getDeger() == value) {
return type.name();
}
}
return null;
}
}
| 739 | 0.667118 | 0.62111 | 44 | 15.795455 | 13.495083 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.636364 | false | false | 1 |
4ced9304e8cfedc09ecdaf30dc7d5cfb83d8ac71 | 13,357,348,329,877 | 111435cfe518ddb98eb3a03abf455d947c3dcaa0 | /app/src/main/java/com/saraltechnomart/hughcustomer1/ETA.java | 46c12154f7a14a8565d4841b503bf7be00688a9e | []
| no_license | rakeshdausa/HughCustomer | https://github.com/rakeshdausa/HughCustomer | 5b06fd81f3fbf43748351f6d92ea725ee5853705 | b13135eaa43ef0d190a0f1b1990950200bd0b10c | refs/heads/master | 2017-12-21T22:32:11.058000 | 2016-12-11T08:57:53 | 2016-12-11T08:57:53 | 76,163,821 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.saraltechnomart.hughcustomer1;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.saraltechnomart.AlertDialog.ShowAlertDialog;
import com.saraltechnomart.Menu.FrontMenu;
import com.saraltechnomart.WebServices.InsertDataService;
import com.saraltechnomart.hughcustomer1.*;
import com.saraltechnomart.hughcustomer1.CommonThings;
import com.saraltechnomart.hughcustomer1.SaveDbHelper;
import com.saraltechnomart.hughcustomer1.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TimePicker;
public class ETA extends Activity {
Spinner SpinCustomerSiteId;
Spinner SpinComplaintNo;
TextView DateTimepicker;
com.saraltechnomart.hughcustomer1.SaveDbHelper saveDbHelper;
InsertDataService insertDataService;
ShowAlertDialog showdialog;
private Dialog dialog;
public static final String[] MONTHS = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.eta);
saveDbHelper = new com.saraltechnomart.hughcustomer1.SaveDbHelper(ETA.this);
insertDataService = new InsertDataService(ETA.this);
showdialog = new ShowAlertDialog(ETA.this);
SpinCustomerSiteId = (Spinner)findViewById(R.id.SpinCustomerSiteId);
SpinComplaintNo = (Spinner)findViewById(R.id.SpinComplaintNo);
DateTimepicker = (TextView)findViewById(R.id.DateTimepicker);
GetCustomerSite();
SpinCustomerSiteId.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
GetComplaint();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SpinComplaintNo.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void ShowDateTimeDailog(View view)
{
SetDialog();
}
@SuppressLint("NewApi")
void SetDialog()
{
dialog = new Dialog(ETA.this);
dialog.setTitle("Date / Time");
dialog.setContentView(R.layout.date_time_dailog);
final DatePicker datePicker1 = (DatePicker)dialog.findViewById(R.id.datePicker1);
datePicker1.setCalendarViewShown(false);
final TimePicker timePicker1 = (TimePicker)dialog.findViewById(R.id.timePicker1);
Button SetDateTime = (Button)dialog.findViewById(R.id.SetDateTime);
SetDateTime.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String day = String.valueOf(datePicker1.getDayOfMonth());
String month = String.valueOf(datePicker1.getMonth());
month = MONTHS[Integer.valueOf(month)];
String year = String.valueOf(datePicker1.getYear());
String hour = String.valueOf(timePicker1.getCurrentHour());
String min = String.valueOf(timePicker1.getCurrentMinute());
DateTimepicker.setText(day+" "+ month+" "+year+" "+hour+":"+min);
dialog.cancel();
}
});
dialog.show();
}
void GetCustomerSite()
{
JSONArray CustomerSiteJson = null;
saveDbHelper.open();
CustomerSiteJson = saveDbHelper.getCustomerSite();
saveDbHelper.close();
List<String> categories = new ArrayList<String>();
categories.add("Select");
if(CustomerSiteJson.length() > 0)
{
for (int i = 0; i < CustomerSiteJson.length(); i++)
{
try
{
JSONObject obj = CustomerSiteJson.getJSONObject(i);
if(obj.getString("Status").equals("1"))
{
categories.add(obj.getString("CustomerSiteNo"));
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ArrayAdapter<String> Cashadapter = new ArrayAdapter<String>(ETA.this,
android.R.layout.simple_spinner_item, categories);
Cashadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinCustomerSiteId.setAdapter(Cashadapter);
}
void GetComplaint()
{
JSONArray CustomerSiteJson = null;
saveDbHelper.open();
CustomerSiteJson = saveDbHelper.getComplaintByCustomerSite(SpinCustomerSiteId.getSelectedItem().toString());
saveDbHelper.close();
List<String> categories = new ArrayList<String>();
categories.add("Select");
if(CustomerSiteJson.length() > 0)
{
for (int i = 0; i < CustomerSiteJson.length(); i++)
{
try
{
JSONObject obj = CustomerSiteJson.getJSONObject(i);
if(obj.getString("Status").equals("1"))
{
categories.add(obj.getString("ComplaintNo"));
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ArrayAdapter<String> Cashadapter = new ArrayAdapter<String>(ETA.this,
android.R.layout.simple_spinner_item, categories);
Cashadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinComplaintNo.setAdapter(Cashadapter);
}
@Override
public void onBackPressed() {
Intent intent = new Intent(ETA.this , com.saraltechnomart.hughcustomer1.CommonThings.GetClassByApi());
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
}
public void Submit(View view)
{
if(SpinComplaintNo.getSelectedItem().toString().equals("Select"))
{
showdialog.showalertDialog("Please Select Complaint", "Complaint");
}
else if(DateTimepicker.getText().toString().equals(""))
{
showdialog.showalertDialog("Please Select ETA", "ETA");
}
else
{
new SubmitData().execute();
}
}
private class SubmitData extends AsyncTask<Void, Void, Void> {
String Result ="0";
ProgressDialog progress = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(ETA.this);
progress.setMessage("Please wait...");
progress.setCancelable(false);
progress.show();
}
@Override
protected Void doInBackground(Void... params) {
Result = insertDataService.UpdateFieldEngineerETA(SpinComplaintNo.getSelectedItem().toString(),
DateTimepicker.getText().toString());
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progress.dismiss();
Log.d("Result", Result);
Intent intent = new Intent(ETA.this , com.saraltechnomart.hughcustomer1.CommonThings.GetClassByApi());
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
}
}
}
| UTF-8 | Java | 7,350 | java | ETA.java | Java | []
| null | []
| package com.saraltechnomart.hughcustomer1;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.saraltechnomart.AlertDialog.ShowAlertDialog;
import com.saraltechnomart.Menu.FrontMenu;
import com.saraltechnomart.WebServices.InsertDataService;
import com.saraltechnomart.hughcustomer1.*;
import com.saraltechnomart.hughcustomer1.CommonThings;
import com.saraltechnomart.hughcustomer1.SaveDbHelper;
import com.saraltechnomart.hughcustomer1.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TimePicker;
public class ETA extends Activity {
Spinner SpinCustomerSiteId;
Spinner SpinComplaintNo;
TextView DateTimepicker;
com.saraltechnomart.hughcustomer1.SaveDbHelper saveDbHelper;
InsertDataService insertDataService;
ShowAlertDialog showdialog;
private Dialog dialog;
public static final String[] MONTHS = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.eta);
saveDbHelper = new com.saraltechnomart.hughcustomer1.SaveDbHelper(ETA.this);
insertDataService = new InsertDataService(ETA.this);
showdialog = new ShowAlertDialog(ETA.this);
SpinCustomerSiteId = (Spinner)findViewById(R.id.SpinCustomerSiteId);
SpinComplaintNo = (Spinner)findViewById(R.id.SpinComplaintNo);
DateTimepicker = (TextView)findViewById(R.id.DateTimepicker);
GetCustomerSite();
SpinCustomerSiteId.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
GetComplaint();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SpinComplaintNo.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void ShowDateTimeDailog(View view)
{
SetDialog();
}
@SuppressLint("NewApi")
void SetDialog()
{
dialog = new Dialog(ETA.this);
dialog.setTitle("Date / Time");
dialog.setContentView(R.layout.date_time_dailog);
final DatePicker datePicker1 = (DatePicker)dialog.findViewById(R.id.datePicker1);
datePicker1.setCalendarViewShown(false);
final TimePicker timePicker1 = (TimePicker)dialog.findViewById(R.id.timePicker1);
Button SetDateTime = (Button)dialog.findViewById(R.id.SetDateTime);
SetDateTime.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String day = String.valueOf(datePicker1.getDayOfMonth());
String month = String.valueOf(datePicker1.getMonth());
month = MONTHS[Integer.valueOf(month)];
String year = String.valueOf(datePicker1.getYear());
String hour = String.valueOf(timePicker1.getCurrentHour());
String min = String.valueOf(timePicker1.getCurrentMinute());
DateTimepicker.setText(day+" "+ month+" "+year+" "+hour+":"+min);
dialog.cancel();
}
});
dialog.show();
}
void GetCustomerSite()
{
JSONArray CustomerSiteJson = null;
saveDbHelper.open();
CustomerSiteJson = saveDbHelper.getCustomerSite();
saveDbHelper.close();
List<String> categories = new ArrayList<String>();
categories.add("Select");
if(CustomerSiteJson.length() > 0)
{
for (int i = 0; i < CustomerSiteJson.length(); i++)
{
try
{
JSONObject obj = CustomerSiteJson.getJSONObject(i);
if(obj.getString("Status").equals("1"))
{
categories.add(obj.getString("CustomerSiteNo"));
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ArrayAdapter<String> Cashadapter = new ArrayAdapter<String>(ETA.this,
android.R.layout.simple_spinner_item, categories);
Cashadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinCustomerSiteId.setAdapter(Cashadapter);
}
void GetComplaint()
{
JSONArray CustomerSiteJson = null;
saveDbHelper.open();
CustomerSiteJson = saveDbHelper.getComplaintByCustomerSite(SpinCustomerSiteId.getSelectedItem().toString());
saveDbHelper.close();
List<String> categories = new ArrayList<String>();
categories.add("Select");
if(CustomerSiteJson.length() > 0)
{
for (int i = 0; i < CustomerSiteJson.length(); i++)
{
try
{
JSONObject obj = CustomerSiteJson.getJSONObject(i);
if(obj.getString("Status").equals("1"))
{
categories.add(obj.getString("ComplaintNo"));
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ArrayAdapter<String> Cashadapter = new ArrayAdapter<String>(ETA.this,
android.R.layout.simple_spinner_item, categories);
Cashadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinComplaintNo.setAdapter(Cashadapter);
}
@Override
public void onBackPressed() {
Intent intent = new Intent(ETA.this , com.saraltechnomart.hughcustomer1.CommonThings.GetClassByApi());
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
}
public void Submit(View view)
{
if(SpinComplaintNo.getSelectedItem().toString().equals("Select"))
{
showdialog.showalertDialog("Please Select Complaint", "Complaint");
}
else if(DateTimepicker.getText().toString().equals(""))
{
showdialog.showalertDialog("Please Select ETA", "ETA");
}
else
{
new SubmitData().execute();
}
}
private class SubmitData extends AsyncTask<Void, Void, Void> {
String Result ="0";
ProgressDialog progress = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(ETA.this);
progress.setMessage("Please wait...");
progress.setCancelable(false);
progress.show();
}
@Override
protected Void doInBackground(Void... params) {
Result = insertDataService.UpdateFieldEngineerETA(SpinComplaintNo.getSelectedItem().toString(),
DateTimepicker.getText().toString());
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progress.dismiss();
Log.d("Result", Result);
Intent intent = new Intent(ETA.this , com.saraltechnomart.hughcustomer1.CommonThings.GetClassByApi());
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
}
}
}
| 7,350 | 0.734966 | 0.731429 | 255 | 27.82353 | 25.049055 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.52549 | false | false | 1 |
3aa032045a65c35b95b5ac44ecf7f5e5b30a94eb | 23,871,428,270,019 | 24bb3eecd6aea84030189f34e54c5c90a410be03 | /src/main/java/annotations/explanation/step1/TheWorst.java | cdc31caed8f2d1b6908532cbbcb15143d2d4efbc | []
| no_license | elvint14/java-reflection | https://github.com/elvint14/java-reflection | 67a9a9648e23c50bf702df4aa3cb8cabc407777b | e33963015b1a714a13c7e70a9b5f0205729c11a1 | refs/heads/master | 2023-08-01T18:09:42.811000 | 2021-07-24T09:11:35 | 2021-07-24T09:11:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package annotations.explanation.step1;
public @interface TheWorst {
}
| UTF-8 | Java | 71 | java | TheWorst.java | Java | []
| null | []
| package annotations.explanation.step1;
public @interface TheWorst {
}
| 71 | 0.802817 | 0.788732 | 4 | 16.75 | 16.633926 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 1 |
10878686316d11ea246ecef850a6ad8e05bfe9f7 | 21,440,476,775,135 | aa2228223455aa03208d3faac5706bace34b01c8 | /src/main/java/com/coshine/batsys/web/HistoryController.java | 70b55b339c0d6f8a46d60705f84307dc59a1ae75 | []
| no_license | cookiecookiecookie/hxp | https://github.com/cookiecookiecookie/hxp | cb2277e8443bc0dfe47231a63525fa202a222b51 | f1aaf7b4f38911b363024935c8653b2cb87e6224 | refs/heads/master | 2021-01-18T09:15:26.368000 | 2016-09-18T01:49:21 | 2016-09-18T01:49:21 | 68,485,967 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.coshine.batsys.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.coshine.batsys.entity.CpJobExec;
import com.coshine.batsys.service.BatsysService;
import com.github.pagehelper.PageInfo;
@Controller
public class HistoryController {
@Autowired
private BatsysService batsysService;
@WebAction(Permission.NEED_AUTH)
@RequestMapping("/history")
public String index(@RequestParam(name="p", defaultValue="1") Integer pageNum, Model m) {
List<CpJobExec> jobExecs = batsysService.searchJobExec(pageNum);
m.addAttribute("pageInfo", new PageInfo<CpJobExec>(jobExecs));
return "history/index";
}
}
| UTF-8 | Java | 883 | java | HistoryController.java | Java | []
| null | []
| package com.coshine.batsys.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.coshine.batsys.entity.CpJobExec;
import com.coshine.batsys.service.BatsysService;
import com.github.pagehelper.PageInfo;
@Controller
public class HistoryController {
@Autowired
private BatsysService batsysService;
@WebAction(Permission.NEED_AUTH)
@RequestMapping("/history")
public String index(@RequestParam(name="p", defaultValue="1") Integer pageNum, Model m) {
List<CpJobExec> jobExecs = batsysService.searchJobExec(pageNum);
m.addAttribute("pageInfo", new PageInfo<CpJobExec>(jobExecs));
return "history/index";
}
}
| 883 | 0.804077 | 0.802944 | 29 | 29.448277 | 25.305834 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.103448 | false | false | 1 |
c5cbe491a7d36c93f4b2af9d5ca2ebc4d4f7dfe6 | 38,465,727,115,290 | 61e3ff6d34297cf444e5749c1e1d7ed5ba93cecd | /com/android/camera/C0226y.java | b8694d7d87d2cbf412ffa6ec4d21a26279d47d99 | []
| no_license | BeYkeRYkt/nubia_cam_smali | https://github.com/BeYkeRYkt/nubia_cam_smali | b49beafe60b989fab02753601735e493f2f72d16 | 39dad22d05b0a2dfd4e9d04acad9673ac1add410 | refs/heads/master | 2020-03-17T18:31:12.851000 | 2018-05-17T15:24:14 | 2018-05-17T15:24:14 | 133,825,725 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.camera;
import com.android.common.appService.C0147A;
import com.android.common.appService.CameraStartUpThread$CameraOpenState;
final class C0226y implements C0147A {
final /* synthetic */ Camera aJg;
final /* synthetic */ int aJh;
C0226y(Camera camera, int i) {
this.aJg = camera;
this.aJh = i;
}
public void ZZ() {
this.aJg.aZb();
this.aJg.auW();
this.aJg.ass();
this.aJg.aYP();
this.aJg.aYD(this.aJh);
}
public void ZY(int[] iArr, CameraStartUpThread$CameraOpenState cameraStartUpThread$CameraOpenState) {
this.aJg.ajb.post(new C0227z(this, cameraStartUpThread$CameraOpenState));
}
}
| UTF-8 | Java | 707 | java | C0226y.java | Java | []
| null | []
| package com.android.camera;
import com.android.common.appService.C0147A;
import com.android.common.appService.CameraStartUpThread$CameraOpenState;
final class C0226y implements C0147A {
final /* synthetic */ Camera aJg;
final /* synthetic */ int aJh;
C0226y(Camera camera, int i) {
this.aJg = camera;
this.aJh = i;
}
public void ZZ() {
this.aJg.aZb();
this.aJg.auW();
this.aJg.ass();
this.aJg.aYP();
this.aJg.aYD(this.aJh);
}
public void ZY(int[] iArr, CameraStartUpThread$CameraOpenState cameraStartUpThread$CameraOpenState) {
this.aJg.ajb.post(new C0227z(this, cameraStartUpThread$CameraOpenState));
}
}
| 707 | 0.653465 | 0.625177 | 26 | 26.192308 | 26.034029 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false | 1 |
595e496b9ac84973471c61291d4485678ecd21cf | 27,324,581,967,175 | 01284037cda99a419503c6012b4ce201a744fe70 | /core/src/main/java/com/betterway/tax/core/service/TcnMonitorService.java | efcc6ef767efec66afe287975282913c7bc95aef | []
| no_license | dev4btw/tax-backend | https://github.com/dev4btw/tax-backend | db0408a543d84085dcc37cd63150d34f3b80c588 | 4bcb45d8d151dd5756de974e7e90a0888bb46bee | refs/heads/master | 2021-01-19T19:06:02.799000 | 2017-06-10T08:05:53 | 2017-06-10T08:05:53 | 88,397,756 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.betterway.tax.core.service;
import com.betterway.tax.core.dto.TcnMonitorDTO;
import com.betterway.tax.core.service.ws.client.Reporter;
import java.util.List;
/**
*
* Created by cowra on 2017/4/6.
*/
public interface TcnMonitorService {
void insert(String source);
void update(String source, int status);
void insert(String source, List<String> filenameList);
void initRawpacks(List<String> rawpackInfos);
void processRawpack(String filename, Reporter reporter);
void success(String filename);
void failure(String filename, String note);
List<TcnMonitorDTO> sendMsgToMQ(String source);
List<TcnMonitorDTO> findBySource(String source);
List<TcnMonitorDTO> findByStatusAndSource(int[] status, String source);
}
| UTF-8 | Java | 777 | java | TcnMonitorService.java | Java | [
{
"context": "ter;\n\nimport java.util.List;\n\n/**\n *\n * Created by cowra on 2017/4/6.\n */\npublic interface TcnMonitorServi",
"end": 199,
"score": 0.9996735453605652,
"start": 194,
"tag": "USERNAME",
"value": "cowra"
}
]
| null | []
| package com.betterway.tax.core.service;
import com.betterway.tax.core.dto.TcnMonitorDTO;
import com.betterway.tax.core.service.ws.client.Reporter;
import java.util.List;
/**
*
* Created by cowra on 2017/4/6.
*/
public interface TcnMonitorService {
void insert(String source);
void update(String source, int status);
void insert(String source, List<String> filenameList);
void initRawpacks(List<String> rawpackInfos);
void processRawpack(String filename, Reporter reporter);
void success(String filename);
void failure(String filename, String note);
List<TcnMonitorDTO> sendMsgToMQ(String source);
List<TcnMonitorDTO> findBySource(String source);
List<TcnMonitorDTO> findByStatusAndSource(int[] status, String source);
}
| 777 | 0.7426 | 0.734878 | 34 | 21.852942 | 24.334837 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.558824 | false | false | 1 |
32ba17c9d1c01d08d63fdb7c17e3809b17e37937 | 29,678,224,049,234 | 64478a9530ac3d0f4e47a19af33b4e287c13d471 | /src/com/tntdjs/soloplayer/playlist/editor/PlaylistEditHelper.java | 5caf94620e2a38a1e9efb8e765f8cea25a3dd1f1 | []
| no_license | tntdjs/SoloPlayer | https://github.com/tntdjs/SoloPlayer | 7c5b194c12cc9a055528075d4a45b87d76b6f3aa | 6973cd2d068ee02f2f4583cd0dc33655ba59e2e0 | refs/heads/master | 2020-05-30T10:15:38.160000 | 2019-06-02T17:04:33 | 2019-06-02T17:04:33 | 189,667,989 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tntdjs.soloplayer.playlist.editor;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.tntdjs.soloplayer.RootAppMgr;
import com.tntdjs.soloplayer.ui.swing.playlist.editor.AudioFilesFilter;
import com.tntdjs.soloplayer.ui.swing.playlist.editor.MP3FileFilter;
/**
* PlaylistEditHelper
* @author tsenausk
*
*/
public class PlaylistEditHelper {
private static Logger LOGGER = LogManager.getRootLogger();
private static PlaylistEditHelper INSTANCE;
private JFileChooser fc;
public PlaylistEditHelper() {
fc = new JFileChooser();
}
public static PlaylistEditHelper getInstance() {
if (null == INSTANCE) {
INSTANCE = new PlaylistEditHelper();
}
return INSTANCE;
}
/**
* getPlaylistFile
* @param parent
* @return String the file selected or empty if cancelled
*/
public String getPlaylistFile(JFrame parent) {
fc.addChoosableFileFilter(new MP3FileFilter());
fc.addChoosableFileFilter(new AudioFilesFilter());
int returnVal = fc.showDialog(parent, "Add");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
// This is where a real application would open the file.
LOGGER.info("Opening: " + file.getName() + ".");
return file.getAbsolutePath();
} else {
LOGGER.info("Open command cancelled by user.");
return "";
}
// log.setCaretPosition(log.getDocument().getLength());
}
/**
* getPlaylistFolder
* @param parent
* @return String of the folder selected or empty if cancelled
*/
public String getPlaylistFolder(JFrame parent) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose a playlist folder");
// Uncomment one of the following lines to try a different
// file selection mode. The first allows just directories
// to be selected (and, at least in the Java look and feel,
// shown). The second allows both files and directories
// to be selected. If you leave these lines commented out,
// then the default mode (FILES_ONLY) will be used.
//
// fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// disable the "All files" option.
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
LOGGER.info("getCurrentDirectory(): " + chooser.getCurrentDirectory());
LOGGER.info("getSelectedFile() : " + chooser.getSelectedFile());
return chooser.getSelectedFile().toString();
} else {
LOGGER.info("No Selection ");
return "";
}
}
public boolean deletePlaylist() {
RootAppMgr.getInstance().getPlayListview().deleteCurrentPlaylist();
return true;
}
}
| UTF-8 | Java | 2,905 | java | PlaylistEditHelper.java | Java | [
{
"context": "3FileFilter;\n\n/**\n * PlaylistEditHelper\n * @author tsenausk\n *\n */\npublic class PlaylistEditHelper {\n\tprivate",
"end": 428,
"score": 0.9996886253356934,
"start": 420,
"tag": "USERNAME",
"value": "tsenausk"
}
]
| null | []
| package com.tntdjs.soloplayer.playlist.editor;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.tntdjs.soloplayer.RootAppMgr;
import com.tntdjs.soloplayer.ui.swing.playlist.editor.AudioFilesFilter;
import com.tntdjs.soloplayer.ui.swing.playlist.editor.MP3FileFilter;
/**
* PlaylistEditHelper
* @author tsenausk
*
*/
public class PlaylistEditHelper {
private static Logger LOGGER = LogManager.getRootLogger();
private static PlaylistEditHelper INSTANCE;
private JFileChooser fc;
public PlaylistEditHelper() {
fc = new JFileChooser();
}
public static PlaylistEditHelper getInstance() {
if (null == INSTANCE) {
INSTANCE = new PlaylistEditHelper();
}
return INSTANCE;
}
/**
* getPlaylistFile
* @param parent
* @return String the file selected or empty if cancelled
*/
public String getPlaylistFile(JFrame parent) {
fc.addChoosableFileFilter(new MP3FileFilter());
fc.addChoosableFileFilter(new AudioFilesFilter());
int returnVal = fc.showDialog(parent, "Add");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
// This is where a real application would open the file.
LOGGER.info("Opening: " + file.getName() + ".");
return file.getAbsolutePath();
} else {
LOGGER.info("Open command cancelled by user.");
return "";
}
// log.setCaretPosition(log.getDocument().getLength());
}
/**
* getPlaylistFolder
* @param parent
* @return String of the folder selected or empty if cancelled
*/
public String getPlaylistFolder(JFrame parent) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose a playlist folder");
// Uncomment one of the following lines to try a different
// file selection mode. The first allows just directories
// to be selected (and, at least in the Java look and feel,
// shown). The second allows both files and directories
// to be selected. If you leave these lines commented out,
// then the default mode (FILES_ONLY) will be used.
//
// fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// disable the "All files" option.
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
LOGGER.info("getCurrentDirectory(): " + chooser.getCurrentDirectory());
LOGGER.info("getSelectedFile() : " + chooser.getSelectedFile());
return chooser.getSelectedFile().toString();
} else {
LOGGER.info("No Selection ");
return "";
}
}
public boolean deletePlaylist() {
RootAppMgr.getInstance().getPlayListview().deleteCurrentPlaylist();
return true;
}
}
| 2,905 | 0.730809 | 0.729432 | 97 | 28.948454 | 23.969643 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.783505 | false | false | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.